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

bootService.ts

1,061 lines39.5 KB

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