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