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

bootService.ts

433 lines15.6 KB

1import * as Context from "effect/Context";
2import * as Config from "effect/Config";
3import * as DateTime from "effect/DateTime";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Option from "effect/Option";
9import * as Path from "effect/Path";
10import * as Schema from "effect/Schema";
11​
12import {
13 HostProcessArguments,
14 HostProcessExecutablePath,
15 HostProcessPlatform,
16} from "@t3tools/shared/hostProcess";
17​
18import * as ProcessRunner from "../processRunner.ts";
19import { ensurePinnedRuntimeInstalled, pinnedRuntimePaths } from "./pinnedRuntime.ts";
20​
21/**
22 * Installs T3 Code as a per-user boot service. Linux-only for now: systemd
23 * user unit + loginctl enable-linger. The service runs a stable or pinned
24 * runtime — never an ephemeral `npx t3` cache whose eviction could break
25 * startup.
26 */
27​
28const BOOT_SERVICE_NAME = "t3code";
29​
30export const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
31export const BOOT_SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT";
32​
33const EPHEMERAL_CACHE_SEGMENTS = [
34 "/_npx/", // npx
35 "\\_npx\\",
36 "/pnpm/dlx/", // pnpm dlx (~/.cache/pnpm/dlx and $PNPM_HOME/.pnpm/dlx)
37 "/.pnpm/dlx/",
38 "/.bun/install/cache/", // bunx
39];
40​
41/**
42 * `npx t3` (and pnpm dlx / bunx) run out of ephemeral package-manager
43 * caches that can be evicted at any time — a boot service must never point
44 * there. Global installs, repo checkouts, and the pinned runtime below are
45 * all stable.
46 */
47export function isEphemeralCacheEntry(entryPath: string): boolean {
48 return EPHEMERAL_CACHE_SEGMENTS.some((segment) => entryPath.includes(segment));
50​
51/**
52 * systemd expands `%` specifiers in most directive values, including the
53 * `append:` file paths, which take the rest of the line literally and must
54 * NOT be quoted.
55 */
56export function escapeSystemdSpecifiers(value: string): string {
57 return value.replaceAll("%", "%%");
59​
60/**
61 * systemd word-splits ExecStart and Environment values and expands `%`
62 * specifiers, so paths with spaces or percents must be quoted and escaped.
63 */
64export function quoteSystemdValue(value: string): string {
65 const escaped = escapeSystemdSpecifiers(value);
66 return /[\s"'\\]/.test(escaped)
67 ? `"${escaped.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`
68 : escaped;
70​
71export interface BootServicePlan {
72 /** Absolute path of the node binary running this CLI. */
73 readonly nodePath: string;
74 /** Absolute path of the pinned t3 entry point the unit will run. */
75 readonly t3EntryPath: string;
76 readonly baseDir: string;
77 readonly logPath: string;
78 readonly unitPath: string;
80​
81/**
82 * Pure so it is testable byte-for-byte. systemd user units run with a
83 * minimal environment: every path must be absolute, and the service must
84 * not rely on PATH, nvm shims, or shell profiles. Failures land in
85 * `logPath` because `systemctl --user` failures are otherwise invisible.
86 */
87export function renderBootServiceUnit(plan: BootServicePlan): string {
88 // No After=network-online.target: it does not exist in the systemd *user*
89 // manager, so ordering on it is silently ignored. The server retries its
90 // relay connection, and Restart=always covers early-boot failures.
91 return [
92 "[Unit]",
93 "Description=T3 Code server",
94 // Give up after 5 crashes in 5 minutes so a persistently broken install
95 // (deleted runtime, broken workspace) stops instead of restarting every
96 // 5s forever and growing the unrotated append log without bound.
97 "StartLimitIntervalSec=300",
98 "StartLimitBurst=5",
99 "",
100 "[Service]",
101 "Type=simple",
102 "WorkingDirectory=%h",
103 `Environment=T3CODE_HOME=${quoteSystemdValue(plan.baseDir)}`,
104 `Environment=${BOOT_SERVICE_UNIT_ENV}=${BOOT_SERVICE_UNIT_FILE}`,
105 `ExecStart=${quoteSystemdValue(plan.nodePath)} ${quoteSystemdValue(plan.t3EntryPath)} serve`,
106 "Restart=always",
107 "RestartSec=5",
108 `StandardOutput=append:${escapeSystemdSpecifiers(plan.logPath)}`,
109 `StandardError=append:${escapeSystemdSpecifiers(plan.logPath)}`,
110 "",
111 "[Install]",
112 "WantedBy=default.target",
113 "",
114 ].join("\n");
116​
117export class BootServiceUnsupportedError extends Schema.TaggedErrorClass<BootServiceUnsupportedError>()(
118 "BootServiceUnsupportedError",
119 { platform: Schema.String },
120) {
121 override get message(): string {
122 return `Background setup currently supports Linux with systemd; this machine reports '${this.platform}'.`;
123 }
125​
126export class BootServiceCommandError extends Schema.TaggedErrorClass<BootServiceCommandError>()(
127 "BootServiceCommandError",
128 {
129 step: Schema.String,
130 exitCode: Schema.optional(Schema.Number),
131 stdoutLength: Schema.optional(Schema.Number),
132 stderrLength: Schema.optional(Schema.Number),
133 cause: Schema.optional(Schema.Defect()),
134 },
135) {
136 override get message(): string {
137 return this.exitCode === undefined
138 ? `Background setup failed while ${this.step}.`
139 : `Background setup failed while ${this.step} (exit code ${this.exitCode}).`;
140 }
142​
143export class BootServiceInstallError extends Schema.TaggedErrorClass<BootServiceInstallError>()(
144 "BootServiceInstallError",
145 { cause: Schema.Defect() },
146) {
147 override get message(): string {
148 return "Could not set up the T3 Code background service.";
149 }
151​
152export type BootServiceError =
153 | BootServiceUnsupportedError
154 | BootServiceCommandError
155 | BootServiceInstallError;
156​
157export interface BootServiceStatus {
158 readonly supported: boolean;
159 readonly installed: boolean;
160 /** False when the installed unit no longer matches what install would write. */
161 readonly current: boolean;
162 readonly unitPath: string;
163 readonly logPath: string;
165​
166export class BootService extends Context.Service<
167 BootService,
168 {
169 /** Installs the pinned runtime + unit, enables linger, starts the service. */
170 readonly install: Effect.Effect<BootServicePlan, BootServiceError>;
171 /**
172 * Stops and removes the unit; leaves the pinned runtime for reuse.
173 * Returns whether a unit was actually removed.
174 */
175 readonly uninstall: Effect.Effect<boolean, BootServiceError>;
176 readonly status: Effect.Effect<BootServiceStatus, BootServiceError>;
177 }
178>()("t3/cloud/bootService") {}
179​
180export interface BootServiceHost {
181 readonly execPath: string;
182 readonly cliEntryPath: string;
184​
185export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
186 readonly baseDir: string;
187 readonly logsDir: string;
188 readonly cliVersion: string;
189 readonly host?: BootServiceHost;
190}) {
191 const hostExecPath = yield* HostProcessExecutablePath;
192 const hostArguments = yield* HostProcessArguments;
193 const host = input.host ?? {
194 execPath: hostExecPath,
195 // When running the packed CLI this is dist/bin.mjs; when stable (global
196 // install, repo checkout) the boot service runs this same artifact.
197 cliEntryPath: hostArguments[1] ?? "",
198 };
199 const platform = yield* HostProcessPlatform;
200 const homeDir = yield* Config.string("HOME").pipe(Config.withDefault(""));
201 const fs = yield* FileSystem.FileSystem;
202 const path = yield* Path.Path;
203 const runner = yield* ProcessRunner.ProcessRunner;
204​
205 const unitDir = path.join(homeDir, ".config", "systemd", "user");
206 const unitPath = path.join(unitDir, BOOT_SERVICE_UNIT_FILE);
207 const logPath = path.join(input.logsDir, "boot-service.log");
208 const runtimePaths = pinnedRuntimePaths(path, input.baseDir, input.cliVersion);
209​
210 const requireSystemdLinux = Effect.gen(function* () {
211 if (platform !== "linux" || homeDir === "") {
212 return yield* new BootServiceUnsupportedError({ platform });
213 }
214 });
215​
216 const runStep = Effect.fn("cloud.boot_service.run_step")(function* (
217 step: string,
218 command: string,
219 args: ReadonlyArray<string>,
220 options?: { readonly timeout?: Duration.Input },
221 ) {
222 return yield* runner.run({ command, args, timeout: options?.timeout }).pipe(
223 Effect.mapError((cause) => new BootServiceCommandError({ step, cause })),
224 Effect.filterOrFail(
225 (result) => result.code === 0,
226 (result) =>
227 new BootServiceCommandError({
228 step,
229 exitCode: Number(result.code),
230 stdoutLength: result.stdout.length,
231 stderrLength: result.stderr.length,
232 }),
233 ),
234 Effect.tapError((error) =>
235 DateTime.now.pipe(
236 Effect.flatMap((now) =>
237 fs.writeFileString(logPath, `${DateTime.formatIso(now)} ${error.message}\n`, {
238 flag: "a",
239 }),
240 ),
241 Effect.ignore,
242 ),
243 ),
244 );
245 });
246​
247 /**
248 * Ensures plannedEntryPath exists before the unit points at it. A stable
249 * install (global bin, repo checkout) is used as-is; an ephemeral cache
250 * entry is replaced by `npm install --prefix`-ing the exact running
251 * version into <baseDir>/runtime/versions/<v>. A real install (not a copy
252 * of bin.mjs) because t3 ships native deps like node-pty.
253 */
254 const ensurePinnedRuntime = Effect.gen(function* () {
255 if (!isEphemeralCacheEntry(host.cliEntryPath)) {
256 return;
257 }
258 yield* ensurePinnedRuntimeInstalled({
259 baseDir: input.baseDir,
260 version: input.cliVersion,
261 fs,
262 path,
263 runner,
264 }).pipe(
265 Effect.mapError((error) =>
266 error.step.startsWith("installing")
267 ? new BootServiceCommandError({
268 step: error.step,
269 exitCode: error.exitCode,
270 stdoutLength: error.stdoutLength,
271 stderrLength: error.stderrLength,
272 cause: error.cause,
273 })
274 : new BootServiceInstallError({ cause: error }),
275 ),
276 Effect.tapError((error) =>
277 DateTime.now.pipe(
278 Effect.flatMap((now) =>
279 fs.writeFileString(logPath, `${DateTime.formatIso(now)} ${error.message}\n`, {
280 flag: "a",
281 }),
282 ),
283 Effect.ignore,
284 ),
285 ),
286 );
287 });
288​
289 // Where the unit will point: derivable without touching the network, so
290 // status can compare units purely; install materializes it first.
291 const plannedEntryPath = isEphemeralCacheEntry(host.cliEntryPath)
292 ? runtimePaths.entryPath
293 : host.cliEntryPath;
294 const plan: BootServicePlan = {
295 nodePath: host.execPath,
296 t3EntryPath: plannedEntryPath,
297 baseDir: input.baseDir,
298 logPath,
299 unitPath,
300 };
301​
302 const install: BootService["Service"]["install"] = Effect.gen(function* () {
303 yield* requireSystemdLinux;
304 yield* fs
305 .makeDirectory(input.logsDir, { recursive: true })
306 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
307​
308 yield* ensurePinnedRuntime;
309​
310 const previousUnit = yield* fs.exists(unitPath).pipe(
311 Effect.flatMap((exists) =>
312 exists
313 ? fs.readFileString(unitPath).pipe(Effect.map(Option.some))
314 : Effect.succeed(Option.none<string>()),
315 ),
316 Effect.mapError((cause) => new BootServiceInstallError({ cause })),
317 );
318​
319 yield* fs.makeDirectory(unitDir, { recursive: true }).pipe(
320 Effect.andThen(fs.writeFileString(unitPath, renderBootServiceUnit(plan))),
321 Effect.mapError((cause) => new BootServiceInstallError({ cause })),
322 );
323​
324 // If any activation step fails, remove the unit again: a leftover file
325 // would make service status report it as installed even though it was
326 // never enabled or lingered.
327 yield* Effect.gen(function* () {
328 yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]);
329 yield* runStep("enabling the service", "systemctl", [
330 "--user",
331 "enable",
332 BOOT_SERVICE_UNIT_FILE,
333 ]);
334 // restart rather than enable --now: --now does not replace an already
335 // running process, so repairing a stale unit would leave the old
336 // server running until reboot. restart also starts a stopped service.
337 yield* runStep("starting the service", "systemctl", [
338 "--user",
339 "restart",
340 BOOT_SERVICE_UNIT_FILE,
341 ]);
342 // Linger keeps the user manager (and this service) running without an
343 // open session — the whole point on a box reached over SSH. No
344 // username argument: loginctl defaults to the calling user, which is
345 // always right, while $USER can be stale (su without -l) or unset.
346 yield* runStep("enabling lingering for this user", "loginctl", ["enable-linger"]);
347 }).pipe(Effect.tapError(() => rollbackFailedInstall(previousUnit)));
348​
349 return plan;
350 }).pipe(Effect.withSpan("cloud.boot_service.install"));
351​
352 // If activation fails partway (e.g. enable succeeds but restart/linger
353 // fails), leave nothing behind: disable removes the enable symlink, remove
354 // deletes the file, daemon-reload clears the stale definition — otherwise a
355 // dangling wants/ symlink logs "Failed to load unit" at every boot and the
356 // next lifecycle command misreports the state.
357 const rollbackFailedInstall = Effect.fn("cloud.boot_service.rollback_failed_install")(function* (
358 previousUnit: Option.Option<string>,
359 ) {
360 if (Option.isSome(previousUnit)) {
361 yield* fs.writeFileString(unitPath, previousUnit.value).pipe(Effect.ignore);
362 } else {
363 yield* runStep("cleaning up the service", "systemctl", [
364 "--user",
365 "disable",
366 "--now",
367 BOOT_SERVICE_UNIT_FILE,
368 ]).pipe(Effect.ignore);
369 yield* fs.remove(unitPath).pipe(Effect.ignore);
370 }
371 yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]).pipe(
372 Effect.ignore,
373 );
374 if (Option.isSome(previousUnit)) {
375 yield* runStep("restoring the previous service", "systemctl", [
376 "--user",
377 "restart",
378 BOOT_SERVICE_UNIT_FILE,
379 ]).pipe(Effect.ignore);
380 }
381 });
382​
383 const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () {
384 yield* requireSystemdLinux;
385 const exists = yield* fs
386 .exists(unitPath)
387 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
388 if (!exists) {
389 return false;
390 }
391 yield* runStep("stopping the service", "systemctl", [
392 "--user",
393 "disable",
394 "--now",
395 BOOT_SERVICE_UNIT_FILE,
396 ]);
397 yield* fs
398 .remove(unitPath)
399 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
400 yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]);
401 return true;
402 }).pipe(Effect.withSpan("cloud.boot_service.uninstall"));
403​
404 const status: BootService["Service"]["status"] = Effect.gen(function* () {
405 if (platform !== "linux" || homeDir === "") {
406 return { supported: false, installed: false, current: false, unitPath, logPath };
407 }
408 const unitExists = yield* fs.exists(unitPath);
409 if (!unitExists) {
410 return { supported: true, installed: false, current: false, unitPath, logPath };
411 }
412 const unit = yield* fs.readFileString(unitPath);
413 // A unit is current only if it matches what install would write now (an
414 // older CLI wrote a different runtime/node path) AND the entry point it
415 // references still exists (a pinned runtime under ~/.t3 can be deleted to
416 // reclaim space). Either mismatch makes connect offer a repair.
417 const entryExists = yield* fs.exists(plannedEntryPath);
418 const current = unit === renderBootServiceUnit(plan) && entryExists;
419 return { supported: true, installed: true, current, unitPath, logPath };
420 }).pipe(
421 Effect.mapError((cause) => new BootServiceInstallError({ cause })),
422 Effect.withSpan("cloud.boot_service.status"),
423 );
424​
425 return BootService.of({ install, uninstall, status });
426});
427​
428export const layer = (input: {
429 readonly baseDir: string;
430 readonly logsDir: string;
431 readonly cliVersion: string;
432 readonly host?: BootServiceHost;
433}) => Layer.effect(BootService, make(input));