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

bootService.ts

1,112 lines41.0 KB

1import {
2 HostProcessArchitecture,
3 HostProcessExecutablePath,
4 HostProcessPlatform,
5 HostProcessUserId,
6} from "@t3tools/shared/hostProcess";
7import * as Config from "effect/Config";
8import * as Context from "effect/Context";
9import * as DateTime from "effect/DateTime";
10import * as Duration from "effect/Duration";
11import * as Effect from "effect/Effect";
12import * as FileSystem from "effect/FileSystem";
13import * as Layer from "effect/Layer";
14import * as Option from "effect/Option";
15import * as Path from "effect/Path";
16import { HttpClient } from "effect/unstable/http";
17import * as Schema from "effect/Schema";
18​
19import { CLI_RELEASE_BASE_URL_ENV } from "@t3tools/shared/cliRelease";
20​
21import * as ProcessRunner from "../processRunner.ts";
22import {
23 ensurePinnedRuntimeInstalled,
24 pinnedRuntimeCommand,
25 pinnedRuntimePaths,
26 PinnedRuntimeInstallError,
27} from "./pinnedRuntime.ts";
28import {
29 SERVICE_LAUNCHER_PROTOCOL,
30 SERVICE_RESTART_PENDING_FILE,
31 SERVICE_STATE_FILE,
32 compareExactServiceVersions,
33 parseServiceState,
34 serviceStateActiveVersion,
35 serviceStateHasPendingUpdate,
36 type ServiceState,
37} from "./serviceProtocol.ts";
38​
39const BOOT_SERVICE_NAME = "t3code";
40const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
41// `.service` suffix keeps the label distinct from the desktop app's bundle id
42// (com.t3tools.t3code), so launchd and TCC records never collide.
43const BOOT_SERVICE_LAUNCHD_LABEL = "com.t3tools.t3code.service";
44const BOOT_SERVICE_PLIST_FILE = `${BOOT_SERVICE_LAUNCHD_LABEL}.plist`;
45const BOOT_SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT";
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​
59/**
60 * Reads `T3CODE_HOME` back out of a rendered unit or plist. Only values this
61 * file writes are expected, so a quoted systemd value is unquoted and
62 * unescaped the same way `quoteSystemdValue` produced it.
63 */
64export function bootServiceBaseDirOf(contents: string): string | undefined {
65 const systemd = /^Environment=T3CODE_HOME=(.*)$/m.exec(contents)?.[1];
66 if (systemd !== undefined) {
67 const raw = systemd.trim();
68 const unquoted =
69 raw.startsWith('"') && raw.endsWith('"')
70 ? raw.slice(1, -1).replaceAll('\\"', '"').replaceAll("\\\\", "\\")
71 : raw;
72 return unquoted.replaceAll("%%", "%");
73 }
74 const plist = /<key>T3CODE_HOME<\/key>\s*<string>([^<]*)<\/string>/.exec(contents)?.[1];
75 if (plist !== undefined) {
76 return plist.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&amp;", "&");
77 }
78 return undefined;
80​
81export interface BootServicePlan {
82 /**
83 * What the service manager executes. npm-distributed runtimes run the
84 * standalone launcher script with the installing Node; archive-distributed
85 * runtimes run their own executable, which hosts the launcher as a hidden
86 * subcommand so the machine never needs Node.
87 */
88 readonly program: ReadonlyArray<string>;
89 readonly baseDir: string;
90 readonly logPath: string;
91 readonly unitPath: string;
93​
94/** Pure renderer: 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 // Agent tool calls run as children of the server, so they share this cgroup.
113 // With the systemd default of OOMPolicy=stop, the kernel killing one greedy
114 // child stops the whole unit: the server, every live agent, and the user's
115 // connection. Keep running and let Restart=always cover the main process.
116 "OOMPolicy=continue",
117 "Restart=always",
118 "RestartSec=5",
119 `StandardOutput=append:${escapeSystemdSpecifiers(plan.logPath)}`,
120 `StandardError=append:${escapeSystemdSpecifiers(plan.logPath)}`,
121 "",
122 "[Install]",
123 "WantedBy=default.target",
124 "",
125 ].join("\n");
127​
128/** Plist values are emitted as XML text nodes; only these three need escaping. */
129function escapeXmlText(value: string): string {
130 return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
132​
133/** Pure renderer: launch agents cannot rely on the user's shell or PATH. */
134export function renderBootServicePlist(
135 plan: BootServicePlan,
136 options: { readonly homeDir: string; readonly environmentPath: string },
137): string {
138 // KeepAlive + ThrottleInterval mirror Restart=always + RestartSec=5. launchd
139 // has no StartLimitBurst analog; a hard crash loop respawns every 5s forever.
140 // ExitTimeOut 90 matches systemd's default TimeoutStopSec. A plain stop
141 // completes within the launcher's 5s child grace, but a stop that queues
142 // behind an in-flight update transition can take much longer; launchd's
143 // system-defined default (5s on current macOS) would SIGKILL the launcher
144 // (and, with it, the process group) mid-handoff.
145 // ProcessType Interactive opts out of background-job resource throttling.
146 // AbandonProcessGroup stays at its default (false): launchd reaps leftover
147 // process-group members only when the launcher itself exits — the analog of
148 // KillMode=mixed's final cgroup kill — and not when the launcher restarts its
149 // child, so agent children survive server updates.
150 return [
151 `<?xml version="1.0" encoding="UTF-8"?>`,
152 `<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">`,
153 `<plist version="1.0">`,
154 `<dict>`,
155 ` <key>Label</key>`,
156 ` <string>${BOOT_SERVICE_LAUNCHD_LABEL}</string>`,
157 ` <key>ProgramArguments</key>`,
158 ` <array>`,
159 ...plan.program.map((argument) => ` <string>${escapeXmlText(argument)}</string>`),
160 ` </array>`,
161 ` <key>EnvironmentVariables</key>`,
162 ` <dict>`,
163 ` <key>PATH</key>`,
164 ` <string>${escapeXmlText(options.environmentPath)}</string>`,
165 ` <key>T3CODE_HOME</key>`,
166 ` <string>${escapeXmlText(plan.baseDir)}</string>`,
167 ` <key>${BOOT_SERVICE_UNIT_ENV}</key>`,
168 ` <string>${BOOT_SERVICE_PLIST_FILE}</string>`,
169 ` </dict>`,
170 ` <key>WorkingDirectory</key>`,
171 ` <string>${escapeXmlText(options.homeDir)}</string>`,
172 ` <key>RunAtLoad</key>`,
173 ` <true/>`,
174 ` <key>KeepAlive</key>`,
175 ` <true/>`,
176 ` <key>ThrottleInterval</key>`,
177 ` <integer>5</integer>`,
178 ` <key>ExitTimeOut</key>`,
179 ` <integer>90</integer>`,
180 ` <key>ProcessType</key>`,
181 ` <string>Interactive</string>`,
182 ` <key>StandardOutPath</key>`,
183 ` <string>${escapeXmlText(plan.logPath)}</string>`,
184 ` <key>StandardErrorPath</key>`,
185 ` <string>${escapeXmlText(plan.logPath)}</string>`,
186 `</dict>`,
187 `</plist>`,
188 ``,
189 ].join("\n");
191​
192interface BootServiceStepBase {
193 readonly step: string;
194 readonly command: string;
195 readonly args: ReadonlyArray<string>;
196 /** Override the ProcessRunner default (60s) for steps that block longer. */
197 readonly timeout?: Duration.Input;
199​
200export type BootServiceStep = BootServiceStepBase &
201 (
202 | { readonly operation?: "command" }
203 | {
204 readonly operation: "launchd-bootout";
205 readonly verifyAbsent: {
206 readonly serviceTarget: string;
207 readonly notLoadedMessages: ReadonlyArray<string>;
208 };
209 }
210 );
211​
212/**
213 * Stop commands block until the service manager gives up: 90s by default for
214 * systemd's TimeoutStopSec, and ExitTimeOut=90 in the rendered plist. This
215 * must stay above both, or the runner cancels the stop mid-shutdown and the
216 * next step races a still-loaded service.
217 */
218const STOP_STEP_TIMEOUT = Duration.seconds(120);
219const LAUNCHD_STOP_POLL_INTERVAL = Duration.millis(100);
220​
221function launchdOutputLines(result: ProcessRunner.ProcessRunOutput): ReadonlyArray<string> {
222 return `${result.stdout}\n${result.stderr}`
223 .split(/\r?\n/)
224 .map((line) => line.trim())
225 .filter((line) => line !== "");
227​
228export function isConfirmedLaunchdNotLoaded(
229 result: ProcessRunner.ProcessRunOutput,
230 notLoadedMessages: ReadonlyArray<string>,
231): boolean {
232 if (result.code === 0 || result.timedOut) return false;
233 const lines = launchdOutputLines(result);
234 return (
235 (lines.length === 1 && notLoadedMessages.includes(lines[0] ?? "")) ||
236 (lines.length === 2 &&
237 lines[0] === "Bad request." &&
238 notLoadedMessages.includes(lines[1] ?? ""))
239 );
241​
242export function isConfirmedLaunchdBootoutNotLoaded(
243 result: ProcessRunner.ProcessRunOutput,
244): boolean {
245 if (result.code === 0 || result.timedOut) return false;
246 const lines = launchdOutputLines(result);
247 return lines.length === 1 && lines[0] === "Boot-out failed: 3: No such process";
249​
250/**
251 * Platform service-manager integration as data: paths, a pure renderer, and
252 * the command steps each flow runs. install/uninstall/status consume this and
253 * never branch on platform.
254 */
255export interface BootServiceManager {
256 readonly kind: "systemd" | "launchd";
257 readonly unitPath: string;
258 readonly render: (plan: BootServicePlan) => string;
259 /** Before rewriting files, when a unit is already installed. */
260 readonly stop: ReadonlyArray<BootServiceStep>;
261 /** After files are written. The last entry starts the service. */
262 readonly activate: ReadonlyArray<BootServiceStep>;
263 /** Best-effort recovery after a failed repair of an installed service. */
264 readonly restart: ReadonlyArray<BootServiceStep>;
265 /** Uninstall, before the unit file is removed. */
266 readonly deactivate: ReadonlyArray<BootServiceStep>;
267 /** Uninstall, after the unit file is removed. */
268 readonly finalize: ReadonlyArray<BootServiceStep>;
270​
271function systemdManager(input: {
272 readonly path: Path.Path;
273 readonly homeDir: string;
274}): BootServiceManager {
275 const unitPath = input.path.join(
276 input.homeDir,
277 ".config",
278 "systemd",
279 "user",
280 BOOT_SERVICE_UNIT_FILE,
281 );
282 return {
283 kind: "systemd",
284 unitPath,
285 render: renderBootServiceUnit,
286 stop: [
287 {
288 step: "stopping the installed service",
289 command: "systemctl",
290 args: ["--user", "stop", BOOT_SERVICE_UNIT_FILE],
291 timeout: STOP_STEP_TIMEOUT,
292 },
293 ],
294 activate: [
295 {
296 step: "reloading systemd user units",
297 command: "systemctl",
298 args: ["--user", "daemon-reload"],
299 },
300 {
301 step: "enabling the service",
302 command: "systemctl",
303 args: ["--user", "enable", BOOT_SERVICE_UNIT_FILE],
304 },
305 // Start last. No administrative state write occurs after this succeeds.
306 {
307 step: "starting the service",
308 command: "systemctl",
309 args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
310 },
311 ],
312 restart: [
313 {
314 step: "restarting the service after a failed update",
315 command: "systemctl",
316 args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
317 },
318 ],
319 deactivate: [
320 {
321 step: "stopping the service",
322 command: "systemctl",
323 args: ["--user", "disable", "--now", BOOT_SERVICE_UNIT_FILE],
324 timeout: STOP_STEP_TIMEOUT,
325 },
326 ],
327 finalize: [
328 {
329 step: "reloading systemd user units",
330 command: "systemctl",
331 args: ["--user", "daemon-reload"],
332 },
333 ],
334 };
336​
337function launchdManager(input: {
338 readonly path: Path.Path;
339 readonly homeDir: string;
340 readonly uid: number;
341 readonly environmentPath: string;
342}): BootServiceManager {
343 const unitPath = input.path.join(
344 input.homeDir,
345 "Library",
346 "LaunchAgents",
347 BOOT_SERVICE_PLIST_FILE,
348 );
349 const domainTarget = `gui/${input.uid}`;
350 const serviceTarget = `${domainTarget}/${BOOT_SERVICE_LAUNCHD_LABEL}`;
351 const notLoadedMessage = `Could not find service "${BOOT_SERVICE_LAUNCHD_LABEL}" in domain for user gui: ${input.uid}`;
352 const missingDomainMessage = `Could not find domain for user gui: ${input.uid}`;
353 // `bootstrap` runs last and is also the start:
354 // loading a RunAtLoad/KeepAlive plist starts the job, so a separate
355 // kickstart would kill and restart a server it just booted. A lingering job
356 // that survived bootout, or a gui domain with nobody logged in at the
357 // screen (SSH install), makes bootstrap fail the flow loudly rather than
358 // silently keeping a stale server.
359 return {
360 kind: "launchd",
361 unitPath,
362 render: (plan) =>
363 renderBootServicePlist(plan, {
364 homeDir: input.homeDir,
365 environmentPath: input.environmentPath,
366 }),
367 // The supported bootout form can return before a draining job is absent.
368 // Poll the exact label so bootstrap cannot race the prior process.
369 stop: [
370 {
371 step: "stopping the installed launch agent",
372 command: "launchctl",
373 args: ["bootout", serviceTarget],
374 timeout: STOP_STEP_TIMEOUT,
375 operation: "launchd-bootout",
376 verifyAbsent: { serviceTarget, notLoadedMessages: [notLoadedMessage] },
377 },
378 ],
379 activate: [
380 // A persisted `launchctl disable` override refuses bootstrap; clear it.
381 {
382 step: "enabling the launch agent",
383 command: "launchctl",
384 args: ["enable", serviceTarget],
385 },
386 // Start last. No administrative state write occurs after this succeeds.
387 {
388 step: "starting the service",
389 command: "launchctl",
390 args: ["bootstrap", domainTarget, unitPath],
391 },
392 ],
393 restart: [
394 {
395 step: "restarting the service after a failed update",
396 command: "launchctl",
397 args: ["bootstrap", domainTarget, unitPath],
398 },
399 ],
400 // No `launchctl disable` here: a persisted override would sabotage a
401 // later reinstall. Removing the plist is what stops the next login load.
402 deactivate: [
403 {
404 step: "stopping the service",
405 command: "launchctl",
406 args: ["bootout", serviceTarget],
407 timeout: STOP_STEP_TIMEOUT,
408 operation: "launchd-bootout",
409 verifyAbsent: {
410 serviceTarget,
411 notLoadedMessages: [notLoadedMessage, missingDomainMessage],
412 },
413 },
414 ],
415 finalize: [],
416 };
418​
419/** Undefined means this host cannot run the background service. */
420function selectBootServiceManager(input: {
421 readonly platform: NodeJS.Platform;
422 readonly homeDir: string;
423 readonly uid: number | undefined;
424 readonly path: Path.Path;
425 readonly environmentPath: string;
426}): BootServiceManager | undefined {
427 if (input.homeDir === "") {
428 return undefined;
429 }
430 if (input.platform === "linux") {
431 return systemdManager({ path: input.path, homeDir: input.homeDir });
432 }
433 if (input.platform === "darwin" && input.uid !== undefined) {
434 return launchdManager({
435 path: input.path,
436 homeDir: input.homeDir,
437 uid: input.uid,
438 environmentPath: input.environmentPath,
439 });
440 }
441 return undefined;
443​
444export class BootServiceUnsupportedError extends Schema.TaggedError<BootServiceUnsupportedError>()(
445 "BootServiceUnsupportedError",
446 { platform: Schema.String },
447) {
448 override get message(): string {
449 return `Background setup supports Linux with systemd and macOS with launchd; this machine reports '${this.platform}'.`;
450 }
452​
453export class BootServiceCommandError extends Schema.TaggedError<BootServiceCommandError>()(
454 "BootServiceCommandError",
455 {
456 step: Schema.String,
457 exitCode: Schema.optional(Schema.Number),
458 stdoutLength: Schema.optional(Schema.Number),
459 stderrLength: Schema.optional(Schema.Number),
460 timedOut: Schema.optional(Schema.Boolean),
461 cause: Schema.optional(Schema.Defect()),
462 },
463) {
464 override get message(): string {
465 if (this.timedOut === true) {
466 return `Background setup timed out while ${this.step}.`;
467 }
468 return this.exitCode === undefined
469 ? `Background setup failed while ${this.step}.`
470 : `Background setup failed while ${this.step} (exit code ${this.exitCode}).`;
471 }
473​
474export class BootServiceInstallError extends Schema.TaggedError<BootServiceInstallError>()(
475 "BootServiceInstallError",
476 { cause: Schema.Defect() },
477) {
478 override get message(): string {
479 return "Could not set up the T3 Code background service.";
480 }
482​
483const BootServiceProblem = Schema.Literals([
484 "user-manager-unavailable",
485 "linger-unavailable",
486 "linger-disabled",
487 "service-disabled",
488 "service-stopped",
489 "restart-pending",
490]);
491type BootServiceProblem = typeof BootServiceProblem.Type;
492​
493/** These codes and recovery steps are documented in docs/user/background-service.md. */
494export function formatBootServiceProblem(problem: BootServiceProblem): string {
495 switch (problem) {
496 case "user-manager-unavailable":
497 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.";
498 case "linger-unavailable":
499 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.';
500 case "linger-disabled":
501 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.';
502 case "service-disabled":
503 return "The service is not enabled to start automatically. Run `t3 service install` to repair it.";
504 case "service-stopped":
505 return "The service is not running. Check the service log and `systemctl --user status t3code.service`, then run `t3 service install`.";
506 case "restart-pending":
507 return "A newer version is installed but the service is still running the previous one. Run `t3 service restart` to switch.";
508 }
510​
511export class BootServicePrerequisiteError extends Schema.TaggedError<BootServicePrerequisiteError>()(
512 "BootServicePrerequisiteError",
513 { problem: BootServiceProblem, cause: Schema.optional(Schema.Defect()) },
514) {
515 override get message(): string {
516 return `[${this.problem}] ${formatBootServiceProblem(this.problem)}`;
517 }
519​
520export class BootServiceUpdatePendingError extends Schema.TaggedError<BootServiceUpdatePendingError>()(
521 "BootServiceUpdatePendingError",
522 {},
523) {
524 override get message(): string {
525 return "A remote server update is still pending. Wait for it to finish, then retry.";
526 }
528​
529export class BootServiceDowngradeRefusedError extends Schema.TaggedError<BootServiceDowngradeRefusedError>()(
530 "BootServiceDowngradeRefusedError",
531 {
532 installedVersion: Schema.String,
533 targetVersion: Schema.String,
534 },
535) {
536 override get message(): string {
537 return `Refusing to replace t3@${this.installedVersion} with older t3@${this.targetVersion}. Run the command again with --allow-downgrade to continue.`;
538 }
540​
541export type BootServiceError =
542 | BootServiceUnsupportedError
543 | BootServiceCommandError
544 | BootServiceInstallError
545 | BootServicePrerequisiteError
546 | BootServiceUpdatePendingError
547 | BootServiceDowngradeRefusedError;
548​
549export interface BootServiceStatus {
550 readonly supported: boolean;
551 readonly installed: boolean;
552 readonly current: boolean;
553 readonly installedVersion?: string;
554 /**
555 * The T3 home the installed unit serves. The unit name is fixed per user,
556 * so a caller working against another base dir must not treat this service
557 * as its own; `t3 update --base-dir` learned that by restarting the live
558 * server of the machine it ran on.
559 */
560 readonly installedBaseDir?: string;
561 readonly problems?: ReadonlyArray<BootServiceProblem>;
562 readonly unitPath: string;
563 readonly logPath: string;
565​
566export class BootService extends Context.Service<
567 BootService,
568 {
569 readonly install: (options?: {
570 readonly allowDowngrade?: boolean;
571 /**
572 * Write the unit for this version but leave the service on whatever it
573 * is running now. `t3 update` uses this when the user declines the
574 * restart, so a later `t3 service restart` lands on the new version.
575 */
576 readonly start?: boolean;
577 }) => Effect.Effect<BootServicePlan, BootServiceError>;
578 /**
579 * Stop and start the installed service on the version its unit names.
580 * Only when the unit serves this base dir: the unit name is per user, so
581 * another home's service is left alone. Resolves false when nothing was
582 * restarted.
583 */
584 readonly restart: Effect.Effect<boolean, BootServiceError>;
585 readonly uninstall: Effect.Effect<boolean, BootServiceError>;
586 readonly status: Effect.Effect<BootServiceStatus, BootServiceError>;
587 }
588>()("t3/cloud/bootService") {}
589​
590export interface BootServiceHost {
591 readonly execPath: string;
593​
594export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
595 readonly baseDir: string;
596 readonly logsDir: string;
597 readonly cliVersion: string;
598 readonly host?: BootServiceHost;
599}) {
600 const hostExecPath = yield* HostProcessExecutablePath;
601 const platform = yield* HostProcessPlatform;
602 const arch = yield* HostProcessArchitecture;
603 const uid = yield* HostProcessUserId;
604 const httpClient = yield* HttpClient.HttpClient;
605 const releaseBaseUrl = Option.getOrUndefined(
606 yield* Config.string(CLI_RELEASE_BASE_URL_ENV).pipe(Config.option),
607 );
608 const homeDir = yield* Config.string("HOME").pipe(Config.withDefault(""));
609 const installerPath = yield* Config.string("PATH").pipe(Config.withDefault(""));
610 const fs = yield* FileSystem.FileSystem;
611 const path = yield* Path.Path;
612 const runner = yield* ProcessRunner.ProcessRunner;
613 const host = input.host ?? { execPath: hostExecPath };
614 const xmlSafeInstallerDirectories = installerPath.split(":").filter(
615 (directory) =>
616 directory.length > 0 &&
617 Array.from(directory).every((character) => {
618 const code = character.charCodeAt(0);
619 return code >= 0x20 || code === 0x09 || code === 0x0a || code === 0x0d;
620 }),
621 );
622 const environmentPath = Array.from(
623 new Set([
624 ...xmlSafeInstallerDirectories,
625 path.dirname(host.execPath),
626 "/opt/homebrew/bin",
627 "/usr/local/bin",
628 "/usr/bin",
629 "/bin",
630 "/usr/sbin",
631 "/sbin",
632 ]),
633 ).join(":");
634​
635 const detectedManager = selectBootServiceManager({
636 platform,
637 homeDir,
638 uid,
639 path,
640 environmentPath,
641 });
642 const unitPath = detectedManager?.unitPath ?? "";
643 const logPath = path.join(input.logsDir, "boot-service.log");
644 const statePath = path.join(input.baseDir, "runtime", SERVICE_STATE_FILE);
645 const restartPendingPath = path.join(input.baseDir, "runtime", SERVICE_RESTART_PENDING_FILE);
646 const runtimePaths = pinnedRuntimePaths(path, input.baseDir, input.cliVersion, platform);
647 const writeDurably = (filePath: string, contents: string) =>
648 Effect.scoped(
649 Effect.gen(function* () {
650 const directory = path.dirname(filePath);
651 yield* fs.makeDirectory(directory, { recursive: true });
652 const tempPath = yield* fs.makeTempFileScoped({ directory, prefix: ".service-write-" });
653 yield* fs.writeFileString(tempPath, contents, { mode: 0o600 });
654 // Opened read-write: Windows refuses to flush a handle without write access.
655 yield* (yield* fs.open(tempPath, { flag: "r+" })).sync;
656 yield* fs.rename(tempPath, filePath);
657 // Windows has no directory fsync (EPERM); NTFS journals the rename.
658 yield* (yield* fs.open(directory, { flag: "r" })).sync.pipe(
659 Effect.catchIf(
660 (error) => (error.reason.cause as NodeJS.ErrnoException | undefined)?.code === "EPERM",
661 () => Effect.void,
662 ),
663 );
664 }),
665 ).pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
666 // The executable hosts the launcher as a hidden subcommand of itself, so
667 // the unit runs the pinned runtime directly.
668 const plan: BootServicePlan = {
669 program: [runtimePaths.entryPath, "__service-launcher"],
670 baseDir: input.baseDir,
671 logPath,
672 unitPath,
673 };
674​
675 const requireManager = Effect.suspend(() =>
676 detectedManager === undefined
677 ? new BootServiceUnsupportedError({ platform })
678 : Effect.succeed(detectedManager),
679 );
680​
681 const logFailure = (error: { readonly message: string }) =>
682 DateTime.now.pipe(
683 Effect.flatMap((now) =>
684 fs.writeFileString(logPath, `${DateTime.formatIso(now)} ${error.message}\n`, { flag: "a" }),
685 ),
686 Effect.ignore,
687 );
688​
689 const runStep = Effect.fn("cloud.boot_service.run_step")(function* (
690 step: string,
691 command: string,
692 args: ReadonlyArray<string>,
693 options?: { readonly timeout?: Duration.Input },
694 ) {
695 return yield* runner.run({ command, args, timeout: options?.timeout }).pipe(
696 Effect.mapError((cause) => new BootServiceCommandError({ step, cause })),
697 Effect.filterOrFail(
698 (result) => result.code === 0,
699 (result) =>
700 new BootServiceCommandError({
701 step,
702 exitCode: Number(result.code),
703 stdoutLength: result.stdout.length,
704 stderrLength: result.stderr.length,
705 }),
706 ),
707 Effect.tapError(logFailure),
708 );
709 });
710​
711 const runLaunchdBootout = Effect.fn("cloud.boot_service.run_launchd_bootout")(function* (
712 entry: Extract<BootServiceStep, { readonly operation: "launchd-bootout" }>,
713 ) {
714 yield* Effect.gen(function* () {
715 const bootoutResult = yield* runner
716 .run({
717 command: entry.command,
718 args: entry.args,
719 timeout: entry.timeout,
720 timeoutBehavior: "timedOutResult",
721 })
722 .pipe(Effect.mapError((cause) => new BootServiceCommandError({ step: entry.step, cause })));
723 const bootoutError =
724 bootoutResult.code === 0
725 ? undefined
726 : new BootServiceCommandError({
727 step: entry.step,
728 exitCode: bootoutResult.code === null ? undefined : Number(bootoutResult.code),
729 stdoutLength: bootoutResult.stdout.length,
730 stderrLength: bootoutResult.stderr.length,
731 timedOut: bootoutResult.timedOut,
732 });
733 if (
734 bootoutError !== undefined &&
735 !isConfirmedLaunchdBootoutNotLoaded(bootoutResult) &&
736 !isConfirmedLaunchdNotLoaded(bootoutResult, entry.verifyAbsent.notLoadedMessages)
737 ) {
738 return yield* bootoutError;
739 }
740​
741 while (true) {
742 const printResult = yield* runner
743 .run({
744 command: "launchctl",
745 args: ["print", entry.verifyAbsent.serviceTarget],
746 timeoutBehavior: "timedOutResult",
747 })
748 .pipe(
749 Effect.mapError(
750 (cause) =>
751 new BootServiceCommandError({
752 step: "checking whether the launch agent stopped",
753 cause,
754 }),
755 ),
756 );
757 if (isConfirmedLaunchdNotLoaded(printResult, entry.verifyAbsent.notLoadedMessages)) return;
758 if (bootoutError !== undefined) return yield* bootoutError;
759 if (printResult.code !== 0) {
760 return yield* new BootServiceCommandError({
761 step: "checking whether the launch agent stopped",
762 exitCode: printResult.code === null ? undefined : Number(printResult.code),
763 stdoutLength: printResult.stdout.length,
764 stderrLength: printResult.stderr.length,
765 timedOut: printResult.timedOut,
766 });
767 }
768 yield* Effect.sleep(LAUNCHD_STOP_POLL_INTERVAL);
769 }
770 }).pipe(
771 Effect.timeoutOrElse({
772 // One deadline covers both bootout and absence verification. Without
773 // this outer bound, each phase could consume a full stop timeout.
774 duration: entry.timeout ?? STOP_STEP_TIMEOUT,
775 orElse: () =>
776 new BootServiceCommandError({
777 step: "waiting for the launch agent to stop",
778 timedOut: true,
779 }),
780 }),
781 );
782 }, Effect.tapError(logFailure));
783​
784 const runSteps = (steps: ReadonlyArray<BootServiceStep>) =>
785 Effect.forEach(
786 steps,
787 (entry) => {
788 if (entry.operation === "launchd-bootout") return runLaunchdBootout(entry);
789 const run = runStep(
790 entry.step,
791 entry.command,
792 entry.args,
793 entry.timeout === undefined ? undefined : { timeout: entry.timeout },
794 );
795 return run.pipe(Effect.asVoid);
796 },
797 { discard: true },
798 );
799​
800 const probe = (command: string, args: ReadonlyArray<string>) =>
801 runner.run({ command, args, timeout: Duration.seconds(5) }).pipe(Effect.option);
802 const succeeded = (result: Option.Option<ProcessRunner.ProcessRunOutput>) =>
803 Option.isSome(result) && result.value.code === 0;
804 const lingerArgs = [
805 "show-user",
806 ...(uid === undefined ? [] : [String(uid)]),
807 "--property=Linger",
808 "--value",
809 ];
810 const readSystemdProblems = Effect.fn("cloud.boot_service.read_systemd_problems")(function* (
811 includeService: boolean,
812 ) {
813 const [manager, linger] = yield* Effect.all(
814 [probe("systemctl", ["--user", "show-environment"]), probe("loginctl", lingerArgs)],
815 { concurrency: "unbounded" },
816 );
817 const problems: BootServiceProblem[] = [];
818 if (!succeeded(manager)) problems.push("user-manager-unavailable");
819 const lingering = succeeded(linger) && Option.isSome(linger) ? linger.value.stdout.trim() : "";
820 if (lingering !== "yes") {
821 problems.push(lingering === "no" ? "linger-disabled" : "linger-unavailable");
822 }
823 if (includeService && succeeded(manager)) {
824 const [enabled, active] = yield* Effect.all(
825 [
826 probe("systemctl", ["--user", "is-enabled", BOOT_SERVICE_UNIT_FILE]),
827 probe("systemctl", ["--user", "is-active", BOOT_SERVICE_UNIT_FILE]),
828 ],
829 { concurrency: "unbounded" },
830 );
831 if (
832 !succeeded(enabled) ||
833 (Option.isSome(enabled) && enabled.value.stdout.trim() !== "enabled")
834 ) {
835 problems.push("service-disabled");
836 }
837 if (!succeeded(active)) problems.push("service-stopped");
838 }
839 return problems;
840 });
841​
842 const requireSystemdPrerequisites = Effect.gen(function* () {
843 const problems = yield* readSystemdProblems(false);
844 const unavailable = problems.find((problem) => problem !== "linger-disabled");
845 if (unavailable) return yield* new BootServicePrerequisiteError({ problem: unavailable });
846 if (!problems.includes("linger-disabled")) return;
847 yield* runStep("enabling lingering for this user", "loginctl", [
848 "enable-linger",
849 "--no-ask-password",
850 ...(uid === undefined ? [] : [String(uid)]),
851 ]).pipe(
852 Effect.mapError(
853 (cause) => new BootServicePrerequisiteError({ problem: "linger-disabled", cause }),
854 ),
855 );
856 const remaining = yield* readSystemdProblems(false);
857 if (remaining[0]) return yield* new BootServicePrerequisiteError({ problem: remaining[0] });
858 });
859​
860 const install = Effect.fn("cloud.boot_service.install")(function* (options?: {
861 readonly allowDowngrade?: boolean;
862 readonly start?: boolean;
863 }) {
864 const manager = yield* requireManager;
865 yield* fs
866 .makeDirectory(input.logsDir, { recursive: true })
867 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
868​
869 // A permissions failure must not leave a partial install or stop a working server.
870 if (manager.kind === "systemd") {
871 yield* requireSystemdPrerequisites.pipe(Effect.tapError(logFailure));
872 }
873​
874 // Prepare every immutable artifact before stopping the installed unit.
875 yield* ensurePinnedRuntimeInstalled({
876 baseDir: input.baseDir,
877 version: input.cliVersion,
878 fs,
879 path,
880 runner,
881 httpClient,
882 platform,
883 arch,
884 releaseBaseUrl,
885 validate: (runtime) =>
886 runner
887 .run({
888 command: pinnedRuntimeCommand(runtime).command,
889 args: [...pinnedRuntimeCommand(runtime).args, "--version"],
890 timeout: Duration.seconds(30),
891 })
892 .pipe(
893 Effect.mapError(
894 (cause) =>
895 new PinnedRuntimeInstallError({
896 step: "verifying the pinned t3 runtime",
897 cause,
898 }),
899 ),
900 Effect.flatMap((result) => {
901 const reportedVersion = /\bv(\S+)\s*$/.exec(result.stdout)?.[1];
902 return result.code === 0 && reportedVersion === input.cliVersion
903 ? Effect.void
904 : Effect.fail(
905 new PinnedRuntimeInstallError({
906 step: "verifying the pinned t3 runtime",
907 exitCode: Number(result.code),
908 stdoutLength: result.stdout.length,
909 stderrLength: result.stderr.length,
910 }),
911 );
912 }),
913 ),
914 }).pipe(
915 Effect.mapError((error) =>
916 error._tag === "PinnedRuntimeInstallError"
917 ? new BootServiceCommandError({
918 step: error.step,
919 exitCode: error.exitCode,
920 stdoutLength: error.stdoutLength,
921 stderrLength: error.stderrLength,
922 cause: error,
923 })
924 : new BootServiceInstallError({ cause: error }),
925 ),
926 );
927 const installed = yield* fs
928 .exists(unitPath)
929 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
930 // With start=false the service keeps running while its files change. The
931 // launcher reads the state file once at startup and the unit only matters
932 // on the next start, so that is safe as long as the launcher is not in
933 // the middle of a remote update, which is the one time it writes the
934 // state file itself. That case is refused below, before anything is
935 // written, from the same read the downgrade check uses; the stop that
936 // normally serialises against the launcher is skipped on purpose.
937 const start = options?.start !== false;
938 if (installed && start) {
939 yield* runSteps(manager.stop);
940 }
941​
942 yield* Effect.gen(function* () {
943 if (installed) {
944 const previousStateText = yield* fs.readFileString(statePath).pipe(Effect.option);
945 if (Option.isSome(previousStateText)) {
946 if (serviceStateHasPendingUpdate(previousStateText.value)) {
947 return yield* new BootServiceUpdatePendingError();
948 }
949 // A remote update can finish after the CLI checks status. Read its
950 // final version after the launcher stops and before changing files.
951 const installedVersion = serviceStateActiveVersion(previousStateText.value);
952 if (
953 installedVersion !== undefined &&
954 options?.allowDowngrade !== true &&
955 compareExactServiceVersions(input.cliVersion, installedVersion) < 0
956 ) {
957 return yield* new BootServiceDowngradeRefusedError({
958 installedVersion,
959 targetVersion: input.cliVersion,
960 });
961 }
962 }
963 }
964 yield* fs
965 .makeDirectory(path.dirname(unitPath), { recursive: true })
966 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
967 if (!start && installed) {
968 // Written first: once the files below name the new version, the
969 // running service is behind them, and a failure between the two
970 // writes must not leave it looking current. The launcher removes the
971 // marker when it starts, `restart` and a started install do too.
972 yield* fs.writeFileString(restartPendingPath, `${input.cliVersion}\n`, { mode: 0o600 });
973 }
974 yield* writeDurably(
975 statePath,
976 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned document.
977 `${JSON.stringify(
978 {
979 protocol: SERVICE_LAUNCHER_PROTOCOL,
980 activeVersion: input.cliVersion,
981 } satisfies ServiceState,
982 null,
983 2,
984 )}\n`,
985 );
986 if (!start && installed) {
987 // The launcher only writes this file while a remote update is in
988 // flight. One that began after the check above lands either before
989 // this write (then the launcher's copy in memory is what it keeps
990 // acting on, and its next write puts its own outcome back) or after
991 // it, which this read catches: the file no longer says what was just
992 // written, so stop here before repointing the unit.
993 const written = yield* fs.readFileString(statePath);
994 if (serviceStateActiveVersion(written) !== input.cliVersion) {
995 return yield* new BootServiceUpdatePendingError();
996 }
997 }
998 yield* writeDurably(unitPath, manager.render(plan));
999​
1000 if (start) {
1001 yield* runSteps(manager.activate);
1002 yield* fs.remove(restartPendingPath, { force: true });
1004 }).pipe(
1005 Effect.mapError((cause) =>
1006 cause._tag === "PlatformError" ? new BootServiceInstallError({ cause }) : cause,
1007 ),
1008 Effect.tapError(() =>
1009 installed && start ? runSteps(manager.restart).pipe(Effect.ignore) : Effect.void,
1010 ),
1011 );
1012 return plan;
1013 });
1014​
1015 const restart: BootService["Service"]["restart"] = Effect.gen(function* () {
1016 const manager = yield* requireManager;
1017 const unit = yield* fs.readFileString(unitPath).pipe(Effect.option);
1018 if (Option.isNone(unit)) return false;
1019 const installedBaseDir = bootServiceBaseDirOf(unit.value);
1020 if (
1021 installedBaseDir === undefined ||
1022 path.resolve(installedBaseDir) !== path.resolve(input.baseDir)
1023 ) {
1024 return false;
1026 yield* runSteps(manager.stop);
1027 yield* runSteps(manager.activate).pipe(
1028 // Same recovery as a failed repair: a service that was running should
1029 // not be left stopped because daemon-reload or enable failed.
1030 Effect.tapError(() => runSteps(manager.restart).pipe(Effect.ignore)),
1031 );
1032 yield* fs.remove(restartPendingPath, { force: true });
1033 return true;
1034 }).pipe(
1035 Effect.mapError((cause) =>
1036 cause._tag === "PlatformError" ? new BootServiceInstallError({ cause }) : cause,
1037 ),
1038 Effect.withSpan("cloud.boot_service.restart"),
1039 );
1040​
1041 const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () {
1042 const manager = yield* requireManager;
1043 if (
1044 !(yield* fs
1045 .exists(unitPath)
1046 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))))
1048 return false;
1049 yield* runSteps(manager.deactivate);
1050 yield* fs
1051 .remove(unitPath)
1052 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
1053 yield* runSteps(manager.finalize);
1054 return true;
1055 }).pipe(Effect.withSpan("cloud.boot_service.uninstall"));
1056​
1057 const status: BootService["Service"]["status"] = Effect.gen(function* () {
1058 if (detectedManager === undefined) {
1059 return { supported: false, installed: false, current: false, unitPath, logPath };
1061 if (!(yield* fs.exists(unitPath))) {
1062 return { supported: true, installed: false, current: false, unitPath, logPath };
1064 const [unit, runtimeEntryExists, runtimeSentinel, stateText] = yield* Effect.all([
1065 fs.readFileString(unitPath),
1066 fs.exists(runtimePaths.entryPath),
1067 fs.readFileString(runtimePaths.sentinelPath).pipe(Effect.option),
1068 fs.readFileString(statePath).pipe(Effect.option),
1069 ]);
1070 const state = Option.isSome(stateText) ? parseServiceState(stateText.value) : undefined;
1071 const installedVersion = Option.isSome(stateText)
1072 ? serviceStateActiveVersion(stateText.value)
1073 : undefined;
1074 const installedBaseDir = bootServiceBaseDirOf(unit);
1075 const normalizeUnit = (contents: string) =>
1076 detectedManager.kind === "launchd"
1077 ? contents.replace(/(<key>PATH<\/key>\n\s*<string>)[^<]*(<\/string>)/, "$1$2")
1078 : contents;
1079 const problems: BootServiceProblem[] =
1080 detectedManager.kind === "systemd" ? [...(yield* readSystemdProblems(true))] : [];
1081 if (yield* fs.exists(restartPendingPath)) problems.push("restart-pending");
1082 return {
1083 supported: true,
1084 installed: true,
1085 ...(installedVersion === undefined ? {} : { installedVersion }),
1086 ...(installedBaseDir === undefined ? {} : { installedBaseDir }),
1087 problems,
1088 current:
1089 problems.length === 0 &&
1090 normalizeUnit(unit) === normalizeUnit(detectedManager.render(plan)) &&
1091 runtimeEntryExists &&
1092 Option.isSome(runtimeSentinel) &&
1093 runtimeSentinel.value.trim() === input.cliVersion &&
1094 state?.activeVersion === input.cliVersion &&
1095 state?.update?.status !== "pending",
1096 unitPath,
1097 logPath,
1098 };
1099 }).pipe(
1100 Effect.mapError((cause) => new BootServiceInstallError({ cause })),
1101 Effect.withSpan("cloud.boot_service.status"),
1102 );
1103​
1104 return BootService.of({ install, restart, uninstall, status });
1105});
1106​
1107export const layer = (input: {
1108 readonly baseDir: string;
1109 readonly logsDir: string;
1110 readonly cliVersion: string;
1111 readonly host?: BootServiceHost;
1112}) => Layer.effect(BootService, make(input));