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

bootService.ts

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