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