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

selfUpdate.ts

396 lines16.0 KB

1import {
2 DESKTOP_UPDATE_IN_PROGRESS_MARKER_FILE,
3 ServerSelfUpdateError,
4 type ServerSelfUpdateCapability,
5 type ServerSelfUpdateInput,
6 type ServerSelfUpdateProgressEvent,
7 type ServerSelfUpdateProgressStage,
8 type ServerSelfUpdateResult,
9} from "@t3tools/contracts";
10import * as HostProcess from "@t3tools/shared/HostProcess";
11import * as Config from "effect/Config";
12import * as Context from "effect/Context";
13import * as Duration from "effect/Duration";
14import * as Effect from "effect/Effect";
15import * as Option from "effect/Option";
16import * as Ref from "effect/Ref";
17import * as FileSystem from "effect/FileSystem";
18import * as Layer from "effect/Layer";
19import * as Path from "effect/Path";
20import * as Queue from "effect/Queue";
21import * as Stream from "effect/Stream";
22import { HttpClient } from "effect/http";
23​
24import {
25 CLI_RELEASE_BASE_URL_ENV,
26 cliReleaseChannelOf,
27 crossesReleaseTrack,
28} from "@t3tools/shared/cliRelease";
29​
30import packageJson from "../../package.json" with { type: "json" };
31import * as ServerConfig from "../config.ts";
32import * as DesktopAppUpdate from "../desktopUpdate/DesktopAppUpdate.ts";
33import * as DesktopUpdateMarker from "../desktopUpdate/DesktopUpdateMarker.ts";
34import { databaseMigrationHead } from "../persistence/databaseMigrationHead.ts";
35import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
36import { managedUpdateMirror, managedUpdateRefusal } from "../policy/managedUpdates.ts";
37import * as ProcessRunner from "../processRunner.ts";
38import {
39 ensurePinnedRuntimeInstalled,
40 isUnpublishedRelease,
41 pinnedRuntimeCommand,
42 PinnedRuntimeInstallError,
43 pinnedRuntimePaths,
44 PinnedRuntimePreflightBlockedError,
45 prunePinnedRuntimes,
46} from "./pinnedRuntime.ts";
47import { bootServiceProgramOf, bootServiceUnitPath } from "./bootService.ts";
48import { decodeServicePreflightResult } from "./servicePreflight.ts";
49import * as ServiceLauncherClient from "./serviceLauncherClient.ts";
50import { isExactServiceVersion } from "./serviceProtocol.ts";
51​
52// A staged runtime's cold start can take over a minute on a loaded, swapping host.
53const PREFLIGHT_TIMEOUT = Duration.minutes(3);
54​
55export function resolveServerSelfUpdateCapability(input: {
56 readonly desktopManaged: boolean;
57 readonly launcherManaged: boolean;
58}): ServerSelfUpdateCapability | null {
59 if (input.desktopManaged) return "desktop-managed" as const;
60 return input.launcherManaged ? ("boot-service" as const) : null;
62​
63export class ServerSelfUpdate extends Context.Service<
64 ServerSelfUpdate,
65 {
66 readonly update: (
67 input: ServerSelfUpdateInput,
68 reportProgress?: (
69 stage: ServerSelfUpdateProgressStage,
70 ) => Effect.Effect<void, ServerSelfUpdateError>,
71 onHandoffAccepted?: () => Effect.Effect<void>,
72 ) => Effect.Effect<ServerSelfUpdateResult, ServerSelfUpdateError>;
73 readonly commitDesktopUpdate: (
74 requestId: string,
75 onHandoffAccepted?: () => Effect.Effect<void>,
76 ) => Effect.Effect<never, ServerSelfUpdateError>;
77 }
78>()("t3/cloud/selfUpdate/ServerSelfUpdate") {}
79​
80/**
81 * A server starting from the runtime its launcher settled on means runtimes left by earlier
82 * updates can go. The boot service says so through its IPC context. The SSH launcher and the
83 * install script's `t3` start this home's pinned runtime directly, without one.
84 */
85export const pruneRuntimesOnStart = Effect.fn("cloud.server_self_update.prune_on_start")(
86 function* (input: { readonly baseDir: string; readonly managed: boolean }) {
87 const fs = yield* FileSystem.FileSystem;
88 const path = yield* Path.Path;
89 const platform = yield* HostProcess.Platform;
90 const executablePath = yield* HostProcess.ExecutablePath;
91 const { entryPath } = pinnedRuntimePaths(path, input.baseDir, packageJson.version, platform);
92 // The executable path is resolved, so it names the real path of a symlinked T3 home.
93 const realEntryPath = yield* fs.realPath(entryPath).pipe(Effect.orElseSucceed(() => entryPath));
94 if (!input.managed && executablePath !== entryPath && executablePath !== realEntryPath) {
95 return [];
96 }
97 const unitPath = yield* bootServiceUnitPath();
98 // A stopped service's unit still names the launcher runtime it will start.
99 const unit =
100 unitPath === undefined
101 ? Option.none<string>()
102 : yield* fs.readFileString(unitPath).pipe(Effect.option);
103 const program = Option.flatMapNullishOr(unit, bootServiceProgramOf);
104 // The unit may name it through another spelling of a symlinked T3 home.
105 const references = Option.isNone(program)
106 ? []
107 : [
108 program.value,
109 yield* fs.realPath(program.value).pipe(Effect.orElseSucceed(() => program.value)),
110 ];
111 const removed = yield* prunePinnedRuntimes({
112 baseDir: input.baseDir,
113 keep: [packageJson.version],
114 references,
115 });
116 if (removed.length > 0) {
117 yield* Effect.logInfo("Removed unused t3 runtimes.", { versions: removed });
118 }
119 return removed;
120 },
121);
122​
123/** The client checks this when planning; the host checks again because its database may have
124 * moved on since (another client updated it). Stable and Nightly each build their own commits,
125 * so crossing tracks needs the target release to know every migration this database holds. */
126export function trackSwitchBlockReason(input: {
127 readonly serverVersion: string;
128 readonly targetVersion: string;
129 readonly targetDatabaseMigration: number | undefined;
130 /** Read only for a crossing; undefined when the database cannot be read. */
131 readonly databaseMigration: () => number | undefined;
132}): string | null {
133 if (!crossesReleaseTrack(input.serverVersion, input.targetVersion)) return null;
134 const databaseMigration = input.databaseMigration();
135 if (input.targetDatabaseMigration === undefined || databaseMigration === undefined) {
136 return `Cannot confirm this database works with t3@${input.targetVersion}. Switch tracks from Settings → About → Update track, which checks it first.`;
137 }
138 return input.targetDatabaseMigration < databaseMigration
139 ? `This database has changes t3@${input.targetVersion} does not support yet; it stays on this release.`
140 : null;
142​
143export const make = Effect.fn("cloud.server_self_update.make")(function* () {
144 const serverConfig = yield* ServerConfig.ServerConfig;
145 const desktopAppUpdate = yield* DesktopAppUpdate.DesktopAppUpdate;
146 const policy = yield* ManagedPolicy.ManagedPolicy;
147 const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
148 const runner = yield* ProcessRunner.ProcessRunner;
149 const fs = yield* FileSystem.FileSystem;
150 const path = yield* Path.Path;
151 const platform = yield* HostProcess.Platform;
152 const arch = yield* HostProcess.Architecture;
153 const httpClient = yield* HttpClient.HttpClient;
154 const mirror = managedUpdateMirror(policy.document);
155 const releaseBaseUrl =
156 mirror?.feedUrl ??
157 Option.getOrUndefined(yield* Config.String(CLI_RELEASE_BASE_URL_ENV).pipe(Config.option));
158 const inFlight = yield* Ref.make(false);
159​
160 yield* pruneRuntimesOnStart({ baseDir: serverConfig.baseDir, managed: launcher.managed }).pipe(
161 Effect.forkScoped,
162 );
163​
164 const capability: ServerSelfUpdateCapability | null =
165 serverConfig.mode === "desktop" ? "desktop-managed" : launcher.managed ? "boot-service" : null;
166 const failWith = (reason: string, cause?: unknown) =>
167 cause === undefined
168 ? new ServerSelfUpdateError({ reason })
169 : new ServerSelfUpdateError({ reason, cause });
170​
171 const crossesTrackUnsafely = (input: ServerSelfUpdateInput) =>
172 trackSwitchBlockReason({
173 serverVersion: packageJson.version,
174 targetVersion: input.targetVersion,
175 targetDatabaseMigration: input.targetDatabaseMigration,
176 databaseMigration: () => databaseMigrationHead(serverConfig.dbPath),
177 });
178​
179 const update: ServerSelfUpdate["Service"]["update"] = Effect.fn(
180 "cloud.server_self_update.update",
181 )(function* (input, reportProgress = () => Effect.void, onHandoffAccepted = () => Effect.void) {
182 const policyRefusal = managedUpdateRefusal(
183 policy.document,
184 capability === "boot-service" ? cliReleaseChannelOf(input.targetVersion.trim()) : undefined,
185 );
186 if (policyRefusal !== undefined) {
187 return yield* failWith(policyRefusal);
188 }
189 if (capability === "desktop-managed") {
190 const unsafeCrossing = input.channel === undefined ? null : crossesTrackUnsafely(input);
191 if (unsafeCrossing !== null) return yield* failWith(unsafeCrossing);
192 if (desktopAppUpdate.available) {
193 return yield* desktopAppUpdate.run(
194 reportProgress,
195 input.channel === undefined
196 ? undefined
197 : { channel: input.channel, targetVersion: input.targetVersion },
198 );
199 }
200 return yield* failWith(
201 "This server is managed by the T3 Code desktop app on its machine; update the desktop app to update it.",
202 );
203 }
204 // The target must accept the launcher that will run it, which can be older than this server.
205 const launcherProtocol = launcher.protocol;
206 if (capability === null || launcherProtocol === undefined) {
207 return yield* failWith(
208 "Remote updates require the T3 Code background service. Run `t3 service install` on the server machine.",
209 );
210 }
211​
212 const unsafeCrossing = crossesTrackUnsafely(input);
213 if (unsafeCrossing !== null) return yield* failWith(unsafeCrossing);
214 const targetVersion = input.targetVersion.trim();
215 if (!isExactServiceVersion(targetVersion)) {
216 return yield* failWith(`'${targetVersion}' is not an exact t3 version.`);
217 }
218 if (yield* Ref.getAndSet(inFlight, true)) {
219 return yield* failWith("A server update is already in progress.");
220 }
221​
222 return yield* Effect.gen(function* () {
223 yield* reportProgress("downloading");
224 const paths = yield* ensurePinnedRuntimeInstalled({
225 baseDir: serverConfig.baseDir,
226 version: targetVersion,
227 fs,
228 path,
229 runner,
230 httpClient,
231 platform,
232 arch,
233 releaseBaseUrl,
234 requirePublishedRelease: mirror !== undefined,
235 validate: (runtime) =>
236 runner
237 .run({
238 command: pinnedRuntimeCommand(runtime).command,
239 args: [
240 ...pinnedRuntimeCommand(runtime).args,
241 "__service-preflight",
242 "--database-path",
243 serverConfig.dbPath,
244 "--launcher-protocol",
245 String(launcherProtocol),
246 ],
247 timeout: PREFLIGHT_TIMEOUT,
248 })
249 .pipe(
250 Effect.mapError(
251 (cause) =>
252 new PinnedRuntimeInstallError({
253 step: "running the staged service preflight",
254 cause,
255 }),
256 ),
257 Effect.flatMap(
258 (
259 result,
260 ): Effect.Effect<
261 void,
262 PinnedRuntimeInstallError | PinnedRuntimePreflightBlockedError
263 > => {
264 if (result.code !== 0) {
265 return Effect.fail(
266 new PinnedRuntimeInstallError({
267 step: "running the staged service preflight",
268 exitCode: Number(result.code),
269 stdoutLength: result.stdout.length,
270 stderrLength: result.stderr.length,
271 }),
272 );
273 }
274 let parsed: unknown;
275 try {
276 parsed = JSON.parse(result.stdout.trim());
277 } catch (cause) {
278 return Effect.fail(
279 new PinnedRuntimeInstallError({
280 step: "decoding the staged service preflight",
281 cause,
282 }),
283 );
284 }
285 const preflight = decodeServicePreflightResult(parsed, launcherProtocol);
286 if (preflight === undefined || preflight.version !== targetVersion) {
287 return Effect.fail(
288 new PinnedRuntimeInstallError({
289 step: "verifying the staged service preflight",
290 }),
291 );
292 }
293 return preflight.status === "ready"
294 ? Effect.void
295 : Effect.fail(
296 new PinnedRuntimePreflightBlockedError({
297 version: targetVersion,
298 reason: preflight.reason,
299 }),
300 );
301 },
302 ),
303 ),
304 }).pipe(
305 Effect.mapError((error) => {
306 if (error._tag === "PinnedRuntimePreflightBlockedError") {
307 return failWith(error.reason, error);
308 }
309 if (mirror !== undefined && isUnpublishedRelease(error)) {
310 return failWith(
311 `${mirror.organization}'s update mirror has no t3@${targetVersion} for this machine.`,
312 error,
313 );
314 }
315 const downloadFailure = [
316 error.httpStatus === undefined ? undefined : `HTTP ${error.httpStatus}`,
317 error.downloadHost === undefined ? undefined : `from ${error.downloadHost}`,
318 ]
319 .filter((part) => part !== undefined)
320 .join(" ");
321 return failWith(
322 `Could not prepare t3@${targetVersion} while ${error.step}${downloadFailure ? ` (${downloadFailure})` : ""}.`,
323 error,
324 );
325 }),
326 );
327​
328 if (input.stageOnly === true) {
329 yield* Ref.set(inFlight, false);
330 return { targetVersion, method: "boot-service" as const };
331 }
332 yield* reportProgress("installing");
333 const updateId = yield* Effect.uninterruptible(
334 launcher.requestUpdate({ targetVersion, dbPath: serverConfig.dbPath }).pipe(
335 Effect.mapError((error) =>
336 failWith(
337 error._tag === "ServiceLauncherRejectedError"
338 ? error.reason
339 : "Could not ask the service launcher to activate the prepared update.",
340 error,
341 ),
342 ),
343 // The launcher stops this server next; one from before its serving lock holds nothing
344 // until the new server starts, so this marker is what an SSH launch waits on.
345 Effect.tap(() =>
346 DesktopUpdateMarker.publish(
347 path.join(serverConfig.baseDir, "runtime", DESKTOP_UPDATE_IN_PROGRESS_MARKER_FILE),
348 ).pipe(Effect.provideService(FileSystem.FileSystem, fs), Effect.ignore({ log: true })),
349 ),
350 Effect.tap(() => onHandoffAccepted()),
351 ),
352 );
353​
354 yield* Effect.logInfo("Server update prepared; handing off to the service launcher.", {
355 updateId,
356 targetVersion,
357 runtimePath: paths.entryPath,
358 });
359 return { targetVersion, method: "boot-service" as const, updateId };
360 }).pipe(Effect.onError(() => Ref.set(inFlight, false)));
361 });
362​
363 return ServerSelfUpdate.of({
364 update,
365 commitDesktopUpdate: Effect.fn("ServerSelfUpdate.commitDesktopUpdate")(
366 function (requestId, onHandoffAccepted) {
367 return desktopAppUpdate.commit(requestId, onHandoffAccepted);
368 },
369 ),
370 });
371});
372​
373export const layer = Layer.effect(ServerSelfUpdate, make()).pipe(
374 Layer.provide(ProcessRunner.layer),
375);
376​
377// The update outlives client sockets; progress offers to a closed queue are ignored.
378export const updateProgressStream = (
379 selfUpdate: ServerSelfUpdate["Service"],
380 input: ServerSelfUpdateInput,
381) =>
382 Stream.callback<ServerSelfUpdateProgressEvent, ServerSelfUpdateError>((queue) => {
383 const offer = (event: ServerSelfUpdateProgressEvent) =>
384 Queue.offer(queue, event).pipe(Effect.ignore);
385​
386 return selfUpdate
387 .update(input, (stage) => offer({ type: "progress", stage }))
388 .pipe(
389 Effect.flatMap((result) => offer({ type: "complete", result })),
390 Effect.catchTags({
391 ServerSelfUpdateError: (error) => Queue.fail(queue, error).pipe(Effect.ignore),
392 }),
393 Effect.andThen(Queue.end(queue).pipe(Effect.ignore)),
394 Effect.forkDetach,
395 );
396 });