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