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

bootService.ts

1,052 lines38.9 KB

1import * as HostProcess from "@t3tools/shared/HostProcess";
2import * as Config from "effect/Config";
3import * as Context from "effect/Context";
4import * as DateTime from "effect/DateTime";
5import * as Duration from "effect/Duration";
6import * as Effect from "effect/Effect";
7import * as Exit from "effect/Exit";
8import * as FileSystem from "effect/FileSystem";
9import * as Layer from "effect/Layer";
10import * as Option from "effect/Option";
11import * as Path from "effect/Path";
12import { HttpClient } from "effect/http";
13import * as Schema from "effect/Schema";
14​
15import { CLI_RELEASE_BASE_URL_ENV } from "@t3tools/shared/cliRelease";
16​
17import * as ProcessRunner from "../processRunner.ts";
18import {
19 ensurePinnedRuntimeInstalled,
20 pinnedRuntimeCommand,
21 pinnedRuntimePaths,
22 PinnedRuntimeInstallError,
23} from "./pinnedRuntime.ts";
24import {
25 SERVICE_LAUNCHER_PROTOCOL,
26 SERVICE_RESTART_PENDING_FILE,
27 SERVICE_STATE_FILE,
28 compareExactServiceVersions,
29 parseServiceState,
30 serviceStateActiveVersion,
31 serviceStateHasPendingUpdate,
32 type ServiceState,
33} from "./serviceProtocol.ts";
34​
35const BOOT_SERVICE_NAME = "t3code";
36const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
37// `.service` suffix keeps the label distinct from the desktop app's bundle id
38// (com.t3tools.t3code), so launchd and TCC records never collide.
39const BOOT_SERVICE_LAUNCHD_LABEL = "com.t3tools.t3code.service";
40const BOOT_SERVICE_PLIST_FILE = `${BOOT_SERVICE_LAUNCHD_LABEL}.plist`;
41const BOOT_SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT";
42export const BOOT_SERVICE_LOG_FILE = "boot-service.log";
43​
44/** systemd expands `%` specifiers, including in unquoted append-log paths. */
45function escapeSystemdSpecifiers(value: string): string {
46 return value.replaceAll("%", "%%");
48​
49function quoteSystemdValue(value: string): string {
50 const escaped = escapeSystemdSpecifiers(value);
51 return /[\s"'\\]/.test(escaped)
52 ? `"${escaped.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`
53 : escaped;
55​
56export function bootServiceBaseDirOf(contents: string): string | undefined {
57 const systemd = /^Environment=T3CODE_HOME=(.*)$/m.exec(contents)?.[1];
58 if (systemd !== undefined) {
59 const raw = systemd.trim();
60 const unquoted =
61 raw.startsWith('"') && raw.endsWith('"')
62 ? raw.slice(1, -1).replaceAll('\\"', '"').replaceAll("\\\\", "\\")
63 : raw;
64 return unquoted.replaceAll("%%", "%");
65 }
66 const plist = /<key>T3CODE_HOME<\/key>\s*<string>([^<]*)<\/string>/.exec(contents)?.[1];
67 if (plist !== undefined) {
68 return plist.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&amp;", "&");
69 }
70 return undefined;
72​
73export interface BootServicePlan {
74 readonly program: ReadonlyArray<string>;
75 readonly baseDir: string;
76 readonly logPath: string;
77 readonly unitPath: string;
78 /** The manager accepted a detached install; its outcome is written to `logPath`. */
79 readonly handedOff?: boolean;
81​
82/** Pure renderer: service units cannot rely on the user's shell or PATH. */
83export function renderBootServiceUnit(plan: BootServicePlan): string {
84 // The user manager has no reliable network-online target; server networking retries itself.
85 return [
86 "[Unit]",
87 "Description=T3 Code server",
88 "StartLimitIntervalSec=300",
89 "StartLimitBurst=5",
90 "",
91 "[Service]",
92 "Type=simple",
93 "WorkingDirectory=%h",
94 `Environment=T3CODE_HOME=${quoteSystemdValue(plan.baseDir)}`,
95 `Environment=${BOOT_SERVICE_UNIT_ENV}=${BOOT_SERVICE_UNIT_FILE}`,
96 `ExecStart=${plan.program.map(quoteSystemdValue).join(" ")}`,
97 // Let the launcher mark an explicit stop before it signals the server.
98 // systemd still SIGKILLs the whole cgroup if graceful shutdown times out.
99 "KillMode=mixed",
100 // Agents and terminals run in their own scopes in app-t3code-agents.slice
101 // (see process/agentScope.ts). Short helper commands still share this
102 // cgroup, and with the systemd default of OOMPolicy=stop, the kernel
103 // killing one of them stops the whole unit.
104 "OOMPolicy=continue",
105 "Restart=always",
106 "RestartSec=5",
107 // The agents slice is a sibling in app.slice, so these weights keep the
108 // server responsive while agents saturate CPU or disk.
109 "CPUWeight=1000",
110 "IOWeight=1000",
111 // systemd-oomd only honors this when the cgroup it watches is owned by the
112 // same user. Distros watch user-1000.slice, which root owns, so there it is
113 // ignored.
114 "ManagedOOMPreference=avoid",
115 `StandardOutput=append:${escapeSystemdSpecifiers(plan.logPath)}`,
116 `StandardError=append:${escapeSystemdSpecifiers(plan.logPath)}`,
117 "",
118 "[Install]",
119 "WantedBy=default.target",
120 "",
121 ].join("\n");
123​
124function escapeXmlText(value: string): string {
125 return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
127​
128/** Pure renderer: launch agents cannot rely on the user's shell or PATH. */
129export function renderBootServicePlist(
130 plan: BootServicePlan,
131 options: { readonly homeDir: string; readonly environmentPath: string },
132): string {
133 // ExitTimeOut 90 matches systemd's default TimeoutStopSec. A plain stop
134 // completes within the launcher's 5s child grace, but a stop that queues
135 // behind an in-flight update transition can take much longer; launchd's
136 // system-defined default (5s on current macOS) would SIGKILL the launcher
137 // (and, with it, the process group) mid-handoff.
138 // ProcessType Interactive opts out of background-job resource throttling.
139 // AbandonProcessGroup stays at its default (false): launchd reaps leftover
140 // process-group members only when the launcher itself exits — the analog of
141 // KillMode=mixed's final cgroup kill — and not when the launcher restarts its
142 // child, so agent children survive server updates.
143 return [
144 `<?xml version="1.0" encoding="UTF-8"?>`,
145 `<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">`,
146 `<plist version="1.0">`,
147 `<dict>`,
148 ` <key>Label</key>`,
149 ` <string>${BOOT_SERVICE_LAUNCHD_LABEL}</string>`,
150 ` <key>ProgramArguments</key>`,
151 ` <array>`,
152 ...plan.program.map((argument) => ` <string>${escapeXmlText(argument)}</string>`),
153 ` </array>`,
154 ` <key>EnvironmentVariables</key>`,
155 ` <dict>`,
156 ` <key>PATH</key>`,
157 ` <string>${escapeXmlText(options.environmentPath)}</string>`,
158 ` <key>T3CODE_HOME</key>`,
159 ` <string>${escapeXmlText(plan.baseDir)}</string>`,
160 ` <key>${BOOT_SERVICE_UNIT_ENV}</key>`,
161 ` <string>${BOOT_SERVICE_PLIST_FILE}</string>`,
162 ` </dict>`,
163 ` <key>WorkingDirectory</key>`,
164 ` <string>${escapeXmlText(options.homeDir)}</string>`,
165 ` <key>RunAtLoad</key>`,
166 ` <true/>`,
167 ` <key>KeepAlive</key>`,
168 ` <true/>`,
169 ` <key>ThrottleInterval</key>`,
170 ` <integer>5</integer>`,
171 ` <key>ExitTimeOut</key>`,
172 ` <integer>90</integer>`,
173 ` <key>ProcessType</key>`,
174 ` <string>Interactive</string>`,
175 ` <key>StandardOutPath</key>`,
176 ` <string>${escapeXmlText(plan.logPath)}</string>`,
177 ` <key>StandardErrorPath</key>`,
178 ` <string>${escapeXmlText(plan.logPath)}</string>`,
179 `</dict>`,
180 `</plist>`,
181 ``,
182 ].join("\n");
184​
185export interface BootServiceStep {
186 readonly step: string;
187 readonly command: string;
188 readonly args: ReadonlyArray<string>;
189 /**
190 * Non-zero exit is logged and ignored.
191 */
192 readonly optional?: boolean;
193 readonly timeout?: Duration.Input;
195​
196/**
197 * Stop commands block until the service manager gives up: 90s by default for
198 * systemd's TimeoutStopSec, and ExitTimeOut=90 in the rendered plist. This
199 * must stay above both, or the runner cancels the stop mid-shutdown and the
200 * next step races a still-loaded service.
201 */
202const STOP_STEP_TIMEOUT = Duration.seconds(120);
203​
204export interface BootServiceManager {
205 readonly kind: "systemd" | "launchd";
206 readonly unitPath: string;
207 readonly render: (plan: BootServicePlan) => string;
208 readonly stop: ReadonlyArray<BootServiceStep>;
209 readonly activate: ReadonlyArray<BootServiceStep>;
210 readonly restart: ReadonlyArray<BootServiceStep>;
211 /** Queue a restart owned by the manager, since stopping would kill the caller. */
212 readonly handoff?: ReadonlyArray<BootServiceStep>;
213 readonly deactivate: ReadonlyArray<BootServiceStep>;
214 readonly finalize: ReadonlyArray<BootServiceStep>;
216​
217function systemdManager(input: {
218 readonly path: Path.Path;
219 readonly homeDir: string;
220}): BootServiceManager {
221 const unitPath = input.path.join(
222 input.homeDir,
223 ".config",
224 "systemd",
225 "user",
226 BOOT_SERVICE_UNIT_FILE,
227 );
228 const prepareActivation = [
229 {
230 step: "reloading systemd user units",
231 command: "systemctl",
232 args: ["--user", "daemon-reload"],
233 },
234 {
235 step: "enabling the service",
236 command: "systemctl",
237 args: ["--user", "enable", BOOT_SERVICE_UNIT_FILE],
238 },
239 ];
240 return {
241 kind: "systemd",
242 unitPath,
243 render: renderBootServiceUnit,
244 stop: [
245 {
246 step: "stopping the installed service",
247 command: "systemctl",
248 args: ["--user", "stop", BOOT_SERVICE_UNIT_FILE],
249 timeout: STOP_STEP_TIMEOUT,
250 },
251 ],
252 activate: [
253 ...prepareActivation,
254 {
255 step: "starting the service",
256 command: "systemctl",
257 args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
258 },
259 ],
260 restart: [
261 {
262 step: "restarting the service after a failed update",
263 command: "systemctl",
264 args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
265 },
266 ],
267 handoff: [
268 ...prepareActivation,
269 {
270 step: "restarting the service",
271 command: "systemctl",
272 args: ["--user", "restart", "--no-block", BOOT_SERVICE_UNIT_FILE],
273 },
274 ],
275 deactivate: [
276 {
277 step: "stopping the service",
278 command: "systemctl",
279 args: ["--user", "disable", "--now", BOOT_SERVICE_UNIT_FILE],
280 timeout: STOP_STEP_TIMEOUT,
281 },
282 ],
283 finalize: [
284 {
285 step: "reloading systemd user units",
286 command: "systemctl",
287 args: ["--user", "daemon-reload"],
288 },
289 ],
290 };
292​
293function launchdManager(input: {
294 readonly path: Path.Path;
295 readonly homeDir: string;
296 readonly uid: number;
297 readonly environmentPath: string;
298}): BootServiceManager {
299 const unitPath = input.path.join(
300 input.homeDir,
301 "Library",
302 "LaunchAgents",
303 BOOT_SERVICE_PLIST_FILE,
304 );
305 const domainTarget = `gui/${input.uid}`;
306 const serviceTarget = `${domainTarget}/${BOOT_SERVICE_LAUNCHD_LABEL}`;
307 // bootout/enable are optional: they fail on not-loaded states that are fine
308 // to proceed from. The strict `bootstrap` runs last and is also the start:
309 // loading a RunAtLoad/KeepAlive plist starts the job, so a separate kickstart
310 // would kill and restart a server it just booted.
311 return {
312 kind: "launchd",
313 unitPath,
314 render: (plan) =>
315 renderBootServicePlist(plan, {
316 homeDir: input.homeDir,
317 environmentPath: input.environmentPath,
318 }),
319 // Without --wait, bootout returns in milliseconds while the job drains
320 // for up to ExitTimeOut, and a bootstrap during the drain fails EIO.
321 // --wait (present on modern macOS, absent from the man page) blocks until
322 // the job is removed from the domain; STOP_STEP_TIMEOUT outlives it.
323 stop: [
324 {
325 step: "stopping the installed launch agent",
326 command: "launchctl",
327 args: ["bootout", "--wait", serviceTarget],
328 optional: true,
329 timeout: STOP_STEP_TIMEOUT,
330 },
331 ],
332 activate: [
333 // A persisted `launchctl disable` override refuses bootstrap; clear it.
334 {
335 step: "enabling the launch agent",
336 command: "launchctl",
337 args: ["enable", serviceTarget],
338 optional: true,
339 },
340 {
341 step: "starting the service",
342 command: "launchctl",
343 args: ["bootstrap", domainTarget, unitPath],
344 },
345 ],
346 restart: [
347 {
348 step: "restarting the service after a failed update",
349 command: "launchctl",
350 args: ["bootstrap", domainTarget, unitPath],
351 },
352 ],
353 // No `launchctl disable` here: a persisted override would sabotage a later
354 // reinstall.
355 deactivate: [
356 {
357 step: "stopping the service",
358 command: "launchctl",
359 args: ["bootout", "--wait", serviceTarget],
360 optional: true,
361 timeout: STOP_STEP_TIMEOUT,
362 },
363 ],
364 finalize: [],
365 };
367​
368function selectBootServiceManager(input: {
369 readonly platform: NodeJS.Platform;
370 readonly homeDir: string;
371 readonly uid: number | undefined;
372 readonly path: Path.Path;
373 readonly environmentPath: string;
374}): BootServiceManager | undefined {
375 if (input.homeDir === "") {
376 return undefined;
377 }
378 if (input.platform === "linux") {
379 return systemdManager({ path: input.path, homeDir: input.homeDir });
380 }
381 if (input.platform === "darwin" && input.uid !== undefined) {
382 return launchdManager({
383 path: input.path,
384 homeDir: input.homeDir,
385 uid: input.uid,
386 environmentPath: input.environmentPath,
387 });
388 }
389 return undefined;
391​
392export class BootServiceUnsupportedError extends Schema.TaggedError<BootServiceUnsupportedError>()(
393 "BootServiceUnsupportedError",
394 { platform: Schema.String },
395) {
396 override get message(): string {
397 return `Background setup supports Linux with systemd and macOS with launchd; this machine reports '${this.platform}'.`;
398 }
400​
401export class BootServiceCommandError extends Schema.TaggedError<BootServiceCommandError>()(
402 "BootServiceCommandError",
403 {
404 step: Schema.String,
405 exitCode: Schema.optional(Schema.Number),
406 stdoutLength: Schema.optional(Schema.Number),
407 stderrLength: Schema.optional(Schema.Number),
408 cause: Schema.optional(Schema.Defect()),
409 },
410) {
411 override get message(): string {
412 return this.exitCode === undefined
413 ? `Background setup failed while ${this.step}.`
414 : `Background setup failed while ${this.step} (exit code ${this.exitCode}).`;
415 }
417​
418export class BootServiceInstallError extends Schema.TaggedError<BootServiceInstallError>()(
419 "BootServiceInstallError",
420 { cause: Schema.Defect() },
421) {
422 override get message(): string {
423 return "Could not set up the T3 Code background service.";
424 }
426​
427const BootServiceProblem = Schema.Literals([
428 "user-manager-unavailable",
429 "linger-unavailable",
430 "linger-disabled",
431 "service-disabled",
432 "service-stopped",
433 "restart-pending",
434]);
435type BootServiceProblem = typeof BootServiceProblem.Type;
436​
437export function formatBootServiceProblem(problem: BootServiceProblem): string {
438 switch (problem) {
439 case "user-manager-unavailable":
440 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.";
441 case "linger-unavailable":
442 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.';
443 case "linger-disabled":
444 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.';
445 case "service-disabled":
446 return "The service is not enabled to start automatically. Run `t3 service install` to repair it.";
447 case "service-stopped":
448 return "The service is not running. Check the service log and `systemctl --user status t3code.service`, then run `t3 service install`.";
449 case "restart-pending":
450 return "A newer version is installed but the service is still running the previous one. Run `t3 service restart` to switch.";
451 }
453​
454export class BootServicePrerequisiteError extends Schema.TaggedError<BootServicePrerequisiteError>()(
455 "BootServicePrerequisiteError",
456 { problem: BootServiceProblem, cause: Schema.optional(Schema.Defect()) },
457) {
458 override get message(): string {
459 return `[${this.problem}] ${formatBootServiceProblem(this.problem)}`;
460 }
462​
463export class BootServiceUpdatePendingError extends Schema.TaggedError<BootServiceUpdatePendingError>()(
464 "BootServiceUpdatePendingError",
465 {},
466) {
467 override get message(): string {
468 return "A remote server update is still pending. Wait for it to finish, then retry.";
469 }
471​
472export class BootServiceDowngradeRefusedError extends Schema.TaggedError<BootServiceDowngradeRefusedError>()(
473 "BootServiceDowngradeRefusedError",
474 {
475 installedVersion: Schema.String,
476 targetVersion: Schema.String,
477 },
478) {
479 override get message(): string {
480 return `Refusing to replace t3@${this.installedVersion} with older t3@${this.targetVersion}. Run the command again with --allow-downgrade to continue.`;
481 }
483​
484export type BootServiceError =
485 | BootServiceUnsupportedError
486 | BootServiceCommandError
487 | BootServiceInstallError
488 | BootServicePrerequisiteError
489 | BootServiceUpdatePendingError
490 | BootServiceDowngradeRefusedError;
491​
492export interface BootServiceStatus {
493 readonly supported: boolean;
494 readonly installed: boolean;
495 readonly current: boolean;
496 readonly installedVersion?: string;
497 readonly installedBaseDir?: string;
498 readonly problems?: ReadonlyArray<BootServiceProblem>;
499 readonly unitPath: string;
500 readonly logPath: string;
502​
503export class BootService extends Context.Service<
504 BootService,
505 {
506 readonly install: (options?: {
507 readonly allowDowngrade?: boolean;
508 readonly start?: boolean;
509 }) => Effect.Effect<BootServicePlan, BootServiceError>;
510 /**
511 * Only when the unit serves this base dir: the unit name is per user, so
512 * another home's service is left alone, which resolves `skipped`. From
513 * inside the service the restart can only be `queued` with the service
514 * manager, since the stop ends this process.
515 */
516 readonly restart: Effect.Effect<"restarted" | "queued" | "skipped", BootServiceError>;
517 /**
518 * Run `operation` while this home's installed service is stopped, then
519 * start it again when it was enabled (systemd) or loaded (launchd)
520 * beforehand. A service that belongs to another home is left alone. The
521 * service is started again even when stopping it failed; the operation's
522 * own failure is reported ahead of a failure to restart.
523 */
524 readonly withStopped: <A, E, R>(
525 operation: Effect.Effect<A, E, R>,
526 ) => Effect.Effect<A, E | BootServiceError, R>;
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* HostProcess.ExecutablePath;
543 const platform = yield* HostProcess.Platform;
544 const arch = yield* HostProcess.Architecture;
545 const uid = yield* HostProcess.UserId;
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 runningInsideService =
553 (yield* Config.String(BOOT_SERVICE_UNIT_ENV).pipe(Config.withDefault(""))) ===
554 BOOT_SERVICE_UNIT_FILE;
555 const fs = yield* FileSystem.FileSystem;
556 const path = yield* Path.Path;
557 const runner = yield* ProcessRunner.ProcessRunner;
558 const host = input.host ?? { execPath: hostExecPath };
559 const xmlSafeInstallerDirectories = installerPath.split(":").filter(
560 (directory) =>
561 directory.length > 0 &&
562 Array.from(directory).every((character) => {
563 const code = character.charCodeAt(0);
564 return code >= 0x20 || code === 0x09 || code === 0x0a || code === 0x0d;
565 }),
566 );
567 const environmentPath = Array.from(
568 new Set([
569 ...xmlSafeInstallerDirectories,
570 path.dirname(host.execPath),
571 "/opt/homebrew/bin",
572 "/usr/local/bin",
573 "/usr/bin",
574 "/bin",
575 "/usr/sbin",
576 "/sbin",
577 ]),
578 ).join(":");
579​
580 const detectedManager = selectBootServiceManager({
581 platform,
582 homeDir,
583 uid,
584 path,
585 environmentPath,
586 });
587 const unitPath = detectedManager?.unitPath ?? "";
588 const logPath = path.join(input.logsDir, BOOT_SERVICE_LOG_FILE);
589 const statePath = path.join(input.baseDir, "runtime", SERVICE_STATE_FILE);
590 const restartPendingPath = path.join(input.baseDir, "runtime", SERVICE_RESTART_PENDING_FILE);
591 const runtimePaths = pinnedRuntimePaths(path, input.baseDir, input.cliVersion, platform);
592 const writeDurably = (filePath: string, contents: string) =>
593 Effect.scoped(
594 Effect.gen(function* () {
595 const directory = path.dirname(filePath);
596 yield* fs.makeDirectory(directory, { recursive: true });
597 const tempPath = yield* fs.makeTempFileScoped({ directory, prefix: ".service-write-" });
598 yield* fs.writeFileString(tempPath, contents, { mode: 0o600 });
599 // Opened read-write: Windows refuses to flush a handle without write access.
600 yield* (yield* fs.open(tempPath, { flag: "r+" })).sync;
601 yield* fs.rename(tempPath, filePath);
602 // Windows has no directory fsync (EPERM); NTFS journals the rename.
603 yield* (yield* fs.open(directory, { flag: "r" })).sync.pipe(
604 Effect.catchIf(
605 (error) => (error.reason.cause as NodeJS.ErrnoException | undefined)?.code === "EPERM",
606 () => Effect.void,
607 ),
608 );
609 }),
610 ).pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
611 const plan: BootServicePlan = {
612 program: [runtimePaths.entryPath, "__service-launcher"],
613 baseDir: input.baseDir,
614 logPath,
615 unitPath,
616 };
617​
618 const requireManager = Effect.suspend(() =>
619 detectedManager === undefined
620 ? new BootServiceUnsupportedError({ platform })
621 : Effect.succeed(detectedManager),
622 );
623​
624 const logFailure = (error: { readonly message: string }) =>
625 DateTime.now.pipe(
626 Effect.flatMap((now) =>
627 fs.writeFileString(logPath, `${DateTime.formatIso(now)} ${error.message}\n`, { flag: "a" }),
628 ),
629 Effect.ignore,
630 );
631​
632 const runStep = Effect.fn("cloud.boot_service.run_step")(function* (
633 step: string,
634 command: string,
635 args: ReadonlyArray<string>,
636 options?: { readonly timeout?: Duration.Input },
637 ) {
638 return yield* runner.run({ command, args, timeout: options?.timeout }).pipe(
639 Effect.mapError((cause) => new BootServiceCommandError({ step, cause })),
640 Effect.filterOrFail(
641 (result) => result.code === 0,
642 (result) =>
643 new BootServiceCommandError({
644 step,
645 exitCode: Number(result.code),
646 stdoutLength: result.stdout.length,
647 stderrLength: result.stderr.length,
648 }),
649 ),
650 Effect.tapError(logFailure),
651 );
652 });
653​
654 const runSteps = (steps: ReadonlyArray<BootServiceStep>) =>
655 Effect.forEach(
656 steps,
657 (entry) => {
658 const run = runStep(
659 entry.step,
660 entry.command,
661 entry.args,
662 entry.timeout === undefined ? undefined : { timeout: entry.timeout },
663 );
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 readonly start?: boolean;
732 }) {
733 const manager = yield* requireManager;
734 yield* fs
735 .makeDirectory(input.logsDir, { recursive: true })
736 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
737​
738 if (manager.kind === "systemd") {
739 yield* requireSystemdPrerequisites.pipe(Effect.tapError(logFailure));
740 }
741​
742 yield* ensurePinnedRuntimeInstalled({
743 baseDir: input.baseDir,
744 version: input.cliVersion,
745 fs,
746 path,
747 runner,
748 httpClient,
749 platform,
750 arch,
751 releaseBaseUrl,
752 validate: (runtime) =>
753 runner
754 .run({
755 command: pinnedRuntimeCommand(runtime).command,
756 args: [...pinnedRuntimeCommand(runtime).args, "--version"],
757 timeout: Duration.seconds(30),
758 })
759 .pipe(
760 Effect.mapError(
761 (cause) =>
762 new PinnedRuntimeInstallError({
763 step: "verifying the pinned t3 runtime",
764 cause,
765 }),
766 ),
767 Effect.flatMap((result) => {
768 const reportedVersion = /\bv(\S+)\s*$/.exec(result.stdout)?.[1];
769 return result.code === 0 && reportedVersion === input.cliVersion
770 ? Effect.void
771 : Effect.fail(
772 new PinnedRuntimeInstallError({
773 step: "verifying the pinned t3 runtime",
774 exitCode: Number(result.code),
775 stdoutLength: result.stdout.length,
776 stderrLength: result.stderr.length,
777 }),
778 );
779 }),
780 ),
781 }).pipe(
782 Effect.mapError((error) =>
783 error._tag === "PinnedRuntimeInstallError"
784 ? new BootServiceCommandError({
785 step: error.step,
786 exitCode: error.exitCode,
787 stdoutLength: error.stdoutLength,
788 stderrLength: error.stderrLength,
789 cause: error,
790 })
791 : new BootServiceInstallError({ cause: error }),
792 ),
793 );
794 const installed = yield* fs
795 .exists(unitPath)
796 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
797 // With start=false the service keeps running while its files change. The
798 // launcher reads the state file once at startup and the unit only matters
799 // on the next start, so that is safe as long as the launcher is not in the
800 // middle of a remote update, which is the one time it writes the state file
801 // itself.
802 const start = options?.start !== false;
803 if (installed && start && runningInsideService && manager.kind === "systemd") {
804 // Stopping the unit from inside it kills this process before the start.
805 // A transient unit runs the same install from outside, stop first, so it
806 // still serialises with a remote update the launcher may be starting.
807 yield* runStep("handing the install to a transient unit", "systemd-run", [
808 "--user",
809 "--collect",
810 "--quiet",
811 // Transient properties reach systemd literally, unlike unit-file specifiers.
812 `--property=StandardOutput=append:${logPath}`,
813 `--property=StandardError=append:${logPath}`,
814 `--setenv=${BOOT_SERVICE_UNIT_ENV}=`,
815 runtimePaths.entryPath,
816 "service",
817 "install",
818 "--base-dir",
819 // systemd expands $VAR in arguments (not in the executable path).
820 input.baseDir.replaceAll("$", () => "$$"),
821 ...(options?.allowDowngrade === true ? ["--allow-downgrade"] : []),
822 ]);
823 return { ...plan, handedOff: true };
824 }
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 // Files can match the new version even when activation fails; keep that install retryable.
855 yield* fs.writeFileString(restartPendingPath, `${input.cliVersion}\n`, { mode: 0o600 });
856 yield* writeDurably(
857 statePath,
858 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned document.
859 `${JSON.stringify(
860 {
861 protocol: SERVICE_LAUNCHER_PROTOCOL,
862 activeVersion: input.cliVersion,
863 } satisfies ServiceState,
864 null,
865 2,
866 )}\n`,
867 );
868 if (!start && installed) {
869 // The launcher only writes this file while a remote update is in
870 // flight. One that began after the check above lands either before
871 // this write (then the launcher's copy in memory is what it keeps
872 // acting on, and its next write puts its own outcome back) or after
873 // it, which this read catches: the file no longer says what was just
874 // written, so stop here before repointing the unit.
875 const written = yield* fs.readFileString(statePath);
876 if (serviceStateActiveVersion(written) !== input.cliVersion) {
877 return yield* new BootServiceUpdatePendingError();
878 }
879 }
880 yield* writeDurably(unitPath, manager.render(plan));
881​
882 if (start) {
883 yield* runSteps(manager.activate);
884 yield* fs.remove(restartPendingPath, { force: true });
885 }
886 }).pipe(
887 Effect.mapError((cause) =>
888 cause._tag === "PlatformError" ? new BootServiceInstallError({ cause }) : cause,
889 ),
890 Effect.tapError(() =>
891 installed && start ? runSteps(manager.restart).pipe(Effect.ignore) : Effect.void,
892 ),
893 );
894 return plan;
895 });
896​
897 const restart: BootService["Service"]["restart"] = Effect.gen(function* () {
898 const manager = yield* requireManager;
899 const unit = yield* fs.readFileString(unitPath).pipe(Effect.option);
900 if (Option.isNone(unit)) return "skipped" as const;
901 const installedBaseDir = bootServiceBaseDirOf(unit.value);
902 if (
903 installedBaseDir === undefined ||
904 path.resolve(installedBaseDir) !== path.resolve(input.baseDir)
905 ) {
906 return "skipped" as const;
907 }
908 // Writes no state, and the launcher lets an update transition in flight
909 // finish before the queued stop tears it down.
910 if (runningInsideService && manager.handoff !== undefined) {
911 yield* runSteps(manager.handoff);
912 return "queued" as const;
913 }
914 yield* runSteps(manager.stop);
915 yield* runSteps(manager.activate).pipe(
916 Effect.tapError(() => runSteps(manager.restart).pipe(Effect.ignore)),
917 );
918 yield* fs.remove(restartPendingPath, { force: true });
919 return "restarted" as const;
920 }).pipe(
921 Effect.mapError((cause) =>
922 cause._tag === "PlatformError" ? new BootServiceInstallError({ cause }) : cause,
923 ),
924 Effect.withSpan("cloud.boot_service.restart"),
925 );
926​
927 const withStopped = Effect.fn("cloud.boot_service.with_stopped")(function* <A, E, R>(
928 operation: Effect.Effect<A, E, R>,
929 ): Effect.fn.Return<A, E | BootServiceError, R> {
930 if (detectedManager === undefined) return yield* operation;
931 const manager = detectedManager;
932 const unit = yield* fs.readFileString(unitPath).pipe(Effect.option);
933 if (Option.isNone(unit)) return yield* operation;
934 const installedBaseDir = bootServiceBaseDirOf(unit.value);
935 if (
936 installedBaseDir === undefined ||
937 path.resolve(installedBaseDir) !== path.resolve(input.baseDir)
938 ) {
939 return yield* operation;
940 }
941 // `is-active` fails while a crash-looping unit sits in `activating
942 // (auto-restart)`, and a throttled launchd job is loaded without a pid;
943 // both would start the server mid-repair. So the unit is always
944 // stopped, and started again when it was active, enabled or loaded
945 // before; a disabled unit caught crash-looping stays stopped.
946 const restore =
947 manager.kind === "systemd"
948 ? yield* Effect.map(
949 Effect.all(
950 [
951 probe("systemctl", ["--user", "is-enabled", BOOT_SERVICE_UNIT_FILE]),
952 probe("systemctl", ["--user", "is-active", BOOT_SERVICE_UNIT_FILE]),
953 ],
954 { concurrency: "unbounded" },
955 ),
956 ([enabled, active]) => succeeded(active) || succeeded(enabled),
957 )
958 : succeeded(
959 yield* probe("launchctl", ["print", `gui/${uid}/${BOOT_SERVICE_LAUNCHD_LABEL}`]),
960 );
961 return yield* Effect.acquireUseRelease(
962 // Every stop step is required when the service is to be restored: a
963 // step that was fine to skip during uninstall would leave the server
964 // holding the database. A stop that fails (a timeout, say) may still
965 // have stopped the service, so the restore below runs either way.
966 // Nothing to restore means nothing is expected to be loaded, and the
967 // stop is best-effort (launchd's bootout fails on an unloaded job).
968 runSteps(manager.stop.map((step) => ({ ...step, optional: !restore }))).pipe(Effect.exit),
969 (stopped): Effect.Effect<A, E | BootServiceError, R> =>
970 Exit.isSuccess(stopped) ? operation : Effect.failCause(stopped.cause),
971 (_, exit) => {
972 if (!restore) return Effect.void;
973 // Start only: `activate` would also enable a unit the user disabled.
974 // When the operation itself failed, its error is the one worth reporting.
975 const start = runSteps(manager.restart);
976 return Exit.isFailure(exit) ? Effect.ignore(start) : start;
977 },
978 );
979 });
980​
981 const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () {
982 const manager = yield* requireManager;
983 if (
984 !(yield* fs
985 .exists(unitPath)
986 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))))
987 )
988 return false;
989 yield* runSteps(manager.deactivate);
990 yield* fs
991 .remove(unitPath)
992 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
993 yield* runSteps(manager.finalize);
994 return true;
995 }).pipe(Effect.withSpan("cloud.boot_service.uninstall"));
996​
997 const status: BootService["Service"]["status"] = Effect.gen(function* () {
998 if (detectedManager === undefined) {
999 return { supported: false, installed: false, current: false, unitPath, logPath };
1001 if (!(yield* fs.exists(unitPath))) {
1002 return { supported: true, installed: false, current: false, unitPath, logPath };
1004 const [unit, runtimeEntryExists, runtimeSentinel, stateText] = yield* Effect.all([
1005 fs.readFileString(unitPath),
1006 fs.exists(runtimePaths.entryPath),
1007 fs.readFileString(runtimePaths.sentinelPath).pipe(Effect.option),
1008 fs.readFileString(statePath).pipe(Effect.option),
1009 ]);
1010 const state = Option.isSome(stateText) ? parseServiceState(stateText.value) : undefined;
1011 const installedVersion = Option.isSome(stateText)
1012 ? serviceStateActiveVersion(stateText.value)
1013 : undefined;
1014 const installedBaseDir = bootServiceBaseDirOf(unit);
1015 const normalizeUnit = (contents: string) =>
1016 detectedManager.kind === "launchd"
1017 ? contents.replace(/(<key>PATH<\/key>\n\s*<string>)[^<]*(<\/string>)/, "$1$2")
1018 : contents;
1019 const problems: BootServiceProblem[] =
1020 detectedManager.kind === "systemd" ? [...(yield* readSystemdProblems(true))] : [];
1021 if (yield* fs.exists(restartPendingPath)) problems.push("restart-pending");
1022 return {
1023 supported: true,
1024 installed: true,
1025 ...(installedVersion === undefined ? {} : { installedVersion }),
1026 ...(installedBaseDir === undefined ? {} : { installedBaseDir }),
1027 problems,
1028 current:
1029 problems.length === 0 &&
1030 normalizeUnit(unit) === normalizeUnit(detectedManager.render(plan)) &&
1031 runtimeEntryExists &&
1032 Option.isSome(runtimeSentinel) &&
1033 runtimeSentinel.value.trim() === input.cliVersion &&
1034 state?.activeVersion === input.cliVersion &&
1035 state?.update?.status !== "pending",
1036 unitPath,
1037 logPath,
1038 };
1039 }).pipe(
1040 Effect.mapError((cause) => new BootServiceInstallError({ cause })),
1041 Effect.withSpan("cloud.boot_service.status"),
1042 );
1043​
1044 return BootService.of({ install, restart, withStopped, uninstall, status });
1045});
1046​
1047export const layer = (input: {
1048 readonly baseDir: string;
1049 readonly logsDir: string;
1050 readonly cliVersion: string;
1051 readonly host?: BootServiceHost;
1052}) => Layer.effect(BootService, make(input));