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