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

selfUpdate.ts

366 lines13.2 KB

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