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