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