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

bootService.ts

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