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

bootService.ts

1,127 lines41.7 KB

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