Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/port-in-use.md
Original file line number Diff line number Diff line change
@@ -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.
4 changes: 3 additions & 1 deletion packages/cli/src/bin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
22 changes: 18 additions & 4 deletions packages/cli/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -52,6 +53,12 @@ export async function devCommand(args: string[]): Promise<number> {
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) });
}
Expand Down Expand Up @@ -91,10 +98,17 @@ export async function devCommand(args: string[]): Promise<number> {
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<ReturnType<typeof host.serve>>;
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;
Expand Down
22 changes: 22 additions & 0 deletions packages/cli/src/port-in-use.ts
Original file line number Diff line number Diff line change
@@ -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<boolean> {
return new Promise((resolve) => {
const probe = createServer();
probe.once("error", () => resolve(false));
probe.listen(port, ip, () => probe.close(() => resolve(true)));
});
}
6 changes: 5 additions & 1 deletion packages/cli/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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/";
Expand Down Expand Up @@ -297,7 +298,10 @@ async function startNodeServer(runtime: EmbeddedRuntime, options: DevServerOptio
});
});

await new Promise<void>((res) => server.listen(options.port, options.ip, res));
await new Promise<void>((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 {
Expand Down
27 changes: 27 additions & 0 deletions packages/cli/test/port-in-use.test.ts
Original file line number Diff line number Diff line change
@@ -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<void>((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<void>((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<void>((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();
});
});
Loading