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 { CliError } from "effect/cli";
13import { HttpClient } from "effect/http";
14import * as Schema from "effect/Schema";
15
16import { CLI_RELEASE_BASE_URL_ENV } from "@t3tools/shared/cliRelease";
17
18import * as ProcessRunner from "../processRunner.ts";
19import { acquireServiceSelectionLock } from "./serviceSelectionLock.ts";
20import {
21 ensurePinnedRuntimeInstalled,
22 launcherOwnsVersionsDir,
23 pinnedRuntimeCommand,
24 pinnedRuntimePaths,
25 pinnedRuntimeVersionsDir,
26 PinnedRuntimeInstallError,
27} from "./pinnedRuntime.ts";
28import {
29 SERVICE_LAUNCHER_PROTOCOL,
30 SERVICE_RESTART_PENDING_FILE,
31 SERVICE_STATE_FILE,
32 SERVICE_UNIT_ENV,
33 compareExactServiceVersions,
34 serviceUnitBaseDirOf as bootServiceBaseDirOf,
35 parseServiceState,
36 serviceStateActiveVersion,
37 serviceStateHasPendingUpdate,
38 type ServiceState,
39} from "./serviceProtocol.ts";
40
41export {
42 serviceUnitBaseDirOf as bootServiceBaseDirOf,
43 serviceUnitProgramOf as bootServiceProgramOf,
44} from "./serviceProtocol.ts";
45
46const BOOT_SERVICE_NAME = "t3code";
47export const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
48// `.service` suffix keeps the label distinct from the desktop app's bundle id
49// (com.t3tools.t3code), so launchd and TCC records never collide.
50export const BOOT_SERVICE_LAUNCHD_LABEL = "com.t3tools.t3code.service";
51export const BOOT_SERVICE_PLIST_FILE = `${BOOT_SERVICE_LAUNCHD_LABEL}.plist`;
52export const BOOT_SERVICE_LOG_FILE = "boot-service.log";
53
54/** systemd expands `%` specifiers, including in unquoted append-log paths. */
55function escapeSystemdSpecifiers(value: string): string {
56 return value.replaceAll("%", "%%");
57}
58
59function quoteSystemdValue(value: string): string {
60 const escaped = escapeSystemdSpecifiers(value);
61 return /[\s"'\\]/.test(escaped)
62 ? `"${escaped.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`
63 : escaped;
64}
65
66export interface BootServicePlan {
67 readonly program: ReadonlyArray<string>;
68 readonly baseDir: string;
69 readonly logPath: string;
70 readonly unitPath: string;
71 /** The manager accepted a detached install; its outcome is written to `logPath`. */
72 readonly handedOff?: boolean;
73}
74
75/** Service units cannot rely on the user's shell or PATH. */
76export function renderBootServiceUnit(plan: BootServicePlan): string {
77 // The user manager has no reliable network-online target; server networking retries itself.
78 return [
79 "[Unit]",
80 "Description=T3 Code server",
81 "StartLimitIntervalSec=300",
82 "StartLimitBurst=5",
83 "",
84 "[Service]",
85 "Type=simple",
86 "WorkingDirectory=%h",
87 `Environment=T3CODE_HOME=${quoteSystemdValue(plan.baseDir)}`,
88 `Environment=${SERVICE_UNIT_ENV}=${BOOT_SERVICE_UNIT_FILE}`,
89 `ExecStart=${plan.program.map(quoteSystemdValue).join(" ")}`,
90 // Let the launcher mark an explicit stop before it signals the server.
91 // systemd still SIGKILLs the whole cgroup if graceful shutdown times out.
92 "KillMode=mixed",
93 // Helpers share this cgroup; default OOMPolicy=stop would stop the unit if one is OOM-killed.
94 "OOMPolicy=continue",
95 "Restart=always",
96 "RestartSec=5",
97 // Weights favor the server over the sibling agents slice; IOWeight needs a delegated io controller.
98 "CPUWeight=1000",
99 "IOWeight=1000",
100 // Reclaim takes the agents' unprotected pages first. The kernel caps this at the
101 // protection of user.slice and user@.service, which only root can grant.
102 "MemoryLow=1536M",
103 // A user manager's own score, the lowest it may set: below its other services (200) and agents (800).
104 // `t3 service protect` lowers it further through a drop-in.
105 "OOMScoreAdjust=100",
106 // systemd-oomd ignores this preference when the watched cgroup is root-owned, as user-1000.slice usually is.
107 "ManagedOOMPreference=avoid",
108 `StandardOutput=append:${escapeSystemdSpecifiers(plan.logPath)}`,
109 `StandardError=append:${escapeSystemdSpecifiers(plan.logPath)}`,
110 "",
111 "[Install]",
112 "WantedBy=default.target",
113 "",
114 ].join("\n");
115}
116
117function escapeXmlText(value: string): string {
118 return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
119}
120
121/** Launch agents cannot rely on the user's shell or PATH. */
122export function renderBootServicePlist(
123 plan: BootServicePlan,
124 options: { readonly homeDir: string; readonly environmentPath: string },
125): string {
126 // Allow 90s stops for update handoffs.
127 // Interactive avoids background throttling.
128 // AbandonProcessGroup=false reaps agents only on launcher exit, preserving them across child updates.
129 return [
130 `<?xml version="1.0" encoding="UTF-8"?>`,
131 `<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">`,
132 `<plist version="1.0">`,
133 `<dict>`,
134 ` <key>Label</key>`,
135 ` <string>${BOOT_SERVICE_LAUNCHD_LABEL}</string>`,
136 ` <key>ProgramArguments</key>`,
137 ` <array>`,
138 ...plan.program.map((argument) => ` <string>${escapeXmlText(argument)}</string>`),
139 ` </array>`,
140 ` <key>EnvironmentVariables</key>`,
141 ` <dict>`,
142 ` <key>PATH</key>`,
143 ` <string>${escapeXmlText(options.environmentPath)}</string>`,
144 ` <key>T3CODE_HOME</key>`,
145 ` <string>${escapeXmlText(plan.baseDir)}</string>`,
146 ` <key>${SERVICE_UNIT_ENV}</key>`,
147 ` <string>${BOOT_SERVICE_PLIST_FILE}</string>`,
148 ` </dict>`,
149 ` <key>WorkingDirectory</key>`,
150 ` <string>${escapeXmlText(options.homeDir)}</string>`,
151 ` <key>RunAtLoad</key>`,
152 ` <true/>`,
153 ` <key>KeepAlive</key>`,
154 ` <true/>`,
155 ` <key>ThrottleInterval</key>`,
156 ` <integer>5</integer>`,
157 ` <key>ExitTimeOut</key>`,
158 ` <integer>90</integer>`,
159 ` <key>ProcessType</key>`,
160 ` <string>Interactive</string>`,
161 ` <key>StandardOutPath</key>`,
162 ` <string>${escapeXmlText(plan.logPath)}</string>`,
163 ` <key>StandardErrorPath</key>`,
164 ` <string>${escapeXmlText(plan.logPath)}</string>`,
165 `</dict>`,
166 `</plist>`,
167 ``,
168 ].join("\n");
169}
170
171export interface BootServiceStep {
172 readonly step: string;
173 readonly command: string;
174 readonly args: ReadonlyArray<string>;
175 /** Non-zero exit is logged and ignored. */
176 readonly optional?: boolean;
177 readonly timeout?: Duration.Input;
178}
179
180/** Must exceed systemd TimeoutStopSec and launchd ExitTimeOut (both 90s) to avoid shutdown races. */
181const STOP_STEP_TIMEOUT = Duration.seconds(120);
182
183export interface BootServiceManager {
184 readonly kind: "systemd" | "launchd";
185 readonly unitPath: string;
186 readonly render: (plan: BootServicePlan) => string;
187 readonly stop: ReadonlyArray<BootServiceStep>;
188 readonly activate: ReadonlyArray<BootServiceStep>;
189 readonly restart: ReadonlyArray<BootServiceStep>;
190 /** Queue a restart owned by the manager, since stopping would kill the caller. */
191 readonly handoff?: ReadonlyArray<BootServiceStep>;
192 readonly deactivate: ReadonlyArray<BootServiceStep>;
193 readonly finalize: ReadonlyArray<BootServiceStep>;
194}
195
196function systemdManager(input: {
197 readonly path: Path.Path;
198 readonly unitDir: string;
199}): BootServiceManager {
200 const unitPath = input.path.join(input.unitDir, BOOT_SERVICE_UNIT_FILE);
201 const prepareActivation = [
202 {
203 step: "reloading systemd user units",
204 command: "systemctl",
205 args: ["--user", "daemon-reload"],
206 },
207 {
208 step: "enabling the service",
209 command: "systemctl",
210 args: ["--user", "enable", BOOT_SERVICE_UNIT_FILE],
211 },
212 ];
213 return {
214 kind: "systemd",
215 unitPath,
216 render: renderBootServiceUnit,
217 stop: [
218 {
219 step: "stopping the installed service",
220 command: "systemctl",
221 args: ["--user", "stop", BOOT_SERVICE_UNIT_FILE],
222 timeout: STOP_STEP_TIMEOUT,
223 },
224 ],
225 activate: [
226 ...prepareActivation,
227 {
228 step: "starting the service",
229 command: "systemctl",
230 args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
231 },
232 ],
233 restart: [
234 {
235 step: "restarting the service after a failed update",
236 command: "systemctl",
237 args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
238 },
239 ],
240 handoff: [
241 ...prepareActivation,
242 {
243 step: "restarting the service",
244 command: "systemctl",
245 args: ["--user", "restart", "--no-block", BOOT_SERVICE_UNIT_FILE],
246 },
247 ],
248 deactivate: [
249 {
250 step: "stopping the service",
251 command: "systemctl",
252 args: ["--user", "disable", "--now", BOOT_SERVICE_UNIT_FILE],
253 timeout: STOP_STEP_TIMEOUT,
254 },
255 ],
256 finalize: [
257 {
258 step: "reloading systemd user units",
259 command: "systemctl",
260 args: ["--user", "daemon-reload"],
261 },
262 ],
263 };
264}
265
266function launchdManager(input: {
267 readonly path: Path.Path;
268 readonly homeDir: string;
269 readonly uid: number;
270 readonly environmentPath: string;
271}): BootServiceManager {
272 const unitPath = input.path.join(
273 input.homeDir,
274 "Library",
275 "LaunchAgents",
276 BOOT_SERVICE_PLIST_FILE,
277 );
278 const domainTarget = `gui/${input.uid}`;
279 const serviceTarget = `${domainTarget}/${BOOT_SERVICE_LAUNCHD_LABEL}`;
280 // Unloaded jobs may reject bootout/enable. Bootstrap starts RunAtLoad/KeepAlive jobs; kickstart would restart them.
281 return {
282 kind: "launchd",
283 unitPath,
284 render: (plan) =>
285 renderBootServicePlist(plan, {
286 homeDir: input.homeDir,
287 environmentPath: input.environmentPath,
288 }),
289 // bootout --wait is undocumented but waits through ExitTimeOut, preventing bootstrap EIO races.
290 stop: [
291 {
292 step: "stopping the installed launch agent",
293 command: "launchctl",
294 args: ["bootout", "--wait", serviceTarget],
295 optional: true,
296 timeout: STOP_STEP_TIMEOUT,
297 },
298 ],
299 activate: [
300 // A persisted `launchctl disable` override refuses bootstrap; clear it.
301 {
302 step: "enabling the launch agent",
303 command: "launchctl",
304 args: ["enable", serviceTarget],
305 optional: true,
306 },
307 {
308 step: "starting the service",
309 command: "launchctl",
310 args: ["bootstrap", domainTarget, unitPath],
311 },
312 ],
313 restart: [
314 {
315 step: "restarting the service after a failed update",
316 command: "launchctl",
317 args: ["bootstrap", domainTarget, unitPath],
318 },
319 ],
320 // Persisted launchctl disable overrides would block reinstall.
321 deactivate: [
322 {
323 step: "stopping the service",
324 command: "launchctl",
325 args: ["bootout", "--wait", serviceTarget],
326 optional: true,
327 timeout: STOP_STEP_TIMEOUT,
328 },
329 ],
330 finalize: [],
331 };
332}
333
334function selectBootServiceManager(input: {
335 readonly platform: NodeJS.Platform;
336 readonly homeDir: string;
337 readonly xdgConfigHome: string;
338 readonly systemdUnitDir: string | undefined;
339 readonly uid: number | undefined;
340 readonly path: Path.Path;
341 readonly environmentPath: string;
342}): BootServiceManager | undefined {
343 if (input.homeDir === "") {
344 return undefined;
345 }
346 if (input.platform === "linux") {
347 return systemdManager({
348 path: input.path,
349 unitDir:
350 input.systemdUnitDir ??
351 input.path.join(
352 input.path.isAbsolute(input.xdgConfigHome)
353 ? input.xdgConfigHome
354 : input.path.join(input.homeDir, ".config"),
355 "systemd",
356 "user",
357 ),
358 });
359 }
360 if (input.platform === "darwin" && input.uid !== undefined) {
361 return launchdManager({
362 path: input.path,
363 homeDir: input.homeDir,
364 uid: input.uid,
365 environmentPath: input.environmentPath,
366 });
367 }
368 return undefined;
369}
370
371const decodeSystemdUnitPaths = Schema.decodeUnknownEffect(
372 Schema.fromJsonString(Schema.Struct({ data: Schema.Array(Schema.String) })),
373);
374
375// The manager may not share the installer's environment; JSON preserves spaces in its paths.
376const readSystemdUnitDirectory = Effect.fn("cloud.boot_service.read_systemd_unit_directory")(
377 function* () {
378 const runner = yield* ProcessRunner.ProcessRunner;
379 const path = yield* Path.Path;
380 const result = yield* runner.run({
381 command: "busctl",
382 args: [
383 "--user",
384 "--json=short",
385 "get-property",
386 "org.freedesktop.systemd1",
387 "/org/freedesktop/systemd1",
388 "org.freedesktop.systemd1.Manager",
389 "UnitPath",
390 ],
391 timeout: Duration.seconds(5),
392 });
393 if (result.code !== 0) return undefined;
394 const { data } = yield* decodeSystemdUnitPaths(result.stdout);
395 // The persistent control directory identifies the manager's config root despite UnitPath overrides.
396 const controlDirectory = data.find(
397 (directory) =>
398 path.isAbsolute(directory) &&
399 directory.endsWith("/systemd/user.control") &&
400 data.includes(directory.slice(0, -".control".length)),
401 );
402 return controlDirectory?.slice(0, -".control".length);
403 },
404 Effect.orElseSucceed(() => undefined),
405);
406
407export class BootServiceUnsupportedError extends Schema.TaggedError<BootServiceUnsupportedError>()(
408 "BootServiceUnsupportedError",
409 { platform: Schema.String },
410) {
411 override get message(): string {
412 return `Background setup supports Linux with systemd and macOS with launchd; this machine reports '${this.platform}'.`;
413 }
414}
415
416export class BootServiceCommandError extends Schema.TaggedError<BootServiceCommandError>()(
417 "BootServiceCommandError",
418 {
419 step: Schema.String,
420 exitCode: Schema.optional(Schema.Number),
421 stdoutLength: Schema.optional(Schema.Number),
422 stderrLength: Schema.optional(Schema.Number),
423 cause: Schema.optional(Schema.Defect()),
424 },
425) {
426 override get message(): string {
427 return this.exitCode === undefined
428 ? `Background setup failed while ${this.step}.`
429 : `Background setup failed while ${this.step} (exit code ${this.exitCode}).`;
430 }
431}
432
433export class BootServiceInstallError extends Schema.TaggedError<BootServiceInstallError>()(
434 "BootServiceInstallError",
435 { cause: Schema.Defect() },
436) {
437 override get message(): string {
438 return "Could not set up the T3 Code background service.";
439 }
440}
441
442const BootServiceProblem = Schema.Literals([
443 "user-manager-unavailable",
444 "linger-unavailable",
445 "linger-disabled",
446 "service-disabled",
447 "service-stopped",
448 "restart-pending",
449]);
450type BootServiceProblem = typeof BootServiceProblem.Type;
451
452export function formatBootServiceProblem(problem: BootServiceProblem): string {
453 switch (problem) {
454 case "user-manager-unavailable":
455 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.";
456 case "linger-unavailable":
457 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.';
458 case "linger-disabled":
459 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.';
460 case "service-disabled":
461 return "The service is not enabled to start automatically. Run `t3 service install` to repair it.";
462 case "service-stopped":
463 return "The service is not running. Check the service log and `systemctl --user status t3code.service`, then run `t3 service install`.";
464 case "restart-pending":
465 return "A newer version is installed but the service is still running the previous one. Run `t3 service restart` to switch.";
466 }
467}
468
469export class BootServicePrerequisiteError extends Schema.TaggedError<BootServicePrerequisiteError>()(
470 "BootServicePrerequisiteError",
471 { problem: BootServiceProblem, cause: Schema.optional(Schema.Defect()) },
472) {
473 override get message(): string {
474 return `[${this.problem}] ${formatBootServiceProblem(this.problem)}`;
475 }
476}
477
478export class BootServiceUpdatePendingError extends Schema.TaggedError<BootServiceUpdatePendingError>()(
479 "BootServiceUpdatePendingError",
480 { recoveryCommand: Schema.optional(Schema.String) },
481) {
482 override get message(): string {
483 if (this.recoveryCommand !== undefined) {
484 return `A remote server update is still pending, but its service definition is missing. With the service stopped, run this on the server machine: ${this.recoveryCommand}\nWait for the update to finish or roll back, stop the foreground launcher with Ctrl-C, then retry the install.`;
485 }
486 return "A remote server update is still pending. Wait for it to finish, then retry.";
487 }
488}
489
490export class BootServiceDowngradeRefusedError extends Schema.TaggedError<BootServiceDowngradeRefusedError>()(
491 "BootServiceDowngradeRefusedError",
492 {
493 installedVersion: Schema.String,
494 targetVersion: Schema.String,
495 },
496) {
497 override get message(): string {
498 return `Refusing to replace t3@${this.installedVersion} with older t3@${this.targetVersion}. Run the command again with --allow-downgrade to continue.`;
499 }
500}
501
502export const formatBootServiceBaseDirOption = (baseDir: string) =>
503 `--base-dir '${baseDir.replaceAll("'", `'"'"'`)}'`;
504
505export class BootServiceOtherBaseDirError extends Schema.TaggedError<BootServiceOtherBaseDirError>()(
506 "BootServiceOtherBaseDirError",
507 {
508 installedBaseDir: Schema.String,
509 baseDir: Schema.String,
510 },
511) {
512 override get message(): string {
513 return `The T3 Code service on this machine serves ${this.installedBaseDir}, not ${this.baseDir}. Pass ${formatBootServiceBaseDirOption(this.installedBaseDir)} to manage it, or run \`t3 service uninstall ${formatBootServiceBaseDirOption(this.installedBaseDir)}\` first to move it; both data directories are kept.`;
514 }
515
516 // A refusal the user fixes by rerunning, so the CLI prints the message, not a stack trace.
517 override get [CliError.userMessage]() {
518 return this.message;
519 }
520}
521
522export type BootServiceError =
523 | BootServiceUnsupportedError
524 | BootServiceOtherBaseDirError
525 | BootServiceCommandError
526 | BootServiceInstallError
527 | BootServicePrerequisiteError
528 | BootServiceUpdatePendingError
529 | BootServiceDowngradeRefusedError;
530
531export interface BootServiceStatus {
532 readonly supported: boolean;
533 readonly installed: boolean;
534 readonly current: boolean;
535 readonly installedVersion?: string;
536 readonly installedBaseDir?: string;
537 /** Set when the installed unit serves a different T3 home than this CLI. */
538 readonly otherBaseDir?: string;
539 readonly problems?: ReadonlyArray<BootServiceProblem>;
540 readonly unitPath: string;
541 readonly logPath: string;
542}
543
544export class BootService extends Context.Service<
545 BootService,
546 {
547 readonly install: (options?: {
548 readonly allowDowngrade?: boolean;
549 readonly start?: boolean;
550 }) => Effect.Effect<BootServicePlan, BootServiceError>;
551 /**
552 * Only when the unit serves this base dir: the unit name is per user, so
553 * another home's service is left alone, which resolves `skipped`. From
554 * inside the service the restart can only be `queued` with the service
555 * manager, since the stop ends this process.
556 */
557 readonly restart: Effect.Effect<"restarted" | "queued" | "skipped", BootServiceError>;
558 /**
559 * Runs the operation with this home's service stopped; other homes are left alone.
560 * Restores a previously enabled or loaded service even if stopping failed.
561 * The operation's failure takes precedence over a restart failure.
562 */
563 readonly withStopped: <A, E, R>(
564 operation: Effect.Effect<A, E, R>,
565 ) => Effect.Effect<A, E | BootServiceError, R>;
566 readonly uninstall: Effect.Effect<boolean, BootServiceError>;
567 readonly status: Effect.Effect<BootServiceStatus, BootServiceError>;
568 }
569>()("t3/cloud/bootService") {}
570
571export interface BootServiceHost {
572 readonly execPath: string;
573}
574
575export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
576 readonly baseDir: string;
577 readonly logsDir: string;
578 readonly cliVersion: string;
579 readonly host?: BootServiceHost;
580}) {
581 const hostExecPath = yield* HostProcess.ExecutablePath;
582 const platform = yield* HostProcess.Platform;
583 const arch = yield* HostProcess.Architecture;
584 const uid = yield* HostProcess.UserId;
585 const httpClient = yield* HttpClient.HttpClient;
586 const releaseBaseUrl = Option.getOrUndefined(
587 yield* Config.String(CLI_RELEASE_BASE_URL_ENV).pipe(Config.option),
588 );
589 const homeDir = yield* Config.String("HOME").pipe(Config.withDefault(""));
590 const xdgConfigHome = yield* Config.String("XDG_CONFIG_HOME").pipe(Config.withDefault(""));
591 const installerPath = yield* Config.String("PATH").pipe(Config.withDefault(""));
592 const runningInsideService =
593 (yield* Config.String(SERVICE_UNIT_ENV).pipe(Config.withDefault(""))) ===
594 BOOT_SERVICE_UNIT_FILE;
595 const fs = yield* FileSystem.FileSystem;
596 const path = yield* Path.Path;
597 const runner = yield* ProcessRunner.ProcessRunner;
598 const host = input.host ?? { execPath: hostExecPath };
599 const runtimePaths = pinnedRuntimePaths(path, input.baseDir, input.cliVersion, platform);
600 const versionsDir = pinnedRuntimeVersionsDir(path, input.baseDir);
601 const xmlSafeInstallerDirectories = installerPath.split(":").filter(
602 (directory) =>
603 directory.length > 0 &&
604 Array.from(directory).every((character) => {
605 const code = character.charCodeAt(0);
606 return code >= 0x20 || code === 0x09 || code === 0x0a || code === 0x0d;
607 }),
608 );
609 // During an update, the running CLI and a PATH inherited from the service name the runtime
610 // being replaced. The service and its agent shells should find the runtime it starts.
611 const environmentPath = Array.from(
612 new Set(
613 [
614 ...xmlSafeInstallerDirectories,
615 path.dirname(host.execPath),
616 "/opt/homebrew/bin",
617 "/usr/local/bin",
618 "/usr/bin",
619 "/bin",
620 "/usr/sbin",
621 "/sbin",
622 ].map((directory) =>
623 launcherOwnsVersionsDir(path, versionsDir, directory) ? runtimePaths.versionDir : directory,
624 ),
625 ),
626 ).join(":");
627
628 const systemdUnitDir = platform === "linux" ? yield* readSystemdUnitDirectory() : undefined;
629 const detectedManager = selectBootServiceManager({
630 platform,
631 homeDir,
632 xdgConfigHome,
633 systemdUnitDir,
634 uid,
635 path,
636 environmentPath,
637 });
638 const unitPath = detectedManager?.unitPath ?? "";
639 const logPath = path.join(input.logsDir, BOOT_SERVICE_LOG_FILE);
640 const statePath = path.join(input.baseDir, "runtime", SERVICE_STATE_FILE);
641 const restartPendingPath = path.join(input.baseDir, "runtime", SERVICE_RESTART_PENDING_FILE);
642 const otherBaseDirOf = (unit: string) => {
643 const installedBaseDir = bootServiceBaseDirOf(unit);
644 return installedBaseDir !== undefined &&
645 path.resolve(installedBaseDir) !== path.resolve(input.baseDir)
646 ? installedBaseDir
647 : undefined;
648 };
649 const writeDurably = (filePath: string, contents: string) =>
650 Effect.scoped(
651 Effect.gen(function* () {
652 const directory = path.dirname(filePath);
653 yield* fs.makeDirectory(directory, { recursive: true });
654 const tempPath = yield* fs.makeTempFileScoped({ directory, prefix: ".service-write-" });
655 yield* fs.writeFileString(tempPath, contents, { mode: 0o600 });
656 // Opened read-write: Windows refuses to flush a handle without write access.
657 yield* (yield* fs.open(tempPath, { flag: "r+" })).sync;
658 yield* fs.rename(tempPath, filePath);
659 // Windows has no directory fsync (EPERM); NTFS journals the rename.
660 yield* (yield* fs.open(directory, { flag: "r" })).sync.pipe(
661 Effect.catchIf(
662 (error) => (error.reason.cause as NodeJS.ErrnoException | undefined)?.code === "EPERM",
663 () => Effect.void,
664 ),
665 );
666 }),
667 ).pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
668 const plan: BootServicePlan = {
669 program: [runtimePaths.entryPath, "__service-launcher"],
670 baseDir: input.baseDir,
671 logPath,
672 unitPath,
673 };
674
675 const requireManager = Effect.suspend(() =>
676 detectedManager === undefined
677 ? new BootServiceUnsupportedError({ platform })
678 : Effect.succeed(detectedManager),
679 );
680
681 const logFailure = (error: { readonly message: string }) =>
682 DateTime.now.pipe(
683 Effect.flatMap((now) =>
684 fs.writeFileString(logPath, `${DateTime.formatIso(now)} ${error.message}\n`, { flag: "a" }),
685 ),
686 Effect.ignore,
687 );
688
689 const runStep = Effect.fn("cloud.boot_service.run_step")(function* (
690 step: string,
691 command: string,
692 args: ReadonlyArray<string>,
693 options?: { readonly timeout?: Duration.Input },
694 ) {
695 return yield* runner.run({ command, args, timeout: options?.timeout }).pipe(
696 Effect.mapError((cause) => new BootServiceCommandError({ step, cause })),
697 Effect.filterOrFail(
698 (result) => result.code === 0,
699 (result) =>
700 new BootServiceCommandError({
701 step,
702 exitCode: Number(result.code),
703 stdoutLength: result.stdout.length,
704 stderrLength: result.stderr.length,
705 }),
706 ),
707 Effect.tapError(logFailure),
708 );
709 });
710
711 const runSteps = (steps: ReadonlyArray<BootServiceStep>) =>
712 Effect.forEach(
713 steps,
714 (entry) => {
715 const run = runStep(
716 entry.step,
717 entry.command,
718 entry.args,
719 entry.timeout === undefined ? undefined : { timeout: entry.timeout },
720 );
721 return entry.optional === true ? run.pipe(Effect.ignore) : run.pipe(Effect.asVoid);
722 },
723 { discard: true },
724 );
725
726 const probe = (command: string, args: ReadonlyArray<string>) =>
727 runner.run({ command, args, timeout: Duration.seconds(5) }).pipe(Effect.option);
728 const succeeded = (result: Option.Option<ProcessRunner.ProcessRunOutput>) =>
729 Option.isSome(result) && result.value.code === 0;
730 const lingerArgs = [
731 "show-user",
732 ...(uid === undefined ? [] : [String(uid)]),
733 "--property=Linger",
734 "--value",
735 ];
736 const readSystemdProblems = Effect.fn("cloud.boot_service.read_systemd_problems")(function* (
737 includeService: boolean,
738 ) {
739 const [manager, linger] = yield* Effect.all(
740 [probe("systemctl", ["--user", "show-environment"]), probe("loginctl", lingerArgs)],
741 { concurrency: "unbounded" },
742 );
743 const problems: BootServiceProblem[] = [];
744 if (!succeeded(manager)) problems.push("user-manager-unavailable");
745 const lingering = succeeded(linger) && Option.isSome(linger) ? linger.value.stdout.trim() : "";
746 if (lingering !== "yes") {
747 problems.push(lingering === "no" ? "linger-disabled" : "linger-unavailable");
748 }
749 if (includeService && succeeded(manager)) {
750 const [enabled, active] = yield* Effect.all(
751 [
752 probe("systemctl", ["--user", "is-enabled", BOOT_SERVICE_UNIT_FILE]),
753 probe("systemctl", ["--user", "is-active", BOOT_SERVICE_UNIT_FILE]),
754 ],
755 { concurrency: "unbounded" },
756 );
757 if (
758 !succeeded(enabled) ||
759 (Option.isSome(enabled) && enabled.value.stdout.trim() !== "enabled")
760 ) {
761 problems.push("service-disabled");
762 }
763 if (!succeeded(active)) problems.push("service-stopped");
764 }
765 return problems;
766 });
767
768 const requireSystemdPrerequisites = Effect.gen(function* () {
769 const problems = yield* readSystemdProblems(false);
770 const unavailable = problems.find((problem) => problem !== "linger-disabled");
771 if (unavailable) return yield* new BootServicePrerequisiteError({ problem: unavailable });
772 if (!problems.includes("linger-disabled")) return;
773 yield* runStep("enabling lingering for this user", "loginctl", [
774 "enable-linger",
775 "--no-ask-password",
776 ...(uid === undefined ? [] : [String(uid)]),
777 ]).pipe(
778 Effect.mapError(
779 (cause) => new BootServicePrerequisiteError({ problem: "linger-disabled", cause }),
780 ),
781 );
782 const remaining = yield* readSystemdProblems(false);
783 if (remaining[0]) return yield* new BootServicePrerequisiteError({ problem: remaining[0] });
784 });
785
786 const withSelectionLock = <A, E, R>(selectionPath: string, operation: Effect.Effect<A, E, R>) =>
787 Effect.acquireUseRelease(
788 Effect.tryPromise({
789 try: () => acquireServiceSelectionLock(selectionPath),
790 catch: (cause) => new BootServiceInstallError({ cause }),
791 }),
792 () => operation,
793 (release) => Effect.sync(release),
794 );
795
796 const install = Effect.fn("cloud.boot_service.install")(function* (options?: {
797 readonly allowDowngrade?: boolean;
798 readonly start?: boolean;
799 }) {
800 const manager = yield* requireManager;
801 // The unit is per user. Rewriting one that serves another home moves the
802 // service onto this home's data, which looks like every thread vanished.
803 const existingUnit = yield* fs.readFileString(unitPath).pipe(Effect.option);
804 const installedBaseDir = Option.isSome(existingUnit)
805 ? otherBaseDirOf(existingUnit.value)
806 : undefined;
807 if (installedBaseDir !== undefined) {
808 return yield* new BootServiceOtherBaseDirError({ installedBaseDir, baseDir: input.baseDir });
809 }
810 yield* fs
811 .makeDirectory(input.logsDir, { recursive: true })
812 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
813
814 if (manager.kind === "systemd") {
815 yield* requireSystemdPrerequisites.pipe(Effect.tapError(logFailure));
816 }
817
818 yield* ensurePinnedRuntimeInstalled({
819 baseDir: input.baseDir,
820 version: input.cliVersion,
821 fs,
822 path,
823 runner,
824 httpClient,
825 platform,
826 arch,
827 releaseBaseUrl,
828 validate: (runtime) =>
829 runner
830 .run({
831 command: pinnedRuntimeCommand(runtime).command,
832 args: [...pinnedRuntimeCommand(runtime).args, "--version"],
833 timeout: Duration.seconds(30),
834 })
835 .pipe(
836 Effect.mapError(
837 (cause) =>
838 new PinnedRuntimeInstallError({
839 step: "verifying the pinned t3 runtime",
840 cause,
841 }),
842 ),
843 Effect.flatMap((result) => {
844 const reportedVersion = /\bv(\S+)\s*$/.exec(result.stdout)?.[1];
845 return result.code === 0 && reportedVersion === input.cliVersion
846 ? Effect.void
847 : Effect.fail(
848 new PinnedRuntimeInstallError({
849 step: "verifying the pinned t3 runtime",
850 exitCode: Number(result.code),
851 stdoutLength: result.stdout.length,
852 stderrLength: result.stderr.length,
853 }),
854 );
855 }),
856 ),
857 }).pipe(
858 Effect.mapError((error) =>
859 error._tag === "PinnedRuntimeInstallError"
860 ? new BootServiceCommandError({
861 step: error.step,
862 exitCode: error.exitCode,
863 stdoutLength: error.stdoutLength,
864 stderrLength: error.stderrLength,
865 cause: error,
866 })
867 : new BootServiceInstallError({ cause: error }),
868 ),
869 );
870 const installed = yield* fs
871 .exists(unitPath)
872 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
873 // Stop outside the selection lock: the launcher may be waiting to acquire it.
874 const start = options?.start !== false;
875 if (installed && start && runningInsideService && manager.kind === "systemd") {
876 // Stopping the unit from inside it kills this process before the start.
877 // A transient unit runs the same install from outside, stop first, so it
878 // still serialises with a remote update the launcher may be starting.
879 yield* runStep("handing the install to a transient unit", "systemd-run", [
880 "--user",
881 "--collect",
882 "--quiet",
883 // Transient properties reach systemd literally, unlike unit-file specifiers.
884 `--property=StandardOutput=append:${logPath}`,
885 `--property=StandardError=append:${logPath}`,
886 `--setenv=${SERVICE_UNIT_ENV}=`,
887 runtimePaths.entryPath,
888 "service",
889 "install",
890 "--base-dir",
891 // systemd expands $VAR in arguments (not in the executable path).
892 input.baseDir.replaceAll("$", () => "$$"),
893 ...(options?.allowDowngrade === true ? ["--allow-downgrade"] : []),
894 ]);
895 return { ...plan, handedOff: true };
896 }
897 if (installed && start) {
898 yield* runSteps(manager.stop);
899 }
900
901 // State first, then unit. The launcher acquires only one at a time, and a
902 // failure to lock the unit must never prevent its durable update commit.
903 yield* withSelectionLock(
904 statePath,
905 withSelectionLock(
906 unitPath,
907 Effect.gen(function* () {
908 const currentlyInstalled = yield* fs.exists(unitPath);
909 const previousStateText = yield* fs.readFileString(statePath).pipe(Effect.option);
910 if (Option.isSome(previousStateText)) {
911 const installedVersion = serviceStateActiveVersion(previousStateText.value);
912 if (serviceStateHasPendingUpdate(previousStateText.value)) {
913 const quote = (word: string) => `'${word.replaceAll("'", "'\\''")}'`;
914 return yield* new BootServiceUpdatePendingError(
915 !currentlyInstalled && installedVersion !== undefined
916 ? {
917 recoveryCommand: `T3CODE_HOME=${quote(input.baseDir)} ${quote(pinnedRuntimePaths(path, input.baseDir, installedVersion, platform).entryPath)} __service-launcher`,
918 }
919 : {},
920 );
921 }
922 // Read the final version after stopping the launcher; a remote update may finish after the status check.
923 if (
924 installedVersion !== undefined &&
925 options?.allowDowngrade !== true &&
926 compareExactServiceVersions(input.cliVersion, installedVersion) < 0
927 ) {
928 return yield* new BootServiceDowngradeRefusedError({
929 installedVersion,
930 targetVersion: input.cliVersion,
931 });
932 }
933 }
934 yield* fs
935 .makeDirectory(path.dirname(unitPath), { recursive: true })
936 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
937 // Files can match the new version even when activation fails; keep that install retryable.
938 yield* fs.writeFileString(restartPendingPath, `${input.cliVersion}\n`, { mode: 0o600 });
939 yield* writeDurably(
940 statePath,
941 // @effect-diagnostics-next-line globalJsonInEffect:off - fixed launcher-owned document.
942 `${JSON.stringify(
943 {
944 protocol: SERVICE_LAUNCHER_PROTOCOL,
945 activeVersion: input.cliVersion,
946 } satisfies ServiceState,
947 null,
948 2,
949 )}\n`,
950 );
951 if (!start && (currentlyInstalled || Option.isSome(previousStateText))) {
952 const written = yield* fs.readFileString(statePath);
953 if (serviceStateActiveVersion(written) !== input.cliVersion) {
954 return yield* new BootServiceUpdatePendingError();
955 }
956 }
957 yield* writeDurably(unitPath, manager.render(plan));
958 }),
959 ),
960 ).pipe(
961 Effect.andThen(
962 Effect.gen(function* () {
963 if (start) {
964 yield* runSteps(manager.activate);
965 yield* withSelectionLock(
966 statePath,
967 Effect.gen(function* () {
968 // A concurrent deferred install may now be waiting for a newer restart.
969 const selected = parseServiceState(yield* fs.readFileString(statePath));
970 if (selected?.activeVersion === input.cliVersion && selected.update === undefined) {
971 yield* fs.remove(restartPendingPath, { force: true });
972 }
973 }),
974 );
975 }
976 }),
977 ),
978 Effect.mapError((cause) =>
979 cause._tag === "PlatformError" ? new BootServiceInstallError({ cause }) : cause,
980 ),
981 Effect.tapError(() =>
982 installed && start ? runSteps(manager.restart).pipe(Effect.ignore) : Effect.void,
983 ),
984 );
985 return plan;
986 });
987
988 const restart: BootService["Service"]["restart"] = Effect.gen(function* () {
989 const manager = yield* requireManager;
990 const unit = yield* fs.readFileString(unitPath).pipe(Effect.option);
991 if (Option.isNone(unit)) return "skipped" as const;
992 const installedBaseDir = bootServiceBaseDirOf(unit.value);
993 if (
994 installedBaseDir === undefined ||
995 path.resolve(installedBaseDir) !== path.resolve(input.baseDir)
996 ) {
997 return "skipped" as const;
998 }
999 // Writes no state, and the launcher lets an update transition in flight
1000 // finish before the queued stop tears it down.
1001 if (runningInsideService && manager.handoff !== undefined) {
1002 yield* runSteps(manager.handoff);
1003 return "queued" as const;
1004 }
1005 yield* runSteps(manager.stop);
1006 yield* runSteps(manager.activate).pipe(
1007 Effect.tapError(() => runSteps(manager.restart).pipe(Effect.ignore)),
1008 );
1009 yield* fs.remove(restartPendingPath, { force: true });
1010 return "restarted" as const;
1011 }).pipe(
1012 Effect.mapError((cause) =>
1013 cause._tag === "PlatformError" ? new BootServiceInstallError({ cause }) : cause,
1014 ),
1015 Effect.withSpan("cloud.boot_service.restart"),
1016 );
1017
1018 const withStopped = Effect.fn("cloud.boot_service.with_stopped")(function* <A, E, R>(
1019 operation: Effect.Effect<A, E, R>,
1020 ): Effect.fn.Return<A, E | BootServiceError, R> {
1021 if (detectedManager === undefined) return yield* operation;
1022 const manager = detectedManager;
1023 const unit = yield* fs.readFileString(unitPath).pipe(Effect.option);
1024 if (Option.isNone(unit)) return yield* operation;
1025 const installedBaseDir = bootServiceBaseDirOf(unit.value);
1026 if (
1027 installedBaseDir === undefined ||
1028 path.resolve(installedBaseDir) !== path.resolve(input.baseDir)
1029 ) {
1030 return yield* operation;
1031 }
1032 // `is-active` misses crash-looping systemd units; launchd can be loaded without a pid.
1033 // Always stop; restore only if previously active, enabled, or loaded,
1034 // so disabled crash loops stay stopped.
1035 const restore =
1036 manager.kind === "systemd"
1037 ? yield* Effect.map(
1038 Effect.all(
1039 [
1040 probe("systemctl", ["--user", "is-enabled", BOOT_SERVICE_UNIT_FILE]),
1041 probe("systemctl", ["--user", "is-active", BOOT_SERVICE_UNIT_FILE]),
1042 ],
1043 { concurrency: "unbounded" },
1044 ),
1045 ([enabled, active]) => succeeded(active) || succeeded(enabled),
1046 )
1047 : succeeded(
1048 yield* probe("launchctl", ["print", `gui/${uid}/${BOOT_SERVICE_LAUNCHD_LABEL}`]),
1049 );
1050 return yield* Effect.acquireUseRelease(
1051 // Require every stop before repair when restoring, so the server releases the database.
1052 // Otherwise stops are best-effort; launchd rejects bootout of an unloaded job.
1053 // A failed stop may still stop the service, so restoration runs either way.
1054 runSteps(manager.stop.map((step) => ({ ...step, optional: !restore }))).pipe(Effect.exit),
1055 (stopped): Effect.Effect<A, E | BootServiceError, R> =>
1056 Exit.isSuccess(stopped) ? operation : Effect.failCause(stopped.cause),
1057 (_, exit) => {
1058 if (!restore) return Effect.void;
1059 // Start only: `activate` would also enable a unit the user disabled.
1060 // When the operation itself failed, its error is the one worth reporting.
1061 const start = runSteps(manager.restart);
1062 return Exit.isFailure(exit) ? Effect.ignore(start) : start;
1063 },
1064 );
1065 });
1066
1067 const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () {
1068 const manager = yield* requireManager;
1069 if (
1070 !(yield* fs
1071 .exists(unitPath)
1072 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))))
1073 )
1074 return false;
1075 yield* runSteps(manager.deactivate);
1076 yield* fs
1077 .remove(unitPath)
1078 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
1079 yield* runSteps(manager.finalize);
1080 return true;
1081 }).pipe(Effect.withSpan("cloud.boot_service.uninstall"));
1082
1083 const status: BootService["Service"]["status"] = Effect.gen(function* () {
1084 if (detectedManager === undefined) {
1085 return { supported: false, installed: false, current: false, unitPath, logPath };
1086 }
1087 if (!(yield* fs.exists(unitPath))) {
1088 return { supported: true, installed: false, current: false, unitPath, logPath };
1089 }
1090 const [unit, runtimeEntryExists, runtimeSentinel, stateText] = yield* Effect.all([
1091 fs.readFileString(unitPath),
1092 fs.exists(runtimePaths.entryPath),
1093 fs.readFileString(runtimePaths.sentinelPath).pipe(Effect.option),
1094 fs.readFileString(statePath).pipe(Effect.option),
1095 ]);
1096 const state = Option.isSome(stateText) ? parseServiceState(stateText.value) : undefined;
1097 const installedVersion = Option.isSome(stateText)
1098 ? serviceStateActiveVersion(stateText.value)
1099 : undefined;
1100 const installedBaseDir = bootServiceBaseDirOf(unit);
1101 const otherBaseDir = otherBaseDirOf(unit);
1102 const normalizeUnit = (contents: string) =>
1103 detectedManager.kind === "launchd"
1104 ? contents.replace(/(<key>PATH<\/key>\n\s*<string>)[^<]*(<\/string>)/, "$1$2")
1105 : contents;
1106 const problems: BootServiceProblem[] =
1107 detectedManager.kind === "systemd" ? [...(yield* readSystemdProblems(true))] : [];
1108 if (yield* fs.exists(restartPendingPath)) problems.push("restart-pending");
1109 return {
1110 supported: true,
1111 installed: true,
1112 ...(installedVersion === undefined ? {} : { installedVersion }),
1113 ...(installedBaseDir === undefined ? {} : { installedBaseDir }),
1114 ...(otherBaseDir === undefined ? {} : { otherBaseDir }),
1115 problems,
1116 current:
1117 problems.length === 0 &&
1118 normalizeUnit(unit) === normalizeUnit(detectedManager.render(plan)) &&
1119 runtimeEntryExists &&
1120 Option.isSome(runtimeSentinel) &&
1121 runtimeSentinel.value.trim() === input.cliVersion &&
1122 state?.activeVersion === input.cliVersion &&
1123 state?.update?.status !== "pending",
1124 unitPath,
1125 logPath,
1126 };
1127 }).pipe(
1128 Effect.mapError((cause) => new BootServiceInstallError({ cause })),
1129 Effect.withSpan("cloud.boot_service.status"),
1130 );
1131
1132 return BootService.of({ install, restart, withStopped, uninstall, status });
1133});
1134
1135export const layer = (input: {
1136 readonly baseDir: string;
1137 readonly logsDir: string;
1138 readonly cliVersion: string;
1139 readonly host?: BootServiceHost;
1140}) => Layer.effect(BootService, make(input));