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