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

selfUpdate.ts

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