fix(cli): preflight native services in manager context

This commit is contained in:
Federico Jaramillo Martinez
2026-07-13 00:25:53 +02:00
parent 5ce793add9
commit 3ac6679952
9 changed files with 1481 additions and 275 deletions
+141 -240
View File
@@ -8,6 +8,22 @@ import { fileURLToPath } from "node:url";
import { defaultPiWebConfigPath, defaultPiWebDataDir, examplePiWebConfig } from "./config.js";
import { packageVersion, printPiWebVersionReport } from "./piWebVersionReport.js";
import { checkNodePtyDarwinSpawnHelper, formatNodePtyDarwinSpawnHelperCheck } from "./server/diagnostics/nodePtySpawnHelper.js";
import {
installNativeServiceCandidate,
type NativeServiceInstallCandidate,
type NativeServiceInstallFailure,
} from "./nativeServices/serviceInstall.js";
import {
nativeServiceManagerRefs,
productionNativeServiceIds,
type NativeServiceBackend,
type NativeServiceId,
type NativeServiceManagerRef,
type NativeServicePlan,
type NativeServiceShell,
} from "./nativeServices/servicePlan.js";
import { createNativeServiceAuthoritativeProbe } from "./nativeServices/serviceProbe.js";
import { renderLaunchdPlist, renderSystemdUnit } from "./nativeServices/serviceRendering.js";
const PI_WEB_PACKAGE_NAME = "@jmfederico/pi-web";
@@ -15,16 +31,10 @@ const systemdServiceDir = join(homedir(), ".config", "systemd", "user");
const launchdServiceDir = join(homedir(), "Library", "LaunchAgents");
const logDir = join(defaultPiWebDataDir(), "logs");
const sessiondServiceName = "pi-web-sessiond.service";
const webServiceName = "pi-web.service";
const uiDevServiceName = "pi-web-ui-dev.service";
type InstallMode = "production" | "dev";
type ServiceBackendKind = "systemd" | "launchd";
type ServiceId = "sessiond" | "web" | "uiDev";
type ServiceId = NativeServiceId;
type ServiceBackend = NativeServiceBackend;
type Check = [string, string[]];
type SupportedShell = "bash" | "zsh" | "fish";
type RestartPolicy = "on-failure" | "never";
interface InstallOptions {
host: string;
@@ -33,34 +43,8 @@ interface InstallOptions {
config?: string;
}
interface ServiceBackend {
kind: ServiceBackendKind;
label: string;
}
interface ServiceRef {
interface ServiceRef extends NativeServiceManagerRef {
id: ServiceId;
systemdName: string;
launchdLabel: string;
launchdPlistName: string;
logName: string;
}
interface ServiceDefinition extends ServiceRef {
description: string;
shellCommand: string;
restart: RestartPolicy;
environment: Record<string, string>;
after?: ServiceId[];
wants?: ServiceId[];
workingDirectory?: string;
}
interface ServiceShell {
name: SupportedShell;
executable: string;
detected?: string;
fallback: boolean;
}
interface ServiceExecutable {
@@ -85,30 +69,12 @@ interface ServiceRuntimeStatus {
}
const serviceRefs: Record<ServiceId, ServiceRef> = {
sessiond: {
id: "sessiond",
systemdName: sessiondServiceName,
launchdLabel: "com.pi-web.sessiond",
launchdPlistName: "com.pi-web.sessiond.plist",
logName: "sessiond.log",
},
web: {
id: "web",
systemdName: webServiceName,
launchdLabel: "com.pi-web.web",
launchdPlistName: "com.pi-web.web.plist",
logName: "web.log",
},
uiDev: {
id: "uiDev",
systemdName: uiDevServiceName,
launchdLabel: "com.pi-web.ui-dev",
launchdPlistName: "com.pi-web.ui-dev.plist",
logName: "ui-dev.log",
},
sessiond: { id: "sessiond", ...nativeServiceManagerRefs.sessiond },
web: { id: "web", ...nativeServiceManagerRefs.web },
uiDev: { id: "uiDev", ...nativeServiceManagerRefs.uiDev },
};
const productionServiceIds: ServiceId[] = ["sessiond", "web"];
const productionServiceIds: ServiceId[] = [...productionNativeServiceIds];
const startServiceOrder: ServiceId[] = ["sessiond", "web", "uiDev"];
const stopServiceOrder: ServiceId[] = ["web", "uiDev", "sessiond"];
// Restart web/UI before sessiond: when `pi-web restart` runs in a pi-web
@@ -236,23 +202,6 @@ function fishSingleQuote(value: string): string {
return `'${value.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`;
}
function systemdEscape(value: string): string {
return value.replaceAll("\\", "\\\\").replaceAll('"', '\\"');
}
function systemdQuotedValue(value: string): string {
return `"${systemdEscape(value)}"`;
}
function xmlEscape(value: string): string {
return value
.replaceAll("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;")
.replaceAll("'", "&apos;");
}
function packageRootPath(): string {
return dirname(dirname(fileURLToPath(import.meta.url)));
}
@@ -261,15 +210,25 @@ function packageEntrypointPath(name: "server" | "sessiond"): string {
return join(packageRootPath(), "dist", "server", name === "server" ? "index.js" : "sessiond.js");
}
function detectServiceShell(): ServiceShell {
function detectServiceShell(): NativeServiceShell {
const userShell = userInfo().shell ?? undefined;
const envShell = process.env["SHELL"]?.trim();
const detected = envShell === undefined || envShell === "" ? userShell : envShell;
const name = basename(detected ?? "").replace(/^-/, "");
if (name === "bash" || name === "zsh" || name === "fish") {
return { name, executable: detected ?? name, detected: detected ?? name, fallback: false };
return {
name,
executable: detected ?? name,
source: "detected",
detectedExecutable: detected ?? name,
};
}
return { name: "bash", executable: "bash", ...(detected === undefined ? {} : { detected }), fallback: true };
return {
name: "bash",
executable: "bash",
source: "fallback",
detectedExecutable: detected ?? null,
};
}
function serviceShellCommand(command: string, cwd?: string): string[] {
@@ -277,18 +236,10 @@ function serviceShellCommand(command: string, cwd?: string): string[] {
return ["/usr/bin/env", detectServiceShell().executable, "-lc", fullCommand];
}
function serviceShellExecPrefix(): string {
return `/usr/bin/env ${detectServiceShell().executable} -lc`;
}
function serviceShellQuote(value: string): string {
return detectServiceShell().name === "fish" ? fishSingleQuote(value) : shellSingleQuote(value);
}
function systemdServiceShellQuote(value: string): string {
return serviceShellQuote(value.replaceAll("%", "%%").replaceAll("$", "$$"));
}
function checkSucceeds(command: string[]): boolean {
const [bin, ...args] = command;
return bin !== undefined && capture(bin, args).status === 0;
@@ -341,12 +292,12 @@ function resolveServiceExecutables(backend: ServiceBackend): ServiceExecutables
function describeServiceShell(): string {
const shell = detectServiceShell();
if (shell.fallback) {
return shell.detected === undefined
if (shell.source === "fallback") {
return shell.detectedExecutable === null
? "could not detect a supported login shell; using bash"
: `detected ${shell.detected}; using bash because PI WEB currently supports bash, zsh, and fish`;
: `detected ${shell.detectedExecutable}; using bash because PI WEB currently supports bash, zsh, and fish`;
}
return shell.detected === undefined ? shell.name : `${shell.name} (${shell.detected})`;
return shell.detectedExecutable === null ? shell.name : `${shell.name} (${shell.detectedExecutable})`;
}
function configEnvironment(options: InstallOptions, configPath: string): Record<string, string> {
@@ -385,28 +336,6 @@ function restartOrder(refs: ServiceRef[]): ServiceRef[] {
return orderServiceRefs(refs, restartServiceOrder);
}
function productionServiceDefinitions(options: InstallOptions, configPath: string, executables: ServiceExecutables): ServiceDefinition[] {
const environment = configEnvironment(options, configPath);
return [
{
...serviceRefs.sessiond,
description: "PI WEB session daemon",
shellCommand: `exec ${executables.sessiond.command}`,
restart: "on-failure",
environment,
},
{
...serviceRefs.web,
description: "PI WEB server",
shellCommand: `exec ${executables.web.command}`,
restart: "on-failure",
environment,
after: ["sessiond"],
wants: ["sessiond"],
},
];
}
function devRootPath(): string {
return resolve(process.cwd());
}
@@ -421,104 +350,21 @@ function validateDevCheckout(root: string): void {
if (!isRecord(parsed) || parsed["name"] !== PI_WEB_PACKAGE_NAME) {
throw new Error(`Development mode must be installed from a PI WEB checkout. ${packageJsonPath} is not ${PI_WEB_PACKAGE_NAME}.`);
}
const scripts = parsed["scripts"];
if (!isRecord(scripts)) throw new Error(`Development mode requires npm scripts in ${packageJsonPath}.`);
const requiredScripts = ["start:sessiond", "dev:web", "dev:client"];
const missing = requiredScripts.filter((script) => typeof scripts[script] !== "string");
if (missing.length > 0) throw new Error(`Development mode requires missing npm scripts: ${missing.join(", ")}.`);
}
function devServiceDefinitions(options: InstallOptions, configPath: string, root: string): ServiceDefinition[] {
const environment = configEnvironment(options, configPath);
return [
{
...serviceRefs.sessiond,
description: "PI WEB session daemon (dev)",
shellCommand: "exec npm run start:sessiond",
restart: "never",
environment,
workingDirectory: root,
},
{
...serviceRefs.uiDev,
description: "PI WEB UI dev server",
shellCommand: `exec /usr/bin/env bash -c ${serviceShellQuote('trap "kill 0" EXIT; npm run dev:web & npm run dev:client & wait')}`,
restart: "never",
environment,
after: ["sessiond"],
wants: ["sessiond"],
workingDirectory: root,
},
];
}
function dependencyLine(name: "After" | "Wants", ids: ServiceId[] | undefined): string {
if (ids === undefined || ids.length === 0) return "";
return `${name}=${ids.map((id) => serviceRefs[id].systemdName).join(" ")}\n`;
}
function environmentLines(environment: Record<string, string>): string {
return Object.entries(environment)
.map(([key, value]) => `Environment="${key}=${systemdEscape(value)}"\n`)
.join("");
}
function systemdUnit(service: ServiceDefinition): string {
const workingDirectory = service.workingDirectory === undefined ? "" : `WorkingDirectory=${systemdQuotedValue(service.workingDirectory)}\n`;
const restart = service.restart === "on-failure" ? "Restart=on-failure\nRestartSec=2\n" : "Restart=no\n";
return `[Unit]
Description=${service.description}
${dependencyLine("After", service.after)}${dependencyLine("Wants", service.wants)}
[Service]
Type=simple
${workingDirectory}${environmentLines(service.environment)}ExecStart=${serviceShellExecPrefix()} ${systemdServiceShellQuote(service.shellCommand)}
${restart}
[Install]
WantedBy=default.target
`;
}
function plistString(key: string, value: string, indent = " "): string {
return `${indent}<key>${xmlEscape(key)}</key>\n${indent}<string>${xmlEscape(value)}</string>\n`;
}
function plistProgramArguments(service: ServiceDefinition): string {
const args = ["/usr/bin/env", detectServiceShell().executable, "-lc", service.shellCommand];
return ` <key>ProgramArguments</key>\n <array>\n${args.map((arg) => ` <string>${xmlEscape(arg)}</string>`).join("\n")}\n </array>\n`;
}
function plistEnvironment(environment: Record<string, string>): string {
const entries = Object.entries(environment);
if (entries.length === 0) return "";
return ` <key>EnvironmentVariables</key>\n <dict>\n${entries.map(([key, value]) => plistString(key, value, " ")).join("")} </dict>\n`;
}
function launchdLogPath(ref: ServiceRef): string {
return join(logDir, ref.logName);
}
function launchdPlist(service: ServiceDefinition): string {
const workingDirectory = service.workingDirectory === undefined ? "" : plistString("WorkingDirectory", service.workingDirectory);
const keepAlive = service.restart === "on-failure" ? " <key>KeepAlive</key>\n <dict>\n <key>SuccessfulExit</key>\n <false/>\n </dict>\n" : "";
return `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
${plistString("Label", service.launchdLabel)}${plistProgramArguments(service)}${workingDirectory}${plistEnvironment(service.environment)} <key>RunAtLoad</key>
<true/>
${keepAlive}${plistString("StandardOutPath", launchdLogPath(service))}${plistString("StandardErrorPath", launchdLogPath(service))}</dict>
</plist>
`;
function installConfigPath(options: InstallOptions): string {
return options.config === undefined ? defaultPiWebConfigPath() : resolve(options.config);
}
async function writeInitialConfig(options: InstallOptions): Promise<string> {
const configPath = options.config === undefined ? defaultPiWebConfigPath() : resolve(options.config);
async function writeInitialConfig(options: InstallOptions, configPath: string): Promise<void> {
await mkdir(dirname(configPath), { recursive: true });
if (!existsSync(configPath)) {
await writeFile(configPath, examplePiWebConfig({ host: options.host, port: Number(options.port) }));
}
return configPath;
}
function systemdServicePath(ref: ServiceRef): string {
@@ -546,8 +392,8 @@ function installedServiceRefs(backend: ServiceBackend): ServiceRef[] {
return installed.length === 0 ? productionServiceRefs() : installed;
}
async function installSystemdServices(services: ServiceDefinition[]): Promise<void> {
const selected = new Set<ServiceId>(services.map((service) => service.id));
async function installSystemdServices(plan: NativeServicePlan): Promise<void> {
const selected = new Set<ServiceId>(plan.services.map((service) => service.id));
const obsolete = stopOrder(allServiceRefs().filter((ref) => !selected.has(ref.id)));
for (const ref of obsolete) {
@@ -556,11 +402,11 @@ async function installSystemdServices(services: ServiceDefinition[]): Promise<vo
}
await mkdir(systemdServiceDir, { recursive: true });
for (const service of services) {
await writeFile(systemdServicePath(service), systemdUnit(service));
for (const service of plan.services) {
await writeFile(join(systemdServiceDir, service.manager.systemdName), renderSystemdUnit(plan, service));
}
const names = services.map((service) => service.systemdName);
const names = plan.services.map((service) => service.manager.systemdName);
run("systemctl", ["--user", "daemon-reload"], { check: true });
run("systemctl", ["--user", "enable", ...names], { check: true });
run("systemctl", ["--user", "restart", ...names], { check: true });
@@ -592,8 +438,8 @@ function launchdStart(ref: ServiceRef): void {
run("launchctl", ["kickstart", launchdServiceTarget(ref)], { check: true });
}
async function installLaunchdServices(services: ServiceDefinition[]): Promise<void> {
const selected = new Set<ServiceId>(services.map((service) => service.id));
async function installLaunchdServices(plan: NativeServicePlan): Promise<void> {
const selected = new Set<ServiceId>(plan.services.map((service) => service.id));
await mkdir(launchdServiceDir, { recursive: true });
await mkdir(logDir, { recursive: true });
@@ -604,16 +450,21 @@ async function installLaunchdServices(services: ServiceDefinition[]): Promise<vo
await rm(launchdPlistPath(ref), { force: true });
}
for (const service of services) {
await writeFile(launchdPlistPath(service), launchdPlist(service));
for (const service of plan.services) {
const plistPath = join(launchdServiceDir, service.manager.launchdPlistName);
await writeFile(plistPath, renderLaunchdPlist(plan, service, logDir));
}
for (const service of services) launchdStart(service);
for (const service of plan.services) launchdStart(serviceRefFromPlan(service.id, service.manager));
}
async function installNativeServices(backend: ServiceBackend, services: ServiceDefinition[]): Promise<void> {
if (backend.kind === "systemd") await installSystemdServices(services);
else await installLaunchdServices(services);
async function installNativeServices(plan: NativeServicePlan): Promise<void> {
if (plan.backend.kind === "systemd") await installSystemdServices(plan);
else await installLaunchdServices(plan);
}
function serviceRefFromPlan(id: ServiceId, manager: NativeServiceManagerRef): ServiceRef {
return { id, ...manager };
}
async function uninstallSystemdServices(): Promise<void> {
@@ -759,28 +610,77 @@ function baseShellChecks(backend: ServiceBackend): Check[] {
return checks;
}
function devInstallChecks(backend: ServiceBackend, root: string): Check[] {
const shell = serviceShellLabel();
const checks: Check[] = [
[`${shell} can find npm`, serviceShellCommand(commandCheck("npm"), root)],
[`${shell} can find bash`, serviceShellCommand(commandCheck("bash"), root)],
];
if (backend.kind === "systemd") {
checks.push(
[`systemd user ${shell} can find npm`, systemdUserServiceShellCommand(commandCheck("npm"), root)],
[`systemd user ${shell} can find bash`, systemdUserServiceShellCommand(commandCheck("bash"), root)],
);
}
return checks;
function configuredServiceCommand(name: "PI_WEB_SERVER_EXEC" | "PI_WEB_SESSIOND_EXEC"): string | undefined {
const value = process.env[name];
return value === undefined || value.trim() === "" ? undefined : value;
}
function installPreflightChecks(backend: ServiceBackend, mode: InstallMode, executables: ServiceExecutables | undefined, devRoot: string | undefined): Check[] {
return [
...backendAvailabilityChecks(backend),
...baseShellChecks(backend),
...(mode === "dev" && devRoot !== undefined ? devInstallChecks(backend, devRoot) : []),
...(mode === "production" && executables !== undefined ? [...executables.web.checks, ...executables.sessiond.checks] : []),
];
function nativeServiceInstallCandidate(
options: InstallOptions,
backend: ServiceBackend,
configPath: string,
devRoot: string | undefined,
): NativeServiceInstallCandidate {
const common = {
backend,
shell: detectServiceShell(),
environment: configEnvironment(options, configPath),
};
if (options.mode === "production") {
return {
mode: "production",
input: {
...common,
executables: {
sessiond: {
configuredCommand: configuredServiceCommand("PI_WEB_SESSIOND_EXEC"),
namedCommand: "pi-web-sessiond",
bundledEntrypointPath: packageEntrypointPath("sessiond"),
},
web: {
configuredCommand: configuredServiceCommand("PI_WEB_SERVER_EXEC"),
namedCommand: "pi-web-server",
bundledEntrypointPath: packageEntrypointPath("server"),
},
},
},
};
}
const root = devRoot ?? devRootPath();
return {
mode: "development",
input: {
...common,
workingDirectory: root,
packageJsonPath: join(root, "package.json"),
},
};
}
function printNativeServiceInstallFailure(failure: NativeServiceInstallFailure): void {
if (failure.kind === "plan-resolution") {
for (const item of failure.failures) {
if (item.kind === "probe-infrastructure") {
console.log(`✗ Service-manager probe infrastructure failure (${item.reason}): ${item.message}`);
} else if (item.kind === "entrypoint-inspection-failure") {
console.log(`✗ Could not inspect bundled ${item.serviceId} entrypoint ${item.entrypointPath}: ${item.message}`);
} else {
console.log(`${item.namedCommand} is unavailable to the service manager, and bundled entrypoint ${item.bundledEntrypointPath} is missing.`);
if (item.namedCommandFailure !== null) console.log(` ${item.namedCommandFailure}`);
}
}
return;
}
for (const item of failure.failures) {
if (item.kind === "probe-infrastructure") {
console.log(`✗ Service-manager probe infrastructure failure (${item.reason}): ${item.message}`);
} else {
console.log(`${item.prerequisite.description}`);
if (item.detail !== null && item.detail !== item.prerequisite.description) console.log(` ${item.detail}`);
}
}
}
async function install(args: string[]): Promise<void> {
@@ -788,23 +688,24 @@ async function install(args: string[]): Promise<void> {
const options = parseInstallOptions(args);
const devRoot = options.mode === "dev" ? devRootPath() : undefined;
if (devRoot !== undefined) validateDevCheckout(devRoot);
const configPath = installConfigPath(options);
const candidate = nativeServiceInstallCandidate(options, backend, configPath, devRoot);
const executables = options.mode === "production" ? resolveServiceExecutables(backend) : undefined;
console.log(`Running PI WEB ${options.mode} install preflight checks...`);
console.log(`Service backend: ${backend.label}`);
console.log(`Service shell: ${describeServiceShell()}`);
if (!runChecks(installPreflightChecks(backend, options.mode, executables, devRoot))) {
const result = await installNativeServiceCandidate(candidate, {
probe: createNativeServiceAuthoritativeProbe(),
fileExists: existsSync,
writeInitialConfig: () => writeInitialConfig(options, configPath),
replaceServices: installNativeServices,
});
if (!result.ok) {
printNativeServiceInstallFailure(result.failure);
printPathSetupAdvice();
throw new Error("Install preflight checks failed. Fix the failed checks above, then run `pi-web doctor` for more detail.");
throw new Error("Install preflight checks failed without changing config or services. Fix the failure above, then run `pi-web doctor` for more detail.");
}
const configPath = await writeInitialConfig(options);
const services = options.mode === "dev"
? devServiceDefinitions(options, configPath, devRoot ?? devRootPath())
: productionServiceDefinitions(options, configPath, executables ?? resolveServiceExecutables(backend));
await installNativeServices(backend, services);
console.log(`\nPI WEB ${options.mode} services are installed and starting.`);
console.log(`Config: ${configPath}`);
if (options.mode === "dev") {