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

bootService.ts

1,024 lines38.3 KB

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