Open History to see the last commit
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 packageJson from "../../package.json" with { type: "json" };
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 pinnedRuntimePaths,
37 PinnedRuntimePreflightBlockedError,
38 prunePinnedRuntimes,
39} from "./pinnedRuntime.ts";
40import { decodeServicePreflightResult } from "./servicePreflight.ts";
41import * as ServiceLauncherClient from "./serviceLauncherClient.ts";
42import { isExactServiceVersion, SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts";
43
44const PREFLIGHT_TIMEOUT = Duration.seconds(30);
45
46export function resolveServerSelfUpdateCapability(input: {
47 readonly desktopManaged: boolean;
48 readonly launcherManaged: boolean;
49}): ServerSelfUpdateCapability | null {
50 if (input.desktopManaged) return "desktop-managed" as const;
51 return input.launcherManaged ? ("boot-service" as const) : null;
52}
53
54export class ServerSelfUpdate extends Context.Service<
55 ServerSelfUpdate,
56 {
57 readonly update: (
58 input: ServerSelfUpdateInput,
59 reportProgress?: (
60 stage: ServerSelfUpdateProgressStage,
61 ) => Effect.Effect<void, ServerSelfUpdateError>,
62 onHandoffAccepted?: () => Effect.Effect<void>,
63 ) => Effect.Effect<ServerSelfUpdateResult, ServerSelfUpdateError>;
64 readonly commitDesktopUpdate: (
65 requestId: string,
66 onHandoffAccepted?: () => Effect.Effect<void>,
67 ) => Effect.Effect<never, ServerSelfUpdateError>;
68 }
69>()("t3/cloud/selfUpdate/ServerSelfUpdate") {}
70
71export const withRunningThreadContinuation = Effect.fn(
72 "cloud.server_self_update.withRunningThreadContinuation",
73)(function* (input: {
74 readonly mode: ServerConfig.RuntimeMode;
75 readonly selfUpdate: ServerSelfUpdate["Service"];
76 readonly prepare: Effect.Effect<ReadonlyArray<ThreadId>, ServerSelfUpdateError>;
77 readonly clear: (
78 threadIds: ReadonlyArray<ThreadId>,
79 ) => Effect.Effect<void, ServerSelfUpdateError>;
80}) {
81 const desktopContinuationTokens = yield* Ref.make(HashSet.empty<string>());
82 const clearOnError = <A>(
83 effect: Effect.Effect<A, ServerSelfUpdateError>,
84 threadIds: () => ReadonlyArray<ThreadId>,
85 handoffAccepted: () => boolean,
86 ): Effect.Effect<A, ServerSelfUpdateError> =>
87 effect.pipe(
88 Effect.catchCause((cause) =>
89 (handoffAccepted() && Cause.hasInterruptsOnly(cause)
90 ? Effect.void
91 : input.clear(threadIds())
92 ).pipe(Effect.andThen(Effect.failCause(cause))),
93 ),
94 );
95
96 const update: ServerSelfUpdate["Service"]["update"] = (
97 request,
98 reportProgress = () => Effect.void,
99 ) => {
100 let prepared = false;
101 let handoffAccepted = false;
102 let continuationThreadIds: ReadonlyArray<ThreadId> = [];
103 return clearOnError(
104 input.selfUpdate
105 .update(
106 request,
107 (stage) =>
108 (request.continueRunningThreads === true &&
109 input.mode !== "desktop" &&
110 stage === "installing" &&
111 !prepared
112 ? input.prepare.pipe(
113 Effect.tap((threadIds) =>
114 Effect.sync(() => {
115 prepared = true;
116 continuationThreadIds = threadIds;
117 }),
118 ),
119 Effect.asVoid,
120 )
121 : Effect.void
122 ).pipe(Effect.andThen(reportProgress(stage))),
123 () =>
124 Effect.sync(() => {
125 handoffAccepted = true;
126 }),
127 )
128 .pipe(
129 Effect.tap((result) => {
130 if (
131 result.method === "desktop-app" &&
132 result.desktopUpdateToken !== undefined &&
133 request.continueRunningThreads === true
134 ) {
135 return Ref.update(desktopContinuationTokens, HashSet.add(result.desktopUpdateToken));
136 }
137 return Effect.void;
138 }),
139 ),
140 () => continuationThreadIds,
141 () => handoffAccepted,
142 );
143 };
144
145 return ServerSelfUpdate.of({
146 update,
147 commitDesktopUpdate: Effect.fn("selfUpdate.commitDesktopUpdate")(function* (requestId) {
148 const shouldContinue = yield* Ref.modify(desktopContinuationTokens, (tokens) => [
149 HashSet.has(tokens, requestId),
150 HashSet.remove(tokens, requestId),
151 ]);
152 let handoffAccepted = false;
153 let continuationThreadIds: ReadonlyArray<ThreadId> = [];
154 return yield* clearOnError(
155 Effect.gen(function* () {
156 continuationThreadIds = shouldContinue ? yield* input.prepare : [];
157 return yield* input.selfUpdate.commitDesktopUpdate(requestId, () =>
158 Effect.sync(() => {
159 handoffAccepted = true;
160 }),
161 );
162 }),
163 () => continuationThreadIds,
164 () => handoffAccepted,
165 ).pipe(
166 Effect.catchCause((cause) =>
167 (shouldContinue && !handoffAccepted
168 ? Ref.update(desktopContinuationTokens, HashSet.add(requestId))
169 : Effect.void
170 ).pipe(Effect.andThen(Effect.failCause(cause))),
171 ),
172 );
173 }),
174 });
175});
176
177/**
178 * A server starting from the runtime its launcher settled on means runtimes left by earlier
179 * updates can go. The boot service says so through its IPC context. The SSH launcher and the
180 * install script's `t3` start this home's pinned runtime directly, without one.
181 */
182export const pruneRuntimesOnStart = Effect.fn("cloud.server_self_update.prune_on_start")(
183 function* (input: { readonly baseDir: string; readonly managed: boolean }) {
184 const fs = yield* FileSystem.FileSystem;
185 const path = yield* Path.Path;
186 const platform = yield* HostProcess.Platform;
187 const executablePath = yield* HostProcess.ExecutablePath;
188 const { entryPath } = pinnedRuntimePaths(path, input.baseDir, packageJson.version, platform);
189 // The executable path is resolved, so it names the real path of a symlinked T3 home.
190 const realEntryPath = yield* fs.realPath(entryPath).pipe(Effect.orElseSucceed(() => entryPath));
191 if (!input.managed && executablePath !== entryPath && executablePath !== realEntryPath) {
192 return [];
193 }
194 const removed = yield* prunePinnedRuntimes({
195 baseDir: input.baseDir,
196 keep: [packageJson.version],
197 });
198 if (removed.length > 0) {
199 yield* Effect.logInfo("Removed unused t3 runtimes.", { versions: removed });
200 }
201 return removed;
202 },
203);
204
205export const make = Effect.fn("cloud.server_self_update.make")(function* () {
206 const serverConfig = yield* ServerConfig.ServerConfig;
207 const desktopAppUpdate = yield* DesktopAppUpdate.DesktopAppUpdate;
208 const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
209 const runner = yield* ProcessRunner.ProcessRunner;
210 const fs = yield* FileSystem.FileSystem;
211 const path = yield* Path.Path;
212 const platform = yield* HostProcess.Platform;
213 const arch = yield* HostProcess.Architecture;
214 const httpClient = yield* HttpClient.HttpClient;
215 const releaseBaseUrl = Option.getOrUndefined(
216 yield* Config.String(CLI_RELEASE_BASE_URL_ENV).pipe(Config.option),
217 );
218 const inFlight = yield* Ref.make(false);
219
220 yield* pruneRuntimesOnStart({ baseDir: serverConfig.baseDir, managed: launcher.managed }).pipe(
221 Effect.forkScoped,
222 );
223
224 const capability: ServerSelfUpdateCapability | null =
225 serverConfig.mode === "desktop" ? "desktop-managed" : launcher.managed ? "boot-service" : null;
226 const failWith = (reason: string, cause?: unknown) =>
227 cause === undefined
228 ? new ServerSelfUpdateError({ reason })
229 : new ServerSelfUpdateError({ reason, cause });
230
231 const update: ServerSelfUpdate["Service"]["update"] = Effect.fn(
232 "cloud.server_self_update.update",
233 )(function* (input, reportProgress = () => Effect.void, onHandoffAccepted = () => Effect.void) {
234 if (capability === "desktop-managed") {
235 if (desktopAppUpdate.available) {
236 return yield* desktopAppUpdate.run(reportProgress);
237 }
238 return yield* failWith(
239 "This server is managed by the T3 Code desktop app on its machine; update the desktop app to update it.",
240 );
241 }
242 if (capability === null) {
243 return yield* failWith(
244 "Remote updates require the T3 Code background service. Run `t3 service install` on the server machine.",
245 );
246 }
247
248 const targetVersion = input.targetVersion.trim();
249 if (!isExactServiceVersion(targetVersion)) {
250 return yield* failWith(`'${targetVersion}' is not an exact t3 version.`);
251 }
252 if (yield* Ref.getAndSet(inFlight, true)) {
253 return yield* failWith("A server update is already in progress.");
254 }
255
256 return yield* Effect.gen(function* () {
257 yield* reportProgress("downloading");
258 const paths = yield* ensurePinnedRuntimeInstalled({
259 baseDir: serverConfig.baseDir,
260 version: targetVersion,
261 fs,
262 path,
263 runner,
264 httpClient,
265 platform,
266 arch,
267 releaseBaseUrl,
268 validate: (runtime) =>
269 runner
270 .run({
271 command: pinnedRuntimeCommand(runtime).command,
272 args: [
273 ...pinnedRuntimeCommand(runtime).args,
274 "__service-preflight",
275 "--database-path",
276 serverConfig.dbPath,
277 "--launcher-protocol",
278 String(SERVICE_LAUNCHER_PROTOCOL),
279 ],
280 timeout: PREFLIGHT_TIMEOUT,
281 })
282 .pipe(
283 Effect.mapError(
284 (cause) =>
285 new PinnedRuntimeInstallError({
286 step: "running the staged service preflight",
287 cause,
288 }),
289 ),
290 Effect.flatMap(
291 (
292 result,
293 ): Effect.Effect<
294 void,
295 PinnedRuntimeInstallError | PinnedRuntimePreflightBlockedError
296 > => {
297 if (result.code !== 0) {
298 return Effect.fail(
299 new PinnedRuntimeInstallError({
300 step: "running the staged service preflight",
301 exitCode: Number(result.code),
302 stdoutLength: result.stdout.length,
303 stderrLength: result.stderr.length,
304 }),
305 );
306 }
307 let parsed: unknown;
308 try {
309 parsed = JSON.parse(result.stdout.trim());
310 } catch (cause) {
311 return Effect.fail(
312 new PinnedRuntimeInstallError({
313 step: "decoding the staged service preflight",
314 cause,
315 }),
316 );
317 }
318 const preflight = decodeServicePreflightResult(parsed);
319 if (preflight === undefined || preflight.version !== targetVersion) {
320 return Effect.fail(
321 new PinnedRuntimeInstallError({
322 step: "verifying the staged service preflight",
323 }),
324 );
325 }
326 return preflight.status === "ready"
327 ? Effect.void
328 : Effect.fail(
329 new PinnedRuntimePreflightBlockedError({
330 version: targetVersion,
331 reason: preflight.reason,
332 }),
333 );
334 },
335 ),
336 ),
337 }).pipe(
338 Effect.mapError((error) =>
339 error._tag === "PinnedRuntimePreflightBlockedError"
340 ? failWith(error.reason, error)
341 : failWith(`Could not prepare t3@${targetVersion}.`, error),
342 ),
343 );
344
345 yield* reportProgress("installing");
346 const updateId = yield* Effect.uninterruptible(
347 launcher.requestUpdate({ targetVersion, dbPath: serverConfig.dbPath }).pipe(
348 Effect.mapError((error) =>
349 failWith(
350 error._tag === "ServiceLauncherRejectedError"
351 ? error.reason
352 : "Could not ask the service launcher to activate the prepared update.",
353 error,
354 ),
355 ),
356 Effect.tap(() => onHandoffAccepted()),
357 ),
358 );
359
360 yield* Effect.logInfo("Server update prepared; handing off to the service launcher.", {
361 updateId,
362 targetVersion,
363 runtimePath: paths.entryPath,
364 });
365 return { targetVersion, method: "boot-service" as const, updateId };
366 }).pipe(Effect.onError(() => Ref.set(inFlight, false)));
367 });
368
369 return ServerSelfUpdate.of({
370 update,
371 commitDesktopUpdate: Effect.fn("ServerSelfUpdate.commitDesktopUpdate")(
372 function (requestId, onHandoffAccepted) {
373 return desktopAppUpdate.commit(requestId, onHandoffAccepted);
374 },
375 ),
376 });
377});
378
379export const layer = Layer.effect(ServerSelfUpdate, make()).pipe(
380 Layer.provide(ProcessRunner.layer),
381);
382
383// The update outlives client sockets; progress offers to a closed queue are ignored.
384export const updateProgressStream = (
385 selfUpdate: ServerSelfUpdate["Service"],
386 input: ServerSelfUpdateInput,
387) =>
388 Stream.callback<ServerSelfUpdateProgressEvent, ServerSelfUpdateError>((queue) => {
389 const offer = (event: ServerSelfUpdateProgressEvent) =>
390 Queue.offer(queue, event).pipe(Effect.ignore);
391
392 return selfUpdate
393 .update(input, (stage) => offer({ type: "progress", stage }))
394 .pipe(
395 Effect.flatMap((result) => offer({ type: "complete", result })),
396 Effect.catchTags({
397 ServerSelfUpdateError: (error) => Queue.fail(queue, error).pipe(Effect.ignore),
398 }),
399 Effect.andThen(Queue.end(queue).pipe(Effect.ignore)),
400 Effect.forkDetach,
401 );
402 });