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

bootService.ts

1,018 lines37.1 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 Exit from "effect/Exit";
8import * as FileSystem from "effect/FileSystem";
9import * as Layer from "effect/Layer";
10import * as Option from "effect/Option";
11import * as Path from "effect/Path";
12import { HttpClient } from "effect/http";
13import * as Schema from "effect/Schema";
14​
15import { CLI_RELEASE_BASE_URL_ENV } from "@t3tools/shared/cliRelease";
16​
17import * as ProcessRunner from "../processRunner.ts";
18import {
19 ensurePinnedRuntimeInstalled,
20 pinnedRuntimeCommand,
21 pinnedRuntimePaths,
22 PinnedRuntimeInstallError,
23} from "./pinnedRuntime.ts";
24import {
25 SERVICE_LAUNCHER_PROTOCOL,
26 SERVICE_RESTART_PENDING_FILE,
27 SERVICE_STATE_FILE,
28 compareExactServiceVersions,
29 parseServiceState,
30 serviceStateActiveVersion,
31 serviceStateHasPendingUpdate,
32 type ServiceState,
33} from "./serviceProtocol.ts";
34​
35const BOOT_SERVICE_NAME = "t3code";
36export const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
37// `.service` suffix keeps the label distinct from the desktop app's bundle id
38// (com.t3tools.t3code), so launchd and TCC records never collide.
39export const BOOT_SERVICE_LAUNCHD_LABEL = "com.t3tools.t3code.service";
40export const BOOT_SERVICE_PLIST_FILE = `${BOOT_SERVICE_LAUNCHD_LABEL}.plist`;
41const BOOT_SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT";
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​
56const unquoteSystemdValue = (raw: string) =>
57 (raw.startsWith('"') && raw.endsWith('"')
58 ? raw.slice(1, -1).replaceAll('\\"', '"').replaceAll("\\\\", "\\")
59 : raw
60 ).replaceAll("%%", "%");
61​
62const unescapeXmlText = (value: string) =>
63 value.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&amp;", "&");
64​
65export function bootServiceBaseDirOf(contents: string): string | undefined {
66 const systemd = /^Environment=T3CODE_HOME=(.*)$/m.exec(contents)?.[1];
67 if (systemd !== undefined) return unquoteSystemdValue(systemd.trim());
68 const plist = /<key>T3CODE_HOME<\/key>\s*<string>([^<]*)<\/string>/.exec(contents)?.[1];
69 return plist === undefined ? undefined : unescapeXmlText(plist);
71​
72/** The executable an installed unit or plist starts: the launcher's runtime. */
73export function bootServiceProgramOf(contents: string): string | undefined {
74 const systemd = /^ExecStart=("(?:\\.|[^"\\])*"|\S+)/m.exec(contents)?.[1];
75 if (systemd !== undefined) return unquoteSystemdValue(systemd);
76 const plist = /<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/.exec(
77 contents,
78 )?.[1];
79 return plist === undefined ? undefined : unescapeXmlText(plist);
81​
82export interface BootServicePlan {
83 readonly program: ReadonlyArray<string>;
84 readonly baseDir: string;
85 readonly logPath: string;
86 readonly unitPath: string;
87 /** The manager accepted a detached install; its outcome is written to `logPath`. */
88 readonly handedOff?: boolean;
90​
91/** 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 // Helpers share this cgroup; default OOMPolicy=stop would stop the unit if one is OOM-killed.
110 "OOMPolicy=continue",
111 "Restart=always",
112 "RestartSec=5",
113 // Weights favor the server over the sibling agents slice during CPU or disk saturation.
114 "CPUWeight=1000",
115 "IOWeight=1000",
116 // systemd-oomd ignores this preference when the watched cgroup is root-owned, as user-1000.slice usually is.
117 "ManagedOOMPreference=avoid",
118 `StandardOutput=append:${escapeSystemdSpecifiers(plan.logPath)}`,
119 `StandardError=append:${escapeSystemdSpecifiers(plan.logPath)}`,
120 "",
121 "[Install]",
122 "WantedBy=default.target",
123 "",
124 ].join("\n");
126​
127function escapeXmlText(value: string): string {
128 return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
130​
131/** Launch agents cannot rely on the user's shell or PATH. */
132export function renderBootServicePlist(
133 plan: BootServicePlan,
134 options: { readonly homeDir: string; readonly environmentPath: string },
135): string {
136 // Allow 90s stops for update handoffs.
137 // Interactive avoids background throttling.
138 // AbandonProcessGroup=false reaps agents only on launcher exit, preserving them across child updates.
139 return [
140 `<?xml version="1.0" encoding="UTF-8"?>`,
141 `<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">`,
142 `<plist version="1.0">`,
143 `<dict>`,
144 ` <key>Label</key>`,
145 ` <string>${BOOT_SERVICE_LAUNCHD_LABEL}</string>`,
146 ` <key>ProgramArguments</key>`,
147 ` <array>`,
148 ...plan.program.map((argument) => ` <string>${escapeXmlText(argument)}</string>`),
149 ` </array>`,
150 ` <key>EnvironmentVariables</key>`,
151 ` <dict>`,
152 ` <key>PATH</key>`,
153 ` <string>${escapeXmlText(options.environmentPath)}</string>`,
154 ` <key>T3CODE_HOME</key>`,
155 ` <string>${escapeXmlText(plan.baseDir)}</string>`,
156 ` <key>${BOOT_SERVICE_UNIT_ENV}</key>`,
157 ` <string>${BOOT_SERVICE_PLIST_FILE}</string>`,
158 ` </dict>`,
159 ` <key>WorkingDirectory</key>`,
160 ` <string>${escapeXmlText(options.homeDir)}</string>`,
161 ` <key>RunAtLoad</key>`,
162 ` <true/>`,
163 ` <key>KeepAlive</key>`,
164 ` <true/>`,
165 ` <key>ThrottleInterval</key>`,
166 ` <integer>5</integer>`,
167 ` <key>ExitTimeOut</key>`,
168 ` <integer>90</integer>`,
169 ` <key>ProcessType</key>`,
170 ` <string>Interactive</string>`,
171 ` <key>StandardOutPath</key>`,
172 ` <string>${escapeXmlText(plan.logPath)}</string>`,
173 ` <key>StandardErrorPath</key>`,
174 ` <string>${escapeXmlText(plan.logPath)}</string>`,
175 `</dict>`,
176 `</plist>`,
177 ``,
178 ].join("\n");
180​
181export interface BootServiceStep {
182 readonly step: string;
183 readonly command: string;
184 readonly args: ReadonlyArray<string>;
185 /** Non-zero exit is logged and ignored. */
186 readonly optional?: boolean;
187 readonly timeout?: Duration.Input;
189​
190/** Must exceed systemd TimeoutStopSec and launchd ExitTimeOut (both 90s) to avoid shutdown races. */
191const STOP_STEP_TIMEOUT = Duration.seconds(120);
192​
193export interface BootServiceManager {
194 readonly kind: "systemd" | "launchd";
195 readonly unitPath: string;
196 readonly render: (plan: BootServicePlan) => string;
197 readonly stop: ReadonlyArray<BootServiceStep>;
198 readonly activate: ReadonlyArray<BootServiceStep>;
199 readonly restart: ReadonlyArray<BootServiceStep>;
200 /** Queue a restart owned by the manager, since stopping would kill the caller. */
201 readonly handoff?: ReadonlyArray<BootServiceStep>;
202 readonly deactivate: ReadonlyArray<BootServiceStep>;
203 readonly finalize: ReadonlyArray<BootServiceStep>;
205​
206function systemdManager(input: {
207 readonly path: Path.Path;
208 readonly homeDir: string;
209}): BootServiceManager {
210 const unitPath = input.path.join(
211 input.homeDir,
212 ".config",
213 "systemd",
214 "user",
215 BOOT_SERVICE_UNIT_FILE,
216 );
217 const prepareActivation = [
218 {
219 step: "reloading systemd user units",
220 command: "systemctl",
221 args: ["--user", "daemon-reload"],
222 },
223 {
224 step: "enabling the service",
225 command: "systemctl",
226 args: ["--user", "enable", BOOT_SERVICE_UNIT_FILE],
227 },
228 ];
229 return {
230 kind: "systemd",
231 unitPath,
232 render: renderBootServiceUnit,
233 stop: [
234 {
235 step: "stopping the installed service",
236 command: "systemctl",
237 args: ["--user", "stop", BOOT_SERVICE_UNIT_FILE],
238 timeout: STOP_STEP_TIMEOUT,
239 },
240 ],
241 activate: [
242 ...prepareActivation,
243 {
244 step: "starting the service",
245 command: "systemctl",
246 args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
247 },
248 ],
249 restart: [
250 {
251 step: "restarting the service after a failed update",
252 command: "systemctl",
253 args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
254 },
255 ],
256 handoff: [
257 ...prepareActivation,
258 {
259 step: "restarting the service",
260 command: "systemctl",
261 args: ["--user", "restart", "--no-block", BOOT_SERVICE_UNIT_FILE],
262 },
263 ],
264 deactivate: [
265 {
266 step: "stopping the service",
267 command: "systemctl",
268 args: ["--user", "disable", "--now", BOOT_SERVICE_UNIT_FILE],
269 timeout: STOP_STEP_TIMEOUT,
270 },
271 ],
272 finalize: [
273 {
274 step: "reloading systemd user units",
275 command: "systemctl",
276 args: ["--user", "daemon-reload"],
277 },
278 ],
279 };
281​
282function launchdManager(input: {
283 readonly path: Path.Path;
284 readonly homeDir: string;
285 readonly uid: number;
286 readonly environmentPath: string;
287}): BootServiceManager {
288 const unitPath = input.path.join(
289 input.homeDir,
290 "Library",
291 "LaunchAgents",
292 BOOT_SERVICE_PLIST_FILE,
293 );
294 const domainTarget = `gui/${input.uid}`;
295 const serviceTarget = `${domainTarget}/${BOOT_SERVICE_LAUNCHD_LABEL}`;
296 // Unloaded jobs may reject bootout/enable. Bootstrap starts RunAtLoad/KeepAlive jobs; kickstart would restart them.
297 return {
298 kind: "launchd",
299 unitPath,
300 render: (plan) =>
301 renderBootServicePlist(plan, {
302 homeDir: input.homeDir,
303 environmentPath: input.environmentPath,
304 }),
305 // bootout --wait is undocumented but waits through ExitTimeOut, preventing bootstrap EIO races.
306 stop: [
307 {
308 step: "stopping the installed launch agent",
309 command: "launchctl",
310 args: ["bootout", "--wait", serviceTarget],
311 optional: true,
312 timeout: STOP_STEP_TIMEOUT,
313 },
314 ],
315 activate: [
316 // A persisted `launchctl disable` override refuses bootstrap; clear it.
317 {
318 step: "enabling the launch agent",
319 command: "launchctl",
320 args: ["enable", serviceTarget],
321 optional: true,
322 },
323 {
324 step: "starting the service",
325 command: "launchctl",
326 args: ["bootstrap", domainTarget, unitPath],
327 },
328 ],
329 restart: [
330 {
331 step: "restarting the service after a failed update",
332 command: "launchctl",
333 args: ["bootstrap", domainTarget, unitPath],
334 },
335 ],
336 // Persisted launchctl disable overrides would block reinstall.
337 deactivate: [
338 {
339 step: "stopping the service",
340 command: "launchctl",
341 args: ["bootout", "--wait", serviceTarget],
342 optional: true,
343 timeout: STOP_STEP_TIMEOUT,
344 },
345 ],
346 finalize: [],
347 };
349​
350function selectBootServiceManager(input: {
351 readonly platform: NodeJS.Platform;
352 readonly homeDir: string;
353 readonly uid: number | undefined;
354 readonly path: Path.Path;
355 readonly environmentPath: string;
356}): BootServiceManager | undefined {
357 if (input.homeDir === "") {
358 return undefined;
359 }
360 if (input.platform === "linux") {
361 return systemdManager({ path: input.path, homeDir: input.homeDir });
362 }
363 if (input.platform === "darwin" && input.uid !== undefined) {
364 return launchdManager({
365 path: input.path,
366 homeDir: input.homeDir,
367 uid: input.uid,
368 environmentPath: input.environmentPath,
369 });
370 }
371 return undefined;
373​
374export class BootServiceUnsupportedError extends Schema.TaggedError<BootServiceUnsupportedError>()(
375 "BootServiceUnsupportedError",
376 { platform: Schema.String },
377) {
378 override get message(): string {
379 return `Background setup supports Linux with systemd and macOS with launchd; this machine reports '${this.platform}'.`;
380 }
382​
383export class BootServiceCommandError extends Schema.TaggedError<BootServiceCommandError>()(
384 "BootServiceCommandError",
385 {
386 step: Schema.String,
387 exitCode: Schema.optional(Schema.Number),
388 stdoutLength: Schema.optional(Schema.Number),
389 stderrLength: Schema.optional(Schema.Number),
390 cause: Schema.optional(Schema.Defect()),
391 },
392) {
393 override get message(): string {
394 return this.exitCode === undefined
395 ? `Background setup failed while ${this.step}.`
396 : `Background setup failed while ${this.step} (exit code ${this.exitCode}).`;
397 }
399​
400export class BootServiceInstallError extends Schema.TaggedError<BootServiceInstallError>()(
401 "BootServiceInstallError",
402 { cause: Schema.Defect() },
403) {
404 override get message(): string {
405 return "Could not set up the T3 Code background service.";
406 }
408​
409const BootServiceProblem = Schema.Literals([
410 "user-manager-unavailable",
411 "linger-unavailable",
412 "linger-disabled",
413 "service-disabled",
414 "service-stopped",
415 "restart-pending",
416]);
417type BootServiceProblem = typeof BootServiceProblem.Type;
418​
419export function formatBootServiceProblem(problem: BootServiceProblem): string {
420 switch (problem) {
421 case "user-manager-unavailable":
422 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.";
423 case "linger-unavailable":
424 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.';
425 case "linger-disabled":
426 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.';
427 case "service-disabled":
428 return "The service is not enabled to start automatically. Run `t3 service install` to repair it.";
429 case "service-stopped":
430 return "The service is not running. Check the service log and `systemctl --user status t3code.service`, then run `t3 service install`.";
431 case "restart-pending":
432 return "A newer version is installed but the service is still running the previous one. Run `t3 service restart` to switch.";
433 }
435​
436export class BootServicePrerequisiteError extends Schema.TaggedError<BootServicePrerequisiteError>()(
437 "BootServicePrerequisiteError",
438 { problem: BootServiceProblem, cause: Schema.optional(Schema.Defect()) },
439) {
440 override get message(): string {
441 return `[${this.problem}] ${formatBootServiceProblem(this.problem)}`;
442 }
444​
445export class BootServiceUpdatePendingError extends Schema.TaggedError<BootServiceUpdatePendingError>()(
446 "BootServiceUpdatePendingError",
447 {},
448) {
449 override get message(): string {
450 return "A remote server update is still pending. Wait for it to finish, then retry.";
451 }
453​
454export class BootServiceDowngradeRefusedError extends Schema.TaggedError<BootServiceDowngradeRefusedError>()(
455 "BootServiceDowngradeRefusedError",
456 {
457 installedVersion: Schema.String,
458 targetVersion: Schema.String,
459 },
460) {
461 override get message(): string {
462 return `Refusing to replace t3@${this.installedVersion} with older t3@${this.targetVersion}. Run the command again with --allow-downgrade to continue.`;
463 }
465​
466export type BootServiceError =
467 | BootServiceUnsupportedError
468 | BootServiceCommandError
469 | BootServiceInstallError
470 | BootServicePrerequisiteError
471 | BootServiceUpdatePendingError
472 | BootServiceDowngradeRefusedError;
473​
474export interface BootServiceStatus {
475 readonly supported: boolean;
476 readonly installed: boolean;
477 readonly current: boolean;
478 readonly installedVersion?: string;
479 readonly installedBaseDir?: string;
480 readonly problems?: ReadonlyArray<BootServiceProblem>;
481 readonly unitPath: string;
482 readonly logPath: string;
484​
485export class BootService extends Context.Service<
486 BootService,
487 {
488 readonly install: (options?: {
489 readonly allowDowngrade?: boolean;
490 readonly start?: boolean;
491 }) => Effect.Effect<BootServicePlan, BootServiceError>;
492 /**
493 * Only when the unit serves this base dir: the unit name is per user, so
494 * another home's service is left alone, which resolves `skipped`. From
495 * inside the service the restart can only be `queued` with the service
496 * manager, since the stop ends this process.
497 */
498 readonly restart: Effect.Effect<"restarted" | "queued" | "skipped", BootServiceError>;
499 /**
500 * Runs the operation with this home's service stopped; other homes are left alone.
501 * Restores a previously enabled or loaded service even if stopping failed.
502 * The operation's failure takes precedence over a restart failure.
503 */
504 readonly withStopped: <A, E, R>(
505 operation: Effect.Effect<A, E, R>,
506 ) => Effect.Effect<A, E | BootServiceError, R>;
507 readonly uninstall: Effect.Effect<boolean, BootServiceError>;
508 readonly status: Effect.Effect<BootServiceStatus, BootServiceError>;
509 }
510>()("t3/cloud/bootService") {}
511​
512export interface BootServiceHost {
513 readonly execPath: string;
515​
516export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
517 readonly baseDir: string;
518 readonly logsDir: string;
519 readonly cliVersion: string;
520 readonly host?: BootServiceHost;
521}) {
522 const hostExecPath = yield* HostProcess.ExecutablePath;
523 const platform = yield* HostProcess.Platform;
524 const arch = yield* HostProcess.Architecture;
525 const uid = yield* HostProcess.UserId;
526 const httpClient = yield* HttpClient.HttpClient;
527 const releaseBaseUrl = Option.getOrUndefined(
528 yield* Config.String(CLI_RELEASE_BASE_URL_ENV).pipe(Config.option),
529 );
530 const homeDir = yield* Config.String("HOME").pipe(Config.withDefault(""));
531 const installerPath = yield* Config.String("PATH").pipe(Config.withDefault(""));
532 const runningInsideService =
533 (yield* Config.String(BOOT_SERVICE_UNIT_ENV).pipe(Config.withDefault(""))) ===
534 BOOT_SERVICE_UNIT_FILE;
535 const fs = yield* FileSystem.FileSystem;
536 const path = yield* Path.Path;
537 const runner = yield* ProcessRunner.ProcessRunner;
538 const host = input.host ?? { execPath: hostExecPath };
539 const xmlSafeInstallerDirectories = installerPath.split(":").filter(
540 (directory) =>
541 directory.length > 0 &&
542 Array.from(directory).every((character) => {
543 const code = character.charCodeAt(0);
544 return code >= 0x20 || code === 0x09 || code === 0x0a || code === 0x0d;
545 }),
546 );
547 const environmentPath = Array.from(
548 new Set([
549 ...xmlSafeInstallerDirectories,
550 path.dirname(host.execPath),
551 "/opt/homebrew/bin",
552 "/usr/local/bin",
553 "/usr/bin",
554 "/bin",
555 "/usr/sbin",
556 "/sbin",
557 ]),
558 ).join(":");
559​
560 const detectedManager = selectBootServiceManager({
561 platform,
562 homeDir,
563 uid,
564 path,
565 environmentPath,
566 });
567 const unitPath = detectedManager?.unitPath ?? "";
568 const logPath = path.join(input.logsDir, BOOT_SERVICE_LOG_FILE);
569 const statePath = path.join(input.baseDir, "runtime", SERVICE_STATE_FILE);
570 const restartPendingPath = path.join(input.baseDir, "runtime", SERVICE_RESTART_PENDING_FILE);
571 const runtimePaths = pinnedRuntimePaths(path, input.baseDir, input.cliVersion, platform);
572 const writeDurably = (filePath: string, contents: string) =>
573 Effect.scoped(
574 Effect.gen(function* () {
575 const directory = path.dirname(filePath);
576 yield* fs.makeDirectory(directory, { recursive: true });
577 const tempPath = yield* fs.makeTempFileScoped({ directory, prefix: ".service-write-" });
578 yield* fs.writeFileString(tempPath, contents, { mode: 0o600 });
579 // Opened read-write: Windows refuses to flush a handle without write access.
580 yield* (yield* fs.open(tempPath, { flag: "r+" })).sync;
581 yield* fs.rename(tempPath, filePath);
582 // Windows has no directory fsync (EPERM); NTFS journals the rename.
583 yield* (yield* fs.open(directory, { flag: "r" })).sync.pipe(
584 Effect.catchIf(
585 (error) => (error.reason.cause as NodeJS.ErrnoException | undefined)?.code === "EPERM",
586 () => Effect.void,
587 ),
588 );
589 }),
590 ).pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
591 const plan: BootServicePlan = {
592 program: [runtimePaths.entryPath, "__service-launcher"],
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 return entry.optional === true ? run.pipe(Effect.ignore) : run.pipe(Effect.asVoid);
645 },
646 { discard: true },
647 );
648​
649 const probe = (command: string, args: ReadonlyArray<string>) =>
650 runner.run({ command, args, timeout: Duration.seconds(5) }).pipe(Effect.option);
651 const succeeded = (result: Option.Option<ProcessRunner.ProcessRunOutput>) =>
652 Option.isSome(result) && result.value.code === 0;
653 const lingerArgs = [
654 "show-user",
655 ...(uid === undefined ? [] : [String(uid)]),
656 "--property=Linger",
657 "--value",
658 ];
659 const readSystemdProblems = Effect.fn("cloud.boot_service.read_systemd_problems")(function* (
660 includeService: boolean,
661 ) {
662 const [manager, linger] = yield* Effect.all(
663 [probe("systemctl", ["--user", "show-environment"]), probe("loginctl", lingerArgs)],
664 { concurrency: "unbounded" },
665 );
666 const problems: BootServiceProblem[] = [];
667 if (!succeeded(manager)) problems.push("user-manager-unavailable");
668 const lingering = succeeded(linger) && Option.isSome(linger) ? linger.value.stdout.trim() : "";
669 if (lingering !== "yes") {
670 problems.push(lingering === "no" ? "linger-disabled" : "linger-unavailable");
671 }
672 if (includeService && succeeded(manager)) {
673 const [enabled, active] = yield* Effect.all(
674 [
675 probe("systemctl", ["--user", "is-enabled", BOOT_SERVICE_UNIT_FILE]),
676 probe("systemctl", ["--user", "is-active", BOOT_SERVICE_UNIT_FILE]),
677 ],
678 { concurrency: "unbounded" },
679 );
680 if (
681 !succeeded(enabled) ||
682 (Option.isSome(enabled) && enabled.value.stdout.trim() !== "enabled")
683 ) {
684 problems.push("service-disabled");
685 }
686 if (!succeeded(active)) problems.push("service-stopped");
687 }
688 return problems;
689 });
690​
691 const requireSystemdPrerequisites = Effect.gen(function* () {
692 const problems = yield* readSystemdProblems(false);
693 const unavailable = problems.find((problem) => problem !== "linger-disabled");
694 if (unavailable) return yield* new BootServicePrerequisiteError({ problem: unavailable });
695 if (!problems.includes("linger-disabled")) return;
696 yield* runStep("enabling lingering for this user", "loginctl", [
697 "enable-linger",
698 "--no-ask-password",
699 ...(uid === undefined ? [] : [String(uid)]),
700 ]).pipe(
701 Effect.mapError(
702 (cause) => new BootServicePrerequisiteError({ problem: "linger-disabled", cause }),
703 ),
704 );
705 const remaining = yield* readSystemdProblems(false);
706 if (remaining[0]) return yield* new BootServicePrerequisiteError({ problem: remaining[0] });
707 });
708​
709 const install = Effect.fn("cloud.boot_service.install")(function* (options?: {
710 readonly allowDowngrade?: boolean;
711 readonly start?: boolean;
712 }) {
713 const manager = yield* requireManager;
714 yield* fs
715 .makeDirectory(input.logsDir, { recursive: true })
716 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
717​
718 if (manager.kind === "systemd") {
719 yield* requireSystemdPrerequisites.pipe(Effect.tapError(logFailure));
720 }
721​
722 yield* ensurePinnedRuntimeInstalled({
723 baseDir: input.baseDir,
724 version: input.cliVersion,
725 fs,
726 path,
727 runner,
728 httpClient,
729 platform,
730 arch,
731 releaseBaseUrl,
732 validate: (runtime) =>
733 runner
734 .run({
735 command: pinnedRuntimeCommand(runtime).command,
736 args: [...pinnedRuntimeCommand(runtime).args, "--version"],
737 timeout: Duration.seconds(30),
738 })
739 .pipe(
740 Effect.mapError(
741 (cause) =>
742 new PinnedRuntimeInstallError({
743 step: "verifying the pinned t3 runtime",
744 cause,
745 }),
746 ),
747 Effect.flatMap((result) => {
748 const reportedVersion = /\bv(\S+)\s*$/.exec(result.stdout)?.[1];
749 return result.code === 0 && reportedVersion === input.cliVersion
750 ? Effect.void
751 : Effect.fail(
752 new PinnedRuntimeInstallError({
753 step: "verifying the pinned t3 runtime",
754 exitCode: Number(result.code),
755 stdoutLength: result.stdout.length,
756 stderrLength: result.stderr.length,
757 }),
758 );
759 }),
760 ),
761 }).pipe(
762 Effect.mapError((error) =>
763 error._tag === "PinnedRuntimeInstallError"
764 ? new BootServiceCommandError({
765 step: error.step,
766 exitCode: error.exitCode,
767 stdoutLength: error.stdoutLength,
768 stderrLength: error.stderrLength,
769 cause: error,
770 })
771 : new BootServiceInstallError({ cause: error }),
772 ),
773 );
774 const installed = yield* fs
775 .exists(unitPath)
776 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
777 // With start=false, changing startup-only files is safe except during a remote update,
778 // when the launcher also writes its state file.
779 const start = options?.start !== false;
780 if (installed && start && runningInsideService && manager.kind === "systemd") {
781 // Stopping the unit from inside it kills this process before the start.
782 // A transient unit runs the same install from outside, stop first, so it
783 // still serialises with a remote update the launcher may be starting.
784 yield* runStep("handing the install to a transient unit", "systemd-run", [
785 "--user",
786 "--collect",
787 "--quiet",
788 // Transient properties reach systemd literally, unlike unit-file specifiers.
789 `--property=StandardOutput=append:${logPath}`,
790 `--property=StandardError=append:${logPath}`,
791 `--setenv=${BOOT_SERVICE_UNIT_ENV}=`,
792 runtimePaths.entryPath,
793 "service",
794 "install",
795 "--base-dir",
796 // systemd expands $VAR in arguments (not in the executable path).
797 input.baseDir.replaceAll("$", () => "$$"),
798 ...(options?.allowDowngrade === true ? ["--allow-downgrade"] : []),
799 ]);
800 return { ...plan, handedOff: true };
801 }
802 if (installed && start) {
803 yield* runSteps(manager.stop);
804 }
805​
806 yield* Effect.gen(function* () {
807 if (installed) {
808 const previousStateText = yield* fs.readFileString(statePath).pipe(Effect.option);
809 if (Option.isSome(previousStateText)) {
810 if (serviceStateHasPendingUpdate(previousStateText.value)) {
811 return yield* new BootServiceUpdatePendingError();
812 }
813 // Read the final version after stopping the launcher; a remote update may finish after the status check.
814 const installedVersion = serviceStateActiveVersion(previousStateText.value);
815 if (
816 installedVersion !== undefined &&
817 options?.allowDowngrade !== true &&
818 compareExactServiceVersions(input.cliVersion, installedVersion) < 0
819 ) {
820 return yield* new BootServiceDowngradeRefusedError({
821 installedVersion,
822 targetVersion: input.cliVersion,
823 });
824 }
825 }
826 }
827 yield* fs
828 .makeDirectory(path.dirname(unitPath), { recursive: true })
829 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
830 // Files can match the new version even when activation fails; keep that install retryable.
831 yield* fs.writeFileString(restartPendingPath, `${input.cliVersion}\n`, { mode: 0o600 });
832 yield* writeDurably(
833 statePath,
834 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned document.
835 `${JSON.stringify(
836 {
837 protocol: SERVICE_LAUNCHER_PROTOCOL,
838 activeVersion: input.cliVersion,
839 } satisfies ServiceState,
840 null,
841 2,
842 )}\n`,
843 );
844 if (!start && installed) {
845 // A concurrent remote update can overwrite launcher state; detect it before repointing the unit.
846 const written = yield* fs.readFileString(statePath);
847 if (serviceStateActiveVersion(written) !== input.cliVersion) {
848 return yield* new BootServiceUpdatePendingError();
849 }
850 }
851 yield* writeDurably(unitPath, manager.render(plan));
852​
853 if (start) {
854 yield* runSteps(manager.activate);
855 yield* fs.remove(restartPendingPath, { force: true });
856 }
857 }).pipe(
858 Effect.mapError((cause) =>
859 cause._tag === "PlatformError" ? new BootServiceInstallError({ cause }) : cause,
860 ),
861 Effect.tapError(() =>
862 installed && start ? runSteps(manager.restart).pipe(Effect.ignore) : Effect.void,
863 ),
864 );
865 return plan;
866 });
867​
868 const restart: BootService["Service"]["restart"] = Effect.gen(function* () {
869 const manager = yield* requireManager;
870 const unit = yield* fs.readFileString(unitPath).pipe(Effect.option);
871 if (Option.isNone(unit)) return "skipped" as const;
872 const installedBaseDir = bootServiceBaseDirOf(unit.value);
873 if (
874 installedBaseDir === undefined ||
875 path.resolve(installedBaseDir) !== path.resolve(input.baseDir)
876 ) {
877 return "skipped" as const;
878 }
879 // Writes no state, and the launcher lets an update transition in flight
880 // finish before the queued stop tears it down.
881 if (runningInsideService && manager.handoff !== undefined) {
882 yield* runSteps(manager.handoff);
883 return "queued" as const;
884 }
885 yield* runSteps(manager.stop);
886 yield* runSteps(manager.activate).pipe(
887 Effect.tapError(() => runSteps(manager.restart).pipe(Effect.ignore)),
888 );
889 yield* fs.remove(restartPendingPath, { force: true });
890 return "restarted" as const;
891 }).pipe(
892 Effect.mapError((cause) =>
893 cause._tag === "PlatformError" ? new BootServiceInstallError({ cause }) : cause,
894 ),
895 Effect.withSpan("cloud.boot_service.restart"),
896 );
897​
898 const withStopped = Effect.fn("cloud.boot_service.with_stopped")(function* <A, E, R>(
899 operation: Effect.Effect<A, E, R>,
900 ): Effect.fn.Return<A, E | BootServiceError, R> {
901 if (detectedManager === undefined) return yield* operation;
902 const manager = detectedManager;
903 const unit = yield* fs.readFileString(unitPath).pipe(Effect.option);
904 if (Option.isNone(unit)) return yield* operation;
905 const installedBaseDir = bootServiceBaseDirOf(unit.value);
906 if (
907 installedBaseDir === undefined ||
908 path.resolve(installedBaseDir) !== path.resolve(input.baseDir)
909 ) {
910 return yield* operation;
911 }
912 // `is-active` misses crash-looping systemd units; launchd can be loaded without a pid.
913 // Always stop; restore only if previously active, enabled, or loaded,
914 // so disabled crash loops stay stopped.
915 const restore =
916 manager.kind === "systemd"
917 ? yield* Effect.map(
918 Effect.all(
919 [
920 probe("systemctl", ["--user", "is-enabled", BOOT_SERVICE_UNIT_FILE]),
921 probe("systemctl", ["--user", "is-active", BOOT_SERVICE_UNIT_FILE]),
922 ],
923 { concurrency: "unbounded" },
924 ),
925 ([enabled, active]) => succeeded(active) || succeeded(enabled),
926 )
927 : succeeded(
928 yield* probe("launchctl", ["print", `gui/${uid}/${BOOT_SERVICE_LAUNCHD_LABEL}`]),
929 );
930 return yield* Effect.acquireUseRelease(
931 // Require every stop before repair when restoring, so the server releases the database.
932 // Otherwise stops are best-effort; launchd rejects bootout of an unloaded job.
933 // A failed stop may still stop the service, so restoration runs either way.
934 runSteps(manager.stop.map((step) => ({ ...step, optional: !restore }))).pipe(Effect.exit),
935 (stopped): Effect.Effect<A, E | BootServiceError, R> =>
936 Exit.isSuccess(stopped) ? operation : Effect.failCause(stopped.cause),
937 (_, exit) => {
938 if (!restore) return Effect.void;
939 // Start only: `activate` would also enable a unit the user disabled.
940 // When the operation itself failed, its error is the one worth reporting.
941 const start = runSteps(manager.restart);
942 return Exit.isFailure(exit) ? Effect.ignore(start) : start;
943 },
944 );
945 });
946​
947 const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () {
948 const manager = yield* requireManager;
949 if (
950 !(yield* fs
951 .exists(unitPath)
952 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))))
953 )
954 return false;
955 yield* runSteps(manager.deactivate);
956 yield* fs
957 .remove(unitPath)
958 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
959 yield* runSteps(manager.finalize);
960 return true;
961 }).pipe(Effect.withSpan("cloud.boot_service.uninstall"));
962​
963 const status: BootService["Service"]["status"] = Effect.gen(function* () {
964 if (detectedManager === undefined) {
965 return { supported: false, installed: false, current: false, unitPath, logPath };
966 }
967 if (!(yield* fs.exists(unitPath))) {
968 return { supported: true, installed: false, current: false, unitPath, logPath };
969 }
970 const [unit, runtimeEntryExists, runtimeSentinel, stateText] = yield* Effect.all([
971 fs.readFileString(unitPath),
972 fs.exists(runtimePaths.entryPath),
973 fs.readFileString(runtimePaths.sentinelPath).pipe(Effect.option),
974 fs.readFileString(statePath).pipe(Effect.option),
975 ]);
976 const state = Option.isSome(stateText) ? parseServiceState(stateText.value) : undefined;
977 const installedVersion = Option.isSome(stateText)
978 ? serviceStateActiveVersion(stateText.value)
979 : undefined;
980 const installedBaseDir = bootServiceBaseDirOf(unit);
981 const normalizeUnit = (contents: string) =>
982 detectedManager.kind === "launchd"
983 ? contents.replace(/(<key>PATH<\/key>\n\s*<string>)[^<]*(<\/string>)/, "$1$2")
984 : contents;
985 const problems: BootServiceProblem[] =
986 detectedManager.kind === "systemd" ? [...(yield* readSystemdProblems(true))] : [];
987 if (yield* fs.exists(restartPendingPath)) problems.push("restart-pending");
988 return {
989 supported: true,
990 installed: true,
991 ...(installedVersion === undefined ? {} : { installedVersion }),
992 ...(installedBaseDir === undefined ? {} : { installedBaseDir }),
993 problems,
994 current:
995 problems.length === 0 &&
996 normalizeUnit(unit) === normalizeUnit(detectedManager.render(plan)) &&
997 runtimeEntryExists &&
998 Option.isSome(runtimeSentinel) &&
999 runtimeSentinel.value.trim() === input.cliVersion &&
1000 state?.activeVersion === input.cliVersion &&
1001 state?.update?.status !== "pending",
1002 unitPath,
1003 logPath,
1004 };
1005 }).pipe(
1006 Effect.mapError((cause) => new BootServiceInstallError({ cause })),
1007 Effect.withSpan("cloud.boot_service.status"),
1008 );
1009​
1010 return BootService.of({ install, restart, withStopped, uninstall, status });
1011});
1012​
1013export const layer = (input: {
1014 readonly baseDir: string;
1015 readonly logsDir: string;
1016 readonly cliVersion: string;
1017 readonly host?: BootServiceHost;
1018}) => Layer.effect(BootService, make(input));