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

bootService.ts

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