From 996b49430c103a879881290f8b8461c7196b56ed Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Mon, 16 Nov 2026 20:34:13 +0000 Subject: [PATCH] feat(cli): add lo1 doctor and fail lo1 up early on port conflicts `lo1 doctor` checks what a first `lo1 up` depends on and prints a fix for each problem: Node.js 24+, Docker installed and its daemon running, Docker Compose v2, Git, a valid lo1.yaml, free ports for the proxy and every service, hosts file entries and ACME credentials. It exits 1 when any check fails, and `--json` prints `{ ok, checks }`. `lo1 up` now checks the same ports before starting anything and stops with a PortConflictError naming each port, what needs it and the lo1.yaml setting that changes it, instead of failing midway with a Docker error. --- packages/cli/src/cli/commands/doctor.ts | 50 ++++ packages/cli/src/cli/index.ts | 2 + packages/cli/src/doctor/checks.ts | 260 ++++++++++++++++++ packages/cli/src/doctor/ports.ts | 99 +++++++ packages/cli/src/orchestrator/start.ts | 5 + packages/cli/src/orchestrator/types.ts | 3 + packages/cli/tests/doctor/checks.test.ts | 175 ++++++++++++ packages/cli/tests/doctor/ports.test.ts | 98 +++++++ packages/cli/tests/orchestrator/start.test.ts | 15 + 9 files changed, 707 insertions(+) create mode 100644 packages/cli/src/cli/commands/doctor.ts create mode 100644 packages/cli/src/doctor/checks.ts create mode 100644 packages/cli/src/doctor/ports.ts create mode 100644 packages/cli/tests/doctor/checks.test.ts create mode 100644 packages/cli/tests/doctor/ports.test.ts diff --git a/packages/cli/src/cli/commands/doctor.ts b/packages/cli/src/cli/commands/doctor.ts new file mode 100644 index 0000000..997c95f --- /dev/null +++ b/packages/cli/src/cli/commands/doctor.ts @@ -0,0 +1,50 @@ +import { Command } from "commander"; +import { createDefaultDoctorDeps, runDoctor, type CheckResult } from "../../doctor/checks"; + +const SYMBOLS: Record = { ok: "✓", warn: "!", fail: "✗" }; + +const COLORS: Record = { + ok: "\x1b[32m", + warn: "\x1b[33m", + fail: "\x1b[31m", +}; + +function plural(count: number, word: string): string { + return `${count} ${word}${count === 1 ? "" : "s"}`; +} + +export function formatDoctorReport(results: CheckResult[], useColor: boolean): string { + const lines = results.map((r) => { + const symbol = useColor ? `${COLORS[r.status]}${SYMBOLS[r.status]}\x1b[0m` : SYMBOLS[r.status]; + const fix = r.fix ? `\n ${r.fix}` : ""; + return ` ${symbol} ${r.message}${fix}`; + }); + + const failures = results.filter((r) => r.status === "fail").length; + const warnings = results.filter((r) => r.status === "warn").length; + const summary = + failures === 0 && warnings === 0 + ? "Everything looks good." + : [failures > 0 && plural(failures, "problem"), warnings > 0 && plural(warnings, "warning")] + .filter(Boolean) + .join(", ") + "."; + + return `${lines.join("\n")}\n\n ${summary}\n`; +} + +export const doctorCommand = new Command("doctor") + .description("Check that this machine and workspace are ready for lo1 up") + .option("--config ", "Path to lo1.yaml config file", "lo1.yaml") + .action(async function (this: Command) { + const { json, config } = this.optsWithGlobals(); + const results = await runDoctor(createDefaultDoctorDeps(config), process.cwd()); + const ok = results.every((r) => r.status !== "fail"); + + if (json === true) { + process.stdout.write(JSON.stringify({ ok, checks: results }) + "\n"); + } else { + process.stdout.write(formatDoctorReport(results, process.stdout.isTTY === true)); + } + + if (!ok) process.exitCode = 1; + }); diff --git a/packages/cli/src/cli/index.ts b/packages/cli/src/cli/index.ts index 2e439ea..a3b7a04 100644 --- a/packages/cli/src/cli/index.ts +++ b/packages/cli/src/cli/index.ts @@ -10,6 +10,7 @@ import { statusCommand } from "./commands/status"; import { hostsCommand } from "./commands/hosts"; import { tlsSetupCommand } from "./commands/tls-setup"; import { logsCommand } from "./commands/logs"; +import { doctorCommand } from "./commands/doctor"; export const program = new Command(); @@ -29,6 +30,7 @@ program.addCommand(statusCommand); program.addCommand(hostsCommand); program.addCommand(tlsSetupCommand); program.addCommand(logsCommand); +program.addCommand(doctorCommand); export function formatErrorForOutput(err: unknown, json: boolean): string { if (json) { diff --git a/packages/cli/src/doctor/checks.ts b/packages/cli/src/doctor/checks.ts new file mode 100644 index 0000000..054fc78 --- /dev/null +++ b/packages/cli/src/doctor/checks.ts @@ -0,0 +1,260 @@ +import { execFile } from "node:child_process"; +import { readFile } from "node:fs/promises"; +import { promisify } from "node:util"; +import type { WorkspaceConfig } from "@lo1/sdk"; +import { loadWorkspaceConfig } from "../config/loader"; +import { readState } from "../orchestrator/state"; +import { collectDomains } from "../proxy/domains"; +import { getHostsFilePath } from "../hosts/index"; +import { getAcmeConfig, verifyAcmeEnv } from "../tls/acme"; +import { findPortConflicts, formatPortConflict, isPortInUse, type PortProbe } from "./ports"; + +export type CheckStatus = "ok" | "warn" | "fail"; + +export type CheckResult = { + id: string; + status: CheckStatus; + message: string; + /** What to do about a warning or failure. */ + fix?: string; +}; + +export type ExecFn = (cmd: string, args: string[]) => Promise<{ stdout: string; stderr: string }>; + +export type DoctorDeps = { + exec: ExecFn; + nodeVersion: string; + loadConfig: () => Promise; + configExists: () => Promise; + isWorkspaceRunning: (workspaceDir: string) => Promise; + readHostsFile: () => Promise; + probePort: PortProbe; + env: NodeJS.ProcessEnv; +}; + +export const MIN_NODE_MAJOR = 24; +const MIN_COMPOSE_MAJOR = 2; + +export function createDefaultDoctorDeps(configPath = "lo1.yaml"): DoctorDeps { + return { + exec: promisify(execFile), + nodeVersion: process.versions.node, + loadConfig: () => loadWorkspaceConfig(configPath), + configExists: () => + readFile(configPath).then( + () => true, + () => false, + ), + isWorkspaceRunning: async (dir) => (await readState(dir)) !== null, + readHostsFile: () => readFile(getHostsFilePath(), "utf-8"), + probePort: isPortInUse, + env: process.env, + }; +} + +function majorVersion(version: string): number { + return Number.parseInt(version.replace(/^v/, "").split(".")[0], 10); +} + +export function checkNode(nodeVersion: string): CheckResult { + if (majorVersion(nodeVersion) >= MIN_NODE_MAJOR) { + return { id: "node", status: "ok", message: `Node.js ${nodeVersion}` }; + } + return { + id: "node", + status: "fail", + message: `Node.js ${nodeVersion} is too old; lo1 needs ${MIN_NODE_MAJOR} or later`, + fix: `Install Node.js ${MIN_NODE_MAJOR} or later from https://nodejs.org`, + }; +} + +function isMissingCommand(err: unknown): boolean { + return typeof err === "object" && err !== null && "code" in err && err.code === "ENOENT"; +} + +export async function checkDocker(exec: ExecFn): Promise { + try { + const { stdout } = await exec("docker", ["version", "--format", "{{.Server.Version}}"]); + return { id: "docker", status: "ok", message: `Docker ${stdout.trim()}` }; + } catch (err) { + if (isMissingCommand(err)) { + return { + id: "docker", + status: "fail", + message: "Docker is not installed", + fix: "Install Docker Desktop or Docker Engine: https://docs.docker.com/get-docker/", + }; + } + return { + id: "docker", + status: "fail", + message: "Docker is installed, but the Docker daemon is not running", + fix: "Start Docker Desktop, or on Linux run: sudo systemctl start docker", + }; + } +} + +export async function checkCompose(exec: ExecFn): Promise { + const fix = "Install Docker Compose v2: https://docs.docker.com/compose/install/"; + try { + const { stdout } = await exec("docker", ["compose", "version", "--short"]); + const version = stdout.trim(); + if (majorVersion(version) >= MIN_COMPOSE_MAJOR) { + return { id: "compose", status: "ok", message: `Docker Compose ${version}` }; + } + return { + id: "compose", + status: "fail", + message: `Docker Compose ${version} is too old; lo1 needs v2`, + fix, + }; + } catch { + return { id: "compose", status: "fail", message: "Docker Compose v2 was not found", fix }; + } +} + +export async function checkGit(exec: ExecFn, needsGit: boolean): Promise { + try { + const { stdout } = await exec("git", ["--version"]); + const version = stdout.trim().replace(/^git version /, ""); + return { id: "git", status: "ok", message: `Git ${version}` }; + } catch { + return { + id: "git", + status: needsGit ? "fail" : "warn", + message: needsGit + ? "Git is not installed, and lo1.yaml lists repositories for lo1 init to clone" + : "Git is not installed; lo1 init needs it to clone repositories", + fix: "Install Git: https://git-scm.com/downloads", + }; + } +} + +export function checkAcme(config: WorkspaceConfig, env: NodeJS.ProcessEnv): CheckResult | null { + const acme = getAcmeConfig(config); + if (!acme) return null; + + try { + verifyAcmeEnv(acme, env); + return { id: "acme", status: "ok", message: `ACME credentials for ${acme.provider} are set` }; + } catch (err) { + const [message, ...rest] = (err as Error).message.split("\n"); + return { id: "acme", status: "fail", message, fix: rest.join(" ").trim() }; + } +} + +export async function checkPorts( + config: WorkspaceConfig, + probe: PortProbe, + workspaceRunning: boolean, +): Promise { + if (workspaceRunning) { + return [ + { + id: "ports", + status: "ok", + message: "Ports not checked: this workspace is running (run lo1 down to check them)", + }, + ]; + } + + const conflicts = await findPortConflicts(config, probe); + if (conflicts.length === 0) { + return [{ id: "ports", status: "ok", message: "All ports lo1 needs are free" }]; + } + return conflicts.map((claim) => ({ + id: "ports", + status: "fail" as const, + message: formatPortConflict(claim), + fix: `Stop whatever is listening on port ${claim.port}, or change ${claim.setting} in lo1.yaml`, + })); +} + +export async function checkHosts( + config: WorkspaceConfig, + readHostsFile: () => Promise, +): Promise { + if (config.proxy?.enabled === false) return null; + const domains = collectDomains(config); + if (domains.length === 0) return null; + + let content: string; + try { + content = await readHostsFile(); + } catch { + return { + id: "hosts", + status: "warn", + message: "Could not read the hosts file", + fix: "lo1 up adds the workspace's domains to it, and asks for sudo to do so", + }; + } + + const listed = new Set(content.split(/\s+/)); + const missing = domains.filter((domain) => !listed.has(domain)); + if (missing.length === 0) { + return { + id: "hosts", + status: "ok", + message: `Hosts file lists all ${domains.length} domain(s)`, + }; + } + return { + id: "hosts", + status: "warn", + message: `${missing.length} of ${domains.length} domain(s) are not in the hosts file yet`, + fix: "lo1 up adds them and asks for sudo to do so; lo1 hosts --apply does it on its own", + }; +} + +async function checkWorkspace(deps: DoctorDeps, workspaceDir: string): Promise { + if (!(await deps.configExists())) { + return [ + { + id: "config", + status: "warn", + message: "No lo1.yaml here, so workspace checks were skipped", + fix: "Run lo1 doctor from your workspace root", + }, + ]; + } + + let config: WorkspaceConfig; + try { + config = await deps.loadConfig(); + } catch (err) { + return [{ id: "config", status: "fail", message: (err as Error).message }]; + } + + const results: CheckResult[] = [ + { id: "config", status: "ok", message: `lo1.yaml is valid (workspace "${config.name}")` }, + ]; + const running = await deps.isWorkspaceRunning(workspaceDir); + results.push(...(await checkPorts(config, deps.probePort, running))); + + const optional = [await checkHosts(config, deps.readHostsFile), checkAcme(config, deps.env)]; + for (const result of optional) if (result) results.push(result); + + return results; +} + +export async function runDoctor(deps: DoctorDeps, workspaceDir = "."): Promise { + const needsGit = await deps + .loadConfig() + .then((c) => Object.keys(c.repositories ?? {}).length > 0) + .catch(() => false); + + const [docker, compose, git] = await Promise.all([ + checkDocker(deps.exec), + checkCompose(deps.exec), + checkGit(deps.exec, needsGit), + ]); + + return [ + checkNode(deps.nodeVersion), + docker, + compose, + git, + ...(await checkWorkspace(deps, workspaceDir)), + ]; +} diff --git a/packages/cli/src/doctor/ports.ts b/packages/cli/src/doctor/ports.ts new file mode 100644 index 0000000..03b6721 --- /dev/null +++ b/packages/cli/src/doctor/ports.ts @@ -0,0 +1,99 @@ +import { connect } from "node:net"; +import type { WorkspaceConfig } from "@lo1/sdk"; +import { Lo1Error } from "../errors"; + +/** A host port lo1 will need, and what needs it. */ +export type PortClaim = { + port: number; + owner: string; + /** The lo1.yaml field that changes this port. */ + setting: string; +}; + +export type PortProbe = (port: number) => Promise; + +export class PortConflictError extends Lo1Error { + constructor(public readonly conflicts: PortClaim[]) { + super(formatPortConflicts(conflicts), "PortConflictError", { + ports: conflicts.map((c) => c.port), + }); + this.name = "PortConflictError"; + } +} + +/** The host ports a workspace binds: the proxy's, then each running service's. */ +export function collectPortClaims(config: WorkspaceConfig): PortClaim[] { + const claims: PortClaim[] = []; + + if (config.proxy?.enabled !== false) { + claims.push({ port: config.proxy?.port ?? 80, owner: "the proxy", setting: "proxy.port" }); + if (config.proxy?.tls?.enabled) { + claims.push({ + port: config.proxy.tls.port ?? 443, + owner: "the proxy", + setting: "proxy.tls.port", + }); + } + } + + for (const [name, service] of Object.entries(config.services)) { + if (service.mode === "skip" || !service.port) continue; + + const isContainer = service.mode === "container"; + claims.push({ + port: isContainer ? (service.hostPort ?? service.port) : service.port, + owner: `service "${name}"`, + setting: isContainer ? `services.${name}.hostPort` : `services.${name}.port`, + }); + } + + return claims; +} + +/** + * Reports whether something accepts connections on the port on this machine. + * Connecting rather than binding avoids false alarms for ports below 1024, + * which an unprivileged process may not bind even when they are free. + */ +export async function isPortInUse(port: number, timeoutMs = 500): Promise { + const results = await Promise.all( + ["127.0.0.1", "::1"].map((host) => acceptsConnections(host, port, timeoutMs)), + ); + return results.some(Boolean); +} + +function acceptsConnections(host: string, port: number, timeoutMs: number): Promise { + return new Promise((resolve) => { + const socket = connect({ host, port }); + const finish = (inUse: boolean) => { + socket.destroy(); + resolve(inUse); + }; + socket.setTimeout(timeoutMs, () => finish(false)); + socket.once("connect", () => finish(true)); + socket.once("error", () => finish(false)); + }); +} + +export async function findPortConflicts( + config: WorkspaceConfig, + probe: PortProbe = isPortInUse, +): Promise { + const claims = collectPortClaims(config); + const inUse = await Promise.all(claims.map((claim) => probe(claim.port))); + return claims.filter((_, i) => inUse[i]); +} + +export function formatPortConflict(claim: PortClaim): string { + return `Port ${claim.port} is already in use, but ${claim.owner} needs it`; +} + +function formatPortConflicts(conflicts: PortClaim[]): string { + const lines = conflicts.map((c) => ` - ${formatPortConflict(c)} (${c.setting})`); + return ( + `Can't start: ${conflicts.length === 1 ? "a port lo1 needs is" : "ports lo1 needs are"} ` + + `already in use.\n${lines.join("\n")}\n` + + `Stop whatever is using ${conflicts.length === 1 ? "it" : "them"}, ` + + `or change the setting in lo1.yaml.` + ); +} diff --git a/packages/cli/src/orchestrator/start.ts b/packages/cli/src/orchestrator/start.ts index c47a7dd..68ddd32 100644 --- a/packages/cli/src/orchestrator/start.ts +++ b/packages/cli/src/orchestrator/start.ts @@ -28,6 +28,7 @@ import { startService as defaultStartService, BUILTIN_TYPES } from "./service"; import { writeState as defaultWriteState } from "./state"; import { resolveServiceFilter } from "./filter"; import { hydrateHandles } from "./stop"; +import { findPortConflicts, PortConflictError } from "../doctor/ports"; import type { OrchestratorDeps, StartOptions, @@ -101,6 +102,7 @@ function createDefaultDeps(): OrchestratorDeps { readState: (dir) => import("./state").then((m) => m.readState(dir)), writeState: defaultWriteState, removeState: (dir) => import("./state").then((m) => m.removeState(dir)), + findPortConflicts: (config) => findPortConflicts(config), }; } @@ -248,6 +250,9 @@ async function prepareWorkspaceConfig( config = applyModeOverride(config, options.modeOverride); config = applyFilter(config, options.serviceFilter); + const conflicts = await deps.findPortConflicts(config); + if (conflicts.length > 0) throw new PortConflictError(conflicts); + emit({ kind: "phase", phase: "Building dependency graph" }); const dag = deps.buildDag(config); const registry = deps.buildEndpointRegistry(config); diff --git a/packages/cli/src/orchestrator/types.ts b/packages/cli/src/orchestrator/types.ts index ce007db..32151e6 100644 --- a/packages/cli/src/orchestrator/types.ts +++ b/packages/cli/src/orchestrator/types.ts @@ -13,6 +13,7 @@ import type { ComposeLogsHandle, } from "../runner/compose"; import type { ServiceHandle, StartServiceOptions } from "./service"; +import type { PortClaim } from "../doctor/ports"; export type ServiceStatus = "starting" | "started" | "completed" | "stopping" | "stopped"; @@ -67,6 +68,8 @@ export type OrchestratorDeps = { readState: (workspaceDir?: string) => Promise; writeState: (state: WorkspaceState, workspaceDir?: string) => Promise; removeState: (workspaceDir?: string) => Promise; + /** Returns the ports the workspace needs that something else is already using. */ + findPortConflicts: (config: WorkspaceConfig) => Promise; }; export type StartOptions = { diff --git a/packages/cli/tests/doctor/checks.test.ts b/packages/cli/tests/doctor/checks.test.ts new file mode 100644 index 0000000..aa7df3b --- /dev/null +++ b/packages/cli/tests/doctor/checks.test.ts @@ -0,0 +1,175 @@ +import { describe, it, expect } from "bun:test"; +import type { WorkspaceConfig } from "@lo1/sdk"; +import { runDoctor, type DoctorDeps, type ExecFn } from "../../src/doctor/checks"; +import { formatDoctorReport } from "../../src/cli/commands/doctor"; + +const config: WorkspaceConfig = { + version: "1", + name: "shop", + services: { + api: { type: "service", path: "./api", port: 3000, mode: "dev", dependsOn: [], initTask: false }, + }, +}; + +function makeExec(responses: Record): ExecFn { + return async (cmd, args) => { + const key = [cmd, ...args].join(" "); + const match = Object.entries(responses).find(([prefix]) => key.startsWith(prefix)); + if (!match) throw new Error(`unexpected command: ${key}`); + if (match[1] instanceof Error) throw match[1]; + return { stdout: match[1], stderr: "" }; + }; +} + +const healthyExec = makeExec({ + "docker version": "29.5.2\n", + "docker compose version": "2.40.0\n", + "git --version": "git version 2.50.1\n", +}); + +function makeDeps(overrides: Partial = {}): DoctorDeps { + return { + exec: healthyExec, + nodeVersion: "24.14.0", + loadConfig: async () => config, + configExists: async () => true, + isWorkspaceRunning: async () => false, + readHostsFile: async () => "127.0.0.1 localhost\n127.0.0.1 api.shop.local\n", + probePort: async () => false, + env: {}, + ...overrides, + }; +} + +function byId(results: Awaited>, id: string) { + return results.filter((r) => r.id === id); +} + +describe("runDoctor", () => { + it("should pass every check on a ready machine", async () => { + const results = await runDoctor(makeDeps()); + + expect(results.map((r) => [r.id, r.status])).toEqual([ + ["node", "ok"], + ["docker", "ok"], + ["compose", "ok"], + ["git", "ok"], + ["config", "ok"], + ["ports", "ok"], + ["hosts", "ok"], + ]); + expect(byId(results, "docker")[0].message).toBe("Docker 29.5.2"); + }); + + it("should fail on an old Node.js", async () => { + const [node] = byId(await runDoctor(makeDeps({ nodeVersion: "22.11.0" })), "node"); + + expect(node.status).toBe("fail"); + expect(node.message).toBe("Node.js 22.11.0 is too old; lo1 needs 24 or later"); + }); + + it("should tell a missing Docker apart from a stopped daemon", async () => { + const missing = Object.assign(new Error("spawn docker ENOENT"), { code: "ENOENT" }); + const notInstalled = await runDoctor(makeDeps({ exec: makeExec({ docker: missing, git: "git version 2" }) })); + expect(byId(notInstalled, "docker")[0].message).toBe("Docker is not installed"); + + const stopped = await runDoctor( + makeDeps({ exec: makeExec({ docker: new Error("Cannot connect"), git: "git version 2" }) }), + ); + expect(byId(stopped, "docker")[0].message).toBe( + "Docker is installed, but the Docker daemon is not running", + ); + }); + + it("should fail on a port conflict with a fix naming the setting", async () => { + const results = await runDoctor(makeDeps({ probePort: async (port) => port === 3000 })); + const [ports] = byId(results, "ports"); + + expect(ports.status).toBe("fail"); + expect(ports.message).toBe('Port 3000 is already in use, but service "api" needs it'); + expect(ports.fix).toBe( + "Stop whatever is listening on port 3000, or change services.api.port in lo1.yaml", + ); + }); + + it("should skip port checks while the workspace is running", async () => { + const results = await runDoctor( + makeDeps({ isWorkspaceRunning: async () => true, probePort: async () => true }), + ); + + expect(byId(results, "ports")[0].status).toBe("ok"); + }); + + it("should warn when domains are missing from the hosts file", async () => { + const results = await runDoctor(makeDeps({ readHostsFile: async () => "127.0.0.1 localhost\n" })); + + expect(byId(results, "hosts")[0]).toMatchObject({ + status: "warn", + message: "1 of 1 domain(s) are not in the hosts file yet", + }); + }); + + it("should warn and skip workspace checks without a lo1.yaml", async () => { + const results = await runDoctor( + makeDeps({ configExists: async () => false, loadConfig: async () => Promise.reject(new Error("no")) }), + ); + + expect(results.map((r) => r.id)).toEqual(["node", "docker", "compose", "git", "config"]); + expect(byId(results, "config")[0].status).toBe("warn"); + }); + + it("should fail when ACME credentials are missing", async () => { + const acmeConfig: WorkspaceConfig = { + ...config, + proxy: { + enabled: true, + port: 80, + tld: "dev", + tls: { + enabled: true, + port: 443, + mode: "acme", + acme: { + provider: "cloudflare", + tokenEnv: "CF_API_TOKEN", + ca: "letsencrypt", + env: [], + options: {}, + resolvers: [], + domains: [], + caddyVersion: "2", + }, + }, + }, + }; + const results = await runDoctor(makeDeps({ loadConfig: async () => acmeConfig })); + + expect(byId(results, "acme")[0].status).toBe("fail"); + }); +}); + +describe("formatDoctorReport", () => { + it("should list each check with its fix and a summary", () => { + const report = formatDoctorReport( + [ + { id: "node", status: "ok", message: "Node.js 24.14.0" }, + { id: "ports", status: "fail", message: "Port 80 is in use", fix: "Stop it" }, + { id: "hosts", status: "warn", message: "Hosts missing", fix: "Run lo1 up" }, + ], + false, + ); + + expect(report).toBe( + " ✓ Node.js 24.14.0\n" + + " ✗ Port 80 is in use\n Stop it\n" + + " ! Hosts missing\n Run lo1 up\n\n" + + " 1 problem, 1 warning.\n", + ); + }); + + it("should say everything looks good when nothing is wrong", () => { + expect(formatDoctorReport([{ id: "node", status: "ok", message: "Node.js 24" }], false)).toBe( + " ✓ Node.js 24\n\n Everything looks good.\n", + ); + }); +}); diff --git a/packages/cli/tests/doctor/ports.test.ts b/packages/cli/tests/doctor/ports.test.ts new file mode 100644 index 0000000..ac85315 --- /dev/null +++ b/packages/cli/tests/doctor/ports.test.ts @@ -0,0 +1,98 @@ +import { describe, it, expect } from "bun:test"; +import { createServer, type Server } from "node:net"; +import type { WorkspaceConfig } from "@lo1/sdk"; +import { + collectPortClaims, + findPortConflicts, + isPortInUse, + PortConflictError, +} from "../../src/doctor/ports"; + +function makeConfig(overrides: Partial = {}): WorkspaceConfig { + return { + version: "1", + name: "shop", + services: { + api: { type: "service", path: "./api", port: 3000, mode: "dev", dependsOn: [], initTask: false }, + db: { + type: "service", + path: "./db", + port: 5432, + hostPort: 15432, + mode: "container", + containerImage: "postgres:17", + dependsOn: [], + initTask: false, + }, + off: { type: "service", path: "./off", port: 9999, mode: "skip", dependsOn: [], initTask: false }, + }, + ...overrides, + }; +} + +function listen(): Promise<{ server: Server; port: number }> { + return new Promise((resolve) => { + const server = createServer(); + server.listen(0, "127.0.0.1", () => { + const address = server.address(); + resolve({ server, port: typeof address === "object" && address ? address.port : 0 }); + }); + }); +} + +describe("collectPortClaims", () => { + it("should claim the proxy port, dev ports and container host ports, skipping skip-mode", () => { + const claims = collectPortClaims(makeConfig()); + + expect(claims).toEqual([ + { port: 80, owner: "the proxy", setting: "proxy.port" }, + { port: 3000, owner: 'service "api"', setting: "services.api.port" }, + { port: 15432, owner: 'service "db"', setting: "services.db.hostPort" }, + ]); + }); + + it("should claim the TLS port and leave out the proxy when it is disabled", () => { + const withTls = collectPortClaims( + makeConfig({ proxy: { enabled: true, port: 8080, tld: "local", tls: { enabled: true, port: 8443, mode: "internal" } } }), + ); + expect(withTls.slice(0, 2).map((c) => c.port)).toEqual([8080, 8443]); + + const noProxy = collectPortClaims(makeConfig({ proxy: { enabled: false, port: 80, tld: "local" } })); + expect(noProxy.some((c) => c.owner === "the proxy")).toBe(false); + }); +}); + +describe("findPortConflicts", () => { + it("should return only the claims whose ports are in use", async () => { + const conflicts = await findPortConflicts(makeConfig(), async (port) => port === 3000); + + expect(conflicts).toEqual([{ port: 3000, owner: 'service "api"', setting: "services.api.port" }]); + }); +}); + +describe("isPortInUse", () => { + it("should detect a listening port and a free one", async () => { + const { server, port } = await listen(); + try { + expect(await isPortInUse(port)).toBe(true); + } finally { + await new Promise((r) => server.close(r)); + } + expect(await isPortInUse(port)).toBe(false); + }); +}); + +describe("PortConflictError", () => { + it("should name each port, its owner and the setting to change", () => { + const err = new PortConflictError([ + { port: 3000, owner: 'service "api"', setting: "services.api.port" }, + ]); + + expect(err.message).toBe( + "Can't start: a port lo1 needs is already in use.\n" + + ' - Port 3000 is already in use, but service "api" needs it (services.api.port)\n' + + "Stop whatever is using it, or change the setting in lo1.yaml.", + ); + expect(err.toJSON()).toMatchObject({ error: "PortConflictError", ports: [3000] }); + }); +}); diff --git a/packages/cli/tests/orchestrator/start.test.ts b/packages/cli/tests/orchestrator/start.test.ts index f269832..11d2b33 100644 --- a/packages/cli/tests/orchestrator/start.test.ts +++ b/packages/cli/tests/orchestrator/start.test.ts @@ -100,11 +100,26 @@ function makeDeps(overrides: Partial = {}): OrchestratorDeps { readState: mock(() => Promise.resolve(null)), writeState: mock(() => Promise.resolve()), removeState: mock(() => Promise.resolve()), + findPortConflicts: mock(() => Promise.resolve([])), ...overrides, }; } describe("startWorkspace", () => { + it("should fail before starting anything when a port it needs is in use", async () => { + const deps = makeDeps({ + findPortConflicts: mock(() => + Promise.resolve([{ port: 3000, owner: 'service "api"', setting: "services.api.port" }]), + ), + }); + + await expect(startWorkspace({}, deps)).rejects.toThrow( + 'Port 3000 is already in use, but service "api" needs it', + ); + expect(deps.composeUp).not.toHaveBeenCalled(); + expect(deps.startService).not.toHaveBeenCalled(); + }); + it("should load config from provided path", async () => { const deps = makeDeps();