diff --git a/.changeset/port-in-use.md b/.changeset/port-in-use.md new file mode 100644 index 00000000..681ffa35 --- /dev/null +++ b/.changeset/port-in-use.md @@ -0,0 +1,5 @@ +--- +"@concile/cli": patch +--- + +`concile dev` and `concile serve` on a busy port print one clear line (what to stop, or which `--port` to use) instead of a Node stack trace. `concile dev --run` checks the port before opening the tabs, so the app never attaches to a server someone else left running there. diff --git a/packages/cli/src/bin.ts b/packages/cli/src/bin.ts index bbc026ba..72262e05 100644 --- a/packages/cli/src/bin.ts +++ b/packages/cli/src/bin.ts @@ -14,6 +14,8 @@ process.emitWarning = ((warning: string | Error, ...rest: unknown[]) => { runCli(process.argv.slice(2)) .then((code) => process.exit(code)) .catch((e) => { - process.stderr.write(`${e instanceof Error ? e.stack ?? e.message : String(e)}\n`); + // A busy port is the user's situation, not a crash: say what to do, without a stack trace. + const busy = e instanceof Error && e.name === "PortInUseError"; + process.stderr.write(`${e instanceof Error ? (busy ? e.message : e.stack ?? e.message) : String(e)}\n`); process.exit(1); }); diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts index 2d385383..a239c1e6 100644 --- a/packages/cli/src/cli.ts +++ b/packages/cli/src/cli.ts @@ -25,6 +25,7 @@ import { fleetCommand } from "./fleet"; import { objectstoreCommand } from "./objectstore"; import { loadEnvFiles } from "./env-files"; import { runAlongside } from "./run-alongside"; +import { isPortFree, portInUseMessage, PortInUseError } from "./port-in-use"; import { afterBackend, backendUrl, BACKEND_ENV, mprocsBinary, runInTabs, wantTabs } from "./dev-tabs"; function parseFlags(args: string[]): DevOptions { @@ -52,6 +53,12 @@ export async function devCommand(args: string[]): Promise { const binary = mprocsBinary(); if (binary) { const { port, ip } = resolveDevOptions(flags); + // Checked before the tabs open: the app tab waits for this port, so a server someone else + // left running here would look like our backend. + if (!(await isPortFree(ip, port))) { + process.stderr.write(`${portInUseMessage(port)}\n`); + return 1; + } const devArgs = args.filter((a, i) => a !== "--run" && args[i - 1] !== "--run"); return runInTabs(binary, { devArgs, run: flags.run, cwd: process.cwd(), url: backendUrl(ip, port) }); } @@ -91,10 +98,17 @@ export async function devCommand(args: string[]): Promise { const dashboard = loadDashboard(ephemeralKey && loopback ? adminKey : undefined); // Reach serving through the RuntimeHost seam (Slice 1) — the CLI never touches Bun.serve/node:http. const host = new ProcessRuntimeHost(); - const server = await host.serve( - runtime, - { port: opts.port, ip: opts.ip, webDir: opts.webDir, admin: { api: adminApi, key: adminKey }, dashboard, routes: project.routes, storageRoutes }, - ); + let server: Awaited>; + try { + server = await host.serve( + runtime, + { port: opts.port, ip: opts.ip, webDir: opts.webDir, admin: { api: adminApi, key: adminKey }, dashboard, routes: project.routes, storageRoutes }, + ); + } catch (e) { + if (!(e instanceof PortInUseError)) throw e; + process.stderr.write(`${e.message}\n`); + return 1; + } if (ui.styled) { const fnCount = Object.keys(project.moduleMap).length; const tableCount = Object.keys(project.tableNumbers).length; diff --git a/packages/cli/src/port-in-use.ts b/packages/cli/src/port-in-use.ts new file mode 100644 index 00000000..810da6f7 --- /dev/null +++ b/packages/cli/src/port-in-use.ts @@ -0,0 +1,22 @@ +import { createServer } from "node:net"; + +/** Thrown when the HTTP server cannot listen because something else holds the port. */ +export class PortInUseError extends Error { + constructor(readonly port: number) { + super(portInUseMessage(port)); + this.name = "PortInUseError"; + } +} + +export function portInUseMessage(port: number): string { + return `Port ${port} is already in use. Another concile server may still be running. Stop it, or pick another port with --port ${port + 100}.`; +} + +/** True when nothing listens on ip:port yet. */ +export function isPortFree(ip: string, port: number): Promise { + return new Promise((resolve) => { + const probe = createServer(); + probe.once("error", () => resolve(false)); + probe.listen(port, ip, () => probe.close(() => resolve(true))); + }); +} diff --git a/packages/cli/src/server.ts b/packages/cli/src/server.ts index cc0dfdf1..c4c40e49 100644 --- a/packages/cli/src/server.ts +++ b/packages/cli/src/server.ts @@ -16,6 +16,7 @@ import { handleHttpRequest, type ServerInfo, type FleetHandles } from "./http-ha import type { ResolvedRoute } from "./project"; import type { DeployWireResult } from "./deploy-apply"; import { detectRuntime } from "./dev-options"; +import { PortInUseError } from "./port-in-use"; const SYNC_PATH = "/api/sync"; const STORAGE_PREFIX = "/api/storage/"; @@ -297,7 +298,10 @@ async function startNodeServer(runtime: EmbeddedRuntime, options: DevServerOptio }); }); - await new Promise((res) => server.listen(options.port, options.ip, res)); + await new Promise((res, rej) => { + server.once("error", (e: NodeJS.ErrnoException) => rej(e.code === "EADDRINUSE" ? new PortInUseError(options.port) : e)); + server.listen(options.port, options.ip, res); + }); const address = server.address(); const port = typeof address === "object" && address ? address.port : options.port; return { diff --git a/packages/cli/test/port-in-use.test.ts b/packages/cli/test/port-in-use.test.ts new file mode 100644 index 00000000..b04d6100 --- /dev/null +++ b/packages/cli/test/port-in-use.test.ts @@ -0,0 +1,27 @@ +import { describe, it, expect } from "vitest"; +import { createServer } from "node:net"; +import { isPortFree, portInUseMessage } from "../src/port-in-use"; +import { ProcessRuntimeHost } from "../src/server"; + +describe("port in use", () => { + it("isPortFree sees a port someone else holds", async () => { + const other = createServer(); + await new Promise((r) => other.listen(0, "127.0.0.1", r)); + const port = (other.address() as { port: number }).port; + expect(await isPortFree("127.0.0.1", port)).toBe(false); + await new Promise((r) => other.close(() => r())); + expect(await isPortFree("127.0.0.1", port)).toBe(true); + }); + + it("the server rejects with a clear message instead of an unhandled error event", async () => { + const other = createServer(); + await new Promise((r) => other.listen(0, "127.0.0.1", r)); + const port = (other.address() as { port: number }).port; + const runtime = { handler: { connect() {}, handleMessage() {}, disconnect() {} } } as never; + await expect(new ProcessRuntimeHost().serve(runtime, { port, ip: "127.0.0.1" } as never)).rejects.toMatchObject({ + name: "PortInUseError", + message: portInUseMessage(port), + }); + other.close(); + }); +});