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

selfUpdate.ts

213 lines7.9 KB

1import {
2 ServerSelfUpdateError,
3 type ServerSelfUpdateCapability,
4 type ServerSelfUpdateInput,
5 type ServerSelfUpdateProgressStage,
6 type ServerSelfUpdateResult,
7} from "@t3tools/contracts";
8import { HostProcessExecutablePath } from "@t3tools/shared/hostProcess";
9import * as Context from "effect/Context";
10import * as Duration from "effect/Duration";
11import * as Effect from "effect/Effect";
12import * as FileSystem from "effect/FileSystem";
13import * as Layer from "effect/Layer";
14import * as Path from "effect/Path";
15import * as Ref from "effect/Ref";
16​
17import * as ServerConfig from "../config.ts";
18import * as DesktopAppUpdate from "../desktopUpdate/DesktopAppUpdate.ts";
19import * as ProcessRunner from "../processRunner.ts";
20import {
21 ensurePinnedRuntimeInstalled,
22 PinnedRuntimeInstallError,
23 PinnedRuntimePreflightBlockedError,
24} from "./pinnedRuntime.ts";
25import { decodeServicePreflightResult } from "./servicePreflight.ts";
26import * as ServiceLauncherClient from "./serviceLauncherClient.ts";
27import { isExactServiceVersion, SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts";
28​
29const PREFLIGHT_TIMEOUT = Duration.seconds(30);
30​
31export function resolveServerSelfUpdateCapability(input: {
32 readonly desktopManaged: boolean;
33 readonly launcherManaged: boolean;
34}): ServerSelfUpdateCapability | null {
35 if (input.desktopManaged) return "desktop-managed" as const;
36 return input.launcherManaged ? ("boot-service" as const) : null;
38​
39export class ServerSelfUpdate extends Context.Service<
40 ServerSelfUpdate,
41 {
42 readonly update: (
43 input: ServerSelfUpdateInput,
44 reportProgress?: (stage: ServerSelfUpdateProgressStage) => Effect.Effect<void>,
45 ) => Effect.Effect<ServerSelfUpdateResult, ServerSelfUpdateError>;
46 readonly commitDesktopUpdate: (
47 requestId: string,
48 ) => Effect.Effect<never, ServerSelfUpdateError>;
49 }
50>()("t3/cloud/selfUpdate/ServerSelfUpdate") {}
51​
52export const make = Effect.fn("cloud.server_self_update.make")(function* () {
53 const serverConfig = yield* ServerConfig.ServerConfig;
54 const desktopAppUpdate = yield* DesktopAppUpdate.DesktopAppUpdate;
55 const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
56 const runner = yield* ProcessRunner.ProcessRunner;
57 const fs = yield* FileSystem.FileSystem;
58 const path = yield* Path.Path;
59 const execPath = yield* HostProcessExecutablePath;
60 const inFlight = yield* Ref.make(false);
61​
62 const capability: ServerSelfUpdateCapability | null =
63 serverConfig.mode === "desktop" ? "desktop-managed" : launcher.managed ? "boot-service" : null;
64 const failWith = (reason: string, cause?: unknown) =>
65 cause === undefined
66 ? new ServerSelfUpdateError({ reason })
67 : new ServerSelfUpdateError({ reason, cause });
68​
69 const update: ServerSelfUpdate["Service"]["update"] = Effect.fn(
70 "cloud.server_self_update.update",
71 )(function* (input, reportProgress = () => Effect.void) {
72 if (capability === "desktop-managed") {
73 // input.targetVersion is meaningless here: the desktop app's own
74 // update feed decides what it downloads, and the result carries what
75 // it actually got.
76 if (desktopAppUpdate.available) {
77 return yield* desktopAppUpdate.run(reportProgress);
78 }
79 return yield* failWith(
80 "This server is managed by the T3 Code desktop app on its machine; update the desktop app to update it.",
81 );
82 }
83 if (capability === null) {
84 return yield* failWith(
85 "Remote updates require the T3 Code background service. Run `t3 service install` on the server machine.",
86 );
87 }
88​
89 const targetVersion = input.targetVersion.trim();
90 if (!isExactServiceVersion(targetVersion)) {
91 return yield* failWith(`'${targetVersion}' is not an exact t3 version.`);
92 }
93 if (yield* Ref.getAndSet(inFlight, true)) {
94 return yield* failWith("A server update is already in progress.");
95 }
96​
97 return yield* Effect.gen(function* () {
98 yield* reportProgress("downloading");
99 const paths = yield* ensurePinnedRuntimeInstalled({
100 baseDir: serverConfig.baseDir,
101 version: targetVersion,
102 fs,
103 path,
104 runner,
105 validate: (runtime) =>
106 runner
107 .run({
108 command: execPath,
109 args: [
110 runtime.entryPath,
111 "__service-preflight",
112 "--database-path",
113 serverConfig.dbPath,
114 "--launcher-protocol",
115 String(SERVICE_LAUNCHER_PROTOCOL),
116 ],
117 timeout: PREFLIGHT_TIMEOUT,
118 })
119 .pipe(
120 Effect.mapError(
121 (cause) =>
122 new PinnedRuntimeInstallError({
123 step: "running the staged service preflight",
124 cause,
125 }),
126 ),
127 Effect.flatMap(
128 (
129 result,
130 ): Effect.Effect<
131 void,
132 PinnedRuntimeInstallError | PinnedRuntimePreflightBlockedError
133 > => {
134 if (result.code !== 0) {
135 return Effect.fail(
136 new PinnedRuntimeInstallError({
137 step: "running the staged service preflight",
138 exitCode: Number(result.code),
139 stdoutLength: result.stdout.length,
140 stderrLength: result.stderr.length,
141 }),
142 );
143 }
144 let parsed: unknown;
145 try {
146 parsed = JSON.parse(result.stdout.trim());
147 } catch (cause) {
148 return Effect.fail(
149 new PinnedRuntimeInstallError({
150 step: "decoding the staged service preflight",
151 cause,
152 }),
153 );
154 }
155 const preflight = decodeServicePreflightResult(parsed);
156 if (preflight === undefined || preflight.version !== targetVersion) {
157 return Effect.fail(
158 new PinnedRuntimeInstallError({
159 step: "verifying the staged service preflight",
160 }),
161 );
162 }
163 return preflight.status === "ready"
164 ? Effect.void
165 : Effect.fail(
166 new PinnedRuntimePreflightBlockedError({
167 version: targetVersion,
168 reason: preflight.reason,
169 }),
170 );
171 },
172 ),
173 ),
174 }).pipe(
175 Effect.mapError((error) =>
176 error._tag === "PinnedRuntimePreflightBlockedError"
177 ? failWith(error.reason, error)
178 : failWith(`Could not prepare t3@${targetVersion}.`, error),
179 ),
180 );
181​
182 yield* reportProgress("installing");
183 const updateId = yield* launcher
184 .requestUpdate({ targetVersion, dbPath: serverConfig.dbPath })
185 .pipe(
186 Effect.mapError((error) =>
187 failWith(
188 error._tag === "ServiceLauncherRejectedError"
189 ? error.reason
190 : "Could not ask the service launcher to activate the prepared update.",
191 error,
192 ),
193 ),
194 );
195​
196 yield* Effect.logInfo("Server update prepared; handing off to the service launcher.", {
197 updateId,
198 targetVersion,
199 runtimePath: paths.entryPath,
200 });
201 return { targetVersion, method: "boot-service" as const, updateId };
202 }).pipe(Effect.onError(() => Ref.set(inFlight, false)));
203 });
204​
205 return ServerSelfUpdate.of({
206 update,
207 commitDesktopUpdate: (requestId) => desktopAppUpdate.commit(requestId),
208 });
209});
210​
211export const layer = Layer.effect(ServerSelfUpdate, make()).pipe(
212 Layer.provide(ProcessRunner.layer),
213);