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

bootService.ts

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