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

selfUpdate.ts

341 lines12.2 KB

1import {
2 ServerSelfUpdateError,
3 type ServerSelfUpdateCapability,
4 type ServerSelfUpdateInput,
5 type ServerSelfUpdateProgressStage,
6 type ServerSelfUpdateResult,
7 type ThreadId,
8} from "@t3tools/contracts";
9import * as HostProcess from "@t3tools/shared/HostProcess";
10import * as Cause from "effect/Cause";
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 HashSet from "effect/HashSet";
16import * as Option from "effect/Option";
17import * as Ref from "effect/Ref";
18import * as FileSystem from "effect/FileSystem";
19import * as Layer from "effect/Layer";
20import * as Path from "effect/Path";
21import { HttpClient } from "effect/http";
22​
23import { CLI_RELEASE_BASE_URL_ENV } from "@t3tools/shared/cliRelease";
24​
25import * as ServerConfig from "../config.ts";
26import * as DesktopAppUpdate from "../desktopUpdate/DesktopAppUpdate.ts";
27import * as ProcessRunner from "../processRunner.ts";
28import {
29 ensurePinnedRuntimeInstalled,
30 pinnedRuntimeCommand,
31 PinnedRuntimeInstallError,
32 PinnedRuntimePreflightBlockedError,
33} from "./pinnedRuntime.ts";
34import { decodeServicePreflightResult } from "./servicePreflight.ts";
35import * as ServiceLauncherClient from "./serviceLauncherClient.ts";
36import { isExactServiceVersion, SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts";
37​
38const PREFLIGHT_TIMEOUT = Duration.seconds(30);
39​
40export function resolveServerSelfUpdateCapability(input: {
41 readonly desktopManaged: boolean;
42 readonly launcherManaged: boolean;
43}): ServerSelfUpdateCapability | null {
44 if (input.desktopManaged) return "desktop-managed" as const;
45 return input.launcherManaged ? ("boot-service" as const) : null;
47​
48export class ServerSelfUpdate extends Context.Service<
49 ServerSelfUpdate,
50 {
51 readonly update: (
52 input: ServerSelfUpdateInput,
53 reportProgress?: (
54 stage: ServerSelfUpdateProgressStage,
55 ) => Effect.Effect<void, ServerSelfUpdateError>,
56 onHandoffAccepted?: () => Effect.Effect<void>,
57 ) => Effect.Effect<ServerSelfUpdateResult, ServerSelfUpdateError>;
58 readonly commitDesktopUpdate: (
59 requestId: string,
60 onHandoffAccepted?: () => Effect.Effect<void>,
61 ) => Effect.Effect<never, ServerSelfUpdateError>;
62 }
63>()("t3/cloud/selfUpdate/ServerSelfUpdate") {}
64​
65export const withRunningThreadContinuation = Effect.fn(
66 "cloud.server_self_update.withRunningThreadContinuation",
67)(function* (input: {
68 readonly mode: ServerConfig.RuntimeMode;
69 readonly selfUpdate: ServerSelfUpdate["Service"];
70 readonly prepare: Effect.Effect<ReadonlyArray<ThreadId>, ServerSelfUpdateError>;
71 readonly clear: (
72 threadIds: ReadonlyArray<ThreadId>,
73 ) => Effect.Effect<void, ServerSelfUpdateError>;
74}) {
75 const desktopContinuationTokens = yield* Ref.make(HashSet.empty<string>());
76 const clearOnError = <A>(
77 effect: Effect.Effect<A, ServerSelfUpdateError>,
78 threadIds: () => ReadonlyArray<ThreadId>,
79 handoffAccepted: () => boolean,
80 ): Effect.Effect<A, ServerSelfUpdateError> =>
81 effect.pipe(
82 Effect.catchCause((cause) =>
83 (handoffAccepted() && Cause.hasInterruptsOnly(cause)
84 ? Effect.void
85 : input.clear(threadIds())
86 ).pipe(Effect.andThen(Effect.failCause(cause))),
87 ),
88 );
89​
90 const update: ServerSelfUpdate["Service"]["update"] = (
91 request,
92 reportProgress = () => Effect.void,
93 ) => {
94 let prepared = false;
95 let handoffAccepted = false;
96 let continuationThreadIds: ReadonlyArray<ThreadId> = [];
97 return clearOnError(
98 input.selfUpdate
99 .update(
100 request,
101 (stage) =>
102 (request.continueRunningThreads === true &&
103 input.mode !== "desktop" &&
104 stage === "installing" &&
105 !prepared
106 ? input.prepare.pipe(
107 Effect.tap((threadIds) =>
108 Effect.sync(() => {
109 prepared = true;
110 continuationThreadIds = threadIds;
111 }),
112 ),
113 Effect.asVoid,
114 )
115 : Effect.void
116 ).pipe(Effect.andThen(reportProgress(stage))),
117 () =>
118 Effect.sync(() => {
119 handoffAccepted = true;
120 }),
121 )
122 .pipe(
123 Effect.tap((result) => {
124 if (
125 result.method === "desktop-app" &&
126 result.desktopUpdateToken !== undefined &&
127 request.continueRunningThreads === true
128 ) {
129 return Ref.update(desktopContinuationTokens, HashSet.add(result.desktopUpdateToken));
130 }
131 return Effect.void;
132 }),
133 ),
134 () => continuationThreadIds,
135 () => handoffAccepted,
136 );
137 };
138​
139 return ServerSelfUpdate.of({
140 update,
141 commitDesktopUpdate: (requestId) =>
142 Effect.gen(function* () {
143 const shouldContinue = yield* Ref.modify(desktopContinuationTokens, (tokens) => [
144 HashSet.has(tokens, requestId),
145 HashSet.remove(tokens, requestId),
146 ]);
147 let handoffAccepted = false;
148 let continuationThreadIds: ReadonlyArray<ThreadId> = [];
149 return yield* clearOnError(
150 Effect.gen(function* () {
151 continuationThreadIds = shouldContinue ? yield* input.prepare : [];
152 return yield* input.selfUpdate.commitDesktopUpdate(requestId, () =>
153 Effect.sync(() => {
154 handoffAccepted = true;
155 }),
156 );
157 }),
158 () => continuationThreadIds,
159 () => handoffAccepted,
160 ).pipe(
161 Effect.catchCause((cause) =>
162 (shouldContinue && !handoffAccepted
163 ? Ref.update(desktopContinuationTokens, HashSet.add(requestId))
164 : Effect.void
165 ).pipe(Effect.andThen(Effect.failCause(cause))),
166 ),
167 );
168 }),
169 });
170});
171​
172export const make = Effect.fn("cloud.server_self_update.make")(function* () {
173 const serverConfig = yield* ServerConfig.ServerConfig;
174 const desktopAppUpdate = yield* DesktopAppUpdate.DesktopAppUpdate;
175 const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
176 const runner = yield* ProcessRunner.ProcessRunner;
177 const fs = yield* FileSystem.FileSystem;
178 const path = yield* Path.Path;
179 const platform = yield* HostProcess.Platform;
180 const arch = yield* HostProcess.Architecture;
181 const httpClient = yield* HttpClient.HttpClient;
182 const releaseBaseUrl = Option.getOrUndefined(
183 yield* Config.String(CLI_RELEASE_BASE_URL_ENV).pipe(Config.option),
184 );
185 const inFlight = yield* Ref.make(false);
186​
187 const capability: ServerSelfUpdateCapability | null =
188 serverConfig.mode === "desktop" ? "desktop-managed" : launcher.managed ? "boot-service" : null;
189 const failWith = (reason: string, cause?: unknown) =>
190 cause === undefined
191 ? new ServerSelfUpdateError({ reason })
192 : new ServerSelfUpdateError({ reason, cause });
193​
194 const update: ServerSelfUpdate["Service"]["update"] = Effect.fn(
195 "cloud.server_self_update.update",
196 )(function* (input, reportProgress = () => Effect.void, onHandoffAccepted = () => Effect.void) {
197 if (capability === "desktop-managed") {
198 if (desktopAppUpdate.available) {
199 return yield* desktopAppUpdate.run(reportProgress);
200 }
201 return yield* failWith(
202 "This server is managed by the T3 Code desktop app on its machine; update the desktop app to update it.",
203 );
204 }
205 if (capability === null) {
206 return yield* failWith(
207 "Remote updates require the T3 Code background service. Run `t3 service install` on the server machine.",
208 );
209 }
210​
211 const targetVersion = input.targetVersion.trim();
212 if (!isExactServiceVersion(targetVersion)) {
213 return yield* failWith(`'${targetVersion}' is not an exact t3 version.`);
214 }
215 if (yield* Ref.getAndSet(inFlight, true)) {
216 return yield* failWith("A server update is already in progress.");
217 }
218​
219 return yield* Effect.gen(function* () {
220 yield* reportProgress("downloading");
221 const paths = yield* ensurePinnedRuntimeInstalled({
222 baseDir: serverConfig.baseDir,
223 version: targetVersion,
224 fs,
225 path,
226 runner,
227 httpClient,
228 platform,
229 arch,
230 releaseBaseUrl,
231 validate: (runtime) =>
232 runner
233 .run({
234 command: pinnedRuntimeCommand(runtime).command,
235 args: [
236 ...pinnedRuntimeCommand(runtime).args,
237 "__service-preflight",
238 "--database-path",
239 serverConfig.dbPath,
240 "--launcher-protocol",
241 String(SERVICE_LAUNCHER_PROTOCOL),
242 ],
243 timeout: PREFLIGHT_TIMEOUT,
244 })
245 .pipe(
246 Effect.mapError(
247 (cause) =>
248 new PinnedRuntimeInstallError({
249 step: "running the staged service preflight",
250 cause,
251 }),
252 ),
253 Effect.flatMap(
254 (
255 result,
256 ): Effect.Effect<
257 void,
258 PinnedRuntimeInstallError | PinnedRuntimePreflightBlockedError
259 > => {
260 if (result.code !== 0) {
261 return Effect.fail(
262 new PinnedRuntimeInstallError({
263 step: "running the staged service preflight",
264 exitCode: Number(result.code),
265 stdoutLength: result.stdout.length,
266 stderrLength: result.stderr.length,
267 }),
268 );
269 }
270 let parsed: unknown;
271 try {
272 parsed = JSON.parse(result.stdout.trim());
273 } catch (cause) {
274 return Effect.fail(
275 new PinnedRuntimeInstallError({
276 step: "decoding the staged service preflight",
277 cause,
278 }),
279 );
280 }
281 const preflight = decodeServicePreflightResult(parsed);
282 if (preflight === undefined || preflight.version !== targetVersion) {
283 return Effect.fail(
284 new PinnedRuntimeInstallError({
285 step: "verifying the staged service preflight",
286 }),
287 );
288 }
289 return preflight.status === "ready"
290 ? Effect.void
291 : Effect.fail(
292 new PinnedRuntimePreflightBlockedError({
293 version: targetVersion,
294 reason: preflight.reason,
295 }),
296 );
297 },
298 ),
299 ),
300 }).pipe(
301 Effect.mapError((error) =>
302 error._tag === "PinnedRuntimePreflightBlockedError"
303 ? failWith(error.reason, error)
304 : failWith(`Could not prepare t3@${targetVersion}.`, error),
305 ),
306 );
307​
308 yield* reportProgress("installing");
309 const updateId = yield* Effect.uninterruptible(
310 launcher.requestUpdate({ targetVersion, dbPath: serverConfig.dbPath }).pipe(
311 Effect.mapError((error) =>
312 failWith(
313 error._tag === "ServiceLauncherRejectedError"
314 ? error.reason
315 : "Could not ask the service launcher to activate the prepared update.",
316 error,
317 ),
318 ),
319 Effect.tap(() => onHandoffAccepted()),
320 ),
321 );
322​
323 yield* Effect.logInfo("Server update prepared; handing off to the service launcher.", {
324 updateId,
325 targetVersion,
326 runtimePath: paths.entryPath,
327 });
328 return { targetVersion, method: "boot-service" as const, updateId };
329 }).pipe(Effect.onError(() => Ref.set(inFlight, false)));
330 });
331​
332 return ServerSelfUpdate.of({
333 update,
334 commitDesktopUpdate: (requestId, onHandoffAccepted) =>
335 desktopAppUpdate.commit(requestId, onHandoffAccepted),
336 });
337});
338​
339export const layer = Layer.effect(ServerSelfUpdate, make()).pipe(
340 Layer.provide(ProcessRunner.layer),
341);