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

bootService.ts

919 lines33.2 KB

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