Open History to see the last commit
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("%", "%%");
45}
46
47function quoteSystemdValue(value: string): string {
48 const escaped = escapeSystemdSpecifiers(value);
49 return /[\s"'\\]/.test(escaped)
50 ? `"${escaped.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`
51 : escaped;
52}
53
54export interface BootServicePlan {
55 readonly nodePath: string;
56 readonly launcherPath: string;
57 readonly baseDir: string;
58 readonly logPath: string;
59 readonly unitPath: string;
60}
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");
94}
95
96/** Plist values are emitted as XML text nodes; only these three need escaping. */
97function escapeXmlText(value: string): string {
98 return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
99}
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");
159}
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;
173}
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>;
202}
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 };
268}
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 };
349}
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;
374}
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 }
383}
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 cause: Schema.optional(Schema.Defect()),
393 },
394) {
395 override get message(): string {
396 return this.exitCode === undefined
397 ? `Background setup failed while ${this.step}.`
398 : `Background setup failed while ${this.step} (exit code ${this.exitCode}).`;
399 }
400}
401
402export class BootServiceInstallError extends Schema.TaggedError<BootServiceInstallError>()(
403 "BootServiceInstallError",
404 { cause: Schema.Defect() },
405) {
406 override get message(): string {
407 return "Could not set up the T3 Code background service.";
408 }
409}
410
411const BootServiceProblem = Schema.Literals([
412 "user-manager-unavailable",
413 "linger-unavailable",
414 "linger-disabled",
415 "service-disabled",
416 "service-stopped",
417]);
418type BootServiceProblem = typeof BootServiceProblem.Type;
419
420/** These codes and recovery steps are documented in docs/user/background-service.md. */
421export function formatBootServiceProblem(problem: BootServiceProblem): string {
422 switch (problem) {
423 case "user-manager-unavailable":
424 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.";
425 case "linger-unavailable":
426 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.';
427 case "linger-disabled":
428 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.';
429 case "service-disabled":
430 return "The service is not enabled to start automatically. Run `t3 service update` to repair it.";
431 case "service-stopped":
432 return "The service is not running. Check the service log and `systemctl --user status t3code.service`, then run `t3 service update`.";
433 }
434}
435
436export class BootServicePrerequisiteError extends Schema.TaggedError<BootServicePrerequisiteError>()(
437 "BootServicePrerequisiteError",
438 { problem: BootServiceProblem, cause: Schema.optional(Schema.Defect()) },
439) {
440 override get message(): string {
441 return `[${this.problem}] ${formatBootServiceProblem(this.problem)}`;
442 }
443}
444
445export class BootServiceUpdatePendingError extends Schema.TaggedError<BootServiceUpdatePendingError>()(
446 "BootServiceUpdatePendingError",
447 {},
448) {
449 override get message(): string {
450 return "A remote server update is still pending. Wait for it to finish, then retry.";
451 }
452}
453
454export class BootServiceDowngradeRefusedError extends Schema.TaggedError<BootServiceDowngradeRefusedError>()(
455 "BootServiceDowngradeRefusedError",
456 {
457 installedVersion: Schema.String,
458 targetVersion: Schema.String,
459 },
460) {
461 override get message(): string {
462 return `Refusing to replace t3@${this.installedVersion} with older t3@${this.targetVersion}. Run the command again with --allow-downgrade to continue.`;
463 }
464}
465
466export type BootServiceError =
467 | BootServiceUnsupportedError
468 | BootServiceCommandError
469 | BootServiceInstallError
470 | BootServicePrerequisiteError
471 | BootServiceUpdatePendingError
472 | BootServiceDowngradeRefusedError;
473
474export interface BootServiceStatus {
475 readonly supported: boolean;
476 readonly installed: boolean;
477 readonly current: boolean;
478 readonly installedVersion?: string;
479 readonly problems?: ReadonlyArray<BootServiceProblem>;
480 readonly unitPath: string;
481 readonly logPath: string;
482}
483
484export class BootService extends Context.Service<
485 BootService,
486 {
487 readonly install: (options?: {
488 readonly allowDowngrade?: boolean;
489 }) => Effect.Effect<BootServicePlan, BootServiceError>;
490 readonly uninstall: Effect.Effect<boolean, BootServiceError>;
491 readonly status: Effect.Effect<BootServiceStatus, BootServiceError>;
492 }
493>()("t3/cloud/bootService") {}
494
495export interface BootServiceHost {
496 readonly execPath: string;
497 readonly launcherSourcePath?: string;
498}
499
500export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
501 readonly baseDir: string;
502 readonly logsDir: string;
503 readonly cliVersion: string;
504 readonly host?: BootServiceHost;
505}) {
506 const hostExecPath = yield* HostProcessExecutablePath;
507 const platform = yield* HostProcessPlatform;
508 const uid = yield* HostProcessUserId;
509 const homeDir = yield* Config.string("HOME").pipe(Config.withDefault(""));
510 const installerPath = yield* Config.string("PATH").pipe(Config.withDefault(""));
511 const fs = yield* FileSystem.FileSystem;
512 const path = yield* Path.Path;
513 const runner = yield* ProcessRunner.ProcessRunner;
514 const host = input.host ?? { execPath: hostExecPath };
515 const xmlSafeInstallerDirectories = installerPath.split(":").filter(
516 (directory) =>
517 directory.length > 0 &&
518 Array.from(directory).every((character) => {
519 const code = character.charCodeAt(0);
520 return code >= 0x20 || code === 0x09 || code === 0x0a || code === 0x0d;
521 }),
522 );
523 const environmentPath = Array.from(
524 new Set([
525 ...xmlSafeInstallerDirectories,
526 path.dirname(host.execPath),
527 "/opt/homebrew/bin",
528 "/usr/local/bin",
529 "/usr/bin",
530 "/bin",
531 "/usr/sbin",
532 "/sbin",
533 ]),
534 ).join(":");
535
536 const detectedManager = selectBootServiceManager({
537 platform,
538 homeDir,
539 uid,
540 path,
541 environmentPath,
542 });
543 const unitPath = detectedManager?.unitPath ?? "";
544 const logPath = path.join(input.logsDir, "boot-service.log");
545 const launcherPath = path.join(input.baseDir, "runtime", SERVICE_LAUNCHER_FILE);
546 const statePath = path.join(input.baseDir, "runtime", SERVICE_STATE_FILE);
547 const runtimePaths = pinnedRuntimePaths(path, input.baseDir, input.cliVersion);
548 const launcherSourcePath =
549 host.launcherSourcePath ??
550 path.join(path.dirname(runtimePaths.entryPath), SERVICE_LAUNCHER_FILE);
551 const writeDurably = (filePath: string, contents: string) =>
552 Effect.scoped(
553 Effect.gen(function* () {
554 const directory = path.dirname(filePath);
555 yield* fs.makeDirectory(directory, { recursive: true });
556 const tempPath = yield* fs.makeTempFileScoped({ directory, prefix: ".service-write-" });
557 yield* fs.writeFileString(tempPath, contents, { mode: 0o600 });
558 // Opened read-write: Windows refuses to flush a handle without write access.
559 yield* (yield* fs.open(tempPath, { flag: "r+" })).sync;
560 yield* fs.rename(tempPath, filePath);
561 // Windows has no directory fsync (EPERM); NTFS journals the rename.
562 yield* (yield* fs.open(directory, { flag: "r" })).sync.pipe(
563 Effect.catchIf(
564 (error) => (error.reason.cause as NodeJS.ErrnoException | undefined)?.code === "EPERM",
565 () => Effect.void,
566 ),
567 );
568 }),
569 ).pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
570 const plan: BootServicePlan = {
571 nodePath: host.execPath,
572 launcherPath,
573 baseDir: input.baseDir,
574 logPath,
575 unitPath,
576 };
577
578 const requireManager = Effect.suspend(() =>
579 detectedManager === undefined
580 ? new BootServiceUnsupportedError({ platform })
581 : Effect.succeed(detectedManager),
582 );
583
584 const logFailure = (error: { readonly message: string }) =>
585 DateTime.now.pipe(
586 Effect.flatMap((now) =>
587 fs.writeFileString(logPath, `${DateTime.formatIso(now)} ${error.message}\n`, { flag: "a" }),
588 ),
589 Effect.ignore,
590 );
591
592 const runStep = Effect.fn("cloud.boot_service.run_step")(function* (
593 step: string,
594 command: string,
595 args: ReadonlyArray<string>,
596 options?: { readonly timeout?: Duration.Input },
597 ) {
598 return yield* runner.run({ command, args, timeout: options?.timeout }).pipe(
599 Effect.mapError((cause) => new BootServiceCommandError({ step, cause })),
600 Effect.filterOrFail(
601 (result) => result.code === 0,
602 (result) =>
603 new BootServiceCommandError({
604 step,
605 exitCode: Number(result.code),
606 stdoutLength: result.stdout.length,
607 stderrLength: result.stderr.length,
608 }),
609 ),
610 Effect.tapError(logFailure),
611 );
612 });
613
614 const runSteps = (steps: ReadonlyArray<BootServiceStep>) =>
615 Effect.forEach(
616 steps,
617 (entry) => {
618 const run = runStep(
619 entry.step,
620 entry.command,
621 entry.args,
622 entry.timeout === undefined ? undefined : { timeout: entry.timeout },
623 );
624 // runStep's tapError already appends the failure to the log, so an
625 // ignored optional step still leaves a trace.
626 return entry.optional === true ? run.pipe(Effect.ignore) : run.pipe(Effect.asVoid);
627 },
628 { discard: true },
629 );
630
631 const probe = (command: string, args: ReadonlyArray<string>) =>
632 runner.run({ command, args, timeout: Duration.seconds(5) }).pipe(Effect.option);
633 const succeeded = (result: Option.Option<ProcessRunner.ProcessRunOutput>) =>
634 Option.isSome(result) && result.value.code === 0;
635 const lingerArgs = [
636 "show-user",
637 ...(uid === undefined ? [] : [String(uid)]),
638 "--property=Linger",
639 "--value",
640 ];
641 const readSystemdProblems = Effect.fn("cloud.boot_service.read_systemd_problems")(function* (
642 includeService: boolean,
643 ) {
644 const [manager, linger] = yield* Effect.all(
645 [probe("systemctl", ["--user", "show-environment"]), probe("loginctl", lingerArgs)],
646 { concurrency: "unbounded" },
647 );
648 const problems: BootServiceProblem[] = [];
649 if (!succeeded(manager)) problems.push("user-manager-unavailable");
650 const lingering = succeeded(linger) && Option.isSome(linger) ? linger.value.stdout.trim() : "";
651 if (lingering !== "yes") {
652 problems.push(lingering === "no" ? "linger-disabled" : "linger-unavailable");
653 }
654 if (includeService && succeeded(manager)) {
655 const [enabled, active] = yield* Effect.all(
656 [
657 probe("systemctl", ["--user", "is-enabled", BOOT_SERVICE_UNIT_FILE]),
658 probe("systemctl", ["--user", "is-active", BOOT_SERVICE_UNIT_FILE]),
659 ],
660 { concurrency: "unbounded" },
661 );
662 if (
663 !succeeded(enabled) ||
664 (Option.isSome(enabled) && enabled.value.stdout.trim() !== "enabled")
665 ) {
666 problems.push("service-disabled");
667 }
668 if (!succeeded(active)) problems.push("service-stopped");
669 }
670 return problems;
671 });
672
673 const requireSystemdPrerequisites = Effect.gen(function* () {
674 const problems = yield* readSystemdProblems(false);
675 const unavailable = problems.find((problem) => problem !== "linger-disabled");
676 if (unavailable) return yield* new BootServicePrerequisiteError({ problem: unavailable });
677 if (!problems.includes("linger-disabled")) return;
678 yield* runStep("enabling lingering for this user", "loginctl", [
679 "enable-linger",
680 "--no-ask-password",
681 ...(uid === undefined ? [] : [String(uid)]),
682 ]).pipe(
683 Effect.mapError(
684 (cause) => new BootServicePrerequisiteError({ problem: "linger-disabled", cause }),
685 ),
686 );
687 const remaining = yield* readSystemdProblems(false);
688 if (remaining[0]) return yield* new BootServicePrerequisiteError({ problem: remaining[0] });
689 });
690
691 const install = Effect.fn("cloud.boot_service.install")(function* (options?: {
692 readonly allowDowngrade?: boolean;
693 }) {
694 const manager = yield* requireManager;
695 yield* fs
696 .makeDirectory(input.logsDir, { recursive: true })
697 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
698
699 // A permissions failure must not leave a partial install or stop a working server.
700 if (manager.kind === "systemd") {
701 yield* requireSystemdPrerequisites.pipe(Effect.tapError(logFailure));
702 }
703
704 // Prepare every immutable artifact before stopping the installed unit.
705 yield* ensurePinnedRuntimeInstalled({
706 baseDir: input.baseDir,
707 version: input.cliVersion,
708 fs,
709 path,
710 runner,
711 validate: (runtime) =>
712 runner
713 .run({
714 command: host.execPath,
715 args: [runtime.entryPath, "--version"],
716 timeout: Duration.seconds(30),
717 })
718 .pipe(
719 Effect.mapError(
720 (cause) =>
721 new PinnedRuntimeInstallError({
722 step: "verifying the pinned t3 runtime",
723 cause,
724 }),
725 ),
726 Effect.flatMap((result) => {
727 const reportedVersion = /\bv(\S+)\s*$/.exec(result.stdout)?.[1];
728 return result.code === 0 && reportedVersion === input.cliVersion
729 ? Effect.void
730 : Effect.fail(
731 new PinnedRuntimeInstallError({
732 step: "verifying the pinned t3 runtime",
733 exitCode: Number(result.code),
734 stdoutLength: result.stdout.length,
735 stderrLength: result.stderr.length,
736 }),
737 );
738 }),
739 ),
740 }).pipe(
741 Effect.mapError((error) =>
742 error._tag === "PinnedRuntimeInstallError"
743 ? new BootServiceCommandError({
744 step: error.step,
745 exitCode: error.exitCode,
746 stdoutLength: error.stdoutLength,
747 stderrLength: error.stderrLength,
748 cause: error,
749 })
750 : new BootServiceInstallError({ cause: error }),
751 ),
752 );
753 const launcherSource = yield* fs
754 .readFileString(launcherSourcePath)
755 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
756
757 const installed = yield* fs
758 .exists(unitPath)
759 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
760 if (installed) {
761 yield* runSteps(manager.stop);
762 }
763
764 yield* Effect.gen(function* () {
765 if (installed) {
766 const previousStateText = yield* fs.readFileString(statePath).pipe(Effect.option);
767 if (Option.isSome(previousStateText)) {
768 if (serviceStateHasPendingUpdate(previousStateText.value)) {
769 return yield* new BootServiceUpdatePendingError();
770 }
771 // A remote update can finish after the CLI checks status. Read its
772 // final version after the launcher stops and before changing files.
773 const installedVersion = serviceStateActiveVersion(previousStateText.value);
774 if (
775 installedVersion !== undefined &&
776 options?.allowDowngrade !== true &&
777 compareExactServiceVersions(input.cliVersion, installedVersion) < 0
778 ) {
779 return yield* new BootServiceDowngradeRefusedError({
780 installedVersion,
781 targetVersion: input.cliVersion,
782 });
783 }
784 }
785 }
786 yield* fs
787 .makeDirectory(path.dirname(unitPath), { recursive: true })
788 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
789 yield* writeDurably(launcherPath, launcherSource);
790 yield* writeDurably(
791 statePath,
792 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned document.
793 `${JSON.stringify(
794 {
795 protocol: SERVICE_LAUNCHER_PROTOCOL,
796 activeVersion: input.cliVersion,
797 } satisfies ServiceState,
798 null,
799 2,
800 )}\n`,
801 );
802 yield* writeDurably(unitPath, manager.render(plan));
803
804 yield* runSteps(manager.activate);
805 }).pipe(
806 Effect.tapError(() =>
807 installed ? runSteps(manager.restart).pipe(Effect.ignore) : Effect.void,
808 ),
809 );
810 return plan;
811 });
812
813 const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () {
814 const manager = yield* requireManager;
815 if (
816 !(yield* fs
817 .exists(unitPath)
818 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))))
819 )
820 return false;
821 yield* runSteps(manager.deactivate);
822 yield* fs
823 .remove(unitPath)
824 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
825 yield* runSteps(manager.finalize);
826 return true;
827 }).pipe(Effect.withSpan("cloud.boot_service.uninstall"));
828
829 const status: BootService["Service"]["status"] = Effect.gen(function* () {
830 if (detectedManager === undefined) {
831 return { supported: false, installed: false, current: false, unitPath, logPath };
832 }
833 if (!(yield* fs.exists(unitPath))) {
834 return { supported: true, installed: false, current: false, unitPath, logPath };
835 }
836 const [unit, launcherExists, runtimeEntryExists, runtimeSentinel, stateText] =
837 yield* Effect.all([
838 fs.readFileString(unitPath),
839 fs.exists(launcherPath),
840 fs.exists(runtimePaths.entryPath),
841 fs.readFileString(runtimePaths.sentinelPath).pipe(Effect.option),
842 fs.readFileString(statePath).pipe(Effect.option),
843 ]);
844 const state = Option.isSome(stateText) ? parseServiceState(stateText.value) : undefined;
845 const installedVersion = Option.isSome(stateText)
846 ? serviceStateActiveVersion(stateText.value)
847 : undefined;
848 const normalizeUnit = (contents: string) =>
849 detectedManager.kind === "launchd"
850 ? contents.replace(/(<key>PATH<\/key>\n\s*<string>)[^<]*(<\/string>)/, "$1$2")
851 : contents;
852 const problems = detectedManager.kind === "systemd" ? yield* readSystemdProblems(true) : [];
853 return {
854 supported: true,
855 installed: true,
856 ...(installedVersion === undefined ? {} : { installedVersion }),
857 problems,
858 current:
859 problems.length === 0 &&
860 normalizeUnit(unit) === normalizeUnit(detectedManager.render(plan)) &&
861 launcherExists &&
862 runtimeEntryExists &&
863 Option.isSome(runtimeSentinel) &&
864 runtimeSentinel.value.trim() === input.cliVersion &&
865 state?.activeVersion === input.cliVersion &&
866 state?.update?.status !== "pending",
867 unitPath,
868 logPath,
869 };
870 }).pipe(
871 Effect.mapError((cause) => new BootServiceInstallError({ cause })),
872 Effect.withSpan("cloud.boot_service.status"),
873 );
874
875 return BootService.of({ install, uninstall, status });
876});
877
878export const layer = (input: {
879 readonly baseDir: string;
880 readonly logsDir: string;
881 readonly cliVersion: string;
882 readonly host?: BootServiceHost;
883}) => Layer.effect(BootService, make(input));