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 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;
66}
67
68function normalizeEntryPath(entryPath: string): string {
69 return entryPath.replaceAll("\\", "/");
70}
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/");
79}
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 const preflightVersion = preflight.stdout.trim();
277 if (preflight.code !== 0 || preflightVersion !== targetVersion) {
278 // A completed npm install can still be unusable under this Node or on
279 // this machine. Remove its sentinel and tree so a retry of the same
280 // version performs a clean install instead of reusing a known-bad one.
281 yield* removePinnedRuntimeInstallation({
282 baseDir: serverConfig.baseDir,
283 version: targetVersion,
284 fs,
285 path,
286 }).pipe(
287 Effect.mapError((error) =>
288 failWith(`Could not remove the failed t3@${targetVersion} installation.`, error),
289 ),
290 );
291 return yield* failWith(
292 preflight.code !== 0
293 ? `The installed t3@${targetVersion} failed its version check (exit code ${String(preflight.code)}).`
294 : `The installed runtime did not report the requested t3@${targetVersion} version.`,
295 );
296 }
297
298 if (activeMethod === "boot-service") {
299 const homeDir = env.HOME ?? "";
300 const unitPath = path.join(homeDir, ".config", "systemd", "user", BOOT_SERVICE_UNIT_FILE);
301 const previousUnit = yield* fs
302 .readFileString(unitPath)
303 .pipe(
304 Effect.mapError((cause) => failWith("Could not read the current systemd unit.", cause)),
305 );
306 // Same shape bootService.install writes, so host lifecycle commands
307 // still recognize the unit as current.
308 const unit = renderBootServiceUnit({
309 nodePath: host.execPath,
310 t3EntryPath: runtimePaths.entryPath,
311 baseDir: serverConfig.baseDir,
312 logPath: path.join(serverConfig.logsDir, "boot-service.log"),
313 unitPath,
314 });
315 yield* writeUnitAtomically(unitPath, unit).pipe(
316 Effect.mapError((cause) => failWith("Could not update the systemd unit.", cause)),
317 );
318
319 const reloadSystemd = Effect.fn("cloud.server_self_update.reload_systemd")(function* () {
320 const reload = yield* runner
321 .run({ command: "systemctl", args: ["--user", "daemon-reload"] })
322 .pipe(Effect.mapError((cause) => failWith("Could not reload systemd units.", cause)));
323 if (reload.code !== 0) {
324 return yield* failWith(
325 `Reloading systemd units failed (exit code ${String(reload.code)}).`,
326 );
327 }
328 });
329
330 yield* reloadSystemd().pipe(
331 Effect.catch((reloadError) =>
332 writeUnitAtomically(unitPath, previousUnit).pipe(
333 Effect.mapError((rollbackCause) =>
334 failWith("Could not restore the previous systemd unit.", {
335 reloadError,
336 rollbackCause,
337 }),
338 ),
339 // Systemd should still have the old unit in memory after the
340 // failed reload, but retry after restoring in case it applied a
341 // partial update before returning an error.
342 Effect.andThen(reloadSystemd().pipe(Effect.ignore)),
343 Effect.andThen(Effect.fail(reloadError)),
344 ),
345 ),
346 );
347 yield* Effect.logInfo("Server self-update installed; restarting boot service.", {
348 targetVersion,
349 });
350 // A successful systemd restart stops this process, so the RPC is
351 // interrupted and the reconnecting client observes the new version.
352 // A rejected restart returns while the old process is still alive;
353 // restore the previous unit and report that failure through the RPC.
354 yield* Effect.gen(function* () {
355 const restart = yield* runner
356 .run({
357 command: "systemctl",
358 args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
359 })
360 .pipe(
361 Effect.mapError((cause) =>
362 failWith("Could not restart the systemd boot service.", cause),
363 ),
364 );
365 if (restart.code !== 0) {
366 return yield* failWith(
367 `Restarting the systemd boot service failed (exit code ${String(restart.code)}).`,
368 );
369 }
370 }).pipe(
371 Effect.catch((restartError) =>
372 writeUnitAtomically(unitPath, previousUnit).pipe(
373 Effect.andThen(reloadSystemd()),
374 Effect.mapError((rollbackError) =>
375 failWith("Could not restore the previous systemd unit.", {
376 restartError,
377 rollbackError,
378 }),
379 ),
380 Effect.andThen(Effect.fail(restartError)),
381 ),
382 ),
383 );
384 } else {
385 // Spawn the shim before acknowledging the RPC so ENOENT/EACCES and
386 // other launch failures leave this server alive and return a useful
387 // error. The shim itself waits until after the acknowledgement and
388 // deferred exit before binding the replacement server.
389 yield* host
390 .spawnDetached("/bin/sh", [
391 "-c",
392 'sleep 3; exec "$@"',
393 "t3-self-update",
394 host.execPath,
395 runtimePaths.entryPath,
396 ...host.cliArgs,
397 ])
398 .pipe(
399 Effect.mapError((cause) =>
400 failWith("Could not start the replacement t3 process.", cause),
401 ),
402 );
403 yield* Effect.logInfo("Server self-update installed; respawning.", { targetVersion });
404 yield* scheduleRestart(
405 Effect.try({
406 try: () => host.exitProcess(),
407 catch: (cause) => failWith("Could not exit the replaced t3 process.", cause),
408 }).pipe(
409 Effect.catch((error) =>
410 Effect.logError("Server self-update could not exit the replaced process.").pipe(
411 Effect.annotateLogs({ targetVersion, error: error.reason }),
412 Effect.ensuring(Ref.set(inFlight, false)),
413 ),
414 ),
415 ),
416 );
417 }
418
419 return { targetVersion, method: activeMethod };
420 }).pipe(Effect.onError(() => Ref.set(inFlight, false)));
421 });
422
423 return ServerSelfUpdate.of({ update });
424});
425
426export const layer = Layer.effect(ServerSelfUpdate, make()).pipe(
427 Layer.provide(ProcessRunner.layer),
428);