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

selfUpdate.ts

330 lines11.8 KB

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