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/bootService.ts (1 of 12 files). Show all

Unified · Split

apps/server/src/cloud/bootService.ts+255−35
@@ -11,16 +11,19 @@ import * as Schema from "effect/Schema"; · 10 unmodified lines
1111
1212 import {
1313 HostProcessArguments,
14+ HostProcessEnvironment,
1415 HostProcessExecutablePath,
1516 HostProcessPlatform,
17+ HostProcessUserId,
1618 } from "@t3tools/shared/hostProcess";
1719
20+import { writeFileStringAtomically, writeSymbolicLinkAtomically } from "../atomicWrite.ts";
1821 import * as ProcessRunner from "../processRunner.ts";
1922 import { ensurePinnedRuntimeInstalled, pinnedRuntimePaths } from "./pinnedRuntime.ts";
2023
2124 /**
22− * Installs T3 Code as a per-user boot service. Linux-only for now: systemd
23− * user unit + loginctl enable-linger. The service runs a stable or pinned
25+ * Installs T3 Code as a per-user background service: systemd + linger on
26+ * Linux, or a LaunchAgent on macOS. The service runs a stable or pinned
2427 * runtime — never an ephemeral `npx t3` cache whose eviction could break
2528 * startup.
2629 */
@@ -29,6 +32,8 @@ const BOOT_SERVICE_NAME = "t3code"; · 2 unmodified lines
2932
3033 export const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
3134 export const BOOT_SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT";
35+export const BOOT_SERVICE_LAUNCH_AGENT_LABEL = "com.t3tools.t3code.server";
36+export const BOOT_SERVICE_LAUNCH_AGENT_FILE = `${BOOT_SERVICE_LAUNCH_AGENT_LABEL}.plist`;
3237
3338 const EPHEMERAL_CACHE_SEGMENTS = [
3439 "/_npx/", // npx
@@ -76,6 +81,39 @@ export interface BootServicePlan { · 41 unmodified lines
7681 readonly baseDir: string;
7782 readonly logPath: string;
7883 readonly unitPath: string;
84+ /** Captured for launchd, whose default PATH omits common CLI install locations. */
85+ readonly pathEnvironment?: string;
86+}
87+
88+export interface LaunchAgentPaths {
89+ readonly unitPath: string;
90+ readonly activeRuntimeLinkPath: string;
91+ readonly activeEntryPath: string;
92+ readonly serviceTarget: string;
93+}
94+
95+export function launchAgentPaths(
96+ path: Path.Path,
97+ homeDir: string,
98+ baseDir: string,
99+ userId: number,
100+): LaunchAgentPaths {
101+ const activeRuntimeLinkPath = path.join(baseDir, "runtime", "service", "current");
102+ return {
103+ unitPath: path.join(homeDir, "Library", "LaunchAgents", BOOT_SERVICE_LAUNCH_AGENT_FILE),
104+ activeRuntimeLinkPath,
105+ activeEntryPath: path.join(activeRuntimeLinkPath, "node_modules", "t3", "dist", "bin.mjs"),
106+ serviceTarget: `gui/${String(userId)}/${BOOT_SERVICE_LAUNCH_AGENT_LABEL}`,
107+ };
108+}
109+
110+export function escapeLaunchdXml(value: string): string {
111+ return value
112+ .replaceAll("&", "&")
113+ .replaceAll("<", "&lt;")
114+ .replaceAll(">", "&gt;")
115+ .replaceAll('"', "&quot;")
116+ .replaceAll("'", "&apos;");
79117 }
80118
81119 /**
@@ -114,12 +152,61 @@ export function renderBootServiceUnit(plan: BootServicePlan): string { · 32 unmodified lines
114152 ].join("\n");
115153 }
116154
155+/**
156+ * LaunchAgents are loaded for a user's GUI session after login. KeepAlive
157+ * restarts crashes, while the stable entry path lets remote updates switch
158+ * exact runtimes without rewriting or unloading the plist from inside the
159+ * process it owns.
160+ */
161+export function renderBootServiceLaunchAgent(plan: BootServicePlan): string {
162+ const value = escapeLaunchdXml;
163+ return [
164+ '<?xml version="1.0" encoding="UTF-8"?>',
165+ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
166+ '<plist version="1.0">',
167+ "<dict>",
168+ " <key>Label</key>",
169+ ` <string>${BOOT_SERVICE_LAUNCH_AGENT_LABEL}</string>`,
170+ " <key>ProgramArguments</key>",
171+ " <array>",
172+ ` <string>${value(plan.nodePath)}</string>`,
173+ ` <string>${value(plan.t3EntryPath)}</string>`,
174+ " <string>serve</string>",
175+ " </array>",
176+ " <key>EnvironmentVariables</key>",
177+ " <dict>",
178+ " <key>T3CODE_HOME</key>",
179+ ` <string>${value(plan.baseDir)}</string>`,
180+ ` <key>${BOOT_SERVICE_UNIT_ENV}</key>`,
181+ ` <string>${BOOT_SERVICE_LAUNCH_AGENT_LABEL}</string>`,
182+ ...(plan.pathEnvironment === undefined
183+ ? []
184+ : [" <key>PATH</key>", ` <string>${value(plan.pathEnvironment)}</string>`]),
185+ " </dict>",
186+ " <key>WorkingDirectory</key>",
187+ ` <string>${value(plan.baseDir)}</string>`,
188+ " <key>RunAtLoad</key>",
189+ " <true/>",
190+ " <key>KeepAlive</key>",
191+ " <true/>",
192+ " <key>ThrottleInterval</key>",
193+ " <integer>5</integer>",
194+ " <key>StandardOutPath</key>",
195+ ` <string>${value(plan.logPath)}</string>`,
196+ " <key>StandardErrorPath</key>",
197+ ` <string>${value(plan.logPath)}</string>`,
198+ "</dict>",
199+ "</plist>",
200+ "",
201+ ].join("\n");
202+}
203+
117204 export class BootServiceUnsupportedError extends Schema.TaggedErrorClass<BootServiceUnsupportedError>()(
118205 "BootServiceUnsupportedError",
119206 { platform: Schema.String },
120207 ) {
121208 override get message(): string {
122− return `Background setup currently supports Linux with systemd; this machine reports '${this.platform}'.`;
209+ return `Background setup supports Linux with systemd and macOS with launchd; this machine reports '${this.platform}'.`;
123210 }
124211 }
125212
@@ -134,9 +221,13 @@ export class BootServiceCommandError extends Schema.TaggedErrorClass<BootService · 8 unmodified lines
134221 },
135222 ) {
136223 override get message(): string {
137− return this.exitCode === undefined
138− ? `Background setup failed while ${this.step}.`
139− : `Background setup failed while ${this.step} (exit code ${this.exitCode}).`;
224+ const detail =
225+ this.exitCode === undefined
226+ ? `Background setup failed while ${this.step}.`
227+ : `Background setup failed while ${this.step} (exit code ${this.exitCode}).`;
228+ return this.step.includes("LaunchAgent")
229+ ? `${detail} If macOS blocked the background item, allow T3 Code in System Settings > General > Login Items & Extensions.`
230+ : detail;
140231 }
141232 }
142233
@@ -157,7 +248,7 @@ export type BootServiceError = · 14 unmodified lines
157248 export interface BootServiceStatus {
158249 readonly supported: boolean;
159250 readonly installed: boolean;
160− /** False when the installed unit no longer matches what install would write. */
251+ /** False when the installed service no longer matches what install would write. */
161252 readonly current: boolean;
162253 readonly unitPath: string;
163254 readonly logPath: string;
@@ -166,7 +257,7 @@ export interface BootServiceStatus { · 2 unmodified lines
166257 export class BootService extends Context.Service<
167258 BootService,
168259 {
169− /** Installs the pinned runtime + unit, enables linger, starts the service. */
260+ /** Installs the runtime + user service and starts it immediately. */
170261 readonly install: Effect.Effect<BootServicePlan, BootServiceError>;
171262 /**
172263 * Stops and removes the unit; leaves the pinned runtime for reuse.
@@ -192,23 +283,37 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { · 19 unmodified lines
192283 const hostArguments = yield* HostProcessArguments;
193284 const host = input.host ?? {
194285 execPath: hostExecPath,
195− // When running the packed CLI this is dist/bin.mjs; when stable (global
196− // install, repo checkout) the boot service runs this same artifact.
286+ // When running the packed CLI this is dist/bin.mjs. Linux can reuse a
287+ // stable global install or checkout; macOS pins the exact CLI version.
197288 cliEntryPath: hostArguments[1] ?? "",
198289 };
199290 const platform = yield* HostProcessPlatform;
291+ const hostEnvironment = yield* HostProcessEnvironment;
292+ const userId = yield* HostProcessUserId;
200293 const homeDir = yield* Config.string("HOME").pipe(Config.withDefault(""));
201294 const fs = yield* FileSystem.FileSystem;
202295 const path = yield* Path.Path;
203296 const runner = yield* ProcessRunner.ProcessRunner;
204297
205− const unitDir = path.join(homeDir, ".config", "systemd", "user");
206− const unitPath = path.join(unitDir, BOOT_SERVICE_UNIT_FILE);
298+ const systemdUnitDir = path.join(homeDir, ".config", "systemd", "user");
299+ const systemdUnitPath = path.join(systemdUnitDir, BOOT_SERVICE_UNIT_FILE);
300+ const launchAgent =
301+ userId === null ? null : launchAgentPaths(path, homeDir, input.baseDir, userId);
302+ const unitDir =
303+ platform === "darwin" && launchAgent !== null
304+ ? path.dirname(launchAgent.unitPath)
305+ : systemdUnitDir;
306+ const unitPath =
307+ platform === "darwin" && launchAgent !== null ? launchAgent.unitPath : systemdUnitPath;
207308 const logPath = path.join(input.logsDir, "boot-service.log");
208309 const runtimePaths = pinnedRuntimePaths(path, input.baseDir, input.cliVersion);
209310
210− const requireSystemdLinux = Effect.gen(function* () {
211− if (platform !== "linux" || homeDir === "") {
311+ const requireSupportedPlatform = Effect.gen(function* () {
312+ if (
313+ homeDir === "" ||
314+ (platform !== "linux" && platform !== "darwin") ||
315+ (platform === "darwin" && userId === null)
316+ ) {
212317 return yield* new BootServiceUnsupportedError({ platform });
213318 }
214319 });
@@ -244,15 +349,24 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { · 29 unmodified lines
244349 );
245350 });
246351
352+ const runOptionalStep = Effect.fn("cloud.boot_service.run_optional_step")(function* (
353+ command: string,
354+ args: ReadonlyArray<string>,
355+ ) {
356+ return yield* runner.run({ command, args }).pipe(
357+ Effect.map((result) => result.code === 0),
358+ Effect.orElseSucceed(() => false),
359+ );
360+ });
361+
247362 /**
248− * Ensures plannedEntryPath exists before the unit points at it. A stable
249− * install (global bin, repo checkout) is used as-is; an ephemeral cache
250− * entry is replaced by `npm install --prefix`-ing the exact running
251− * version into <baseDir>/runtime/versions/<v>. A real install (not a copy
252− * of bin.mjs) because t3 ships native deps like node-pty.
363+ * Ensures plannedRuntimeEntryPath exists before the service points at it.
364+ * macOS always gets an exact managed runtime so the LaunchAgent can use a
365+ * stable symlink across remote updates. Linux can reuse a stable global or
366+ * checkout entry; ephemeral cache entries are pinned on both platforms.
253367 */
254368 const ensurePinnedRuntime = Effect.gen(function* () {
255− if (!isEphemeralCacheEntry(host.cliEntryPath)) {
369+ if (platform !== "darwin" && !isEphemeralCacheEntry(host.cliEntryPath)) {
256370 return;
257371 }
258372 yield* ensurePinnedRuntimeInstalled({
@@ -286,21 +400,44 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { · 27 unmodified lines
286400 );
287401 });
288402
289− // Where the unit will point: derivable without touching the network, so
290− // status can compare units purely; install materializes it first.
291− const plannedEntryPath = isEphemeralCacheEntry(host.cliEntryPath)
292− ? runtimePaths.entryPath
293− : host.cliEntryPath;
403+ // Where the service definition will point; install materializes it first.
404+ const plannedRuntimeEntryPath =
405+ platform === "darwin" || isEphemeralCacheEntry(host.cliEntryPath)
406+ ? runtimePaths.entryPath
407+ : host.cliEntryPath;
408+ const plannedEntryPath =
409+ platform === "darwin" && launchAgent !== null
410+ ? launchAgent.activeEntryPath
411+ : plannedRuntimeEntryPath;
294412 const plan: BootServicePlan = {
295413 nodePath: host.execPath,
296414 t3EntryPath: plannedEntryPath,
297415 baseDir: input.baseDir,
298416 logPath,
299417 unitPath,
418+ pathEnvironment: hostEnvironment.PATH ?? "/usr/bin:/bin:/usr/sbin:/sbin",
419+ };
420+
421+ const writeUnit = (contents: string) =>
422+ writeFileStringAtomically({ filePath: unitPath, contents }).pipe(
423+ Effect.provideService(FileSystem.FileSystem, fs),
424+ Effect.provideService(Path.Path, path),
425+ );
426+ const writeActiveRuntimeLink = (targetPath: string) => {
427+ if (launchAgent === null) {
428+ return Effect.void;
429+ }
430+ return writeSymbolicLinkAtomically({
431+ linkPath: launchAgent.activeRuntimeLinkPath,
432+ targetPath,
433+ }).pipe(
434+ Effect.provideService(FileSystem.FileSystem, fs),
435+ Effect.provideService(Path.Path, path),
436+ );
300437 };
301438
302439 const install: BootService["Service"]["install"] = Effect.gen(function* () {
303− yield* requireSystemdLinux;
440+ yield* requireSupportedPlatform;
304441 yield* fs
305442 .makeDirectory(input.logsDir, { recursive: true })
306443 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
@@ -316,15 +453,54 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { · 9 unmodified lines
316453 Effect.mapError((cause) => new BootServiceInstallError({ cause })),
317454 );
318455
456+ const previousRuntimeLink =
457+ platform === "darwin" && launchAgent !== null
458+ ? yield* fs.exists(launchAgent.activeRuntimeLinkPath).pipe(
459+ Effect.flatMap((exists) =>
460+ exists
461+ ? fs.readLink(launchAgent.activeRuntimeLinkPath).pipe(Effect.map(Option.some))
462+ : Effect.succeed(Option.none<string>()),
463+ ),
464+ Effect.mapError((cause) => new BootServiceInstallError({ cause })),
465+ )
466+ : Option.none<string>();
467+
319468 yield* fs.makeDirectory(unitDir, { recursive: true }).pipe(
320− Effect.andThen(fs.writeFileString(unitPath, renderBootServiceUnit(plan))),
469+ Effect.andThen(
470+ platform === "darwin"
471+ ? writeActiveRuntimeLink(runtimePaths.versionDir).pipe(
472+ Effect.andThen(writeUnit(renderBootServiceLaunchAgent(plan))),
473+ )
474+ : writeUnit(renderBootServiceUnit(plan)),
475+ ),
321476 Effect.mapError((cause) => new BootServiceInstallError({ cause })),
477+ Effect.tapError(() => rollbackFailedInstall(previousUnit, previousRuntimeLink)),
322478 );
323479
324− // If any activation step fails, remove the unit again: a leftover file
325− // would make service status report it as installed even though it was
326− // never enabled or lingered.
327480 yield* Effect.gen(function* () {
481+ if (platform === "darwin" && launchAgent !== null && userId !== null) {
482+ const domain = `gui/${String(userId)}`;
483+ // An explicit install repairs a background item the user previously
484+ // disabled in System Settings.
485+ yield* runStep("enabling the LaunchAgent", "/bin/launchctl", [
486+ "enable",
487+ launchAgent.serviceTarget,
488+ ]);
489+ // bootout is expected to fail on first install. On repair it stops
490+ // the old job before bootstrap loads the new definition.
491+ yield* runOptionalStep("/bin/launchctl", ["bootout", launchAgent.serviceTarget]);
492+ yield* runStep("loading the LaunchAgent", "/bin/launchctl", [
493+ "bootstrap",
494+ domain,
495+ unitPath,
496+ ]);
497+ yield* runStep("checking the LaunchAgent", "/bin/launchctl", [
498+ "print",
499+ launchAgent.serviceTarget,
500+ ]);
501+ return;
502+ }
503+
328504 yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]);
329505 yield* runStep("enabling the service", "systemctl", [
330506 "--user",
@@ -344,7 +520,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { · 13 unmodified lines
344520 // username argument: loginctl defaults to the calling user, which is
345521 // always right, while $USER can be stale (su without -l) or unset.
346522 yield* runStep("enabling lingering for this user", "loginctl", ["enable-linger"]);
347− }).pipe(Effect.tapError(() => rollbackFailedInstall(previousUnit)));
523+ }).pipe(Effect.tapError(() => rollbackFailedInstall(previousUnit, previousRuntimeLink)));
348524
349525 return plan;
350526 }).pipe(Effect.withSpan("cloud.boot_service.install"));
@@ -356,9 +532,26 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { · 5 unmodified lines
356532 // next lifecycle command misreports the state.
357533 const rollbackFailedInstall = Effect.fn("cloud.boot_service.rollback_failed_install")(function* (
358534 previousUnit: Option.Option<string>,
535+ previousRuntimeLink: Option.Option<string>,
359536 ) {
537+ if (platform === "darwin" && launchAgent !== null && userId !== null) {
538+ yield* runOptionalStep("/bin/launchctl", ["bootout", launchAgent.serviceTarget]);
539+ if (Option.isSome(previousRuntimeLink)) {
540+ yield* writeActiveRuntimeLink(previousRuntimeLink.value).pipe(Effect.ignore);
541+ } else {
542+ yield* fs.remove(launchAgent.activeRuntimeLinkPath).pipe(Effect.ignore);
543+ }
544+ if (Option.isSome(previousUnit)) {
545+ yield* writeUnit(previousUnit.value).pipe(Effect.ignore);
546+ yield* runOptionalStep("/bin/launchctl", ["bootstrap", `gui/${String(userId)}`, unitPath]);
547+ } else {
548+ yield* fs.remove(unitPath).pipe(Effect.ignore);
549+ }
550+ return;
551+ }
552+
360553 if (Option.isSome(previousUnit)) {
361− yield* fs.writeFileString(unitPath, previousUnit.value).pipe(Effect.ignore);
554+ yield* writeUnit(previousUnit.value).pipe(Effect.ignore);
362555 } else {
363556 yield* runStep("cleaning up the service", "systemctl", [
364557 "--user",
@@ -381,13 +574,22 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { · 16 unmodified lines
381574 });
382575
383576 const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () {
384− yield* requireSystemdLinux;
577+ yield* requireSupportedPlatform;
385578 const exists = yield* fs
386579 .exists(unitPath)
387580 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
388581 if (!exists) {
389582 return false;
390583 }
584+ if (platform === "darwin" && launchAgent !== null) {
585+ // A disabled or already-unloaded agent returns non-zero from bootout;
586+ // the plist is still safe to remove and is the durable source of truth.
587+ yield* runOptionalStep("/bin/launchctl", ["bootout", launchAgent.serviceTarget]);
588+ yield* fs
589+ .remove(unitPath)
590+ .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
591+ return true;
592+ }
391593 yield* runStep("stopping the service", "systemctl", [
392594 "--user",
393595 "disable",
@@ -402,7 +604,11 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { · 8 unmodified lines
402604 }).pipe(Effect.withSpan("cloud.boot_service.uninstall"));
403605
404606 const status: BootService["Service"]["status"] = Effect.gen(function* () {
405− if (platform !== "linux" || homeDir === "") {
607+ if (
608+ homeDir === "" ||
609+ (platform !== "linux" && platform !== "darwin") ||
610+ (platform === "darwin" && launchAgent === null)
611+ ) {
406612 return { supported: false, installed: false, current: false, unitPath, logPath };
407613 }
408614 const unitExists = yield* fs.exists(unitPath);
@@ -410,11 +616,25 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { · 1 unmodified line
410616 return { supported: true, installed: false, current: false, unitPath, logPath };
411617 }
412618 const unit = yield* fs.readFileString(unitPath);
619+ const entryExists = yield* fs.exists(plannedEntryPath);
620+ if (platform === "darwin" && launchAgent !== null) {
621+ const activeRuntimeIsCurrent = yield* fs.readLink(launchAgent.activeRuntimeLinkPath).pipe(
622+ Effect.map((target) => target === runtimePaths.versionDir),
623+ Effect.orElseSucceed(() => false),
624+ );
625+ const loaded = yield* runOptionalStep("/bin/launchctl", ["print", launchAgent.serviceTarget]);
626+ const current =
627+ unit === renderBootServiceLaunchAgent(plan) &&
628+ entryExists &&
629+ activeRuntimeIsCurrent &&
630+ loaded;
631+ return { supported: true, installed: true, current, unitPath, logPath };
632+ }
633+
413634 // A unit is current only if it matches what install would write now (an
414635 // older CLI wrote a different runtime/node path) AND the entry point it
415636 // references still exists (a pinned runtime under ~/.t3 can be deleted to
416637 // reclaim space). Either mismatch makes connect offer a repair.
417− const entryExists = yield* fs.exists(plannedEntryPath);
418638 const current = unit === renderBootServiceUnit(plan) && entryExists;
419639 return { supported: true, installed: true, current, unitPath, logPath };
420640 }).pipe(

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