Open History to see the last commit
1import {
2 HostProcessExecutablePath,
3 HostProcessPlatform,
4 HostProcessUserId,
5} from "@t3tools/shared/hostProcess";
6import * as Config from "effect/Config";
7import * as Context from "effect/Context";
8import * as DateTime from "effect/DateTime";
9import * as Duration from "effect/Duration";
10import * as Effect from "effect/Effect";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Path from "effect/Path";
15import * as Schema from "effect/Schema";
16
17import * as ProcessRunner from "../processRunner.ts";
18import {
19 ensurePinnedRuntimeInstalled,
20 pinnedRuntimePaths,
21 PinnedRuntimeInstallError,
22} from "./pinnedRuntime.ts";
23import {
24 SERVICE_LAUNCHER_FILE,
25 SERVICE_LAUNCHER_PROTOCOL,
26 SERVICE_STATE_FILE,
27 parseServiceState,
28 serviceStateHasPendingUpdate,
29 type ServiceState,
30} from "./serviceProtocol.ts";
31
32const BOOT_SERVICE_NAME = "t3code";
33export const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
34// `.service` suffix keeps the label distinct from the desktop app's bundle id
35// (com.t3tools.t3code), so launchd and TCC records never collide.
36export const BOOT_SERVICE_LAUNCHD_LABEL = "com.t3tools.t3code.service";
37export const BOOT_SERVICE_PLIST_FILE = `${BOOT_SERVICE_LAUNCHD_LABEL}.plist`;
38export const BOOT_SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT";
39
40/** systemd expands `%` specifiers, including in unquoted append-log paths. */
41export function escapeSystemdSpecifiers(value: string): string {
42 return value.replaceAll("%", "%%");
43}
44
45export function quoteSystemdValue(value: string): string {
46 const escaped = escapeSystemdSpecifiers(value);
47 return /[\s"'\\]/.test(escaped)
48 ? `"${escaped.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`
49 : escaped;
50}
51
52export interface BootServicePlan {
53 readonly nodePath: string;
54 readonly launcherPath: string;
55 readonly baseDir: string;
56 readonly logPath: string;
57 readonly unitPath: string;
58}
59
60/** Pure renderer: service units cannot rely on the user's shell or PATH. */
61export function renderBootServiceUnit(plan: BootServicePlan): string {
62 // The user manager has no reliable network-online target; server networking retries itself.
63 return [
64 "[Unit]",
65 "Description=T3 Code server",
66 "StartLimitIntervalSec=300",
67 "StartLimitBurst=5",
68 "",
69 "[Service]",
70 "Type=simple",
71 "WorkingDirectory=%h",
72 `Environment=T3CODE_HOME=${quoteSystemdValue(plan.baseDir)}`,
73 `Environment=${BOOT_SERVICE_UNIT_ENV}=${BOOT_SERVICE_UNIT_FILE}`,
74 `ExecStart=${quoteSystemdValue(plan.nodePath)} ${quoteSystemdValue(plan.launcherPath)}`,
75 // Let the launcher mark an explicit stop before it signals the server.
76 // systemd still SIGKILLs the whole cgroup if graceful shutdown times out.
77 "KillMode=mixed",
78 // Agent tool calls run as children of the server, so they share this cgroup.
79 // With the systemd default of OOMPolicy=stop, the kernel killing one greedy
80 // child stops the whole unit: the server, every live agent, and the user's
81 // connection. Keep running and let Restart=always cover the main process.
82 "OOMPolicy=continue",
83 "Restart=always",
84 "RestartSec=5",
85 `StandardOutput=append:${escapeSystemdSpecifiers(plan.logPath)}`,
86 `StandardError=append:${escapeSystemdSpecifiers(plan.logPath)}`,
87 "",
88 "[Install]",
89 "WantedBy=default.target",
90 "",
91 ].join("\n");
92}
93
94/** Plist values are emitted as XML text nodes; only these three need escaping. */
95export function escapeXmlText(value: string): string {
96 return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
97}
98
99/** Pure renderer: launch agents cannot rely on the user's shell or PATH. */
100export function renderBootServicePlist(
101 plan: BootServicePlan,
102 options: { readonly homeDir: string },
103): string {
104 // KeepAlive + ThrottleInterval mirror Restart=always + RestartSec=5. launchd
105 // has no StartLimitBurst analog; a hard crash loop respawns every 5s forever.
106 // ExitTimeOut 90 matches systemd's default TimeoutStopSec. A plain stop
107 // completes within the launcher's 5s child grace, but a stop that queues
108 // behind an in-flight update transition can take much longer; launchd's
109 // system-defined default (5s on current macOS) would SIGKILL the launcher
110 // (and, with it, the process group) mid-handoff.
111 // ProcessType Interactive opts out of background-job resource throttling.
112 // AbandonProcessGroup stays at its default (false): launchd reaps leftover
113 // process-group members only when the launcher itself exits — the analog of
114 // KillMode=mixed's final cgroup kill — and not when the launcher restarts its
115 // child, so agent children survive server updates.
116 return [
117 `<?xml version="1.0" encoding="UTF-8"?>`,
118 `<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">`,
119 `<plist version="1.0">`,
120 `<dict>`,
121 ` <key>Label</key>`,
122 ` <string>${BOOT_SERVICE_LAUNCHD_LABEL}</string>`,
123 ` <key>ProgramArguments</key>`,
124 ` <array>`,
125 ` <string>${escapeXmlText(plan.nodePath)}</string>`,
126 ` <string>${escapeXmlText(plan.launcherPath)}</string>`,
127 ` </array>`,
128 ` <key>EnvironmentVariables</key>`,
129 ` <dict>`,
130 ` <key>T3CODE_HOME</key>`,
131 ` <string>${escapeXmlText(plan.baseDir)}</string>`,
132 ` <key>${BOOT_SERVICE_UNIT_ENV}</key>`,
133 ` <string>${BOOT_SERVICE_PLIST_FILE}</string>`,
134 ` </dict>`,
135 ` <key>WorkingDirectory</key>`,
136 ` <string>${escapeXmlText(options.homeDir)}</string>`,
137 ` <key>RunAtLoad</key>`,
138 ` <true/>`,
139 ` <key>KeepAlive</key>`,
140 ` <true/>`,
141 ` <key>ThrottleInterval</key>`,
142 ` <integer>5</integer>`,
143 ` <key>ExitTimeOut</key>`,
144 ` <integer>90</integer>`,
145 ` <key>ProcessType</key>`,
146 ` <string>Interactive</string>`,
147 ` <key>StandardOutPath</key>`,
148 ` <string>${escapeXmlText(plan.logPath)}</string>`,
149 ` <key>StandardErrorPath</key>`,
150 ` <string>${escapeXmlText(plan.logPath)}</string>`,
151 `</dict>`,
152 `</plist>`,
153 ``,
154 ].join("\n");
155}
156
157interface BootServiceStepBase {
158 readonly step: string;
159 readonly command: string;
160 readonly args: ReadonlyArray<string>;
161 /** Override the ProcessRunner default (60s) for steps that block longer. */
162 readonly timeout?: Duration.Input;
163}
164
165export type BootServiceStep = BootServiceStepBase &
166 (
167 | { readonly operation?: "command" }
168 | {
169 readonly operation: "launchd-bootout";
170 /** After launchd bootout, prove the job left the domain before continuing. */
171 readonly verifyAbsent: {
172 readonly serviceTarget: string;
173 readonly notLoadedMessages: ReadonlyArray<string>;
174 };
175 }
176 );
177
178/**
179 * A stop can take 90s: systemd blocks for TimeoutStopSec, while launchd's
180 * supported bootout command returns before the job finishes honoring the
181 * plist's ExitTimeOut. Keep both the command and launchd verification bounds
182 * above that window.
183 */
184const STOP_STEP_TIMEOUT = Duration.seconds(120);
185const LAUNCHD_STOP_POLL_INTERVAL = Duration.millis(100);
186
187export function isConfirmedLaunchdNotLoaded(
188 result: ProcessRunner.ProcessRunOutput,
189 notLoadedMessages: ReadonlyArray<string>,
190): boolean {
191 if (result.code === 0 || result.timedOut) return false;
192 const lines = `${result.stdout}\n${result.stderr}`
193 .split(/\r?\n/)
194 .map((line) => line.trim())
195 .filter((line) => line !== "");
196 return (
197 (lines.length === 1 && notLoadedMessages.includes(lines[0] ?? "")) ||
198 (lines.length === 2 &&
199 lines[0] === "Bad request." &&
200 notLoadedMessages.includes(lines[1] ?? ""))
201 );
202}
203
204export function isConfirmedLaunchdBootoutNotLoaded(
205 result: ProcessRunner.ProcessRunOutput,
206): boolean {
207 if (result.code === 0 || result.timedOut) return false;
208 const lines = `${result.stdout}\n${result.stderr}`
209 .split(/\r?\n/)
210 .map((line) => line.trim())
211 .filter((line) => line !== "");
212 return lines.length === 1 && lines[0] === "Boot-out failed: 3: No such process";
213}
214
215/**
216 * Platform service-manager integration as data: paths, a pure renderer, and
217 * the command steps each flow runs. install/uninstall/status consume this and
218 * never branch on platform.
219 */
220export interface BootServiceManager {
221 readonly kind: "systemd" | "launchd";
222 readonly unitPath: string;
223 readonly render: (plan: BootServicePlan) => string;
224 /** Before rewriting files, when a unit is already installed. */
225 readonly stop: ReadonlyArray<BootServiceStep>;
226 /** After files are written. The last entry starts the service. */
227 readonly activate: ReadonlyArray<BootServiceStep>;
228 /** Best-effort recovery after a failed repair of an installed service. */
229 readonly restart: ReadonlyArray<BootServiceStep>;
230 /** Uninstall, before the unit file is removed. */
231 readonly deactivate: ReadonlyArray<BootServiceStep>;
232 /** Uninstall, after the unit file is removed. */
233 readonly finalize: ReadonlyArray<BootServiceStep>;
234}
235
236export function systemdManager(input: {
237 readonly path: Path.Path;
238 readonly homeDir: string;
239}): BootServiceManager {
240 const unitPath = input.path.join(
241 input.homeDir,
242 ".config",
243 "systemd",
244 "user",
245 BOOT_SERVICE_UNIT_FILE,
246 );
247 return {
248 kind: "systemd",
249 unitPath,
250 render: renderBootServiceUnit,
251 stop: [
252 {
253 step: "stopping the installed service",
254 command: "systemctl",
255 args: ["--user", "stop", BOOT_SERVICE_UNIT_FILE],
256 timeout: STOP_STEP_TIMEOUT,
257 },
258 ],
259 activate: [
260 {
261 step: "reloading systemd user units",
262 command: "systemctl",
263 args: ["--user", "daemon-reload"],
264 },
265 {
266 step: "enabling the service",
267 command: "systemctl",
268 args: ["--user", "enable", BOOT_SERVICE_UNIT_FILE],
269 },
270 { step: "enabling lingering for this user", command: "loginctl", args: ["enable-linger"] },
271 // Start last. No administrative state write occurs after this succeeds.
272 {
273 step: "starting the service",
274 command: "systemctl",
275 args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
276 },
277 ],
278 restart: [
279 {
280 step: "restarting the service after a failed update",
281 command: "systemctl",
282 args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
283 },
284 ],
285 deactivate: [
286 {
287 step: "stopping the service",
288 command: "systemctl",
289 args: ["--user", "disable", "--now", BOOT_SERVICE_UNIT_FILE],
290 timeout: STOP_STEP_TIMEOUT,
291 },
292 ],
293 finalize: [
294 {
295 step: "reloading systemd user units",
296 command: "systemctl",
297 args: ["--user", "daemon-reload"],
298 },
299 ],
300 };
301}
302
303export function launchdManager(input: {
304 readonly path: Path.Path;
305 readonly homeDir: string;
306 readonly uid: number;
307}): BootServiceManager {
308 const unitPath = input.path.join(
309 input.homeDir,
310 "Library",
311 "LaunchAgents",
312 BOOT_SERVICE_PLIST_FILE,
313 );
314 const domainTarget = `gui/${input.uid}`;
315 const serviceTarget = `${domainTarget}/${BOOT_SERVICE_LAUNCHD_LABEL}`;
316 const notLoadedMessage = `Could not find service "${BOOT_SERVICE_LAUNCHD_LABEL}" in domain for user gui: ${input.uid}`;
317 const missingDomainMessage = `Could not find domain for user gui: ${input.uid}`;
318 // `bootstrap` runs last and is also the start:
319 // loading a RunAtLoad/KeepAlive plist starts the job, so a separate
320 // kickstart would kill and restart a server it just booted. A lingering job
321 // that survived bootout, a persisted disable override, or a gui domain with
322 // nobody logged in at the screen (SSH install) fails the flow loudly.
323 return {
324 kind: "launchd",
325 unitPath,
326 render: (plan) => renderBootServicePlist(plan, { homeDir: input.homeDir }),
327 // bootout has no supported wait flag and returns before a draining job is
328 // absent. Probe the exact service until launchd confirms it left the
329 // domain, so bootstrap cannot race the prior process.
330 stop: [
331 {
332 step: "stopping the installed launch agent",
333 command: "launchctl",
334 args: ["bootout", serviceTarget],
335 timeout: STOP_STEP_TIMEOUT,
336 operation: "launchd-bootout",
337 verifyAbsent: { serviceTarget, notLoadedMessages: [notLoadedMessage] },
338 },
339 ],
340 activate: [
341 // A persisted `launchctl disable` override refuses bootstrap; clear it.
342 {
343 step: "enabling the launch agent",
344 command: "launchctl",
345 args: ["enable", serviceTarget],
346 },
347 // Start last. No administrative state write occurs after this succeeds.
348 {
349 step: "starting the service",
350 command: "launchctl",
351 args: ["bootstrap", domainTarget, unitPath],
352 },
353 ],
354 restart: [
355 {
356 step: "restarting the service after a failed update",
357 command: "launchctl",
358 args: ["bootstrap", domainTarget, unitPath],
359 },
360 ],
361 // No `launchctl disable` here: a persisted override would sabotage a
362 // later reinstall. Removing the plist is what stops the next login load.
363 deactivate: [
364 {
365 step: "stopping the service",
366 command: "launchctl",
367 args: ["bootout", serviceTarget],
368 timeout: STOP_STEP_TIMEOUT,
369 operation: "launchd-bootout",
370 verifyAbsent: {
371 serviceTarget,
372 notLoadedMessages: [notLoadedMessage, missingDomainMessage],
373 },
374 },
375 ],
376 finalize: [],
377 };
378}
379
380/** Undefined means this host cannot run the background service. */
381export function selectBootServiceManager(input: {
382 readonly platform: NodeJS.Platform;
383 readonly homeDir: string;
384 readonly uid: number | undefined;
385 readonly path: Path.Path;
386}): BootServiceManager | undefined {
387 if (input.homeDir === "") {
388 return undefined;
389 }
390 if (input.platform === "linux") {
391 return systemdManager({ path: input.path, homeDir: input.homeDir });
392 }
393 if (input.platform === "darwin" && input.uid !== undefined) {
394 return launchdManager({ path: input.path, homeDir: input.homeDir, uid: input.uid });
395 }
396 return undefined;
397}
398
399export class BootServiceUnsupportedError extends Schema.TaggedErrorClass<BootServiceUnsupportedError>()(
400 "BootServiceUnsupportedError",
401 { platform: Schema.String },
402) {
403 override get message(): string {
404 return `Background setup supports Linux with systemd and macOS with launchd; this machine reports '${this.platform}'.`;
405 }
406}
407
408export class BootServiceCommandError extends Schema.TaggedErrorClass<BootServiceCommandError>()(
409 "BootServiceCommandError",
410 {
411 step: Schema.String,
412 exitCode: Schema.optional(Schema.Number),
413 stdoutLength: Schema.optional(Schema.Number),
414 stderrLength: Schema.optional(Schema.Number),
415 timedOut: Schema.optional(Schema.Boolean),
416 cause: Schema.optional(Schema.Defect()),
417 },
418) {
419 override get message(): string {
420 if (this.timedOut === true) {
421 return `Background setup timed out while ${this.step}.`;
422 }
423 return this.exitCode === undefined
424 ? `Background setup failed while ${this.step}.`
425 : `Background setup failed while ${this.step} (exit code ${this.exitCode}).`;
426 }
427}
428
429export class BootServiceInstallError extends Schema.TaggedErrorClass<BootServiceInstallError>()(
430 "BootServiceInstallError",
431 { cause: Schema.Defect() },
432) {
433 override get message(): string {
434 return "Could not set up the T3 Code background service.";
435 }
436}
437
438export class BootServiceUpdatePendingError extends Schema.TaggedErrorClass<BootServiceUpdatePendingError>()(
439 "BootServiceUpdatePendingError",
440 {},
441) {
442 override get message(): string {
443 return "A remote server update is still pending. Wait for it to finish, then retry.";
444 }
445}
446
447export type BootServiceError =
448 | BootServiceUnsupportedError
449 | BootServiceCommandError
450 | BootServiceInstallError
451 | BootServiceUpdatePendingError;
452
453export interface BootServiceStatus {
454 readonly supported: boolean;
455 readonly installed: boolean;
456 readonly current: boolean;
457 readonly unitPath: string;
458 readonly logPath: string;
459}
460
461export class BootService extends Context.Service<
462 BootService,
463 {
464 readonly install: Effect.Effect<BootServicePlan, BootServiceError>;
465 readonly uninstall: Effect.Effect<boolean, BootServiceError>;
466 readonly status: Effect.Effect<BootServiceStatus, BootServiceError>;
467 }
468>()("t3/cloud/bootService") {}
469
470export interface BootServiceHost {
471 readonly execPath: string;
472 readonly launcherSourcePath?: string;
473}
474
475export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
476 readonly baseDir: string;
477 readonly logsDir: string;
478 readonly cliVersion: string;
479 readonly host?: BootServiceHost;
480}) {
481 const hostExecPath = yield* HostProcessExecutablePath;
482 const platform = yield* HostProcessPlatform;
483 const uid = yield* HostProcessUserId;
484 const homeDir = yield* Config.string("HOME").pipe(Config.withDefault(""));
485 const fs = yield* FileSystem.FileSystem;
486 const path = yield* Path.Path;
487 const runner = yield* ProcessRunner.ProcessRunner;
488 const host = input.host ?? { execPath: hostExecPath };
489
490 const detectedManager = selectBootServiceManager({ platform, homeDir, uid, path });
491 const unitPath = detectedManager?.unitPath ?? "";
492 const logPath = path.join(input.logsDir, "boot-service.log");
493 const launcherPath = path.join(input.baseDir, "runtime", SERVICE_LAUNCHER_FILE);
494 const statePath = path.join(input.baseDir, "runtime", SERVICE_STATE_FILE);
495 const runtimePaths = pinnedRuntimePaths(path, input.baseDir, input.cliVersion);
496 const launcherSourcePath =
497 host.launcherSourcePath ??
498 path.join(path.dirname(runtimePaths.entryPath), SERVICE_LAUNCHER_FILE);
499 const writeDurably = (filePath: string, contents: string) =>
500 Effect.scoped(
501 Effect.gen(function* () {
502 const directory = path.dirname(filePath);
503 yield* fs.makeDirectory(directory, { recursive: true });
504 const tempPath = yield* fs.makeTempFileScoped({ directory, prefix: ".service-write-" });
505 yield* fs.writeFileString(tempPath, contents, { mode: 0o600 });
506 yield* (yield* fs.open(tempPath, { flag: "r" })).sync;
507 yield* fs.rename(tempPath, filePath);
508 yield* (yield* fs.open(directory, { flag: "r" })).sync;
509 }),
510 ).pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
511 const plan: BootServicePlan = {
512 nodePath: host.execPath,
513 launcherPath,
514 baseDir: input.baseDir,
515 logPath,
516 unitPath,
517 };
518
519 const requireManager = Effect.suspend(() =>
520 detectedManager === undefined
521 ? new BootServiceUnsupportedError({ platform })
522 : Effect.succeed(detectedManager),
523 );
524
525 const logCommandError = (error: BootServiceCommandError) =>
526 DateTime.now.pipe(
527 Effect.flatMap((now) =>
528 fs.writeFileString(logPath, `${DateTime.formatIso(now)} ${error.message}\n`, {
529 flag: "a",
530 }),
531 ),
532 Effect.ignore,
533 );
534
535 const runStep = Effect.fn("cloud.boot_service.run_step")(function* (
536 step: string,
537 command: string,
538 args: ReadonlyArray<string>,
539 options?: { readonly timeout?: Duration.Input },
540 ) {
541 return yield* runner.run({ command, args, timeout: options?.timeout }).pipe(
542 Effect.mapError((cause) => new BootServiceCommandError({ step, cause })),
543 Effect.filterOrFail(
544 (result) => result.code === 0,
545 (result) =>
546 new BootServiceCommandError({
547 step,
548 exitCode: Number(result.code),
549 stdoutLength: result.stdout.length,
550 stderrLength: result.stderr.length,
551 }),
552 ),
553 Effect.tapError(logCommandError),
554 );
555 });
556
557 const runLaunchdBootout = Effect.fn("cloud.boot_service.run_launchd_bootout")(function* (
558 entry: Extract<BootServiceStep, { readonly operation: "launchd-bootout" }>,
559 ) {
560 const bootoutResult = yield* runner
561 .run({
562 command: entry.command,
563 args: entry.args,
564 timeout: entry.timeout,
565 })
566 .pipe(Effect.mapError((cause) => new BootServiceCommandError({ step: entry.step, cause })));
567 const bootoutError =
568 bootoutResult.code === 0
569 ? undefined
570 : new BootServiceCommandError({
571 step: entry.step,
572 exitCode: bootoutResult.code === null ? undefined : Number(bootoutResult.code),
573 stdoutLength: bootoutResult.stdout.length,
574 stderrLength: bootoutResult.stderr.length,
575 });
576 if (
577 bootoutError !== undefined &&
578 !isConfirmedLaunchdBootoutNotLoaded(bootoutResult) &&
579 !isConfirmedLaunchdNotLoaded(bootoutResult, entry.verifyAbsent.notLoadedMessages)
580 ) {
581 return yield* bootoutError;
582 }
583
584 yield* Effect.gen(function* () {
585 while (true) {
586 const printResult = yield* runner
587 .run({
588 command: "launchctl",
589 args: ["print", entry.verifyAbsent.serviceTarget],
590 })
591 .pipe(
592 Effect.mapError(
593 (cause) =>
594 new BootServiceCommandError({
595 step: "checking whether the launch agent stopped",
596 cause,
597 }),
598 ),
599 );
600 if (isConfirmedLaunchdNotLoaded(printResult, entry.verifyAbsent.notLoadedMessages)) {
601 return;
602 }
603 if (bootoutError !== undefined) return yield* bootoutError;
604 if (printResult.code !== 0) {
605 return yield* new BootServiceCommandError({
606 step: "checking whether the launch agent stopped",
607 exitCode: printResult.code === null ? undefined : Number(printResult.code),
608 stdoutLength: printResult.stdout.length,
609 stderrLength: printResult.stderr.length,
610 });
611 }
612 yield* Effect.sleep(LAUNCHD_STOP_POLL_INTERVAL);
613 }
614 }).pipe(
615 Effect.timeoutOrElse({
616 duration: STOP_STEP_TIMEOUT,
617 orElse: () =>
618 new BootServiceCommandError({
619 step: "waiting for the launch agent to stop",
620 timedOut: true,
621 }),
622 }),
623 );
624 }, Effect.tapError(logCommandError));
625
626 const runSteps = (steps: ReadonlyArray<BootServiceStep>) =>
627 Effect.forEach(
628 steps,
629 (entry) => {
630 if (entry.operation === "launchd-bootout") {
631 return runLaunchdBootout(entry);
632 }
633 const run = runStep(
634 entry.step,
635 entry.command,
636 entry.args,
637 entry.timeout === undefined ? undefined : { timeout: entry.timeout },
638 );
639 return run.pipe(Effect.asVoid);
640 },
641 { discard: true },
642 );
643
644 const install: BootService["Service"]["install"] = Effect.gen(function* () {
645 const manager = yield* requireManager;
646 yield* fs
647 .makeDirectory(input.logsDir, { recursive: true })
648 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
649
650 // Prepare every immutable artifact before stopping the installed unit.
651 yield* ensurePinnedRuntimeInstalled({
652 baseDir: input.baseDir,
653 version: input.cliVersion,
654 fs,
655 path,
656 runner,
657 validate: (runtime) =>
658 runner
659 .run({
660 command: host.execPath,
661 args: [runtime.entryPath, "--version"],
662 timeout: Duration.seconds(30),
663 })
664 .pipe(
665 Effect.mapError(
666 (cause) =>
667 new PinnedRuntimeInstallError({
668 step: "verifying the pinned t3 runtime",
669 cause,
670 }),
671 ),
672 Effect.flatMap((result) => {
673 const reportedVersion = /\bv(\S+)\s*$/.exec(result.stdout)?.[1];
674 return result.code === 0 && reportedVersion === input.cliVersion
675 ? Effect.void
676 : Effect.fail(
677 new PinnedRuntimeInstallError({
678 step: "verifying the pinned t3 runtime",
679 exitCode: Number(result.code),
680 stdoutLength: result.stdout.length,
681 stderrLength: result.stderr.length,
682 }),
683 );
684 }),
685 ),
686 }).pipe(
687 Effect.mapError((error) =>
688 error._tag === "PinnedRuntimeInstallError"
689 ? new BootServiceCommandError({
690 step: error.step,
691 exitCode: error.exitCode,
692 stdoutLength: error.stdoutLength,
693 stderrLength: error.stderrLength,
694 cause: error,
695 })
696 : new BootServiceInstallError({ cause: error }),
697 ),
698 );
699 const launcherSource = yield* fs
700 .readFileString(launcherSourcePath)
701 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
702
703 const installed = yield* fs
704 .exists(unitPath)
705 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
706 if (installed) {
707 yield* runSteps(manager.stop);
708 }
709
710 yield* Effect.gen(function* () {
711 if (installed) {
712 const previousStateText = yield* fs.readFileString(statePath).pipe(Effect.option);
713 if (
714 Option.isSome(previousStateText) &&
715 serviceStateHasPendingUpdate(previousStateText.value)
716 ) {
717 return yield* new BootServiceUpdatePendingError();
718 }
719 }
720 yield* fs
721 .makeDirectory(path.dirname(unitPath), { recursive: true })
722 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
723 yield* writeDurably(launcherPath, launcherSource);
724 yield* writeDurably(
725 statePath,
726 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned document.
727 `${JSON.stringify(
728 {
729 protocol: SERVICE_LAUNCHER_PROTOCOL,
730 activeVersion: input.cliVersion,
731 } satisfies ServiceState,
732 null,
733 2,
734 )}\n`,
735 );
736 yield* writeDurably(unitPath, manager.render(plan));
737
738 yield* runSteps(manager.activate);
739 }).pipe(
740 Effect.tapError(() =>
741 installed ? runSteps(manager.restart).pipe(Effect.ignore) : Effect.void,
742 ),
743 );
744 return plan;
745 }).pipe(Effect.withSpan("cloud.boot_service.install"));
746
747 const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () {
748 const manager = yield* requireManager;
749 if (
750 !(yield* fs
751 .exists(unitPath)
752 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))))
753 )
754 return false;
755 yield* runSteps(manager.deactivate);
756 yield* fs
757 .remove(unitPath)
758 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
759 yield* runSteps(manager.finalize);
760 return true;
761 }).pipe(Effect.withSpan("cloud.boot_service.uninstall"));
762
763 const status: BootService["Service"]["status"] = Effect.gen(function* () {
764 if (detectedManager === undefined) {
765 return { supported: false, installed: false, current: false, unitPath, logPath };
766 }
767 if (!(yield* fs.exists(unitPath))) {
768 return { supported: true, installed: false, current: false, unitPath, logPath };
769 }
770 const [unit, launcherExists, runtimeEntryExists, runtimeSentinel, stateText] =
771 yield* Effect.all([
772 fs.readFileString(unitPath),
773 fs.exists(launcherPath),
774 fs.exists(runtimePaths.entryPath),
775 fs.readFileString(runtimePaths.sentinelPath).pipe(Effect.option),
776 fs.readFileString(statePath).pipe(Effect.option),
777 ]);
778 const state = Option.isSome(stateText) ? parseServiceState(stateText.value) : undefined;
779 return {
780 supported: true,
781 installed: true,
782 current:
783 unit === detectedManager.render(plan) &&
784 launcherExists &&
785 runtimeEntryExists &&
786 Option.isSome(runtimeSentinel) &&
787 runtimeSentinel.value.trim() === input.cliVersion &&
788 state?.activeVersion === input.cliVersion &&
789 state?.update?.status !== "pending",
790 unitPath,
791 logPath,
792 };
793 }).pipe(
794 Effect.mapError((cause) => new BootServiceInstallError({ cause })),
795 Effect.withSpan("cloud.boot_service.status"),
796 );
797
798 return BootService.of({ install, uninstall, status });
799});
800
801export const layer = (input: {
802 readonly baseDir: string;
803 readonly logsDir: string;
804 readonly cliVersion: string;
805 readonly host?: BootServiceHost;
806}) => Layer.effect(BootService, make(input));