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