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

bootService.ts

1,080 lines39.7 KB

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