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

selfUpdate.ts

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