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

selfUpdate.ts

430 lines16.7 KB

1// @effect-diagnostics nodeBuiltinImport:off
2// node:child_process directly: the foreground-server replacement must be a
3// detached fire-and-forget child that outlives this process, while Effect's
4// ChildProcessSpawner ties every child to a scope that kills it.
5import {
6 ServerSelfUpdateError,
7 type ServerSelfUpdateCapability,
8 type ServerSelfUpdateInput,
9 type ServerSelfUpdateResult,
10} from "@t3tools/contracts";
11import {
12 HostProcessArguments,
13 HostProcessEnvironment,
14 HostProcessExecutablePath,
15 HostProcessPlatform,
16} from "@t3tools/shared/hostProcess";
17import * as NodeChildProcess from "node:child_process";
18import * as Context from "effect/Context";
19import * as Duration from "effect/Duration";
20import * as Effect from "effect/Effect";
21import * as FileSystem from "effect/FileSystem";
22import * as Layer from "effect/Layer";
23import * as Path from "effect/Path";
24import * as Ref from "effect/Ref";
25​
26import * as ServerConfig from "../config.ts";
27import { writeFileStringAtomically } from "../atomicWrite.ts";
28import * as ProcessRunner from "../processRunner.ts";
29import {
30 BOOT_SERVICE_UNIT_ENV,
31 BOOT_SERVICE_UNIT_FILE,
32 quoteSystemdValue,
33 renderBootServiceUnit,
34} from "./bootService.ts";
35import { ensurePinnedRuntimeInstalled, removePinnedRuntimeInstallation } from "./pinnedRuntime.ts";
36​
37/**
38 * Lets a connected client replace this server with another published `t3`
39 * version over RPC — the only update path that works when the user is not at
40 * the machine (phone against a home server, relay-managed box). The target
41 * version is npm-installed into the pinned runtime and verified before
42 * anything restarts, so a failed install leaves the running server untouched.
43 */
44​
45const PREFLIGHT_TIMEOUT = Duration.seconds(30);
46/** Grace between acknowledging the RPC and killing the process, so the
47 response (and its relay hop) flushes before the socket drops. */
48const RESTART_DELAY = Duration.seconds(2);
49​
50/** Exact npm versions only — never dist-tags — so the acknowledgement names
51 the version that was actually installed. Also keeps the value safe to
52 pass to npm and embed in filesystem paths. */
53const EXACT_VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
54​
55export interface ServerSelfUpdateHost {
56 readonly execPath: string;
57 readonly cliEntryPath: string;
58 /** Original CLI arguments after the entry path, replayed on respawn. */
59 readonly cliArgs: ReadonlyArray<string>;
60 /** Resolves once the foreground replacement process has actually spawned. */
61 readonly spawnDetached: (
62 command: string,
63 args: ReadonlyArray<string>,
64 ) => Effect.Effect<void, ProcessRunner.ProcessSpawnError>;
65 readonly exitProcess: () => void;
67​
68function normalizeEntryPath(entryPath: string): string {
69 return entryPath.replaceAll("\\", "/");
71​
72/**
73 * Only a published npm artifact can be swapped for another version: dev
74 * checkouts (apps/server/dist) and the desktop app's bundled backend have no
75 * npm identity, and the desktop manages its own updates.
76 */
77export function isPublishedCliEntry(entryPath: string): boolean {
78 return normalizeEntryPath(entryPath).includes("/node_modules/t3/dist/");
80​
81/**
82 * The update path this process can offer, or null when only a manual
83 * relaunch works. "desktop-managed" — the T3 Code desktop app spawned this
84 * backend and owns its version; only updating the app updates it.
85 * "boot-service" — this is the systemd-supervised process from
86 * bootService.ts: rewrite the unit and let systemd swap it. "respawn" — a
87 * foreground POSIX process running a published artifact: replace it with a
88 * detached child. Windows foreground runs are unsupported for now (no
89 * equivalent of the detach-and-exec handoff below).
90 */
91export const resolveServerSelfUpdateCapability = Effect.fn(
92 "cloud.server_self_update.resolve_capability",
93)(function* (input: {
94 /** True when the desktop app supervises this backend (mode "desktop"). */
95 readonly desktopManaged: boolean;
96}) {
97 if (input.desktopManaged) {
98 return "desktop-managed" as const;
99 }
100​
101 const platform = yield* HostProcessPlatform;
102 const env = yield* HostProcessEnvironment;
103 const hostArguments = yield* HostProcessArguments;
104 const fs = yield* FileSystem.FileSystem;
105 const path = yield* Path.Path;
106​
107 const entryPath = hostArguments[1] ?? "";
108 if (entryPath === "") {
109 return null;
110 }
111​
112 const homeDir = env.HOME ?? "";
113 if (platform === "linux" && homeDir !== "") {
114 const unitPath = path.join(homeDir, ".config", "systemd", "user", BOOT_SERVICE_UNIT_FILE);
115 const unitReferencesEntry = yield* fs.readFileString(unitPath).pipe(
116 Effect.map((unit) => unit.includes(quoteSystemdValue(entryPath))),
117 Effect.orElseSucceed(() => false),
118 );
119 // INVOCATION_ID only proves that some systemd unit launched us. The
120 // explicit marker written into t3code.service identifies this unit as the
121 // supervisor that will replace the current process when restarted.
122 if (
123 unitReferencesEntry &&
124 (env.INVOCATION_ID ?? "") !== "" &&
125 env[BOOT_SERVICE_UNIT_ENV] === BOOT_SERVICE_UNIT_FILE
126 ) {
127 return "boot-service" as const;
128 }
129​
130 // A process owned by another (or a legacy unmarked) systemd unit must not
131 // use the foreground respawn path: Restart=always could otherwise launch
132 // the old unit beside the detached replacement.
133 if ((env.INVOCATION_ID ?? "") !== "") {
134 return null;
135 }
136 }
137​
138 if ((platform === "linux" || platform === "darwin") && isPublishedCliEntry(entryPath)) {
139 return "respawn" as const;
140 }
141​
142 return null;
143});
144​
145export class ServerSelfUpdate extends Context.Service<
146 ServerSelfUpdate,
147 {
148 readonly update: (
149 input: ServerSelfUpdateInput,
150 ) => Effect.Effect<ServerSelfUpdateResult, ServerSelfUpdateError>;
151 }
152>()("t3/cloud/selfUpdate/ServerSelfUpdate") {}
153​
154export const make = Effect.fn("cloud.server_self_update.make")(function* (options?: {
155 readonly host?: Partial<ServerSelfUpdateHost>;
156}) {
157 const serverConfig = yield* ServerConfig.ServerConfig;
158 const fs = yield* FileSystem.FileSystem;
159 const path = yield* Path.Path;
160 const runner = yield* ProcessRunner.ProcessRunner;
161 const env = yield* HostProcessEnvironment;
162 const hostExecPath = yield* HostProcessExecutablePath;
163 const hostArguments = yield* HostProcessArguments;
164 const capability: ServerSelfUpdateCapability | null = yield* resolveServerSelfUpdateCapability({
165 desktopManaged: serverConfig.mode === "desktop",
166 });
167​
168 const host: ServerSelfUpdateHost = {
169 execPath: options?.host?.execPath ?? hostExecPath,
170 cliEntryPath: options?.host?.cliEntryPath ?? hostArguments[1] ?? "",
171 cliArgs: options?.host?.cliArgs ?? hostArguments.slice(2),
172 spawnDetached:
173 options?.host?.spawnDetached ??
174 ((command, args) =>
175 Effect.callback<void, ProcessRunner.ProcessSpawnError>((resume) => {
176 const spawnError = (cause: unknown) =>
177 new ProcessRunner.ProcessSpawnError({
178 command,
179 argumentCount: args.length,
180 cause,
181 });
182 let child: NodeChildProcess.ChildProcess;
183 try {
184 child = NodeChildProcess.spawn(command, [...args], {
185 detached: true,
186 stdio: "ignore",
187 });
188 } catch (cause) {
189 resume(Effect.fail(spawnError(cause)));
190 return;
191 }
192​
193 const onSpawnError = (cause: Error) => resume(Effect.fail(spawnError(cause)));
194 child.once("error", onSpawnError);
195 child.once("spawn", () => {
196 child.removeListener("error", onSpawnError);
197 // Keep asynchronous child errors from becoming uncaught after the
198 // successful spawn handoff has already been acknowledged.
199 child.on("error", () => undefined);
200 child.unref();
201 resume(Effect.void);
202 });
203 })),
204 exitProcess: options?.host?.exitProcess ?? (() => process.exit(0)),
205 };
206​
207 const inFlight = yield* Ref.make(false);
208​
209 const failWith = (reason: string, cause?: unknown) =>
210 cause === undefined
211 ? new ServerSelfUpdateError({ reason })
212 : new ServerSelfUpdateError({ reason, cause });
213​
214 /** Deferred so the RPC acknowledgement flushes before the process dies.
215 Detached from the request scope: the triggering connection is exactly
216 what the restart tears down. */
217 const scheduleRestart = (restart: Effect.Effect<void>) =>
218 Effect.sleep(RESTART_DELAY).pipe(
219 Effect.andThen(restart),
220 Effect.forkDetach({ startImmediately: true }),
221 );
222 const writeUnitAtomically = (filePath: string, contents: string) =>
223 writeFileStringAtomically({ filePath, contents }).pipe(
224 Effect.provideService(FileSystem.FileSystem, fs),
225 Effect.provideService(Path.Path, path),
226 );
227​
228 const update: ServerSelfUpdate["Service"]["update"] = Effect.fn(
229 "cloud.server_self_update.update",
230 )(function* (input) {
231 if (capability === "desktop-managed") {
232 return yield* failWith(
233 "This server is managed by the T3 Code desktop app on its machine; update the desktop app to update it.",
234 );
235 }
236 if (capability === null) {
237 return yield* failWith(
238 "This server cannot update itself; relaunch it manually with the new version.",
239 );
240 }
241 const activeMethod = capability;
242 const targetVersion = input.targetVersion.trim();
243 if (!EXACT_VERSION_PATTERN.test(targetVersion)) {
244 return yield* failWith(`'${targetVersion}' is not an exact t3 version.`);
245 }
246​
247 const alreadyRunning = yield* Ref.getAndSet(inFlight, true);
248 if (alreadyRunning) {
249 return yield* failWith("A server update is already in progress.");
250 }
251​
252 return yield* Effect.gen(function* () {
253 const runtimePaths = yield* ensurePinnedRuntimeInstalled({
254 baseDir: serverConfig.baseDir,
255 version: targetVersion,
256 fs,
257 path,
258 runner,
259 }).pipe(
260 Effect.mapError((error) => failWith("Could not install the requested t3 version.", error)),
261 );
262​
263 // A broken artifact (failed native build, incompatible node) must be
264 // caught while the current server is still alive to report it.
265 const preflight = yield* runner
266 .run({
267 command: host.execPath,
268 args: [runtimePaths.entryPath, "--version"],
269 timeout: PREFLIGHT_TIMEOUT,
270 })
271 .pipe(
272 Effect.mapError((cause) =>
273 failWith(`Could not verify the installed t3@${targetVersion}.`, cause),
274 ),
275 );
276 // Effect CLI's unstable formatVersion currently emits `${name} v${version}`.
277 // Extract the version token so surrounding presentation changes do not break updates.
278 const reportedVersion = /\bv(\S+)\s*$/.exec(preflight.stdout)?.[1];
279 if (preflight.code !== 0 || reportedVersion !== targetVersion) {
280 // A completed npm install can still be unusable under this Node or on
281 // this machine. Remove its sentinel and tree so a retry of the same
282 // version performs a clean install instead of reusing a known-bad one.
283 yield* removePinnedRuntimeInstallation({
284 baseDir: serverConfig.baseDir,
285 version: targetVersion,
286 fs,
287 path,
288 }).pipe(
289 Effect.mapError((error) =>
290 failWith(`Could not remove the failed t3@${targetVersion} installation.`, error),
291 ),
292 );
293 return yield* failWith(
294 preflight.code !== 0
295 ? `The installed t3@${targetVersion} failed its version check (exit code ${String(preflight.code)}).`
296 : `The installed runtime did not report the requested t3@${targetVersion} version.`,
297 );
298 }
299​
300 if (activeMethod === "boot-service") {
301 const homeDir = env.HOME ?? "";
302 const unitPath = path.join(homeDir, ".config", "systemd", "user", BOOT_SERVICE_UNIT_FILE);
303 const previousUnit = yield* fs
304 .readFileString(unitPath)
305 .pipe(
306 Effect.mapError((cause) => failWith("Could not read the current systemd unit.", cause)),
307 );
308 // Same shape bootService.install writes, so host lifecycle commands
309 // still recognize the unit as current.
310 const unit = renderBootServiceUnit({
311 nodePath: host.execPath,
312 t3EntryPath: runtimePaths.entryPath,
313 baseDir: serverConfig.baseDir,
314 logPath: path.join(serverConfig.logsDir, "boot-service.log"),
315 unitPath,
316 });
317 yield* writeUnitAtomically(unitPath, unit).pipe(
318 Effect.mapError((cause) => failWith("Could not update the systemd unit.", cause)),
319 );
320​
321 const reloadSystemd = Effect.fn("cloud.server_self_update.reload_systemd")(function* () {
322 const reload = yield* runner
323 .run({ command: "systemctl", args: ["--user", "daemon-reload"] })
324 .pipe(Effect.mapError((cause) => failWith("Could not reload systemd units.", cause)));
325 if (reload.code !== 0) {
326 return yield* failWith(
327 `Reloading systemd units failed (exit code ${String(reload.code)}).`,
328 );
329 }
330 });
331​
332 yield* reloadSystemd().pipe(
333 Effect.catch((reloadError) =>
334 writeUnitAtomically(unitPath, previousUnit).pipe(
335 Effect.mapError((rollbackCause) =>
336 failWith("Could not restore the previous systemd unit.", {
337 reloadError,
338 rollbackCause,
339 }),
340 ),
341 // Systemd should still have the old unit in memory after the
342 // failed reload, but retry after restoring in case it applied a
343 // partial update before returning an error.
344 Effect.andThen(reloadSystemd().pipe(Effect.ignore)),
345 Effect.andThen(Effect.fail(reloadError)),
346 ),
347 ),
348 );
349 yield* Effect.logInfo("Server self-update installed; restarting boot service.", {
350 targetVersion,
351 });
352 // A successful systemd restart stops this process, so the RPC is
353 // interrupted and the reconnecting client observes the new version.
354 // A rejected restart returns while the old process is still alive;
355 // restore the previous unit and report that failure through the RPC.
356 yield* Effect.gen(function* () {
357 const restart = yield* runner
358 .run({
359 command: "systemctl",
360 args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
361 })
362 .pipe(
363 Effect.mapError((cause) =>
364 failWith("Could not restart the systemd boot service.", cause),
365 ),
366 );
367 if (restart.code !== 0) {
368 return yield* failWith(
369 `Restarting the systemd boot service failed (exit code ${String(restart.code)}).`,
370 );
371 }
372 }).pipe(
373 Effect.catch((restartError) =>
374 writeUnitAtomically(unitPath, previousUnit).pipe(
375 Effect.andThen(reloadSystemd()),
376 Effect.mapError((rollbackError) =>
377 failWith("Could not restore the previous systemd unit.", {
378 restartError,
379 rollbackError,
380 }),
381 ),
382 Effect.andThen(Effect.fail(restartError)),
383 ),
384 ),
385 );
386 } else {
387 // Spawn the shim before acknowledging the RPC so ENOENT/EACCES and
388 // other launch failures leave this server alive and return a useful
389 // error. The shim itself waits until after the acknowledgement and
390 // deferred exit before binding the replacement server.
391 yield* host
392 .spawnDetached("/bin/sh", [
393 "-c",
394 'sleep 3; exec "$@"',
395 "t3-self-update",
396 host.execPath,
397 runtimePaths.entryPath,
398 ...host.cliArgs,
399 ])
400 .pipe(
401 Effect.mapError((cause) =>
402 failWith("Could not start the replacement t3 process.", cause),
403 ),
404 );
405 yield* Effect.logInfo("Server self-update installed; respawning.", { targetVersion });
406 yield* scheduleRestart(
407 Effect.try({
408 try: () => host.exitProcess(),
409 catch: (cause) => failWith("Could not exit the replaced t3 process.", cause),
410 }).pipe(
411 Effect.catch((error) =>
412 Effect.logError("Server self-update could not exit the replaced process.").pipe(
413 Effect.annotateLogs({ targetVersion, error: error.reason }),
414 Effect.ensuring(Ref.set(inFlight, false)),
415 ),
416 ),
417 ),
418 );
419 }
420​
421 return { targetVersion, method: activeMethod };
422 }).pipe(Effect.onError(() => Ref.set(inFlight, false)));
423 });
424​
425 return ServerSelfUpdate.of({ update });
426});
427​
428export const layer = Layer.effect(ServerSelfUpdate, make()).pipe(
429 Layer.provide(ProcessRunner.layer),
430);