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} from "@t3tools/contracts";
9import * as HostProcess from "@t3tools/shared/HostProcess";
10import * as Config from "effect/Config";
11import * as Context from "effect/Context";
12import * as Duration from "effect/Duration";
13import * as Effect from "effect/Effect";
14import * as Option from "effect/Option";
15import * as Ref from "effect/Ref";
16import * as FileSystem from "effect/FileSystem";
17import * as Layer from "effect/Layer";
18import * as Path from "effect/Path";
19import * as Queue from "effect/Queue";
20import * as Stream from "effect/Stream";
21import { HttpClient } from "effect/http";
22
23import {
24 CLI_RELEASE_BASE_URL_ENV,
25 cliReleaseChannelOf,
26 crossesReleaseTrack,
27} from "@t3tools/shared/cliRelease";
28
29import packageJson from "../../package.json" with { type: "json" };
30import * as ServerConfig from "../config.ts";
31import * as DesktopAppUpdate from "../desktopUpdate/DesktopAppUpdate.ts";
32import { databaseMigrationHead } from "../persistence/databaseMigrationHead.ts";
33import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
34import { managedUpdateMirror, managedUpdateRefusal } from "../policy/managedUpdates.ts";
35import * as ProcessRunner from "../processRunner.ts";
36import {
37 ensurePinnedRuntimeInstalled,
38 isUnpublishedRelease,
39 pinnedRuntimeCommand,
40 PinnedRuntimeInstallError,
41 pinnedRuntimePaths,
42 PinnedRuntimePreflightBlockedError,
43 prunePinnedRuntimes,
44} from "./pinnedRuntime.ts";
45import { decodeServicePreflightResult } from "./servicePreflight.ts";
46import * as ServiceLauncherClient from "./serviceLauncherClient.ts";
47import { isExactServiceVersion, SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts";
48
49// A staged runtime's cold start can take over a minute on a loaded, swapping host.
50const PREFLIGHT_TIMEOUT = Duration.minutes(3);
51
52export function resolveServerSelfUpdateCapability(input: {
53 readonly desktopManaged: boolean;
54 readonly launcherManaged: boolean;
55}): ServerSelfUpdateCapability | null {
56 if (input.desktopManaged) return "desktop-managed" as const;
57 return input.launcherManaged ? ("boot-service" as const) : null;
58}
59
60export class ServerSelfUpdate extends Context.Service<
61 ServerSelfUpdate,
62 {
63 readonly update: (
64 input: ServerSelfUpdateInput,
65 reportProgress?: (
66 stage: ServerSelfUpdateProgressStage,
67 ) => Effect.Effect<void, ServerSelfUpdateError>,
68 onHandoffAccepted?: () => Effect.Effect<void>,
69 ) => Effect.Effect<ServerSelfUpdateResult, ServerSelfUpdateError>;
70 readonly commitDesktopUpdate: (
71 requestId: string,
72 onHandoffAccepted?: () => Effect.Effect<void>,
73 ) => Effect.Effect<never, ServerSelfUpdateError>;
74 }
75>()("t3/cloud/selfUpdate/ServerSelfUpdate") {}
76
77/**
78 * A server starting from the runtime its launcher settled on means runtimes left by earlier
79 * updates can go. The boot service says so through its IPC context. The SSH launcher and the
80 * install script's `t3` start this home's pinned runtime directly, without one.
81 */
82export const pruneRuntimesOnStart = Effect.fn("cloud.server_self_update.prune_on_start")(
83 function* (input: { readonly baseDir: string; readonly managed: boolean }) {
84 const fs = yield* FileSystem.FileSystem;
85 const path = yield* Path.Path;
86 const platform = yield* HostProcess.Platform;
87 const executablePath = yield* HostProcess.ExecutablePath;
88 const { entryPath } = pinnedRuntimePaths(path, input.baseDir, packageJson.version, platform);
89 // The executable path is resolved, so it names the real path of a symlinked T3 home.
90 const realEntryPath = yield* fs.realPath(entryPath).pipe(Effect.orElseSucceed(() => entryPath));
91 if (!input.managed && executablePath !== entryPath && executablePath !== realEntryPath) {
92 return [];
93 }
94 const removed = yield* prunePinnedRuntimes({
95 baseDir: input.baseDir,
96 keep: [packageJson.version],
97 });
98 if (removed.length > 0) {
99 yield* Effect.logInfo("Removed unused t3 runtimes.", { versions: removed });
100 }
101 return removed;
102 },
103);
104
105/** The client checks this when planning; the host checks again because its database may have
106 * moved on since (another client updated it). Stable and Nightly each build their own commits,
107 * so crossing tracks needs the target release to know every migration this database holds. */
108export function trackSwitchBlockReason(input: {
109 readonly serverVersion: string;
110 readonly targetVersion: string;
111 readonly targetDatabaseMigration: number | undefined;
112 /** Read only for a crossing; undefined when the database cannot be read. */
113 readonly databaseMigration: () => number | undefined;
114}): string | null {
115 if (!crossesReleaseTrack(input.serverVersion, input.targetVersion)) return null;
116 const databaseMigration = input.databaseMigration();
117 if (input.targetDatabaseMigration === undefined || databaseMigration === undefined) {
118 return `Cannot confirm this database works with t3@${input.targetVersion}. Switch tracks from Settings → About → Update track, which checks it first.`;
119 }
120 return input.targetDatabaseMigration < databaseMigration
121 ? `This database has changes t3@${input.targetVersion} does not support yet; it stays on this release.`
122 : null;
123}
124
125export const make = Effect.fn("cloud.server_self_update.make")(function* () {
126 const serverConfig = yield* ServerConfig.ServerConfig;
127 const desktopAppUpdate = yield* DesktopAppUpdate.DesktopAppUpdate;
128 const policy = yield* ManagedPolicy.ManagedPolicy;
129 const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
130 const runner = yield* ProcessRunner.ProcessRunner;
131 const fs = yield* FileSystem.FileSystem;
132 const path = yield* Path.Path;
133 const platform = yield* HostProcess.Platform;
134 const arch = yield* HostProcess.Architecture;
135 const httpClient = yield* HttpClient.HttpClient;
136 const mirror = managedUpdateMirror(policy.document);
137 const releaseBaseUrl =
138 mirror?.feedUrl ??
139 Option.getOrUndefined(yield* Config.String(CLI_RELEASE_BASE_URL_ENV).pipe(Config.option));
140 const inFlight = yield* Ref.make(false);
141
142 yield* pruneRuntimesOnStart({ baseDir: serverConfig.baseDir, managed: launcher.managed }).pipe(
143 Effect.forkScoped,
144 );
145
146 const capability: ServerSelfUpdateCapability | null =
147 serverConfig.mode === "desktop" ? "desktop-managed" : launcher.managed ? "boot-service" : null;
148 const failWith = (reason: string, cause?: unknown) =>
149 cause === undefined
150 ? new ServerSelfUpdateError({ reason })
151 : new ServerSelfUpdateError({ reason, cause });
152
153 const crossesTrackUnsafely = (input: ServerSelfUpdateInput) =>
154 trackSwitchBlockReason({
155 serverVersion: packageJson.version,
156 targetVersion: input.targetVersion,
157 targetDatabaseMigration: input.targetDatabaseMigration,
158 databaseMigration: () => databaseMigrationHead(serverConfig.dbPath),
159 });
160
161 const update: ServerSelfUpdate["Service"]["update"] = Effect.fn(
162 "cloud.server_self_update.update",
163 )(function* (input, reportProgress = () => Effect.void, onHandoffAccepted = () => Effect.void) {
164 const policyRefusal = managedUpdateRefusal(
165 policy.document,
166 capability === "boot-service" ? cliReleaseChannelOf(input.targetVersion.trim()) : undefined,
167 );
168 if (policyRefusal !== undefined) {
169 return yield* failWith(policyRefusal);
170 }
171 if (capability === "desktop-managed") {
172 const unsafeCrossing = input.channel === undefined ? null : crossesTrackUnsafely(input);
173 if (unsafeCrossing !== null) return yield* failWith(unsafeCrossing);
174 if (desktopAppUpdate.available) {
175 return yield* desktopAppUpdate.run(
176 reportProgress,
177 input.channel === undefined
178 ? undefined
179 : { channel: input.channel, targetVersion: input.targetVersion },
180 );
181 }
182 return yield* failWith(
183 "This server is managed by the T3 Code desktop app on its machine; update the desktop app to update it.",
184 );
185 }
186 if (capability === null) {
187 return yield* failWith(
188 "Remote updates require the T3 Code background service. Run `t3 service install` on the server machine.",
189 );
190 }
191
192 const unsafeCrossing = crossesTrackUnsafely(input);
193 if (unsafeCrossing !== null) return yield* failWith(unsafeCrossing);
194 const targetVersion = input.targetVersion.trim();
195 if (!isExactServiceVersion(targetVersion)) {
196 return yield* failWith(`'${targetVersion}' is not an exact t3 version.`);
197 }
198 if (yield* Ref.getAndSet(inFlight, true)) {
199 return yield* failWith("A server update is already in progress.");
200 }
201
202 return yield* Effect.gen(function* () {
203 yield* reportProgress("downloading");
204 const paths = yield* ensurePinnedRuntimeInstalled({
205 baseDir: serverConfig.baseDir,
206 version: targetVersion,
207 fs,
208 path,
209 runner,
210 httpClient,
211 platform,
212 arch,
213 releaseBaseUrl,
214 requirePublishedRelease: mirror !== undefined,
215 validate: (runtime) =>
216 runner
217 .run({
218 command: pinnedRuntimeCommand(runtime).command,
219 args: [
220 ...pinnedRuntimeCommand(runtime).args,
221 "__service-preflight",
222 "--database-path",
223 serverConfig.dbPath,
224 "--launcher-protocol",
225 String(SERVICE_LAUNCHER_PROTOCOL),
226 ],
227 timeout: PREFLIGHT_TIMEOUT,
228 })
229 .pipe(
230 Effect.mapError(
231 (cause) =>
232 new PinnedRuntimeInstallError({
233 step: "running the staged service preflight",
234 cause,
235 }),
236 ),
237 Effect.flatMap(
238 (
239 result,
240 ): Effect.Effect<
241 void,
242 PinnedRuntimeInstallError | PinnedRuntimePreflightBlockedError
243 > => {
244 if (result.code !== 0) {
245 return Effect.fail(
246 new PinnedRuntimeInstallError({
247 step: "running the staged service preflight",
248 exitCode: Number(result.code),
249 stdoutLength: result.stdout.length,
250 stderrLength: result.stderr.length,
251 }),
252 );
253 }
254 let parsed: unknown;
255 try {
256 parsed = JSON.parse(result.stdout.trim());
257 } catch (cause) {
258 return Effect.fail(
259 new PinnedRuntimeInstallError({
260 step: "decoding the staged service preflight",
261 cause,
262 }),
263 );
264 }
265 const preflight = decodeServicePreflightResult(parsed);
266 if (preflight === undefined || preflight.version !== targetVersion) {
267 return Effect.fail(
268 new PinnedRuntimeInstallError({
269 step: "verifying the staged service preflight",
270 }),
271 );
272 }
273 return preflight.status === "ready"
274 ? Effect.void
275 : Effect.fail(
276 new PinnedRuntimePreflightBlockedError({
277 version: targetVersion,
278 reason: preflight.reason,
279 }),
280 );
281 },
282 ),
283 ),
284 }).pipe(
285 Effect.mapError((error) => {
286 if (error._tag === "PinnedRuntimePreflightBlockedError") {
287 return failWith(error.reason, error);
288 }
289 if (mirror !== undefined && isUnpublishedRelease(error)) {
290 return failWith(
291 `${mirror.organization}'s update mirror has no t3@${targetVersion} for this machine.`,
292 error,
293 );
294 }
295 const downloadFailure = [
296 error.httpStatus === undefined ? undefined : `HTTP ${error.httpStatus}`,
297 error.downloadHost === undefined ? undefined : `from ${error.downloadHost}`,
298 ]
299 .filter((part) => part !== undefined)
300 .join(" ");
301 return failWith(
302 `Could not prepare t3@${targetVersion} while ${error.step}${downloadFailure ? ` (${downloadFailure})` : ""}.`,
303 error,
304 );
305 }),
306 );
307
308 yield* reportProgress("installing");
309 const updateId = yield* Effect.uninterruptible(
310 launcher.requestUpdate({ targetVersion, dbPath: serverConfig.dbPath }).pipe(
311 Effect.mapError((error) =>
312 failWith(
313 error._tag === "ServiceLauncherRejectedError"
314 ? error.reason
315 : "Could not ask the service launcher to activate the prepared update.",
316 error,
317 ),
318 ),
319 Effect.tap(() => onHandoffAccepted()),
320 ),
321 );
322
323 yield* Effect.logInfo("Server update prepared; handing off to the service launcher.", {
324 updateId,
325 targetVersion,
326 runtimePath: paths.entryPath,
327 });
328 return { targetVersion, method: "boot-service" as const, updateId };
329 }).pipe(Effect.onError(() => Ref.set(inFlight, false)));
330 });
331
332 return ServerSelfUpdate.of({
333 update,
334 commitDesktopUpdate: Effect.fn("ServerSelfUpdate.commitDesktopUpdate")(
335 function (requestId, onHandoffAccepted) {
336 return desktopAppUpdate.commit(requestId, onHandoffAccepted);
337 },
338 ),
339 });
340});
341
342export const layer = Layer.effect(ServerSelfUpdate, make()).pipe(
343 Layer.provide(ProcessRunner.layer),
344);
345
346// The update outlives client sockets; progress offers to a closed queue are ignored.
347export const updateProgressStream = (
348 selfUpdate: ServerSelfUpdate["Service"],
349 input: ServerSelfUpdateInput,
350) =>
351 Stream.callback<ServerSelfUpdateProgressEvent, ServerSelfUpdateError>((queue) => {
352 const offer = (event: ServerSelfUpdateProgressEvent) =>
353 Queue.offer(queue, event).pipe(Effect.ignore);
354
355 return selfUpdate
356 .update(input, (stage) => offer({ type: "progress", stage }))
357 .pipe(
358 Effect.flatMap((result) => offer({ type: "complete", result })),
359 Effect.catchTags({
360 ServerSelfUpdateError: (error) => Queue.fail(queue, error).pipe(Effect.ignore),
361 }),
362 Effect.andThen(Queue.end(queue).pipe(Effect.ignore)),
363 Effect.forkDetach,
364 );
365 });