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

bootService.ts

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