History

feat(connect): keep macOS hosts reachable after reboot

Theo Browne committed 3 months ago

Commit ec3c5f61 parent 90f391312 files · +690 −91Browse files

Showing the changes to apps/server/src/cloud/selfUpdate.ts (1 of 12 files). Show all

Unified · Split

apps/server/src/cloud/selfUpdate.ts+89−7
@@ -13,6 +13,7 @@ import { · 12 unmodified lines
1313 HostProcessEnvironment,
1414 HostProcessExecutablePath,
1515 HostProcessPlatform,
16+ HostProcessUserId,
1617 } from "@t3tools/shared/hostProcess";
1718 import * as NodeChildProcess from "node:child_process";
1819 import * as Context from "effect/Context";
@@ -24,11 +25,13 @@ import * as Path from "effect/Path"; · 5 unmodified lines
2425 import * as Ref from "effect/Ref";
2526
2627 import * as ServerConfig from "../config.ts";
27−import { writeFileStringAtomically } from "../atomicWrite.ts";
28+import { writeFileStringAtomically, writeSymbolicLinkAtomically } from "../atomicWrite.ts";
2829 import * as ProcessRunner from "../processRunner.ts";
2930 import {
31+ BOOT_SERVICE_LAUNCH_AGENT_LABEL,
3032 BOOT_SERVICE_UNIT_ENV,
3133 BOOT_SERVICE_UNIT_FILE,
34+ launchAgentPaths,
3235 quoteSystemdValue,
3336 renderBootServiceUnit,
3437 } from "./bootService.ts";
@@ -82,11 +85,11 @@ export function isPublishedCliEntry(entryPath: string): boolean { · 47 unmodified lines
8285 * The update path this process can offer, or null when only a manual
8386 * relaunch works. "desktop-managed" — the T3 Code desktop app spawned this
8487 * 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).
88+ * "boot-service" — this is the systemd- or launchd-supervised process from
89+ * bootService.ts: switch the service to the verified runtime and restart it.
90+ * "respawn" — a foreground POSIX process running a published artifact:
91+ * replace it with a detached child. Windows foreground runs are unsupported
92+ * for now (no equivalent of the detach-and-exec handoff below).
9093 */
9194 export const resolveServerSelfUpdateCapability = Effect.fn(
9295 "cloud.server_self_update.resolve_capability",
@@ -101,6 +104,7 @@ export const resolveServerSelfUpdateCapability = Effect.fn( · 8 unmodified lines
101104 const platform = yield* HostProcessPlatform;
102105 const env = yield* HostProcessEnvironment;
103106 const hostArguments = yield* HostProcessArguments;
107+ const userId = yield* HostProcessUserId;
104108 const fs = yield* FileSystem.FileSystem;
105109 const path = yield* Path.Path;
106110
@@ -110,6 +114,26 @@ export const resolveServerSelfUpdateCapability = Effect.fn( · 3 unmodified lines
110114 }
111115
112116 const homeDir = env.HOME ?? "";
117+ if (platform === "darwin" && homeDir !== "" && userId !== null) {
118+ const launchAgent = launchAgentPaths(path, homeDir, env.T3CODE_HOME ?? "", userId);
119+ const unitExists = yield* fs
120+ .exists(launchAgent.unitPath)
121+ .pipe(Effect.orElseSucceed(() => false));
122+ if (
123+ unitExists &&
124+ entryPath === launchAgent.activeEntryPath &&
125+ env[BOOT_SERVICE_UNIT_ENV] === BOOT_SERVICE_LAUNCH_AGENT_LABEL
126+ ) {
127+ return "boot-service" as const;
128+ }
129+
130+ // A marked LaunchAgent process with an unexpected definition must not
131+ // detach a second server outside its supervisor.
132+ if (env[BOOT_SERVICE_UNIT_ENV] === BOOT_SERVICE_LAUNCH_AGENT_LABEL) {
133+ return null;
134+ }
135+ }
136+
113137 if (platform === "linux" && homeDir !== "") {
114138 const unitPath = path.join(homeDir, ".config", "systemd", "user", BOOT_SERVICE_UNIT_FILE);
115139 const unitReferencesEntry = yield* fs.readFileString(unitPath).pipe(
@@ -159,6 +183,8 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* (option · 43 unmodified lines
159183 const path = yield* Path.Path;
160184 const runner = yield* ProcessRunner.ProcessRunner;
161185 const env = yield* HostProcessEnvironment;
186+ const platform = yield* HostProcessPlatform;
187+ const userId = yield* HostProcessUserId;
162188 const hostExecPath = yield* HostProcessExecutablePath;
163189 const hostArguments = yield* HostProcessArguments;
164190 const capability: ServerSelfUpdateCapability | null = yield* resolveServerSelfUpdateCapability({
@@ -224,6 +250,11 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* (option · 59 unmodified lines
224250 Effect.provideService(FileSystem.FileSystem, fs),
225251 Effect.provideService(Path.Path, path),
226252 );
253+ const writeRuntimeLinkAtomically = (linkPath: string, targetPath: string) =>
254+ writeSymbolicLinkAtomically({ linkPath, targetPath }).pipe(
255+ Effect.provideService(FileSystem.FileSystem, fs),
256+ Effect.provideService(Path.Path, path),
257+ );
227258
228259 const update: ServerSelfUpdate["Service"]["update"] = Effect.fn(
229260 "cloud.server_self_update.update",
@@ -297,7 +328,58 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* (option · 67 unmodified lines
297328 );
298329 }
299330
300− if (activeMethod === "boot-service") {
331+ if (activeMethod === "boot-service" && platform === "darwin" && userId !== null) {
332+ const homeDir = env.HOME ?? "";
333+ const launchAgent = launchAgentPaths(path, homeDir, serverConfig.baseDir, userId);
334+ const previousRuntime = yield* fs
335+ .readLink(launchAgent.activeRuntimeLinkPath)
336+ .pipe(
337+ Effect.mapError((cause) =>
338+ failWith("Could not read the active launchd runtime.", cause),
339+ ),
340+ );
341+ yield* writeRuntimeLinkAtomically(
342+ launchAgent.activeRuntimeLinkPath,
343+ runtimePaths.versionDir,
344+ ).pipe(
345+ Effect.mapError((cause) =>
346+ failWith("Could not activate the requested launchd runtime.", cause),
347+ ),
348+ );
349+ yield* Effect.logInfo("Server self-update installed; restarting LaunchAgent.", {
350+ targetVersion,
351+ });
352+
353+ yield* Effect.gen(function* () {
354+ const kickstart = yield* runner
355+ .run({
356+ command: "/bin/launchctl",
357+ args: ["kickstart", "-k", launchAgent.serviceTarget],
358+ })
359+ .pipe(
360+ Effect.mapError((cause) =>
361+ failWith("Could not restart the T3 Code LaunchAgent.", cause),
362+ ),
363+ );
364+ if (kickstart.code !== 0) {
365+ return yield* failWith(
366+ `Restarting the T3 Code LaunchAgent failed (exit code ${String(kickstart.code)}).`,
367+ );
368+ }
369+ }).pipe(
370+ Effect.catch((restartError) =>
371+ writeRuntimeLinkAtomically(launchAgent.activeRuntimeLinkPath, previousRuntime).pipe(
372+ Effect.mapError((rollbackCause) =>
373+ failWith("Could not restore the previous launchd runtime.", {
374+ restartError,
375+ rollbackCause,
376+ }),
377+ ),
378+ Effect.andThen(Effect.fail(restartError)),
379+ ),
380+ ),
381+ );
382+ } else if (activeMethod === "boot-service") {
301383 const homeDir = env.HOME ?? "";
302384 const unitPath = path.join(homeDir, ".config", "systemd", "user", BOOT_SERVICE_UNIT_FILE);
303385 const previousUnit = yield* fs

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t