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

bootService.ts

1,033 lines37.9 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 homeDir: string;
217}): BootServiceManager {
218 const unitPath = input.path.join(
219 input.homeDir,
220 ".config",
221 "systemd",
222 "user",
223 BOOT_SERVICE_UNIT_FILE,
224 );
225 const prepareActivation = [
226 {
227 step: "reloading systemd user units",
228 command: "systemctl",
229 args: ["--user", "daemon-reload"],
230 },
231 {
232 step: "enabling the service",
233 command: "systemctl",
234 args: ["--user", "enable", BOOT_SERVICE_UNIT_FILE],
235 },
236 ];
237 return {
238 kind: "systemd",
239 unitPath,
240 render: renderBootServiceUnit,
241 stop: [
242 {
243 step: "stopping the installed service",
244 command: "systemctl",
245 args: ["--user", "stop", BOOT_SERVICE_UNIT_FILE],
246 timeout: STOP_STEP_TIMEOUT,
247 },
248 ],
249 activate: [
250 ...prepareActivation,
251 {
252 step: "starting the service",
253 command: "systemctl",
254 args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
255 },
256 ],
257 restart: [
258 {
259 step: "restarting the service after a failed update",
260 command: "systemctl",
261 args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
262 },
263 ],
264 handoff: [
265 ...prepareActivation,
266 {
267 step: "restarting the service",
268 command: "systemctl",
269 args: ["--user", "restart", "--no-block", BOOT_SERVICE_UNIT_FILE],
270 },
271 ],
272 deactivate: [
273 {
274 step: "stopping the service",
275 command: "systemctl",
276 args: ["--user", "disable", "--now", BOOT_SERVICE_UNIT_FILE],
277 timeout: STOP_STEP_TIMEOUT,
278 },
279 ],
280 finalize: [
281 {
282 step: "reloading systemd user units",
283 command: "systemctl",
284 args: ["--user", "daemon-reload"],
285 },
286 ],
287 };
289​
290function launchdManager(input: {
291 readonly path: Path.Path;
292 readonly homeDir: string;
293 readonly uid: number;
294 readonly environmentPath: string;
295}): BootServiceManager {
296 const unitPath = input.path.join(
297 input.homeDir,
298 "Library",
299 "LaunchAgents",
300 BOOT_SERVICE_PLIST_FILE,
301 );
302 const domainTarget = `gui/${input.uid}`;
303 const serviceTarget = `${domainTarget}/${BOOT_SERVICE_LAUNCHD_LABEL}`;
304 // Unloaded jobs may reject bootout/enable. Bootstrap starts RunAtLoad/KeepAlive jobs; kickstart would restart them.
305 return {
306 kind: "launchd",
307 unitPath,
308 render: (plan) =>
309 renderBootServicePlist(plan, {
310 homeDir: input.homeDir,
311 environmentPath: input.environmentPath,
312 }),
313 // bootout --wait is undocumented but waits through ExitTimeOut, preventing bootstrap EIO races.
314 stop: [
315 {
316 step: "stopping the installed launch agent",
317 command: "launchctl",
318 args: ["bootout", "--wait", serviceTarget],
319 optional: true,
320 timeout: STOP_STEP_TIMEOUT,
321 },
322 ],
323 activate: [
324 // A persisted `launchctl disable` override refuses bootstrap; clear it.
325 {
326 step: "enabling the launch agent",
327 command: "launchctl",
328 args: ["enable", serviceTarget],
329 optional: true,
330 },
331 {
332 step: "starting the service",
333 command: "launchctl",
334 args: ["bootstrap", domainTarget, unitPath],
335 },
336 ],
337 restart: [
338 {
339 step: "restarting the service after a failed update",
340 command: "launchctl",
341 args: ["bootstrap", domainTarget, unitPath],
342 },
343 ],
344 // Persisted launchctl disable overrides would block reinstall.
345 deactivate: [
346 {
347 step: "stopping the service",
348 command: "launchctl",
349 args: ["bootout", "--wait", serviceTarget],
350 optional: true,
351 timeout: STOP_STEP_TIMEOUT,
352 },
353 ],
354 finalize: [],
355 };
357​
358function selectBootServiceManager(input: {
359 readonly platform: NodeJS.Platform;
360 readonly homeDir: string;
361 readonly uid: number | undefined;
362 readonly path: Path.Path;
363 readonly environmentPath: string;
364}): BootServiceManager | undefined {
365 if (input.homeDir === "") {
366 return undefined;
367 }
368 if (input.platform === "linux") {
369 return systemdManager({ path: input.path, homeDir: input.homeDir });
370 }
371 if (input.platform === "darwin" && input.uid !== undefined) {
372 return launchdManager({
373 path: input.path,
374 homeDir: input.homeDir,
375 uid: input.uid,
376 environmentPath: input.environmentPath,
377 });
378 }
379 return undefined;
381​
382export class BootServiceUnsupportedError extends Schema.TaggedError<BootServiceUnsupportedError>()(
383 "BootServiceUnsupportedError",
384 { platform: Schema.String },
385) {
386 override get message(): string {
387 return `Background setup supports Linux with systemd and macOS with launchd; this machine reports '${this.platform}'.`;
388 }
390​
391export class BootServiceCommandError extends Schema.TaggedError<BootServiceCommandError>()(
392 "BootServiceCommandError",
393 {
394 step: Schema.String,
395 exitCode: Schema.optional(Schema.Number),
396 stdoutLength: Schema.optional(Schema.Number),
397 stderrLength: Schema.optional(Schema.Number),
398 cause: Schema.optional(Schema.Defect()),
399 },
400) {
401 override get message(): string {
402 return this.exitCode === undefined
403 ? `Background setup failed while ${this.step}.`
404 : `Background setup failed while ${this.step} (exit code ${this.exitCode}).`;
405 }
407​
408export class BootServiceInstallError extends Schema.TaggedError<BootServiceInstallError>()(
409 "BootServiceInstallError",
410 { cause: Schema.Defect() },
411) {
412 override get message(): string {
413 return "Could not set up the T3 Code background service.";
414 }
416​
417const BootServiceProblem = Schema.Literals([
418 "user-manager-unavailable",
419 "linger-unavailable",
420 "linger-disabled",
421 "service-disabled",
422 "service-stopped",
423 "restart-pending",
424]);
425type BootServiceProblem = typeof BootServiceProblem.Type;
426​
427export function formatBootServiceProblem(problem: BootServiceProblem): string {
428 switch (problem) {
429 case "user-manager-unavailable":
430 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.";
431 case "linger-unavailable":
432 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.';
433 case "linger-disabled":
434 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.';
435 case "service-disabled":
436 return "The service is not enabled to start automatically. Run `t3 service install` to repair it.";
437 case "service-stopped":
438 return "The service is not running. Check the service log and `systemctl --user status t3code.service`, then run `t3 service install`.";
439 case "restart-pending":
440 return "A newer version is installed but the service is still running the previous one. Run `t3 service restart` to switch.";
441 }
443​
444export class BootServicePrerequisiteError extends Schema.TaggedError<BootServicePrerequisiteError>()(
445 "BootServicePrerequisiteError",
446 { problem: BootServiceProblem, cause: Schema.optional(Schema.Defect()) },
447) {
448 override get message(): string {
449 return `[${this.problem}] ${formatBootServiceProblem(this.problem)}`;
450 }
452​
453export class BootServiceUpdatePendingError extends Schema.TaggedError<BootServiceUpdatePendingError>()(
454 "BootServiceUpdatePendingError",
455 {},
456) {
457 override get message(): string {
458 return "A remote server update is still pending. Wait for it to finish, then retry.";
459 }
461​
462export class BootServiceDowngradeRefusedError extends Schema.TaggedError<BootServiceDowngradeRefusedError>()(
463 "BootServiceDowngradeRefusedError",
464 {
465 installedVersion: Schema.String,
466 targetVersion: Schema.String,
467 },
468) {
469 override get message(): string {
470 return `Refusing to replace t3@${this.installedVersion} with older t3@${this.targetVersion}. Run the command again with --allow-downgrade to continue.`;
471 }
473​
474export type BootServiceError =
475 | BootServiceUnsupportedError
476 | BootServiceCommandError
477 | BootServiceInstallError
478 | BootServicePrerequisiteError
479 | BootServiceUpdatePendingError
480 | BootServiceDowngradeRefusedError;
481​
482export interface BootServiceStatus {
483 readonly supported: boolean;
484 readonly installed: boolean;
485 readonly current: boolean;
486 readonly installedVersion?: string;
487 readonly installedBaseDir?: string;
488 readonly problems?: ReadonlyArray<BootServiceProblem>;
489 readonly unitPath: string;
490 readonly logPath: string;
492​
493export class BootService extends Context.Service<
494 BootService,
495 {
496 readonly install: (options?: {
497 readonly allowDowngrade?: boolean;
498 readonly start?: boolean;
499 }) => Effect.Effect<BootServicePlan, BootServiceError>;
500 /**
501 * Only when the unit serves this base dir: the unit name is per user, so
502 * another home's service is left alone, which resolves `skipped`. From
503 * inside the service the restart can only be `queued` with the service
504 * manager, since the stop ends this process.
505 */
506 readonly restart: Effect.Effect<"restarted" | "queued" | "skipped", BootServiceError>;
507 /**
508 * Runs the operation with this home's service stopped; other homes are left alone.
509 * Restores a previously enabled or loaded service even if stopping failed.
510 * The operation's failure takes precedence over a restart failure.
511 */
512 readonly withStopped: <A, E, R>(
513 operation: Effect.Effect<A, E, R>,
514 ) => Effect.Effect<A, E | BootServiceError, R>;
515 readonly uninstall: Effect.Effect<boolean, BootServiceError>;
516 readonly status: Effect.Effect<BootServiceStatus, BootServiceError>;
517 }
518>()("t3/cloud/bootService") {}
519​
520export interface BootServiceHost {
521 readonly execPath: string;
523​
524export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
525 readonly baseDir: string;
526 readonly logsDir: string;
527 readonly cliVersion: string;
528 readonly host?: BootServiceHost;
529}) {
530 const hostExecPath = yield* HostProcess.ExecutablePath;
531 const platform = yield* HostProcess.Platform;
532 const arch = yield* HostProcess.Architecture;
533 const uid = yield* HostProcess.UserId;
534 const httpClient = yield* HttpClient.HttpClient;
535 const releaseBaseUrl = Option.getOrUndefined(
536 yield* Config.String(CLI_RELEASE_BASE_URL_ENV).pipe(Config.option),
537 );
538 const homeDir = yield* Config.String("HOME").pipe(Config.withDefault(""));
539 const installerPath = yield* Config.String("PATH").pipe(Config.withDefault(""));
540 const runningInsideService =
541 (yield* Config.String(BOOT_SERVICE_UNIT_ENV).pipe(Config.withDefault(""))) ===
542 BOOT_SERVICE_UNIT_FILE;
543 const fs = yield* FileSystem.FileSystem;
544 const path = yield* Path.Path;
545 const runner = yield* ProcessRunner.ProcessRunner;
546 const host = input.host ?? { execPath: hostExecPath };
547 const runtimePaths = pinnedRuntimePaths(path, input.baseDir, input.cliVersion, platform);
548 const versionsDir = pinnedRuntimeVersionsDir(path, input.baseDir);
549 const xmlSafeInstallerDirectories = installerPath.split(":").filter(
550 (directory) =>
551 directory.length > 0 &&
552 Array.from(directory).every((character) => {
553 const code = character.charCodeAt(0);
554 return code >= 0x20 || code === 0x09 || code === 0x0a || code === 0x0d;
555 }),
556 );
557 // During an update, the running CLI and a PATH inherited from the service name the runtime
558 // being replaced. The service and its agent shells should find the runtime it starts.
559 const environmentPath = Array.from(
560 new Set(
561 [
562 ...xmlSafeInstallerDirectories,
563 path.dirname(host.execPath),
564 "/opt/homebrew/bin",
565 "/usr/local/bin",
566 "/usr/bin",
567 "/bin",
568 "/usr/sbin",
569 "/sbin",
570 ].map((directory) =>
571 launcherOwnsVersionsDir(path, versionsDir, directory) ? runtimePaths.versionDir : directory,
572 ),
573 ),
574 ).join(":");
575​
576 const detectedManager = selectBootServiceManager({
577 platform,
578 homeDir,
579 uid,
580 path,
581 environmentPath,
582 });
583 const unitPath = detectedManager?.unitPath ?? "";
584 const logPath = path.join(input.logsDir, BOOT_SERVICE_LOG_FILE);
585 const statePath = path.join(input.baseDir, "runtime", SERVICE_STATE_FILE);
586 const restartPendingPath = path.join(input.baseDir, "runtime", SERVICE_RESTART_PENDING_FILE);
587 const writeDurably = (filePath: string, contents: string) =>
588 Effect.scoped(
589 Effect.gen(function* () {
590 const directory = path.dirname(filePath);
591 yield* fs.makeDirectory(directory, { recursive: true });
592 const tempPath = yield* fs.makeTempFileScoped({ directory, prefix: ".service-write-" });
593 yield* fs.writeFileString(tempPath, contents, { mode: 0o600 });
594 // Opened read-write: Windows refuses to flush a handle without write access.
595 yield* (yield* fs.open(tempPath, { flag: "r+" })).sync;
596 yield* fs.rename(tempPath, filePath);
597 // Windows has no directory fsync (EPERM); NTFS journals the rename.
598 yield* (yield* fs.open(directory, { flag: "r" })).sync.pipe(
599 Effect.catchIf(
600 (error) => (error.reason.cause as NodeJS.ErrnoException | undefined)?.code === "EPERM",
601 () => Effect.void,
602 ),
603 );
604 }),
605 ).pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
606 const plan: BootServicePlan = {
607 program: [runtimePaths.entryPath, "__service-launcher"],
608 baseDir: input.baseDir,
609 logPath,
610 unitPath,
611 };
612​
613 const requireManager = Effect.suspend(() =>
614 detectedManager === undefined
615 ? new BootServiceUnsupportedError({ platform })
616 : Effect.succeed(detectedManager),
617 );
618​
619 const logFailure = (error: { readonly message: string }) =>
620 DateTime.now.pipe(
621 Effect.flatMap((now) =>
622 fs.writeFileString(logPath, `${DateTime.formatIso(now)} ${error.message}\n`, { flag: "a" }),
623 ),
624 Effect.ignore,
625 );
626​
627 const runStep = Effect.fn("cloud.boot_service.run_step")(function* (
628 step: string,
629 command: string,
630 args: ReadonlyArray<string>,
631 options?: { readonly timeout?: Duration.Input },
632 ) {
633 return yield* runner.run({ command, args, timeout: options?.timeout }).pipe(
634 Effect.mapError((cause) => new BootServiceCommandError({ step, cause })),
635 Effect.filterOrFail(
636 (result) => result.code === 0,
637 (result) =>
638 new BootServiceCommandError({
639 step,
640 exitCode: Number(result.code),
641 stdoutLength: result.stdout.length,
642 stderrLength: result.stderr.length,
643 }),
644 ),
645 Effect.tapError(logFailure),
646 );
647 });
648​
649 const runSteps = (steps: ReadonlyArray<BootServiceStep>) =>
650 Effect.forEach(
651 steps,
652 (entry) => {
653 const run = runStep(
654 entry.step,
655 entry.command,
656 entry.args,
657 entry.timeout === undefined ? undefined : { timeout: entry.timeout },
658 );
659 return entry.optional === true ? run.pipe(Effect.ignore) : run.pipe(Effect.asVoid);
660 },
661 { discard: true },
662 );
663​
664 const probe = (command: string, args: ReadonlyArray<string>) =>
665 runner.run({ command, args, timeout: Duration.seconds(5) }).pipe(Effect.option);
666 const succeeded = (result: Option.Option<ProcessRunner.ProcessRunOutput>) =>
667 Option.isSome(result) && result.value.code === 0;
668 const lingerArgs = [
669 "show-user",
670 ...(uid === undefined ? [] : [String(uid)]),
671 "--property=Linger",
672 "--value",
673 ];
674 const readSystemdProblems = Effect.fn("cloud.boot_service.read_systemd_problems")(function* (
675 includeService: boolean,
676 ) {
677 const [manager, linger] = yield* Effect.all(
678 [probe("systemctl", ["--user", "show-environment"]), probe("loginctl", lingerArgs)],
679 { concurrency: "unbounded" },
680 );
681 const problems: BootServiceProblem[] = [];
682 if (!succeeded(manager)) problems.push("user-manager-unavailable");
683 const lingering = succeeded(linger) && Option.isSome(linger) ? linger.value.stdout.trim() : "";
684 if (lingering !== "yes") {
685 problems.push(lingering === "no" ? "linger-disabled" : "linger-unavailable");
686 }
687 if (includeService && succeeded(manager)) {
688 const [enabled, active] = yield* Effect.all(
689 [
690 probe("systemctl", ["--user", "is-enabled", BOOT_SERVICE_UNIT_FILE]),
691 probe("systemctl", ["--user", "is-active", BOOT_SERVICE_UNIT_FILE]),
692 ],
693 { concurrency: "unbounded" },
694 );
695 if (
696 !succeeded(enabled) ||
697 (Option.isSome(enabled) && enabled.value.stdout.trim() !== "enabled")
698 ) {
699 problems.push("service-disabled");
700 }
701 if (!succeeded(active)) problems.push("service-stopped");
702 }
703 return problems;
704 });
705​
706 const requireSystemdPrerequisites = Effect.gen(function* () {
707 const problems = yield* readSystemdProblems(false);
708 const unavailable = problems.find((problem) => problem !== "linger-disabled");
709 if (unavailable) return yield* new BootServicePrerequisiteError({ problem: unavailable });
710 if (!problems.includes("linger-disabled")) return;
711 yield* runStep("enabling lingering for this user", "loginctl", [
712 "enable-linger",
713 "--no-ask-password",
714 ...(uid === undefined ? [] : [String(uid)]),
715 ]).pipe(
716 Effect.mapError(
717 (cause) => new BootServicePrerequisiteError({ problem: "linger-disabled", cause }),
718 ),
719 );
720 const remaining = yield* readSystemdProblems(false);
721 if (remaining[0]) return yield* new BootServicePrerequisiteError({ problem: remaining[0] });
722 });
723​
724 const install = Effect.fn("cloud.boot_service.install")(function* (options?: {
725 readonly allowDowngrade?: boolean;
726 readonly start?: boolean;
727 }) {
728 const manager = yield* requireManager;
729 yield* fs
730 .makeDirectory(input.logsDir, { recursive: true })
731 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
732​
733 if (manager.kind === "systemd") {
734 yield* requireSystemdPrerequisites.pipe(Effect.tapError(logFailure));
735 }
736​
737 yield* ensurePinnedRuntimeInstalled({
738 baseDir: input.baseDir,
739 version: input.cliVersion,
740 fs,
741 path,
742 runner,
743 httpClient,
744 platform,
745 arch,
746 releaseBaseUrl,
747 validate: (runtime) =>
748 runner
749 .run({
750 command: pinnedRuntimeCommand(runtime).command,
751 args: [...pinnedRuntimeCommand(runtime).args, "--version"],
752 timeout: Duration.seconds(30),
753 })
754 .pipe(
755 Effect.mapError(
756 (cause) =>
757 new PinnedRuntimeInstallError({
758 step: "verifying the pinned t3 runtime",
759 cause,
760 }),
761 ),
762 Effect.flatMap((result) => {
763 const reportedVersion = /\bv(\S+)\s*$/.exec(result.stdout)?.[1];
764 return result.code === 0 && reportedVersion === input.cliVersion
765 ? Effect.void
766 : Effect.fail(
767 new PinnedRuntimeInstallError({
768 step: "verifying the pinned t3 runtime",
769 exitCode: Number(result.code),
770 stdoutLength: result.stdout.length,
771 stderrLength: result.stderr.length,
772 }),
773 );
774 }),
775 ),
776 }).pipe(
777 Effect.mapError((error) =>
778 error._tag === "PinnedRuntimeInstallError"
779 ? new BootServiceCommandError({
780 step: error.step,
781 exitCode: error.exitCode,
782 stdoutLength: error.stdoutLength,
783 stderrLength: error.stderrLength,
784 cause: error,
785 })
786 : new BootServiceInstallError({ cause: error }),
787 ),
788 );
789 const installed = yield* fs
790 .exists(unitPath)
791 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
792 // With start=false, changing startup-only files is safe except during a remote update,
793 // when the launcher also writes its state file.
794 const start = options?.start !== false;
795 if (installed && start && runningInsideService && manager.kind === "systemd") {
796 // Stopping the unit from inside it kills this process before the start.
797 // A transient unit runs the same install from outside, stop first, so it
798 // still serialises with a remote update the launcher may be starting.
799 yield* runStep("handing the install to a transient unit", "systemd-run", [
800 "--user",
801 "--collect",
802 "--quiet",
803 // Transient properties reach systemd literally, unlike unit-file specifiers.
804 `--property=StandardOutput=append:${logPath}`,
805 `--property=StandardError=append:${logPath}`,
806 `--setenv=${BOOT_SERVICE_UNIT_ENV}=`,
807 runtimePaths.entryPath,
808 "service",
809 "install",
810 "--base-dir",
811 // systemd expands $VAR in arguments (not in the executable path).
812 input.baseDir.replaceAll("$", () => "$$"),
813 ...(options?.allowDowngrade === true ? ["--allow-downgrade"] : []),
814 ]);
815 return { ...plan, handedOff: true };
816 }
817 if (installed && start) {
818 yield* runSteps(manager.stop);
819 }
820​
821 yield* Effect.gen(function* () {
822 if (installed) {
823 const previousStateText = yield* fs.readFileString(statePath).pipe(Effect.option);
824 if (Option.isSome(previousStateText)) {
825 if (serviceStateHasPendingUpdate(previousStateText.value)) {
826 return yield* new BootServiceUpdatePendingError();
827 }
828 // Read the final version after stopping the launcher; a remote update may finish after the status check.
829 const installedVersion = serviceStateActiveVersion(previousStateText.value);
830 if (
831 installedVersion !== undefined &&
832 options?.allowDowngrade !== true &&
833 compareExactServiceVersions(input.cliVersion, installedVersion) < 0
834 ) {
835 return yield* new BootServiceDowngradeRefusedError({
836 installedVersion,
837 targetVersion: input.cliVersion,
838 });
839 }
840 }
841 }
842 yield* fs
843 .makeDirectory(path.dirname(unitPath), { recursive: true })
844 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
845 // Files can match the new version even when activation fails; keep that install retryable.
846 yield* fs.writeFileString(restartPendingPath, `${input.cliVersion}\n`, { mode: 0o600 });
847 yield* writeDurably(
848 statePath,
849 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned document.
850 `${JSON.stringify(
851 {
852 protocol: SERVICE_LAUNCHER_PROTOCOL,
853 activeVersion: input.cliVersion,
854 } satisfies ServiceState,
855 null,
856 2,
857 )}\n`,
858 );
859 if (!start && installed) {
860 // A concurrent remote update can overwrite launcher state; detect it before repointing the unit.
861 const written = yield* fs.readFileString(statePath);
862 if (serviceStateActiveVersion(written) !== input.cliVersion) {
863 return yield* new BootServiceUpdatePendingError();
864 }
865 }
866 yield* writeDurably(unitPath, manager.render(plan));
867​
868 if (start) {
869 yield* runSteps(manager.activate);
870 yield* fs.remove(restartPendingPath, { force: true });
871 }
872 }).pipe(
873 Effect.mapError((cause) =>
874 cause._tag === "PlatformError" ? new BootServiceInstallError({ cause }) : cause,
875 ),
876 Effect.tapError(() =>
877 installed && start ? runSteps(manager.restart).pipe(Effect.ignore) : Effect.void,
878 ),
879 );
880 return plan;
881 });
882​
883 const restart: BootService["Service"]["restart"] = Effect.gen(function* () {
884 const manager = yield* requireManager;
885 const unit = yield* fs.readFileString(unitPath).pipe(Effect.option);
886 if (Option.isNone(unit)) return "skipped" as const;
887 const installedBaseDir = bootServiceBaseDirOf(unit.value);
888 if (
889 installedBaseDir === undefined ||
890 path.resolve(installedBaseDir) !== path.resolve(input.baseDir)
891 ) {
892 return "skipped" as const;
893 }
894 // Writes no state, and the launcher lets an update transition in flight
895 // finish before the queued stop tears it down.
896 if (runningInsideService && manager.handoff !== undefined) {
897 yield* runSteps(manager.handoff);
898 return "queued" as const;
899 }
900 yield* runSteps(manager.stop);
901 yield* runSteps(manager.activate).pipe(
902 Effect.tapError(() => runSteps(manager.restart).pipe(Effect.ignore)),
903 );
904 yield* fs.remove(restartPendingPath, { force: true });
905 return "restarted" as const;
906 }).pipe(
907 Effect.mapError((cause) =>
908 cause._tag === "PlatformError" ? new BootServiceInstallError({ cause }) : cause,
909 ),
910 Effect.withSpan("cloud.boot_service.restart"),
911 );
912​
913 const withStopped = Effect.fn("cloud.boot_service.with_stopped")(function* <A, E, R>(
914 operation: Effect.Effect<A, E, R>,
915 ): Effect.fn.Return<A, E | BootServiceError, R> {
916 if (detectedManager === undefined) return yield* operation;
917 const manager = detectedManager;
918 const unit = yield* fs.readFileString(unitPath).pipe(Effect.option);
919 if (Option.isNone(unit)) return yield* operation;
920 const installedBaseDir = bootServiceBaseDirOf(unit.value);
921 if (
922 installedBaseDir === undefined ||
923 path.resolve(installedBaseDir) !== path.resolve(input.baseDir)
924 ) {
925 return yield* operation;
926 }
927 // `is-active` misses crash-looping systemd units; launchd can be loaded without a pid.
928 // Always stop; restore only if previously active, enabled, or loaded,
929 // so disabled crash loops stay stopped.
930 const restore =
931 manager.kind === "systemd"
932 ? yield* Effect.map(
933 Effect.all(
934 [
935 probe("systemctl", ["--user", "is-enabled", BOOT_SERVICE_UNIT_FILE]),
936 probe("systemctl", ["--user", "is-active", BOOT_SERVICE_UNIT_FILE]),
937 ],
938 { concurrency: "unbounded" },
939 ),
940 ([enabled, active]) => succeeded(active) || succeeded(enabled),
941 )
942 : succeeded(
943 yield* probe("launchctl", ["print", `gui/${uid}/${BOOT_SERVICE_LAUNCHD_LABEL}`]),
944 );
945 return yield* Effect.acquireUseRelease(
946 // Require every stop before repair when restoring, so the server releases the database.
947 // Otherwise stops are best-effort; launchd rejects bootout of an unloaded job.
948 // A failed stop may still stop the service, so restoration runs either way.
949 runSteps(manager.stop.map((step) => ({ ...step, optional: !restore }))).pipe(Effect.exit),
950 (stopped): Effect.Effect<A, E | BootServiceError, R> =>
951 Exit.isSuccess(stopped) ? operation : Effect.failCause(stopped.cause),
952 (_, exit) => {
953 if (!restore) return Effect.void;
954 // Start only: `activate` would also enable a unit the user disabled.
955 // When the operation itself failed, its error is the one worth reporting.
956 const start = runSteps(manager.restart);
957 return Exit.isFailure(exit) ? Effect.ignore(start) : start;
958 },
959 );
960 });
961​
962 const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () {
963 const manager = yield* requireManager;
964 if (
965 !(yield* fs
966 .exists(unitPath)
967 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))))
968 )
969 return false;
970 yield* runSteps(manager.deactivate);
971 yield* fs
972 .remove(unitPath)
973 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
974 yield* runSteps(manager.finalize);
975 return true;
976 }).pipe(Effect.withSpan("cloud.boot_service.uninstall"));
977​
978 const status: BootService["Service"]["status"] = Effect.gen(function* () {
979 if (detectedManager === undefined) {
980 return { supported: false, installed: false, current: false, unitPath, logPath };
981 }
982 if (!(yield* fs.exists(unitPath))) {
983 return { supported: true, installed: false, current: false, unitPath, logPath };
984 }
985 const [unit, runtimeEntryExists, runtimeSentinel, stateText] = yield* Effect.all([
986 fs.readFileString(unitPath),
987 fs.exists(runtimePaths.entryPath),
988 fs.readFileString(runtimePaths.sentinelPath).pipe(Effect.option),
989 fs.readFileString(statePath).pipe(Effect.option),
990 ]);
991 const state = Option.isSome(stateText) ? parseServiceState(stateText.value) : undefined;
992 const installedVersion = Option.isSome(stateText)
993 ? serviceStateActiveVersion(stateText.value)
994 : undefined;
995 const installedBaseDir = bootServiceBaseDirOf(unit);
996 const normalizeUnit = (contents: string) =>
997 detectedManager.kind === "launchd"
998 ? contents.replace(/(<key>PATH<\/key>\n\s*<string>)[^<]*(<\/string>)/, "$1$2")
999 : contents;
1000 const problems: BootServiceProblem[] =
1001 detectedManager.kind === "systemd" ? [...(yield* readSystemdProblems(true))] : [];
1002 if (yield* fs.exists(restartPendingPath)) problems.push("restart-pending");
1003 return {
1004 supported: true,
1005 installed: true,
1006 ...(installedVersion === undefined ? {} : { installedVersion }),
1007 ...(installedBaseDir === undefined ? {} : { installedBaseDir }),
1008 problems,
1009 current:
1010 problems.length === 0 &&
1011 normalizeUnit(unit) === normalizeUnit(detectedManager.render(plan)) &&
1012 runtimeEntryExists &&
1013 Option.isSome(runtimeSentinel) &&
1014 runtimeSentinel.value.trim() === input.cliVersion &&
1015 state?.activeVersion === input.cliVersion &&
1016 state?.update?.status !== "pending",
1017 unitPath,
1018 logPath,
1019 };
1020 }).pipe(
1021 Effect.mapError((cause) => new BootServiceInstallError({ cause })),
1022 Effect.withSpan("cloud.boot_service.status"),
1023 );
1024​
1025 return BootService.of({ install, restart, withStopped, uninstall, status });
1026});
1027​
1028export const layer = (input: {
1029 readonly baseDir: string;
1030 readonly logsDir: string;
1031 readonly cliVersion: string;
1032 readonly host?: BootServiceHost;
1033}) => Layer.effect(BootService, make(input));