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