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

bootService.ts

889 lines31.8 KB

1import {
2 HostProcessExecutablePath,
3 HostProcessPlatform,
4 HostProcessUserId,
5} from "@t3tools/shared/hostProcess";
6import * as Config from "effect/Config";
7import * as Context from "effect/Context";
8import * as DateTime from "effect/DateTime";
9import * as Duration from "effect/Duration";
10import * as Effect from "effect/Effect";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Path from "effect/Path";
15import * as Schema from "effect/Schema";
16​
17import * as ProcessRunner from "../processRunner.ts";
18import {
19 ensurePinnedRuntimeInstalled,
20 pinnedRuntimePaths,
21 PinnedRuntimeInstallError,
22} from "./pinnedRuntime.ts";
23import {
24 SERVICE_LAUNCHER_FILE,
25 SERVICE_LAUNCHER_PROTOCOL,
26 SERVICE_STATE_FILE,
27 compareExactServiceVersions,
28 parseServiceState,
29 serviceStateActiveVersion,
30 serviceStateHasPendingUpdate,
31 type ServiceState,
32} from "./serviceProtocol.ts";
33​
34const BOOT_SERVICE_NAME = "t3code";
35const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
36// `.service` suffix keeps the label distinct from the desktop app's bundle id
37// (com.t3tools.t3code), so launchd and TCC records never collide.
38const BOOT_SERVICE_LAUNCHD_LABEL = "com.t3tools.t3code.service";
39const BOOT_SERVICE_PLIST_FILE = `${BOOT_SERVICE_LAUNCHD_LABEL}.plist`;
40const BOOT_SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT";
41​
42/** systemd expands `%` specifiers, including in unquoted append-log paths. */
43function escapeSystemdSpecifiers(value: string): string {
44 return value.replaceAll("%", "%%");
46​
47function quoteSystemdValue(value: string): string {
48 const escaped = escapeSystemdSpecifiers(value);
49 return /[\s"'\\]/.test(escaped)
50 ? `"${escaped.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`
51 : escaped;
53​
54export interface BootServicePlan {
55 readonly nodePath: string;
56 readonly launcherPath: string;
57 readonly baseDir: string;
58 readonly logPath: string;
59 readonly unitPath: string;
61​
62/** Pure renderer: service units cannot rely on the user's shell or PATH. */
63export function renderBootServiceUnit(plan: BootServicePlan): string {
64 // The user manager has no reliable network-online target; server networking retries itself.
65 return [
66 "[Unit]",
67 "Description=T3 Code server",
68 "StartLimitIntervalSec=300",
69 "StartLimitBurst=5",
70 "",
71 "[Service]",
72 "Type=simple",
73 "WorkingDirectory=%h",
74 `Environment=T3CODE_HOME=${quoteSystemdValue(plan.baseDir)}`,
75 `Environment=${BOOT_SERVICE_UNIT_ENV}=${BOOT_SERVICE_UNIT_FILE}`,
76 `ExecStart=${quoteSystemdValue(plan.nodePath)} ${quoteSystemdValue(plan.launcherPath)}`,
77 // Let the launcher mark an explicit stop before it signals the server.
78 // systemd still SIGKILLs the whole cgroup if graceful shutdown times out.
79 "KillMode=mixed",
80 // Agent tool calls run as children of the server, so they share this cgroup.
81 // With the systemd default of OOMPolicy=stop, the kernel killing one greedy
82 // child stops the whole unit: the server, every live agent, and the user's
83 // connection. Keep running and let Restart=always cover the main process.
84 "OOMPolicy=continue",
85 "Restart=always",
86 "RestartSec=5",
87 `StandardOutput=append:${escapeSystemdSpecifiers(plan.logPath)}`,
88 `StandardError=append:${escapeSystemdSpecifiers(plan.logPath)}`,
89 "",
90 "[Install]",
91 "WantedBy=default.target",
92 "",
93 ].join("\n");
95​
96/** Plist values are emitted as XML text nodes; only these three need escaping. */
97function escapeXmlText(value: string): string {
98 return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
100​
101/** Pure renderer: launch agents cannot rely on the user's shell or PATH. */
102export function renderBootServicePlist(
103 plan: BootServicePlan,
104 options: { readonly homeDir: string; readonly environmentPath: string },
105): string {
106 // KeepAlive + ThrottleInterval mirror Restart=always + RestartSec=5. launchd
107 // has no StartLimitBurst analog; a hard crash loop respawns every 5s forever.
108 // ExitTimeOut 90 matches systemd's default TimeoutStopSec. A plain stop
109 // completes within the launcher's 5s child grace, but a stop that queues
110 // behind an in-flight update transition can take much longer; launchd's
111 // system-defined default (5s on current macOS) would SIGKILL the launcher
112 // (and, with it, the process group) mid-handoff.
113 // ProcessType Interactive opts out of background-job resource throttling.
114 // AbandonProcessGroup stays at its default (false): launchd reaps leftover
115 // process-group members only when the launcher itself exits — the analog of
116 // KillMode=mixed's final cgroup kill — and not when the launcher restarts its
117 // child, so agent children survive server updates.
118 return [
119 `<?xml version="1.0" encoding="UTF-8"?>`,
120 `<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">`,
121 `<plist version="1.0">`,
122 `<dict>`,
123 ` <key>Label</key>`,
124 ` <string>${BOOT_SERVICE_LAUNCHD_LABEL}</string>`,
125 ` <key>ProgramArguments</key>`,
126 ` <array>`,
127 ` <string>${escapeXmlText(plan.nodePath)}</string>`,
128 ` <string>${escapeXmlText(plan.launcherPath)}</string>`,
129 ` </array>`,
130 ` <key>EnvironmentVariables</key>`,
131 ` <dict>`,
132 ` <key>PATH</key>`,
133 ` <string>${escapeXmlText(options.environmentPath)}</string>`,
134 ` <key>T3CODE_HOME</key>`,
135 ` <string>${escapeXmlText(plan.baseDir)}</string>`,
136 ` <key>${BOOT_SERVICE_UNIT_ENV}</key>`,
137 ` <string>${BOOT_SERVICE_PLIST_FILE}</string>`,
138 ` </dict>`,
139 ` <key>WorkingDirectory</key>`,
140 ` <string>${escapeXmlText(options.homeDir)}</string>`,
141 ` <key>RunAtLoad</key>`,
142 ` <true/>`,
143 ` <key>KeepAlive</key>`,
144 ` <true/>`,
145 ` <key>ThrottleInterval</key>`,
146 ` <integer>5</integer>`,
147 ` <key>ExitTimeOut</key>`,
148 ` <integer>90</integer>`,
149 ` <key>ProcessType</key>`,
150 ` <string>Interactive</string>`,
151 ` <key>StandardOutPath</key>`,
152 ` <string>${escapeXmlText(plan.logPath)}</string>`,
153 ` <key>StandardErrorPath</key>`,
154 ` <string>${escapeXmlText(plan.logPath)}</string>`,
155 `</dict>`,
156 `</plist>`,
157 ``,
158 ].join("\n");
160​
161export interface BootServiceStep {
162 readonly step: string;
163 readonly command: string;
164 readonly args: ReadonlyArray<string>;
165 /**
166 * Non-zero exit is logged and ignored. Reserved for steps whose common
167 * failures (not loaded, already enabled) leave a state a later strict step
168 * either tolerates or fails loudly on.
169 */
170 readonly optional?: boolean;
171 /** Override the ProcessRunner default (60s) for steps that block longer. */
172 readonly timeout?: Duration.Input;
174​
175/**
176 * Stop commands block until the service manager gives up: 90s by default for
177 * systemd's TimeoutStopSec, and ExitTimeOut=90 in the rendered plist. This
178 * must stay above both, or the runner cancels the stop mid-shutdown and the
179 * next step races a still-loaded service.
180 */
181const STOP_STEP_TIMEOUT = Duration.seconds(120);
182​
183/**
184 * Platform service-manager integration as data: paths, a pure renderer, and
185 * the command steps each flow runs. install/uninstall/status consume this and
186 * never branch on platform.
187 */
188export interface BootServiceManager {
189 readonly kind: "systemd" | "launchd";
190 readonly unitPath: string;
191 readonly render: (plan: BootServicePlan) => string;
192 /** Before rewriting files, when a unit is already installed. */
193 readonly stop: ReadonlyArray<BootServiceStep>;
194 /** After files are written. The last entry starts the service. */
195 readonly activate: ReadonlyArray<BootServiceStep>;
196 /** Best-effort recovery after a failed repair of an installed service. */
197 readonly restart: ReadonlyArray<BootServiceStep>;
198 /** Uninstall, before the unit file is removed. */
199 readonly deactivate: ReadonlyArray<BootServiceStep>;
200 /** Uninstall, after the unit file is removed. */
201 readonly finalize: ReadonlyArray<BootServiceStep>;
203​
204function systemdManager(input: {
205 readonly path: Path.Path;
206 readonly homeDir: string;
207}): BootServiceManager {
208 const unitPath = input.path.join(
209 input.homeDir,
210 ".config",
211 "systemd",
212 "user",
213 BOOT_SERVICE_UNIT_FILE,
214 );
215 return {
216 kind: "systemd",
217 unitPath,
218 render: renderBootServiceUnit,
219 stop: [
220 {
221 step: "stopping the installed service",
222 command: "systemctl",
223 args: ["--user", "stop", BOOT_SERVICE_UNIT_FILE],
224 timeout: STOP_STEP_TIMEOUT,
225 },
226 ],
227 activate: [
228 {
229 step: "reloading systemd user units",
230 command: "systemctl",
231 args: ["--user", "daemon-reload"],
232 },
233 {
234 step: "enabling the service",
235 command: "systemctl",
236 args: ["--user", "enable", BOOT_SERVICE_UNIT_FILE],
237 },
238 // Start last. No administrative state write occurs after this succeeds.
239 {
240 step: "starting the service",
241 command: "systemctl",
242 args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
243 },
244 ],
245 restart: [
246 {
247 step: "restarting the service after a failed update",
248 command: "systemctl",
249 args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
250 },
251 ],
252 deactivate: [
253 {
254 step: "stopping the service",
255 command: "systemctl",
256 args: ["--user", "disable", "--now", BOOT_SERVICE_UNIT_FILE],
257 timeout: STOP_STEP_TIMEOUT,
258 },
259 ],
260 finalize: [
261 {
262 step: "reloading systemd user units",
263 command: "systemctl",
264 args: ["--user", "daemon-reload"],
265 },
266 ],
267 };
269​
270function launchdManager(input: {
271 readonly path: Path.Path;
272 readonly homeDir: string;
273 readonly uid: number;
274 readonly environmentPath: string;
275}): BootServiceManager {
276 const unitPath = input.path.join(
277 input.homeDir,
278 "Library",
279 "LaunchAgents",
280 BOOT_SERVICE_PLIST_FILE,
281 );
282 const domainTarget = `gui/${input.uid}`;
283 const serviceTarget = `${domainTarget}/${BOOT_SERVICE_LAUNCHD_LABEL}`;
284 // bootout/enable are optional: they fail on not-loaded states that are fine
285 // to proceed from. The strict `bootstrap` runs last and is also the start:
286 // loading a RunAtLoad/KeepAlive plist starts the job, so a separate
287 // kickstart would kill and restart a server it just booted. A lingering job
288 // that survived bootout, or a gui domain with nobody logged in at the
289 // screen (SSH install), makes bootstrap fail the flow loudly rather than
290 // silently keeping a stale server.
291 return {
292 kind: "launchd",
293 unitPath,
294 render: (plan) =>
295 renderBootServicePlist(plan, {
296 homeDir: input.homeDir,
297 environmentPath: input.environmentPath,
298 }),
299 // Without --wait, bootout returns in milliseconds while the job drains
300 // for up to ExitTimeOut, and a bootstrap during the drain fails EIO.
301 // --wait (present on modern macOS, absent from the man page) blocks until
302 // the job is removed from the domain; STOP_STEP_TIMEOUT outlives it.
303 stop: [
304 {
305 step: "stopping the installed launch agent",
306 command: "launchctl",
307 args: ["bootout", "--wait", serviceTarget],
308 optional: true,
309 timeout: STOP_STEP_TIMEOUT,
310 },
311 ],
312 activate: [
313 // A persisted `launchctl disable` override refuses bootstrap; clear it.
314 {
315 step: "enabling the launch agent",
316 command: "launchctl",
317 args: ["enable", serviceTarget],
318 optional: true,
319 },
320 // Start last. No administrative state write occurs after this succeeds.
321 {
322 step: "starting the service",
323 command: "launchctl",
324 args: ["bootstrap", domainTarget, unitPath],
325 },
326 ],
327 restart: [
328 {
329 step: "restarting the service after a failed update",
330 command: "launchctl",
331 args: ["bootstrap", domainTarget, unitPath],
332 },
333 ],
334 // No `launchctl disable` here: a persisted override would sabotage a
335 // later reinstall. Removing the plist is what stops the next login load.
336 // A bootout that fails for a reason other than "not loaded" leaves the
337 // job running until logout; the failure is in the boot-service log.
338 deactivate: [
339 {
340 step: "stopping the service",
341 command: "launchctl",
342 args: ["bootout", "--wait", serviceTarget],
343 optional: true,
344 timeout: STOP_STEP_TIMEOUT,
345 },
346 ],
347 finalize: [],
348 };
350​
351/** Undefined means this host cannot run the background service. */
352function selectBootServiceManager(input: {
353 readonly platform: NodeJS.Platform;
354 readonly homeDir: string;
355 readonly uid: number | undefined;
356 readonly path: Path.Path;
357 readonly environmentPath: string;
358}): BootServiceManager | undefined {
359 if (input.homeDir === "") {
360 return undefined;
361 }
362 if (input.platform === "linux") {
363 return systemdManager({ path: input.path, homeDir: input.homeDir });
364 }
365 if (input.platform === "darwin" && input.uid !== undefined) {
366 return launchdManager({
367 path: input.path,
368 homeDir: input.homeDir,
369 uid: input.uid,
370 environmentPath: input.environmentPath,
371 });
372 }
373 return undefined;
375​
376export class BootServiceUnsupportedError extends Schema.TaggedError<BootServiceUnsupportedError>()(
377 "BootServiceUnsupportedError",
378 { platform: Schema.String },
379) {
380 override get message(): string {
381 return `Background setup supports Linux with systemd and macOS with launchd; this machine reports '${this.platform}'.`;
382 }
384​
385export class BootServiceCommandError extends Schema.TaggedError<BootServiceCommandError>()(
386 "BootServiceCommandError",
387 {
388 step: Schema.String,
389 exitCode: Schema.optional(Schema.Number),
390 stdoutLength: Schema.optional(Schema.Number),
391 stderrLength: Schema.optional(Schema.Number),
392 outputTail: Schema.optional(Schema.String),
393 cause: Schema.optional(Schema.Defect()),
394 },
395) {
396 override get message(): string {
397 const base =
398 this.exitCode === undefined
399 ? `Background setup failed while ${this.step}.`
400 : `Background setup failed while ${this.step} (exit code ${this.exitCode}).`;
401 return this.outputTail === undefined || this.outputTail.length === 0
402 ? base
403 : `${base}\n${this.outputTail}`;
404 }
406​
407export class BootServiceInstallError extends Schema.TaggedError<BootServiceInstallError>()(
408 "BootServiceInstallError",
409 { cause: Schema.Defect() },
410) {
411 override get message(): string {
412 return "Could not set up the T3 Code background service.";
413 }
415​
416const BootServiceProblem = Schema.Literals([
417 "user-manager-unavailable",
418 "linger-unavailable",
419 "linger-disabled",
420 "service-disabled",
421 "service-stopped",
422]);
423type BootServiceProblem = typeof BootServiceProblem.Type;
424​
425/** These codes and recovery steps are documented in docs/user/background-service.md. */
426export function formatBootServiceProblem(problem: BootServiceProblem): string {
427 switch (problem) {
428 case "user-manager-unavailable":
429 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.";
430 case "linger-unavailable":
431 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.';
432 case "linger-disabled":
433 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.';
434 case "service-disabled":
435 return "The service is not enabled to start automatically. Run `t3 service update` to repair it.";
436 case "service-stopped":
437 return "The service is not running. Check the service log and `systemctl --user status t3code.service`, then run `t3 service update`.";
438 }
440​
441export class BootServicePrerequisiteError extends Schema.TaggedError<BootServicePrerequisiteError>()(
442 "BootServicePrerequisiteError",
443 { problem: BootServiceProblem, cause: Schema.optional(Schema.Defect()) },
444) {
445 override get message(): string {
446 return `[${this.problem}] ${formatBootServiceProblem(this.problem)}`;
447 }
449​
450export class BootServiceUpdatePendingError extends Schema.TaggedError<BootServiceUpdatePendingError>()(
451 "BootServiceUpdatePendingError",
452 {},
453) {
454 override get message(): string {
455 return "A remote server update is still pending. Wait for it to finish, then retry.";
456 }
458​
459export class BootServiceDowngradeRefusedError extends Schema.TaggedError<BootServiceDowngradeRefusedError>()(
460 "BootServiceDowngradeRefusedError",
461 {
462 installedVersion: Schema.String,
463 targetVersion: Schema.String,
464 },
465) {
466 override get message(): string {
467 return `Refusing to replace t3@${this.installedVersion} with older t3@${this.targetVersion}. Run the command again with --allow-downgrade to continue.`;
468 }
470​
471export type BootServiceError =
472 | BootServiceUnsupportedError
473 | BootServiceCommandError
474 | BootServiceInstallError
475 | BootServicePrerequisiteError
476 | BootServiceUpdatePendingError
477 | BootServiceDowngradeRefusedError;
478​
479export interface BootServiceStatus {
480 readonly supported: boolean;
481 readonly installed: boolean;
482 readonly current: boolean;
483 readonly installedVersion?: string;
484 readonly problems?: ReadonlyArray<BootServiceProblem>;
485 readonly unitPath: string;
486 readonly logPath: string;
488​
489export class BootService extends Context.Service<
490 BootService,
491 {
492 readonly install: (options?: {
493 readonly allowDowngrade?: boolean;
494 }) => Effect.Effect<BootServicePlan, BootServiceError>;
495 readonly uninstall: Effect.Effect<boolean, BootServiceError>;
496 readonly status: Effect.Effect<BootServiceStatus, BootServiceError>;
497 }
498>()("t3/cloud/bootService") {}
499​
500export interface BootServiceHost {
501 readonly execPath: string;
502 readonly launcherSourcePath?: string;
504​
505export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
506 readonly baseDir: string;
507 readonly logsDir: string;
508 readonly cliVersion: string;
509 readonly host?: BootServiceHost;
510}) {
511 const hostExecPath = yield* HostProcessExecutablePath;
512 const platform = yield* HostProcessPlatform;
513 const uid = yield* HostProcessUserId;
514 const homeDir = yield* Config.string("HOME").pipe(Config.withDefault(""));
515 const installerPath = yield* Config.string("PATH").pipe(Config.withDefault(""));
516 const fs = yield* FileSystem.FileSystem;
517 const path = yield* Path.Path;
518 const runner = yield* ProcessRunner.ProcessRunner;
519 const host = input.host ?? { execPath: hostExecPath };
520 const xmlSafeInstallerDirectories = installerPath.split(":").filter(
521 (directory) =>
522 directory.length > 0 &&
523 Array.from(directory).every((character) => {
524 const code = character.charCodeAt(0);
525 return code >= 0x20 || code === 0x09 || code === 0x0a || code === 0x0d;
526 }),
527 );
528 const environmentPath = Array.from(
529 new Set([
530 ...xmlSafeInstallerDirectories,
531 path.dirname(host.execPath),
532 "/opt/homebrew/bin",
533 "/usr/local/bin",
534 "/usr/bin",
535 "/bin",
536 "/usr/sbin",
537 "/sbin",
538 ]),
539 ).join(":");
540​
541 const detectedManager = selectBootServiceManager({
542 platform,
543 homeDir,
544 uid,
545 path,
546 environmentPath,
547 });
548 const unitPath = detectedManager?.unitPath ?? "";
549 const logPath = path.join(input.logsDir, "boot-service.log");
550 const launcherPath = path.join(input.baseDir, "runtime", SERVICE_LAUNCHER_FILE);
551 const statePath = path.join(input.baseDir, "runtime", SERVICE_STATE_FILE);
552 const runtimePaths = pinnedRuntimePaths(path, input.baseDir, input.cliVersion);
553 const launcherSourcePath =
554 host.launcherSourcePath ??
555 path.join(path.dirname(runtimePaths.entryPath), SERVICE_LAUNCHER_FILE);
556 const writeDurably = (filePath: string, contents: string) =>
557 Effect.scoped(
558 Effect.gen(function* () {
559 const directory = path.dirname(filePath);
560 yield* fs.makeDirectory(directory, { recursive: true });
561 const tempPath = yield* fs.makeTempFileScoped({ directory, prefix: ".service-write-" });
562 yield* fs.writeFileString(tempPath, contents, { mode: 0o600 });
563 // Opened read-write: Windows refuses to flush a handle without write access.
564 yield* (yield* fs.open(tempPath, { flag: "r+" })).sync;
565 yield* fs.rename(tempPath, filePath);
566 // Windows has no directory fsync (EPERM); NTFS journals the rename.
567 yield* (yield* fs.open(directory, { flag: "r" })).sync.pipe(
568 Effect.catchIf(
569 (error) => (error.reason.cause as NodeJS.ErrnoException | undefined)?.code === "EPERM",
570 () => Effect.void,
571 ),
572 );
573 }),
574 ).pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
575 const plan: BootServicePlan = {
576 nodePath: host.execPath,
577 launcherPath,
578 baseDir: input.baseDir,
579 logPath,
580 unitPath,
581 };
582​
583 const requireManager = Effect.suspend(() =>
584 detectedManager === undefined
585 ? new BootServiceUnsupportedError({ platform })
586 : Effect.succeed(detectedManager),
587 );
588​
589 const logFailure = (error: { readonly message: string }) =>
590 DateTime.now.pipe(
591 Effect.flatMap((now) =>
592 fs.writeFileString(logPath, `${DateTime.formatIso(now)} ${error.message}\n`, { flag: "a" }),
593 ),
594 Effect.ignore,
595 );
596​
597 const runStep = Effect.fn("cloud.boot_service.run_step")(function* (
598 step: string,
599 command: string,
600 args: ReadonlyArray<string>,
601 options?: { readonly timeout?: Duration.Input },
602 ) {
603 return yield* runner.run({ command, args, timeout: options?.timeout }).pipe(
604 Effect.mapError((cause) => new BootServiceCommandError({ step, cause })),
605 Effect.filterOrFail(
606 (result) => result.code === 0,
607 (result) =>
608 new BootServiceCommandError({
609 step,
610 exitCode: Number(result.code),
611 stdoutLength: result.stdout.length,
612 stderrLength: result.stderr.length,
613 }),
614 ),
615 Effect.tapError(logFailure),
616 );
617 });
618​
619 const runSteps = (steps: ReadonlyArray<BootServiceStep>) =>
620 Effect.forEach(
621 steps,
622 (entry) => {
623 const run = runStep(
624 entry.step,
625 entry.command,
626 entry.args,
627 entry.timeout === undefined ? undefined : { timeout: entry.timeout },
628 );
629 // runStep's tapError already appends the failure to the log, so an
630 // ignored optional step still leaves a trace.
631 return entry.optional === true ? run.pipe(Effect.ignore) : run.pipe(Effect.asVoid);
632 },
633 { discard: true },
634 );
635​
636 const probe = (command: string, args: ReadonlyArray<string>) =>
637 runner.run({ command, args, timeout: Duration.seconds(5) }).pipe(Effect.option);
638 const succeeded = (result: Option.Option<ProcessRunner.ProcessRunOutput>) =>
639 Option.isSome(result) && result.value.code === 0;
640 const lingerArgs = [
641 "show-user",
642 ...(uid === undefined ? [] : [String(uid)]),
643 "--property=Linger",
644 "--value",
645 ];
646 const readSystemdProblems = Effect.fn("cloud.boot_service.read_systemd_problems")(function* (
647 includeService: boolean,
648 ) {
649 const [manager, linger] = yield* Effect.all(
650 [probe("systemctl", ["--user", "show-environment"]), probe("loginctl", lingerArgs)],
651 { concurrency: "unbounded" },
652 );
653 const problems: BootServiceProblem[] = [];
654 if (!succeeded(manager)) problems.push("user-manager-unavailable");
655 const lingering = succeeded(linger) && Option.isSome(linger) ? linger.value.stdout.trim() : "";
656 if (lingering !== "yes") {
657 problems.push(lingering === "no" ? "linger-disabled" : "linger-unavailable");
658 }
659 if (includeService && succeeded(manager)) {
660 const [enabled, active] = yield* Effect.all(
661 [
662 probe("systemctl", ["--user", "is-enabled", BOOT_SERVICE_UNIT_FILE]),
663 probe("systemctl", ["--user", "is-active", BOOT_SERVICE_UNIT_FILE]),
664 ],
665 { concurrency: "unbounded" },
666 );
667 if (
668 !succeeded(enabled) ||
669 (Option.isSome(enabled) && enabled.value.stdout.trim() !== "enabled")
670 ) {
671 problems.push("service-disabled");
672 }
673 if (!succeeded(active)) problems.push("service-stopped");
674 }
675 return problems;
676 });
677​
678 const requireSystemdPrerequisites = Effect.gen(function* () {
679 const problems = yield* readSystemdProblems(false);
680 const unavailable = problems.find((problem) => problem !== "linger-disabled");
681 if (unavailable) return yield* new BootServicePrerequisiteError({ problem: unavailable });
682 if (!problems.includes("linger-disabled")) return;
683 yield* runStep("enabling lingering for this user", "loginctl", [
684 "enable-linger",
685 "--no-ask-password",
686 ...(uid === undefined ? [] : [String(uid)]),
687 ]).pipe(
688 Effect.mapError(
689 (cause) => new BootServicePrerequisiteError({ problem: "linger-disabled", cause }),
690 ),
691 );
692 const remaining = yield* readSystemdProblems(false);
693 if (remaining[0]) return yield* new BootServicePrerequisiteError({ problem: remaining[0] });
694 });
695​
696 const install = Effect.fn("cloud.boot_service.install")(function* (options?: {
697 readonly allowDowngrade?: boolean;
698 }) {
699 const manager = yield* requireManager;
700 yield* fs
701 .makeDirectory(input.logsDir, { recursive: true })
702 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
703​
704 // A permissions failure must not leave a partial install or stop a working server.
705 if (manager.kind === "systemd") {
706 yield* requireSystemdPrerequisites.pipe(Effect.tapError(logFailure));
707 }
708​
709 // Prepare every immutable artifact before stopping the installed unit.
710 yield* ensurePinnedRuntimeInstalled({
711 baseDir: input.baseDir,
712 version: input.cliVersion,
713 fs,
714 path,
715 runner,
716 validate: (runtime) =>
717 runner
718 .run({
719 command: host.execPath,
720 args: [runtime.entryPath, "--version"],
721 timeout: Duration.seconds(30),
722 })
723 .pipe(
724 Effect.mapError(
725 (cause) =>
726 new PinnedRuntimeInstallError({
727 step: "verifying the pinned t3 runtime",
728 cause,
729 }),
730 ),
731 Effect.flatMap((result) => {
732 const reportedVersion = /\bv(\S+)\s*$/.exec(result.stdout)?.[1];
733 return result.code === 0 && reportedVersion === input.cliVersion
734 ? Effect.void
735 : Effect.fail(
736 new PinnedRuntimeInstallError({
737 step: "verifying the pinned t3 runtime",
738 exitCode: Number(result.code),
739 stdoutLength: result.stdout.length,
740 stderrLength: result.stderr.length,
741 }),
742 );
743 }),
744 ),
745 }).pipe(
746 Effect.mapError((error) =>
747 error._tag === "PinnedRuntimeInstallError"
748 ? new BootServiceCommandError({
749 step: error.step,
750 exitCode: error.exitCode,
751 stdoutLength: error.stdoutLength,
752 stderrLength: error.stderrLength,
753 outputTail: error.outputTail,
754 cause: error,
755 })
756 : new BootServiceInstallError({ cause: error }),
757 ),
758 );
759 const launcherSource = yield* fs
760 .readFileString(launcherSourcePath)
761 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
762​
763 const installed = yield* fs
764 .exists(unitPath)
765 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
766 if (installed) {
767 yield* runSteps(manager.stop);
768 }
769​
770 yield* Effect.gen(function* () {
771 if (installed) {
772 const previousStateText = yield* fs.readFileString(statePath).pipe(Effect.option);
773 if (Option.isSome(previousStateText)) {
774 if (serviceStateHasPendingUpdate(previousStateText.value)) {
775 return yield* new BootServiceUpdatePendingError();
776 }
777 // A remote update can finish after the CLI checks status. Read its
778 // final version after the launcher stops and before changing files.
779 const installedVersion = serviceStateActiveVersion(previousStateText.value);
780 if (
781 installedVersion !== undefined &&
782 options?.allowDowngrade !== true &&
783 compareExactServiceVersions(input.cliVersion, installedVersion) < 0
784 ) {
785 return yield* new BootServiceDowngradeRefusedError({
786 installedVersion,
787 targetVersion: input.cliVersion,
788 });
789 }
790 }
791 }
792 yield* fs
793 .makeDirectory(path.dirname(unitPath), { recursive: true })
794 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
795 yield* writeDurably(launcherPath, launcherSource);
796 yield* writeDurably(
797 statePath,
798 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned document.
799 `${JSON.stringify(
800 {
801 protocol: SERVICE_LAUNCHER_PROTOCOL,
802 activeVersion: input.cliVersion,
803 } satisfies ServiceState,
804 null,
805 2,
806 )}\n`,
807 );
808 yield* writeDurably(unitPath, manager.render(plan));
809​
810 yield* runSteps(manager.activate);
811 }).pipe(
812 Effect.tapError(() =>
813 installed ? runSteps(manager.restart).pipe(Effect.ignore) : Effect.void,
814 ),
815 );
816 return plan;
817 });
818​
819 const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () {
820 const manager = yield* requireManager;
821 if (
822 !(yield* fs
823 .exists(unitPath)
824 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))))
825 )
826 return false;
827 yield* runSteps(manager.deactivate);
828 yield* fs
829 .remove(unitPath)
830 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
831 yield* runSteps(manager.finalize);
832 return true;
833 }).pipe(Effect.withSpan("cloud.boot_service.uninstall"));
834​
835 const status: BootService["Service"]["status"] = Effect.gen(function* () {
836 if (detectedManager === undefined) {
837 return { supported: false, installed: false, current: false, unitPath, logPath };
838 }
839 if (!(yield* fs.exists(unitPath))) {
840 return { supported: true, installed: false, current: false, unitPath, logPath };
841 }
842 const [unit, launcherExists, runtimeEntryExists, runtimeSentinel, stateText] =
843 yield* Effect.all([
844 fs.readFileString(unitPath),
845 fs.exists(launcherPath),
846 fs.exists(runtimePaths.entryPath),
847 fs.readFileString(runtimePaths.sentinelPath).pipe(Effect.option),
848 fs.readFileString(statePath).pipe(Effect.option),
849 ]);
850 const state = Option.isSome(stateText) ? parseServiceState(stateText.value) : undefined;
851 const installedVersion = Option.isSome(stateText)
852 ? serviceStateActiveVersion(stateText.value)
853 : undefined;
854 const normalizeUnit = (contents: string) =>
855 detectedManager.kind === "launchd"
856 ? contents.replace(/(<key>PATH<\/key>\n\s*<string>)[^<]*(<\/string>)/, "$1$2")
857 : contents;
858 const problems = detectedManager.kind === "systemd" ? yield* readSystemdProblems(true) : [];
859 return {
860 supported: true,
861 installed: true,
862 ...(installedVersion === undefined ? {} : { installedVersion }),
863 problems,
864 current:
865 problems.length === 0 &&
866 normalizeUnit(unit) === normalizeUnit(detectedManager.render(plan)) &&
867 launcherExists &&
868 runtimeEntryExists &&
869 Option.isSome(runtimeSentinel) &&
870 runtimeSentinel.value.trim() === input.cliVersion &&
871 state?.activeVersion === input.cliVersion &&
872 state?.update?.status !== "pending",
873 unitPath,
874 logPath,
875 };
876 }).pipe(
877 Effect.mapError((cause) => new BootServiceInstallError({ cause })),
878 Effect.withSpan("cloud.boot_service.status"),
879 );
880​
881 return BootService.of({ install, uninstall, status });
882});
883​
884export const layer = (input: {
885 readonly baseDir: string;
886 readonly logsDir: string;
887 readonly cliVersion: string;
888 readonly host?: BootServiceHost;
889}) => Layer.effect(BootService, make(input));