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

bootService.ts

1,122 lines41.6 KB

1import * as HostProcess from "@t3tools/shared/HostProcess";
2import * as Config from "effect/Config";
3import * as Context from "effect/Context";
4import * as DateTime from "effect/DateTime";
5import * as Duration from "effect/Duration";
6import * as Effect from "effect/Effect";
7import * as Exit from "effect/Exit";
8import * as FileSystem from "effect/FileSystem";
9import * as Layer from "effect/Layer";
10import * as Option from "effect/Option";
11import * as Path from "effect/Path";
12import { CliError } from "effect/cli";
13import { HttpClient } from "effect/http";
14import * as Schema from "effect/Schema";
15​
16import { CLI_RELEASE_BASE_URL_ENV } from "@t3tools/shared/cliRelease";
17​
18import * as ProcessRunner from "../processRunner.ts";
19import {
20 ensurePinnedRuntimeInstalled,
21 launcherOwnsVersionsDir,
22 pinnedRuntimeCommand,
23 pinnedRuntimePaths,
24 pinnedRuntimeVersionsDir,
25 PinnedRuntimeInstallError,
26} from "./pinnedRuntime.ts";
27import {
28 SERVICE_LAUNCHER_PROTOCOL,
29 SERVICE_RESTART_PENDING_FILE,
30 SERVICE_STATE_FILE,
31 compareExactServiceVersions,
32 parseServiceState,
33 serviceStateActiveVersion,
34 serviceStateHasPendingUpdate,
35 type ServiceState,
36} from "./serviceProtocol.ts";
37​
38const BOOT_SERVICE_NAME = "t3code";
39export const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
40// `.service` suffix keeps the label distinct from the desktop app's bundle id
41// (com.t3tools.t3code), so launchd and TCC records never collide.
42export const BOOT_SERVICE_LAUNCHD_LABEL = "com.t3tools.t3code.service";
43export const BOOT_SERVICE_PLIST_FILE = `${BOOT_SERVICE_LAUNCHD_LABEL}.plist`;
44const BOOT_SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT";
45export const BOOT_SERVICE_LOG_FILE = "boot-service.log";
46​
47/** systemd expands `%` specifiers, including in unquoted append-log paths. */
48function escapeSystemdSpecifiers(value: string): string {
49 return value.replaceAll("%", "%%");
51​
52function quoteSystemdValue(value: string): string {
53 const escaped = escapeSystemdSpecifiers(value);
54 return /[\s"'\\]/.test(escaped)
55 ? `"${escaped.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`
56 : escaped;
58​
59const unquoteSystemdValue = (raw: string) =>
60 (raw.startsWith('"') && raw.endsWith('"')
61 ? raw.slice(1, -1).replaceAll('\\"', '"').replaceAll("\\\\", "\\")
62 : raw
63 ).replaceAll("%%", "%");
64​
65const unescapeXmlText = (value: string) =>
66 value.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&amp;", "&");
67​
68export function bootServiceBaseDirOf(contents: string): string | undefined {
69 const systemd = /^Environment=T3CODE_HOME=(.*)$/m.exec(contents)?.[1];
70 if (systemd !== undefined) return unquoteSystemdValue(systemd.trim());
71 const plist = /<key>T3CODE_HOME<\/key>\s*<string>([^<]*)<\/string>/.exec(contents)?.[1];
72 return plist === undefined ? undefined : unescapeXmlText(plist);
74​
75/** The executable an installed unit or plist starts: the launcher's runtime. */
76export function bootServiceProgramOf(contents: string): string | undefined {
77 const systemd = /^ExecStart=("(?:\\.|[^"\\])*"|\S+)/m.exec(contents)?.[1];
78 if (systemd !== undefined) return unquoteSystemdValue(systemd);
79 const plist = /<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/.exec(
80 contents,
81 )?.[1];
82 return plist === undefined ? undefined : unescapeXmlText(plist);
84​
85export interface BootServicePlan {
86 readonly program: ReadonlyArray<string>;
87 readonly baseDir: string;
88 readonly logPath: string;
89 readonly unitPath: string;
90 /** The manager accepted a detached install; its outcome is written to `logPath`. */
91 readonly handedOff?: boolean;
93​
94/** Service units cannot rely on the user's shell or PATH. */
95export function renderBootServiceUnit(plan: BootServicePlan): string {
96 // The user manager has no reliable network-online target; server networking retries itself.
97 return [
98 "[Unit]",
99 "Description=T3 Code server",
100 "StartLimitIntervalSec=300",
101 "StartLimitBurst=5",
102 "",
103 "[Service]",
104 "Type=simple",
105 "WorkingDirectory=%h",
106 `Environment=T3CODE_HOME=${quoteSystemdValue(plan.baseDir)}`,
107 `Environment=${BOOT_SERVICE_UNIT_ENV}=${BOOT_SERVICE_UNIT_FILE}`,
108 `ExecStart=${plan.program.map(quoteSystemdValue).join(" ")}`,
109 // Let the launcher mark an explicit stop before it signals the server.
110 // systemd still SIGKILLs the whole cgroup if graceful shutdown times out.
111 "KillMode=mixed",
112 // Helpers share this cgroup; default OOMPolicy=stop would stop the unit if one is OOM-killed.
113 "OOMPolicy=continue",
114 "Restart=always",
115 "RestartSec=5",
116 // Weights favor the server over the sibling agents slice; IOWeight needs a delegated io controller.
117 "CPUWeight=1000",
118 "IOWeight=1000",
119 // Reclaim takes the agents' unprotected pages first. The kernel caps this at the
120 // protection of user.slice and user@.service, which only root can grant.
121 "MemoryLow=1536M",
122 // A user manager's own score, the lowest it may set: below its other services (200) and agents (800).
123 // `t3 service protect` lowers it further through a drop-in.
124 "OOMScoreAdjust=100",
125 // systemd-oomd ignores this preference when the watched cgroup is root-owned, as user-1000.slice usually is.
126 "ManagedOOMPreference=avoid",
127 `StandardOutput=append:${escapeSystemdSpecifiers(plan.logPath)}`,
128 `StandardError=append:${escapeSystemdSpecifiers(plan.logPath)}`,
129 "",
130 "[Install]",
131 "WantedBy=default.target",
132 "",
133 ].join("\n");
135​
136function escapeXmlText(value: string): string {
137 return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
139​
140/** Launch agents cannot rely on the user's shell or PATH. */
141export function renderBootServicePlist(
142 plan: BootServicePlan,
143 options: { readonly homeDir: string; readonly environmentPath: string },
144): string {
145 // Allow 90s stops for update handoffs.
146 // Interactive avoids background throttling.
147 // AbandonProcessGroup=false reaps agents only on launcher exit, preserving them across child updates.
148 return [
149 `<?xml version="1.0" encoding="UTF-8"?>`,
150 `<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">`,
151 `<plist version="1.0">`,
152 `<dict>`,
153 ` <key>Label</key>`,
154 ` <string>${BOOT_SERVICE_LAUNCHD_LABEL}</string>`,
155 ` <key>ProgramArguments</key>`,
156 ` <array>`,
157 ...plan.program.map((argument) => ` <string>${escapeXmlText(argument)}</string>`),
158 ` </array>`,
159 ` <key>EnvironmentVariables</key>`,
160 ` <dict>`,
161 ` <key>PATH</key>`,
162 ` <string>${escapeXmlText(options.environmentPath)}</string>`,
163 ` <key>T3CODE_HOME</key>`,
164 ` <string>${escapeXmlText(plan.baseDir)}</string>`,
165 ` <key>${BOOT_SERVICE_UNIT_ENV}</key>`,
166 ` <string>${BOOT_SERVICE_PLIST_FILE}</string>`,
167 ` </dict>`,
168 ` <key>WorkingDirectory</key>`,
169 ` <string>${escapeXmlText(options.homeDir)}</string>`,
170 ` <key>RunAtLoad</key>`,
171 ` <true/>`,
172 ` <key>KeepAlive</key>`,
173 ` <true/>`,
174 ` <key>ThrottleInterval</key>`,
175 ` <integer>5</integer>`,
176 ` <key>ExitTimeOut</key>`,
177 ` <integer>90</integer>`,
178 ` <key>ProcessType</key>`,
179 ` <string>Interactive</string>`,
180 ` <key>StandardOutPath</key>`,
181 ` <string>${escapeXmlText(plan.logPath)}</string>`,
182 ` <key>StandardErrorPath</key>`,
183 ` <string>${escapeXmlText(plan.logPath)}</string>`,
184 `</dict>`,
185 `</plist>`,
186 ``,
187 ].join("\n");
189​
190export interface BootServiceStep {
191 readonly step: string;
192 readonly command: string;
193 readonly args: ReadonlyArray<string>;
194 /** Non-zero exit is logged and ignored. */
195 readonly optional?: boolean;
196 readonly timeout?: Duration.Input;
198​
199/** Must exceed systemd TimeoutStopSec and launchd ExitTimeOut (both 90s) to avoid shutdown races. */
200const STOP_STEP_TIMEOUT = Duration.seconds(120);
201​
202export interface BootServiceManager {
203 readonly kind: "systemd" | "launchd";
204 readonly unitPath: string;
205 readonly render: (plan: BootServicePlan) => string;
206 readonly stop: ReadonlyArray<BootServiceStep>;
207 readonly activate: ReadonlyArray<BootServiceStep>;
208 readonly restart: ReadonlyArray<BootServiceStep>;
209 /** Queue a restart owned by the manager, since stopping would kill the caller. */
210 readonly handoff?: ReadonlyArray<BootServiceStep>;
211 readonly deactivate: ReadonlyArray<BootServiceStep>;
212 readonly finalize: ReadonlyArray<BootServiceStep>;
214​
215function systemdManager(input: {
216 readonly path: Path.Path;
217 readonly unitDir: string;
218}): BootServiceManager {
219 const unitPath = input.path.join(input.unitDir, BOOT_SERVICE_UNIT_FILE);
220 const prepareActivation = [
221 {
222 step: "reloading systemd user units",
223 command: "systemctl",
224 args: ["--user", "daemon-reload"],
225 },
226 {
227 step: "enabling the service",
228 command: "systemctl",
229 args: ["--user", "enable", BOOT_SERVICE_UNIT_FILE],
230 },
231 ];
232 return {
233 kind: "systemd",
234 unitPath,
235 render: renderBootServiceUnit,
236 stop: [
237 {
238 step: "stopping the installed service",
239 command: "systemctl",
240 args: ["--user", "stop", BOOT_SERVICE_UNIT_FILE],
241 timeout: STOP_STEP_TIMEOUT,
242 },
243 ],
244 activate: [
245 ...prepareActivation,
246 {
247 step: "starting the service",
248 command: "systemctl",
249 args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
250 },
251 ],
252 restart: [
253 {
254 step: "restarting the service after a failed update",
255 command: "systemctl",
256 args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
257 },
258 ],
259 handoff: [
260 ...prepareActivation,
261 {
262 step: "restarting the service",
263 command: "systemctl",
264 args: ["--user", "restart", "--no-block", BOOT_SERVICE_UNIT_FILE],
265 },
266 ],
267 deactivate: [
268 {
269 step: "stopping the service",
270 command: "systemctl",
271 args: ["--user", "disable", "--now", BOOT_SERVICE_UNIT_FILE],
272 timeout: STOP_STEP_TIMEOUT,
273 },
274 ],
275 finalize: [
276 {
277 step: "reloading systemd user units",
278 command: "systemctl",
279 args: ["--user", "daemon-reload"],
280 },
281 ],
282 };
284​
285function launchdManager(input: {
286 readonly path: Path.Path;
287 readonly homeDir: string;
288 readonly uid: number;
289 readonly environmentPath: string;
290}): BootServiceManager {
291 const unitPath = input.path.join(
292 input.homeDir,
293 "Library",
294 "LaunchAgents",
295 BOOT_SERVICE_PLIST_FILE,
296 );
297 const domainTarget = `gui/${input.uid}`;
298 const serviceTarget = `${domainTarget}/${BOOT_SERVICE_LAUNCHD_LABEL}`;
299 // Unloaded jobs may reject bootout/enable. Bootstrap starts RunAtLoad/KeepAlive jobs; kickstart would restart them.
300 return {
301 kind: "launchd",
302 unitPath,
303 render: (plan) =>
304 renderBootServicePlist(plan, {
305 homeDir: input.homeDir,
306 environmentPath: input.environmentPath,
307 }),
308 // bootout --wait is undocumented but waits through ExitTimeOut, preventing bootstrap EIO races.
309 stop: [
310 {
311 step: "stopping the installed launch agent",
312 command: "launchctl",
313 args: ["bootout", "--wait", serviceTarget],
314 optional: true,
315 timeout: STOP_STEP_TIMEOUT,
316 },
317 ],
318 activate: [
319 // A persisted `launchctl disable` override refuses bootstrap; clear it.
320 {
321 step: "enabling the launch agent",
322 command: "launchctl",
323 args: ["enable", serviceTarget],
324 optional: true,
325 },
326 {
327 step: "starting the service",
328 command: "launchctl",
329 args: ["bootstrap", domainTarget, unitPath],
330 },
331 ],
332 restart: [
333 {
334 step: "restarting the service after a failed update",
335 command: "launchctl",
336 args: ["bootstrap", domainTarget, unitPath],
337 },
338 ],
339 // Persisted launchctl disable overrides would block reinstall.
340 deactivate: [
341 {
342 step: "stopping the service",
343 command: "launchctl",
344 args: ["bootout", "--wait", serviceTarget],
345 optional: true,
346 timeout: STOP_STEP_TIMEOUT,
347 },
348 ],
349 finalize: [],
350 };
352​
353function selectBootServiceManager(input: {
354 readonly platform: NodeJS.Platform;
355 readonly homeDir: string;
356 readonly xdgConfigHome: string;
357 readonly systemdUnitDir: string | undefined;
358 readonly uid: number | undefined;
359 readonly path: Path.Path;
360 readonly environmentPath: string;
361}): BootServiceManager | undefined {
362 if (input.homeDir === "") {
363 return undefined;
364 }
365 if (input.platform === "linux") {
366 return systemdManager({
367 path: input.path,
368 unitDir:
369 input.systemdUnitDir ??
370 input.path.join(
371 input.path.isAbsolute(input.xdgConfigHome)
372 ? input.xdgConfigHome
373 : input.path.join(input.homeDir, ".config"),
374 "systemd",
375 "user",
376 ),
377 });
378 }
379 if (input.platform === "darwin" && input.uid !== undefined) {
380 return launchdManager({
381 path: input.path,
382 homeDir: input.homeDir,
383 uid: input.uid,
384 environmentPath: input.environmentPath,
385 });
386 }
387 return undefined;
389​
390const decodeSystemdUnitPaths = Schema.decodeUnknownEffect(
391 Schema.fromJsonString(Schema.Struct({ data: Schema.Array(Schema.String) })),
392);
393​
394// The manager may not share the installer's environment; JSON preserves spaces in its paths.
395const readSystemdUnitDirectory = Effect.fn("cloud.boot_service.read_systemd_unit_directory")(
396 function* () {
397 const runner = yield* ProcessRunner.ProcessRunner;
398 const path = yield* Path.Path;
399 const result = yield* runner.run({
400 command: "busctl",
401 args: [
402 "--user",
403 "--json=short",
404 "get-property",
405 "org.freedesktop.systemd1",
406 "/org/freedesktop/systemd1",
407 "org.freedesktop.systemd1.Manager",
408 "UnitPath",
409 ],
410 timeout: Duration.seconds(5),
411 });
412 if (result.code !== 0) return undefined;
413 const { data } = yield* decodeSystemdUnitPaths(result.stdout);
414 // The persistent control directory identifies the manager's config root despite UnitPath overrides.
415 const controlDirectory = data.find(
416 (directory) =>
417 path.isAbsolute(directory) &&
418 directory.endsWith("/systemd/user.control") &&
419 data.includes(directory.slice(0, -".control".length)),
420 );
421 return controlDirectory?.slice(0, -".control".length);
422 },
423 Effect.orElseSucceed(() => undefined),
424);
425​
426export class BootServiceUnsupportedError extends Schema.TaggedError<BootServiceUnsupportedError>()(
427 "BootServiceUnsupportedError",
428 { platform: Schema.String },
429) {
430 override get message(): string {
431 return `Background setup supports Linux with systemd and macOS with launchd; this machine reports '${this.platform}'.`;
432 }
434​
435export class BootServiceCommandError extends Schema.TaggedError<BootServiceCommandError>()(
436 "BootServiceCommandError",
437 {
438 step: Schema.String,
439 exitCode: Schema.optional(Schema.Number),
440 stdoutLength: Schema.optional(Schema.Number),
441 stderrLength: Schema.optional(Schema.Number),
442 cause: Schema.optional(Schema.Defect()),
443 },
444) {
445 override get message(): string {
446 return this.exitCode === undefined
447 ? `Background setup failed while ${this.step}.`
448 : `Background setup failed while ${this.step} (exit code ${this.exitCode}).`;
449 }
451​
452export class BootServiceInstallError extends Schema.TaggedError<BootServiceInstallError>()(
453 "BootServiceInstallError",
454 { cause: Schema.Defect() },
455) {
456 override get message(): string {
457 return "Could not set up the T3 Code background service.";
458 }
460​
461const BootServiceProblem = Schema.Literals([
462 "user-manager-unavailable",
463 "linger-unavailable",
464 "linger-disabled",
465 "service-disabled",
466 "service-stopped",
467 "restart-pending",
468]);
469type BootServiceProblem = typeof BootServiceProblem.Type;
470​
471export function formatBootServiceProblem(problem: BootServiceProblem): string {
472 switch (problem) {
473 case "user-manager-unavailable":
474 return "Cannot reach the systemd user manager. Run `systemctl --user status` in a login session for the service user. Install your distribution's systemd user-session support if it is missing; do not run T3 with sudo.";
475 case "linger-unavailable":
476 return 'Cannot check whether this user can run services after logout. Run `loginctl show-user "$(id -un)" --property=Linger` and check that systemd-logind is available.';
477 case "linger-disabled":
478 return 'Lingering is disabled. T3 Code will stop when your last login session ends and will not start at boot. Run `sudo loginctl enable-linger "$(id -un)"` on this machine, then retry the service command as your normal user.';
479 case "service-disabled":
480 return "The service is not enabled to start automatically. Run `t3 service install` to repair it.";
481 case "service-stopped":
482 return "The service is not running. Check the service log and `systemctl --user status t3code.service`, then run `t3 service install`.";
483 case "restart-pending":
484 return "A newer version is installed but the service is still running the previous one. Run `t3 service restart` to switch.";
485 }
487​
488export class BootServicePrerequisiteError extends Schema.TaggedError<BootServicePrerequisiteError>()(
489 "BootServicePrerequisiteError",
490 { problem: BootServiceProblem, cause: Schema.optional(Schema.Defect()) },
491) {
492 override get message(): string {
493 return `[${this.problem}] ${formatBootServiceProblem(this.problem)}`;
494 }
496​
497export class BootServiceUpdatePendingError extends Schema.TaggedError<BootServiceUpdatePendingError>()(
498 "BootServiceUpdatePendingError",
499 {},
500) {
501 override get message(): string {
502 return "A remote server update is still pending. Wait for it to finish, then retry.";
503 }
505​
506export class BootServiceDowngradeRefusedError extends Schema.TaggedError<BootServiceDowngradeRefusedError>()(
507 "BootServiceDowngradeRefusedError",
508 {
509 installedVersion: Schema.String,
510 targetVersion: Schema.String,
511 },
512) {
513 override get message(): string {
514 return `Refusing to replace t3@${this.installedVersion} with older t3@${this.targetVersion}. Run the command again with --allow-downgrade to continue.`;
515 }
517​
518export const formatBootServiceBaseDirOption = (baseDir: string) =>
519 `--base-dir '${baseDir.replaceAll("'", `'"'"'`)}'`;
520​
521export class BootServiceOtherBaseDirError extends Schema.TaggedError<BootServiceOtherBaseDirError>()(
522 "BootServiceOtherBaseDirError",
523 {
524 installedBaseDir: Schema.String,
525 baseDir: Schema.String,
526 },
527) {
528 override get message(): string {
529 return `The T3 Code service on this machine serves ${this.installedBaseDir}, not ${this.baseDir}. Pass ${formatBootServiceBaseDirOption(this.installedBaseDir)} to manage it, or run \`t3 service uninstall ${formatBootServiceBaseDirOption(this.installedBaseDir)}\` first to move it; both data directories are kept.`;
530 }
531​
532 // A refusal the user fixes by rerunning, so the CLI prints the message, not a stack trace.
533 override get [CliError.userMessage]() {
534 return this.message;
535 }
537​
538export type BootServiceError =
539 | BootServiceUnsupportedError
540 | BootServiceOtherBaseDirError
541 | BootServiceCommandError
542 | BootServiceInstallError
543 | BootServicePrerequisiteError
544 | BootServiceUpdatePendingError
545 | BootServiceDowngradeRefusedError;
546​
547export interface BootServiceStatus {
548 readonly supported: boolean;
549 readonly installed: boolean;
550 readonly current: boolean;
551 readonly installedVersion?: string;
552 readonly installedBaseDir?: string;
553 /** Set when the installed unit serves a different T3 home than this CLI. */
554 readonly otherBaseDir?: string;
555 readonly problems?: ReadonlyArray<BootServiceProblem>;
556 readonly unitPath: string;
557 readonly logPath: string;
559​
560export class BootService extends Context.Service<
561 BootService,
562 {
563 readonly install: (options?: {
564 readonly allowDowngrade?: boolean;
565 readonly start?: boolean;
566 }) => Effect.Effect<BootServicePlan, BootServiceError>;
567 /**
568 * Only when the unit serves this base dir: the unit name is per user, so
569 * another home's service is left alone, which resolves `skipped`. From
570 * inside the service the restart can only be `queued` with the service
571 * manager, since the stop ends this process.
572 */
573 readonly restart: Effect.Effect<"restarted" | "queued" | "skipped", BootServiceError>;
574 /**
575 * Runs the operation with this home's service stopped; other homes are left alone.
576 * Restores a previously enabled or loaded service even if stopping failed.
577 * The operation's failure takes precedence over a restart failure.
578 */
579 readonly withStopped: <A, E, R>(
580 operation: Effect.Effect<A, E, R>,
581 ) => Effect.Effect<A, E | BootServiceError, R>;
582 readonly uninstall: Effect.Effect<boolean, BootServiceError>;
583 readonly status: Effect.Effect<BootServiceStatus, BootServiceError>;
584 }
585>()("t3/cloud/bootService") {}
586​
587export interface BootServiceHost {
588 readonly execPath: string;
590​
591export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
592 readonly baseDir: string;
593 readonly logsDir: string;
594 readonly cliVersion: string;
595 readonly host?: BootServiceHost;
596}) {
597 const hostExecPath = yield* HostProcess.ExecutablePath;
598 const platform = yield* HostProcess.Platform;
599 const arch = yield* HostProcess.Architecture;
600 const uid = yield* HostProcess.UserId;
601 const httpClient = yield* HttpClient.HttpClient;
602 const releaseBaseUrl = Option.getOrUndefined(
603 yield* Config.String(CLI_RELEASE_BASE_URL_ENV).pipe(Config.option),
604 );
605 const homeDir = yield* Config.String("HOME").pipe(Config.withDefault(""));
606 const xdgConfigHome = yield* Config.String("XDG_CONFIG_HOME").pipe(Config.withDefault(""));
607 const installerPath = yield* Config.String("PATH").pipe(Config.withDefault(""));
608 const runningInsideService =
609 (yield* Config.String(BOOT_SERVICE_UNIT_ENV).pipe(Config.withDefault(""))) ===
610 BOOT_SERVICE_UNIT_FILE;
611 const fs = yield* FileSystem.FileSystem;
612 const path = yield* Path.Path;
613 const runner = yield* ProcessRunner.ProcessRunner;
614 const host = input.host ?? { execPath: hostExecPath };
615 const runtimePaths = pinnedRuntimePaths(path, input.baseDir, input.cliVersion, platform);
616 const versionsDir = pinnedRuntimeVersionsDir(path, input.baseDir);
617 const xmlSafeInstallerDirectories = installerPath.split(":").filter(
618 (directory) =>
619 directory.length > 0 &&
620 Array.from(directory).every((character) => {
621 const code = character.charCodeAt(0);
622 return code >= 0x20 || code === 0x09 || code === 0x0a || code === 0x0d;
623 }),
624 );
625 // During an update, the running CLI and a PATH inherited from the service name the runtime
626 // being replaced. The service and its agent shells should find the runtime it starts.
627 const environmentPath = Array.from(
628 new Set(
629 [
630 ...xmlSafeInstallerDirectories,
631 path.dirname(host.execPath),
632 "/opt/homebrew/bin",
633 "/usr/local/bin",
634 "/usr/bin",
635 "/bin",
636 "/usr/sbin",
637 "/sbin",
638 ].map((directory) =>
639 launcherOwnsVersionsDir(path, versionsDir, directory) ? runtimePaths.versionDir : directory,
640 ),
641 ),
642 ).join(":");
643​
644 const systemdUnitDir = platform === "linux" ? yield* readSystemdUnitDirectory() : undefined;
645 const detectedManager = selectBootServiceManager({
646 platform,
647 homeDir,
648 xdgConfigHome,
649 systemdUnitDir,
650 uid,
651 path,
652 environmentPath,
653 });
654 const unitPath = detectedManager?.unitPath ?? "";
655 const logPath = path.join(input.logsDir, BOOT_SERVICE_LOG_FILE);
656 const statePath = path.join(input.baseDir, "runtime", SERVICE_STATE_FILE);
657 const restartPendingPath = path.join(input.baseDir, "runtime", SERVICE_RESTART_PENDING_FILE);
658 const otherBaseDirOf = (unit: string) => {
659 const installedBaseDir = bootServiceBaseDirOf(unit);
660 return installedBaseDir !== undefined &&
661 path.resolve(installedBaseDir) !== path.resolve(input.baseDir)
662 ? installedBaseDir
663 : undefined;
664 };
665 const writeDurably = (filePath: string, contents: string) =>
666 Effect.scoped(
667 Effect.gen(function* () {
668 const directory = path.dirname(filePath);
669 yield* fs.makeDirectory(directory, { recursive: true });
670 const tempPath = yield* fs.makeTempFileScoped({ directory, prefix: ".service-write-" });
671 yield* fs.writeFileString(tempPath, contents, { mode: 0o600 });
672 // Opened read-write: Windows refuses to flush a handle without write access.
673 yield* (yield* fs.open(tempPath, { flag: "r+" })).sync;
674 yield* fs.rename(tempPath, filePath);
675 // Windows has no directory fsync (EPERM); NTFS journals the rename.
676 yield* (yield* fs.open(directory, { flag: "r" })).sync.pipe(
677 Effect.catchIf(
678 (error) => (error.reason.cause as NodeJS.ErrnoException | undefined)?.code === "EPERM",
679 () => Effect.void,
680 ),
681 );
682 }),
683 ).pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
684 const plan: BootServicePlan = {
685 program: [runtimePaths.entryPath, "__service-launcher"],
686 baseDir: input.baseDir,
687 logPath,
688 unitPath,
689 };
690​
691 const requireManager = Effect.suspend(() =>
692 detectedManager === undefined
693 ? new BootServiceUnsupportedError({ platform })
694 : Effect.succeed(detectedManager),
695 );
696​
697 const logFailure = (error: { readonly message: string }) =>
698 DateTime.now.pipe(
699 Effect.flatMap((now) =>
700 fs.writeFileString(logPath, `${DateTime.formatIso(now)} ${error.message}\n`, { flag: "a" }),
701 ),
702 Effect.ignore,
703 );
704​
705 const runStep = Effect.fn("cloud.boot_service.run_step")(function* (
706 step: string,
707 command: string,
708 args: ReadonlyArray<string>,
709 options?: { readonly timeout?: Duration.Input },
710 ) {
711 return yield* runner.run({ command, args, timeout: options?.timeout }).pipe(
712 Effect.mapError((cause) => new BootServiceCommandError({ step, cause })),
713 Effect.filterOrFail(
714 (result) => result.code === 0,
715 (result) =>
716 new BootServiceCommandError({
717 step,
718 exitCode: Number(result.code),
719 stdoutLength: result.stdout.length,
720 stderrLength: result.stderr.length,
721 }),
722 ),
723 Effect.tapError(logFailure),
724 );
725 });
726​
727 const runSteps = (steps: ReadonlyArray<BootServiceStep>) =>
728 Effect.forEach(
729 steps,
730 (entry) => {
731 const run = runStep(
732 entry.step,
733 entry.command,
734 entry.args,
735 entry.timeout === undefined ? undefined : { timeout: entry.timeout },
736 );
737 return entry.optional === true ? run.pipe(Effect.ignore) : run.pipe(Effect.asVoid);
738 },
739 { discard: true },
740 );
741​
742 const probe = (command: string, args: ReadonlyArray<string>) =>
743 runner.run({ command, args, timeout: Duration.seconds(5) }).pipe(Effect.option);
744 const succeeded = (result: Option.Option<ProcessRunner.ProcessRunOutput>) =>
745 Option.isSome(result) && result.value.code === 0;
746 const lingerArgs = [
747 "show-user",
748 ...(uid === undefined ? [] : [String(uid)]),
749 "--property=Linger",
750 "--value",
751 ];
752 const readSystemdProblems = Effect.fn("cloud.boot_service.read_systemd_problems")(function* (
753 includeService: boolean,
754 ) {
755 const [manager, linger] = yield* Effect.all(
756 [probe("systemctl", ["--user", "show-environment"]), probe("loginctl", lingerArgs)],
757 { concurrency: "unbounded" },
758 );
759 const problems: BootServiceProblem[] = [];
760 if (!succeeded(manager)) problems.push("user-manager-unavailable");
761 const lingering = succeeded(linger) && Option.isSome(linger) ? linger.value.stdout.trim() : "";
762 if (lingering !== "yes") {
763 problems.push(lingering === "no" ? "linger-disabled" : "linger-unavailable");
764 }
765 if (includeService && succeeded(manager)) {
766 const [enabled, active] = yield* Effect.all(
767 [
768 probe("systemctl", ["--user", "is-enabled", BOOT_SERVICE_UNIT_FILE]),
769 probe("systemctl", ["--user", "is-active", BOOT_SERVICE_UNIT_FILE]),
770 ],
771 { concurrency: "unbounded" },
772 );
773 if (
774 !succeeded(enabled) ||
775 (Option.isSome(enabled) && enabled.value.stdout.trim() !== "enabled")
776 ) {
777 problems.push("service-disabled");
778 }
779 if (!succeeded(active)) problems.push("service-stopped");
780 }
781 return problems;
782 });
783​
784 const requireSystemdPrerequisites = Effect.gen(function* () {
785 const problems = yield* readSystemdProblems(false);
786 const unavailable = problems.find((problem) => problem !== "linger-disabled");
787 if (unavailable) return yield* new BootServicePrerequisiteError({ problem: unavailable });
788 if (!problems.includes("linger-disabled")) return;
789 yield* runStep("enabling lingering for this user", "loginctl", [
790 "enable-linger",
791 "--no-ask-password",
792 ...(uid === undefined ? [] : [String(uid)]),
793 ]).pipe(
794 Effect.mapError(
795 (cause) => new BootServicePrerequisiteError({ problem: "linger-disabled", cause }),
796 ),
797 );
798 const remaining = yield* readSystemdProblems(false);
799 if (remaining[0]) return yield* new BootServicePrerequisiteError({ problem: remaining[0] });
800 });
801​
802 const install = Effect.fn("cloud.boot_service.install")(function* (options?: {
803 readonly allowDowngrade?: boolean;
804 readonly start?: boolean;
805 }) {
806 const manager = yield* requireManager;
807 // The unit is per user. Rewriting one that serves another home moves the
808 // service onto this home's data, which looks like every thread vanished.
809 const existingUnit = yield* fs.readFileString(unitPath).pipe(Effect.option);
810 const installedBaseDir = Option.isSome(existingUnit)
811 ? otherBaseDirOf(existingUnit.value)
812 : undefined;
813 if (installedBaseDir !== undefined) {
814 return yield* new BootServiceOtherBaseDirError({ installedBaseDir, baseDir: input.baseDir });
815 }
816 yield* fs
817 .makeDirectory(input.logsDir, { recursive: true })
818 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
819​
820 if (manager.kind === "systemd") {
821 yield* requireSystemdPrerequisites.pipe(Effect.tapError(logFailure));
822 }
823​
824 yield* ensurePinnedRuntimeInstalled({
825 baseDir: input.baseDir,
826 version: input.cliVersion,
827 fs,
828 path,
829 runner,
830 httpClient,
831 platform,
832 arch,
833 releaseBaseUrl,
834 validate: (runtime) =>
835 runner
836 .run({
837 command: pinnedRuntimeCommand(runtime).command,
838 args: [...pinnedRuntimeCommand(runtime).args, "--version"],
839 timeout: Duration.seconds(30),
840 })
841 .pipe(
842 Effect.mapError(
843 (cause) =>
844 new PinnedRuntimeInstallError({
845 step: "verifying the pinned t3 runtime",
846 cause,
847 }),
848 ),
849 Effect.flatMap((result) => {
850 const reportedVersion = /\bv(\S+)\s*$/.exec(result.stdout)?.[1];
851 return result.code === 0 && reportedVersion === input.cliVersion
852 ? Effect.void
853 : Effect.fail(
854 new PinnedRuntimeInstallError({
855 step: "verifying the pinned t3 runtime",
856 exitCode: Number(result.code),
857 stdoutLength: result.stdout.length,
858 stderrLength: result.stderr.length,
859 }),
860 );
861 }),
862 ),
863 }).pipe(
864 Effect.mapError((error) =>
865 error._tag === "PinnedRuntimeInstallError"
866 ? new BootServiceCommandError({
867 step: error.step,
868 exitCode: error.exitCode,
869 stdoutLength: error.stdoutLength,
870 stderrLength: error.stderrLength,
871 cause: error,
872 })
873 : new BootServiceInstallError({ cause: error }),
874 ),
875 );
876 const installed = yield* fs
877 .exists(unitPath)
878 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
879 // With start=false, changing startup-only files is safe except during a remote update,
880 // when the launcher also writes its state file.
881 const start = options?.start !== false;
882 if (installed && start && runningInsideService && manager.kind === "systemd") {
883 // Stopping the unit from inside it kills this process before the start.
884 // A transient unit runs the same install from outside, stop first, so it
885 // still serialises with a remote update the launcher may be starting.
886 yield* runStep("handing the install to a transient unit", "systemd-run", [
887 "--user",
888 "--collect",
889 "--quiet",
890 // Transient properties reach systemd literally, unlike unit-file specifiers.
891 `--property=StandardOutput=append:${logPath}`,
892 `--property=StandardError=append:${logPath}`,
893 `--setenv=${BOOT_SERVICE_UNIT_ENV}=`,
894 runtimePaths.entryPath,
895 "service",
896 "install",
897 "--base-dir",
898 // systemd expands $VAR in arguments (not in the executable path).
899 input.baseDir.replaceAll("$", () => "$$"),
900 ...(options?.allowDowngrade === true ? ["--allow-downgrade"] : []),
901 ]);
902 return { ...plan, handedOff: true };
903 }
904 if (installed && start) {
905 yield* runSteps(manager.stop);
906 }
907​
908 yield* Effect.gen(function* () {
909 if (installed) {
910 const previousStateText = yield* fs.readFileString(statePath).pipe(Effect.option);
911 if (Option.isSome(previousStateText)) {
912 if (serviceStateHasPendingUpdate(previousStateText.value)) {
913 return yield* new BootServiceUpdatePendingError();
914 }
915 // Read the final version after stopping the launcher; a remote update may finish after the status check.
916 const installedVersion = serviceStateActiveVersion(previousStateText.value);
917 if (
918 installedVersion !== undefined &&
919 options?.allowDowngrade !== true &&
920 compareExactServiceVersions(input.cliVersion, installedVersion) < 0
921 ) {
922 return yield* new BootServiceDowngradeRefusedError({
923 installedVersion,
924 targetVersion: input.cliVersion,
925 });
926 }
927 }
928 }
929 yield* fs
930 .makeDirectory(path.dirname(unitPath), { recursive: true })
931 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
932 // Files can match the new version even when activation fails; keep that install retryable.
933 yield* fs.writeFileString(restartPendingPath, `${input.cliVersion}\n`, { mode: 0o600 });
934 yield* writeDurably(
935 statePath,
936 // @effect-diagnostics-next-line globalJsonInEffect:off - fixed launcher-owned document.
937 `${JSON.stringify(
938 {
939 protocol: SERVICE_LAUNCHER_PROTOCOL,
940 activeVersion: input.cliVersion,
941 } satisfies ServiceState,
942 null,
943 2,
944 )}\n`,
945 );
946 if (!start && installed) {
947 // A concurrent remote update can overwrite launcher state; detect it before repointing the unit.
948 const written = yield* fs.readFileString(statePath);
949 if (serviceStateActiveVersion(written) !== input.cliVersion) {
950 return yield* new BootServiceUpdatePendingError();
951 }
952 }
953 yield* writeDurably(unitPath, manager.render(plan));
954​
955 if (start) {
956 yield* runSteps(manager.activate);
957 yield* fs.remove(restartPendingPath, { force: true });
958 }
959 }).pipe(
960 Effect.mapError((cause) =>
961 cause._tag === "PlatformError" ? new BootServiceInstallError({ cause }) : cause,
962 ),
963 Effect.tapError(() =>
964 installed && start ? runSteps(manager.restart).pipe(Effect.ignore) : Effect.void,
965 ),
966 );
967 return plan;
968 });
969​
970 const restart: BootService["Service"]["restart"] = Effect.gen(function* () {
971 const manager = yield* requireManager;
972 const unit = yield* fs.readFileString(unitPath).pipe(Effect.option);
973 if (Option.isNone(unit)) return "skipped" as const;
974 const installedBaseDir = bootServiceBaseDirOf(unit.value);
975 if (
976 installedBaseDir === undefined ||
977 path.resolve(installedBaseDir) !== path.resolve(input.baseDir)
978 ) {
979 return "skipped" as const;
980 }
981 // Writes no state, and the launcher lets an update transition in flight
982 // finish before the queued stop tears it down.
983 if (runningInsideService && manager.handoff !== undefined) {
984 yield* runSteps(manager.handoff);
985 return "queued" as const;
986 }
987 yield* runSteps(manager.stop);
988 yield* runSteps(manager.activate).pipe(
989 Effect.tapError(() => runSteps(manager.restart).pipe(Effect.ignore)),
990 );
991 yield* fs.remove(restartPendingPath, { force: true });
992 return "restarted" as const;
993 }).pipe(
994 Effect.mapError((cause) =>
995 cause._tag === "PlatformError" ? new BootServiceInstallError({ cause }) : cause,
996 ),
997 Effect.withSpan("cloud.boot_service.restart"),
998 );
999​
1000 const withStopped = Effect.fn("cloud.boot_service.with_stopped")(function* <A, E, R>(
1001 operation: Effect.Effect<A, E, R>,
1002 ): Effect.fn.Return<A, E | BootServiceError, R> {
1003 if (detectedManager === undefined) return yield* operation;
1004 const manager = detectedManager;
1005 const unit = yield* fs.readFileString(unitPath).pipe(Effect.option);
1006 if (Option.isNone(unit)) return yield* operation;
1007 const installedBaseDir = bootServiceBaseDirOf(unit.value);
1008 if (
1009 installedBaseDir === undefined ||
1010 path.resolve(installedBaseDir) !== path.resolve(input.baseDir)
1011 ) {
1012 return yield* operation;
1014 // `is-active` misses crash-looping systemd units; launchd can be loaded without a pid.
1015 // Always stop; restore only if previously active, enabled, or loaded,
1016 // so disabled crash loops stay stopped.
1017 const restore =
1018 manager.kind === "systemd"
1019 ? yield* Effect.map(
1020 Effect.all(
1022 probe("systemctl", ["--user", "is-enabled", BOOT_SERVICE_UNIT_FILE]),
1023 probe("systemctl", ["--user", "is-active", BOOT_SERVICE_UNIT_FILE]),
1024 ],
1025 { concurrency: "unbounded" },
1026 ),
1027 ([enabled, active]) => succeeded(active) || succeeded(enabled),
1029 : succeeded(
1030 yield* probe("launchctl", ["print", `gui/${uid}/${BOOT_SERVICE_LAUNCHD_LABEL}`]),
1031 );
1032 return yield* Effect.acquireUseRelease(
1033 // Require every stop before repair when restoring, so the server releases the database.
1034 // Otherwise stops are best-effort; launchd rejects bootout of an unloaded job.
1035 // A failed stop may still stop the service, so restoration runs either way.
1036 runSteps(manager.stop.map((step) => ({ ...step, optional: !restore }))).pipe(Effect.exit),
1037 (stopped): Effect.Effect<A, E | BootServiceError, R> =>
1038 Exit.isSuccess(stopped) ? operation : Effect.failCause(stopped.cause),
1039 (_, exit) => {
1040 if (!restore) return Effect.void;
1041 // Start only: `activate` would also enable a unit the user disabled.
1042 // When the operation itself failed, its error is the one worth reporting.
1043 const start = runSteps(manager.restart);
1044 return Exit.isFailure(exit) ? Effect.ignore(start) : start;
1045 },
1046 );
1047 });
1048​
1049 const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () {
1050 const manager = yield* requireManager;
1051 if (
1052 !(yield* fs
1053 .exists(unitPath)
1054 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))))
1056 return false;
1057 yield* runSteps(manager.deactivate);
1058 yield* fs
1059 .remove(unitPath)
1060 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
1061 yield* runSteps(manager.finalize);
1062 return true;
1063 }).pipe(Effect.withSpan("cloud.boot_service.uninstall"));
1064​
1065 const status: BootService["Service"]["status"] = Effect.gen(function* () {
1066 if (detectedManager === undefined) {
1067 return { supported: false, installed: false, current: false, unitPath, logPath };
1069 if (!(yield* fs.exists(unitPath))) {
1070 return { supported: true, installed: false, current: false, unitPath, logPath };
1072 const [unit, runtimeEntryExists, runtimeSentinel, stateText] = yield* Effect.all([
1073 fs.readFileString(unitPath),
1074 fs.exists(runtimePaths.entryPath),
1075 fs.readFileString(runtimePaths.sentinelPath).pipe(Effect.option),
1076 fs.readFileString(statePath).pipe(Effect.option),
1077 ]);
1078 const state = Option.isSome(stateText) ? parseServiceState(stateText.value) : undefined;
1079 const installedVersion = Option.isSome(stateText)
1080 ? serviceStateActiveVersion(stateText.value)
1081 : undefined;
1082 const installedBaseDir = bootServiceBaseDirOf(unit);
1083 const otherBaseDir = otherBaseDirOf(unit);
1084 const normalizeUnit = (contents: string) =>
1085 detectedManager.kind === "launchd"
1086 ? contents.replace(/(<key>PATH<\/key>\n\s*<string>)[^<]*(<\/string>)/, "$1$2")
1087 : contents;
1088 const problems: BootServiceProblem[] =
1089 detectedManager.kind === "systemd" ? [...(yield* readSystemdProblems(true))] : [];
1090 if (yield* fs.exists(restartPendingPath)) problems.push("restart-pending");
1091 return {
1092 supported: true,
1093 installed: true,
1094 ...(installedVersion === undefined ? {} : { installedVersion }),
1095 ...(installedBaseDir === undefined ? {} : { installedBaseDir }),
1096 ...(otherBaseDir === undefined ? {} : { otherBaseDir }),
1097 problems,
1098 current:
1099 problems.length === 0 &&
1100 normalizeUnit(unit) === normalizeUnit(detectedManager.render(plan)) &&
1101 runtimeEntryExists &&
1102 Option.isSome(runtimeSentinel) &&
1103 runtimeSentinel.value.trim() === input.cliVersion &&
1104 state?.activeVersion === input.cliVersion &&
1105 state?.update?.status !== "pending",
1106 unitPath,
1107 logPath,
1108 };
1109 }).pipe(
1110 Effect.mapError((cause) => new BootServiceInstallError({ cause })),
1111 Effect.withSpan("cloud.boot_service.status"),
1112 );
1113​
1114 return BootService.of({ install, restart, withStopped, uninstall, status });
1115});
1116​
1117export const layer = (input: {
1118 readonly baseDir: string;
1119 readonly logsDir: string;
1120 readonly cliVersion: string;
1121 readonly host?: BootServiceHost;
1122}) => Layer.effect(BootService, make(input));