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

selfUpdate.ts

367 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: (requestId) =>
145 Effect.gen(function* () {
146 const shouldContinue = yield* Ref.modify(desktopContinuationTokens, (tokens) => [
147 HashSet.has(tokens, requestId),
148 HashSet.remove(tokens, requestId),
149 ]);
150 let handoffAccepted = false;
151 let continuationThreadIds: ReadonlyArray<ThreadId> = [];
152 return yield* clearOnError(
153 Effect.gen(function* () {
154 continuationThreadIds = shouldContinue ? yield* input.prepare : [];
155 return yield* input.selfUpdate.commitDesktopUpdate(requestId, () =>
156 Effect.sync(() => {
157 handoffAccepted = true;
158 }),
159 );
160 }),
161 () => continuationThreadIds,
162 () => handoffAccepted,
163 ).pipe(
164 Effect.catchCause((cause) =>
165 (shouldContinue && !handoffAccepted
166 ? Ref.update(desktopContinuationTokens, HashSet.add(requestId))
167 : Effect.void
168 ).pipe(Effect.andThen(Effect.failCause(cause))),
169 ),
170 );
171 }),
172 });
173});
174​
175export const make = Effect.fn("cloud.server_self_update.make")(function* () {
176 const serverConfig = yield* ServerConfig.ServerConfig;
177 const desktopAppUpdate = yield* DesktopAppUpdate.DesktopAppUpdate;
178 const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
179 const runner = yield* ProcessRunner.ProcessRunner;
180 const fs = yield* FileSystem.FileSystem;
181 const path = yield* Path.Path;
182 const platform = yield* HostProcess.Platform;
183 const arch = yield* HostProcess.Architecture;
184 const httpClient = yield* HttpClient.HttpClient;
185 const releaseBaseUrl = Option.getOrUndefined(
186 yield* Config.String(CLI_RELEASE_BASE_URL_ENV).pipe(Config.option),
187 );
188 const inFlight = yield* Ref.make(false);
189​
190 const capability: ServerSelfUpdateCapability | null =
191 serverConfig.mode === "desktop" ? "desktop-managed" : launcher.managed ? "boot-service" : null;
192 const failWith = (reason: string, cause?: unknown) =>
193 cause === undefined
194 ? new ServerSelfUpdateError({ reason })
195 : new ServerSelfUpdateError({ reason, cause });
196​
197 const update: ServerSelfUpdate["Service"]["update"] = Effect.fn(
198 "cloud.server_self_update.update",
199 )(function* (input, reportProgress = () => Effect.void, onHandoffAccepted = () => Effect.void) {
200 if (capability === "desktop-managed") {
201 if (desktopAppUpdate.available) {
202 return yield* desktopAppUpdate.run(reportProgress);
203 }
204 return yield* failWith(
205 "This server is managed by the T3 Code desktop app on its machine; update the desktop app to update it.",
206 );
207 }
208 if (capability === null) {
209 return yield* failWith(
210 "Remote updates require the T3 Code background service. Run `t3 service install` on the server machine.",
211 );
212 }
213​
214 const targetVersion = input.targetVersion.trim();
215 if (!isExactServiceVersion(targetVersion)) {
216 return yield* failWith(`'${targetVersion}' is not an exact t3 version.`);
217 }
218 if (yield* Ref.getAndSet(inFlight, true)) {
219 return yield* failWith("A server update is already in progress.");
220 }
221​
222 return yield* Effect.gen(function* () {
223 yield* reportProgress("downloading");
224 const paths = yield* ensurePinnedRuntimeInstalled({
225 baseDir: serverConfig.baseDir,
226 version: targetVersion,
227 fs,
228 path,
229 runner,
230 httpClient,
231 platform,
232 arch,
233 releaseBaseUrl,
234 validate: (runtime) =>
235 runner
236 .run({
237 command: pinnedRuntimeCommand(runtime).command,
238 args: [
239 ...pinnedRuntimeCommand(runtime).args,
240 "__service-preflight",
241 "--database-path",
242 serverConfig.dbPath,
243 "--launcher-protocol",
244 String(SERVICE_LAUNCHER_PROTOCOL),
245 ],
246 timeout: PREFLIGHT_TIMEOUT,
247 })
248 .pipe(
249 Effect.mapError(
250 (cause) =>
251 new PinnedRuntimeInstallError({
252 step: "running the staged service preflight",
253 cause,
254 }),
255 ),
256 Effect.flatMap(
257 (
258 result,
259 ): Effect.Effect<
260 void,
261 PinnedRuntimeInstallError | PinnedRuntimePreflightBlockedError
262 > => {
263 if (result.code !== 0) {
264 return Effect.fail(
265 new PinnedRuntimeInstallError({
266 step: "running the staged service preflight",
267 exitCode: Number(result.code),
268 stdoutLength: result.stdout.length,
269 stderrLength: result.stderr.length,
270 }),
271 );
272 }
273 let parsed: unknown;
274 try {
275 parsed = JSON.parse(result.stdout.trim());
276 } catch (cause) {
277 return Effect.fail(
278 new PinnedRuntimeInstallError({
279 step: "decoding the staged service preflight",
280 cause,
281 }),
282 );
283 }
284 const preflight = decodeServicePreflightResult(parsed);
285 if (preflight === undefined || preflight.version !== targetVersion) {
286 return Effect.fail(
287 new PinnedRuntimeInstallError({
288 step: "verifying the staged service preflight",
289 }),
290 );
291 }
292 return preflight.status === "ready"
293 ? Effect.void
294 : Effect.fail(
295 new PinnedRuntimePreflightBlockedError({
296 version: targetVersion,
297 reason: preflight.reason,
298 }),
299 );
300 },
301 ),
302 ),
303 }).pipe(
304 Effect.mapError((error) =>
305 error._tag === "PinnedRuntimePreflightBlockedError"
306 ? failWith(error.reason, error)
307 : failWith(`Could not prepare t3@${targetVersion}.`, error),
308 ),
309 );
310​
311 yield* reportProgress("installing");
312 const updateId = yield* Effect.uninterruptible(
313 launcher.requestUpdate({ targetVersion, dbPath: serverConfig.dbPath }).pipe(
314 Effect.mapError((error) =>
315 failWith(
316 error._tag === "ServiceLauncherRejectedError"
317 ? error.reason
318 : "Could not ask the service launcher to activate the prepared update.",
319 error,
320 ),
321 ),
322 Effect.tap(() => onHandoffAccepted()),
323 ),
324 );
325​
326 yield* Effect.logInfo("Server update prepared; handing off to the service launcher.", {
327 updateId,
328 targetVersion,
329 runtimePath: paths.entryPath,
330 });
331 return { targetVersion, method: "boot-service" as const, updateId };
332 }).pipe(Effect.onError(() => Ref.set(inFlight, false)));
333 });
334​
335 return ServerSelfUpdate.of({
336 update,
337 commitDesktopUpdate: (requestId, onHandoffAccepted) =>
338 desktopAppUpdate.commit(requestId, onHandoffAccepted),
339 });
340});
341​
342export const layer = Layer.effect(ServerSelfUpdate, make()).pipe(
343 Layer.provide(ProcessRunner.layer),
344);
345​
346// The RPC stream used to own this fiber, so a dropped client socket interrupted
347// the download. Offers after the queue shuts down are ignored; the update
348// still finishes, and the in-flight guard stays as it was.
349export const updateProgressStream = (
350 selfUpdate: ServerSelfUpdate["Service"],
351 input: ServerSelfUpdateInput,
352) =>
353 Stream.callback<ServerSelfUpdateProgressEvent, ServerSelfUpdateError>((queue) => {
354 const offer = (event: ServerSelfUpdateProgressEvent) =>
355 Queue.offer(queue, event).pipe(Effect.ignore);
356​
357 return selfUpdate
358 .update(input, (stage) => offer({ type: "progress", stage }))
359 .pipe(
360 Effect.flatMap((result) => offer({ type: "complete", result })),
361 Effect.catchTags({
362 ServerSelfUpdateError: (error) => Queue.fail(queue, error).pipe(Effect.ignore),
363 }),
364 Effect.andThen(Queue.end(queue).pipe(Effect.ignore)),
365 Effect.forkDetach,
366 );
367 });