Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): fail eve start fast when its port is already in use (#5259)

Andrew Barbadb18149aa404
diff --git a/.changeset/start-port-in-use.md b/.changeset/start-port-in-use.md
new file mode 100644
index 000000000..cd3104cfe
--- /dev/null
+++ b/.changeset/start-port-in-use.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+`eve start` and the `withEve` production server for Next.js now fail fast with a clear "port is already in use" error when another process holds the port, instead of reporting a server they did not start and leaving the built server running in the background. Thanks @KingAmo for reporting this in #4938.
diff --git a/packages/eve/src/internal/nitro/host/start-production-server.scenario.test.ts b/packages/eve/src/internal/nitro/host/start-production-server.scenario.test.ts
index 318c16592..bf85944b4 100644
--- a/packages/eve/src/internal/nitro/host/start-production-server.scenario.test.ts
+++ b/packages/eve/src/internal/nitro/host/start-production-server.scenario.test.ts
@@ -1,3 +1,5 @@
+import { createServer } from "node:http";
+import type { AddressInfo } from "node:net";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
@@ -50,4 +52,37 @@ describe("production server output", () => {
}
},
);
+
+ it("fails when another process already holds the requested port", async () => {
+ const occupant = createServer((_request, response) => response.end("not eve"));
+ await new Promise<void>((resolveListen) => occupant.listen(0, "127.0.0.1", resolveListen));
+ const { port } = occupant.address() as AddressInfo;
+ const { appRoot } = await createApp("eve-production-port-taken-", {
+ files: {
+ // Like srvx: a failed bind is logged and sets exitCode, while other
+ // work keeps the process alive.
+ ".output/server/index.mjs": [
+ 'import { createServer } from "node:http";',
+ "createServer()",
+ " .listen(Number(process.env.PORT), process.env.HOST)",
+ ' .once("error", (error) => {',
+ ' console.error("[srvx] Failed to start server:", error);',
+ " process.exitCode = 1;",
+ " });",
+ "setInterval(() => {}, 1_000);",
+ ].join("\n"),
+ },
+ });
+
+ const started = startProductionServer(appRoot, { host: "127.0.0.1", port });
+ try {
+ await expect(started).rejects.toThrow(`Port ${port} on 127.0.0.1 is already in use.`);
+ } finally {
+ await started.then(
+ (server) => server.close(),
+ () => undefined,
+ );
+ await new Promise((resolveClose) => occupant.close(resolveClose));
+ }
+ });
});
diff --git a/packages/eve/src/internal/nitro/host/start-production-server.test.ts b/packages/eve/src/internal/nitro/host/start-production-server.test.ts
index df13d8aad..6c736779d 100644
--- a/packages/eve/src/internal/nitro/host/start-production-server.test.ts
+++ b/packages/eve/src/internal/nitro/host/start-production-server.test.ts
@@ -121,6 +121,23 @@ describe("startProductionServer", () => {
expect(child.kill).toHaveBeenCalledWith("SIGTERM");
});
+ it("stops a built server that stays alive after its port turned out to be taken", async () => {
+ const { startProductionServer } = await import("./start-production-server.js");
+ vi.spyOn(process.stderr, "write").mockImplementation(() => true);
+ const child = createChildProcess();
+ (child.stderr as PassThrough).write(
+ "[srvx] Failed to start server: Error: listen EADDRINUSE: address already in use 127.0.0.1:4321\n",
+ );
+ mocks.spawn.mockReturnValueOnce(child);
+
+ await expect(
+ startProductionServer("/tmp/app", { host: "127.0.0.1", port: 4321 }),
+ ).rejects.toThrow(
+ "Port 4321 on 127.0.0.1 is already in use. Another process is listening there; stop it or choose another port with --port or the PORT environment variable.",
+ );
+ expect(child.kill).toHaveBeenCalledWith("SIGTERM");
+ });
+
it.each([
{ schedules: undefined, inherited: undefined, expected: undefined },
{ schedules: false, inherited: undefined, expected: "1" },
diff --git a/packages/eve/src/internal/nitro/host/start-production-server.ts b/packages/eve/src/internal/nitro/host/start-production-server.ts
index 7fa30c289..2638fc1c9 100644
--- a/packages/eve/src/internal/nitro/host/start-production-server.ts
+++ b/packages/eve/src/internal/nitro/host/start-production-server.ts
@@ -1,18 +1,20 @@
import { spawn, type ChildProcess } from "node:child_process";
import { existsSync } from "node:fs";
-import { createConnection, createServer } from "node:net";
+import { createServer } from "node:net";
import { join, resolve } from "node:path";
import { setTimeout as sleep } from "node:timers/promises";
import { loadDevelopmentEnvironmentFiles } from "#cli/dev/environment.js";
import type { ProductionServerHandle } from "#internal/nitro/host/types.js";
import { EVE_SCHEDULES_DISABLED_ENV } from "#internal/schedules/disabled.js";
+import { readBuiltServerStartFailure } from "#shared/built-server-start-failure.js";
const DEFAULT_PRODUCTION_SERVER_HOST = "0.0.0.0";
const DEFAULT_PRODUCTION_SERVER_PORT = 3000;
const HEALTH_POLL_INTERVAL_MS = 250;
const HEALTH_TIMEOUT_MS = 60_000;
-const LOCAL_SERVER_URL_PATTERN = /https?:\/\/(?:\[[^\]\s]+\]|[^\s/:[\]]+)(?::\d+)?/;
+// srvx prints this line only after its own listener is bound.
+const LISTENING_URL_PATTERN = /Listening on:?\s+(https?:\/\/\S+)/;
// Must exceed the server's bounded sandbox shutdown (15s in
// sandbox-shutdown-plugin.ts) so stopping sandboxes on SIGTERM is not
// cut short by SIGKILL.
@@ -51,22 +53,6 @@ function normalizeServerClientUrl(serverUrl: string): string {
return url.toString();
}
-function formatClientHost(host: string): string {
- if (WILDCARD_LISTEN_HOSTNAMES.has(host)) {
- return "127.0.0.1";
- }
-
- if (host.includes(":") && !host.startsWith("[")) {
- return `[${host}]`;
- }
-
- return host;
-}
-
-function createKnownPortUrl(input: { host: string; port: number }): string | undefined {
- return `http://${formatClientHost(input.host)}:${String(input.port)}/`;
-}
-
async function resolveListenPort(input: { host: string; port: number }): Promise<number> {
if (input.port !== 0) {
return input.port;
@@ -97,35 +83,21 @@ async function resolveListenPort(input: { host: string; port: number }): Promise
}
function parseServerUrlFromOutput(output: string): string | undefined {
- const match = LOCAL_SERVER_URL_PATTERN.exec(output);
+ const match = LISTENING_URL_PATTERN.exec(output);
- if (match === null) {
+ if (match?.[1] === undefined) {
return undefined;
}
- return normalizeServerClientUrl(match[0]);
-}
-
-async function isListening(url: string): Promise<boolean> {
- const target = new URL(url);
- const port = Number(target.port || (target.protocol === "https:" ? 443 : 80));
- return await new Promise((resolveReady) => {
- const socket = createConnection({ host: target.hostname, port });
- const finish = (ready: boolean) => {
- socket.destroy();
- resolveReady(ready);
- };
- socket.setTimeout(2_000, () => finish(false));
- socket.once("connect", () => finish(true));
- socket.once("error", () => finish(false));
- });
+ return normalizeServerClientUrl(match[1]);
}
async function waitForReady(input: {
child: ChildProcess;
getStartError(): unknown;
getOutput(): string;
- knownUrl?: string;
+ host: string;
+ port: number;
}): Promise<string> {
const deadline = Date.now() + HEALTH_TIMEOUT_MS;
@@ -135,11 +107,19 @@ async function waitForReady(input: {
throw startError;
}
- const parsedUrl = parseServerUrlFromOutput(input.getOutput());
- const url = parsedUrl ?? input.knownUrl;
+ const output = input.getOutput();
+ const startFailure = readBuiltServerStartFailure(output, {
+ host: input.host,
+ port: input.port,
+ retryHint: "choose another port with --port or the PORT environment variable",
+ });
+ if (startFailure !== undefined) {
+ throw startFailure;
+ }
- if (url !== undefined && (parsedUrl !== undefined || (await isListening(url)))) {
- return new URL(url).toString();
+ const url = parseServerUrlFromOutput(output);
+ if (url !== undefined) {
+ return url;
}
if (input.child.exitCode !== null || input.child.signalCode !== null) {
@@ -212,10 +192,6 @@ export async function startProductionServer(
host,
port: options.port ?? readEnvironmentPort() ?? DEFAULT_PRODUCTION_SERVER_PORT,
});
- const knownUrl = createKnownPortUrl({
- host,
- port,
- });
// Startup output is kept only for URL detection and startup diagnostics.
// After readiness it is dropped so a long-running server does not grow it.
let output = "";
@@ -230,6 +206,9 @@ export async function startProductionServer(
NITRO_PORT: String(port),
PORT: String(port),
};
+ // srvx hides its listening line when TEST is set, and that line is the only
+ // proof that this child, not another process, owns the port.
+ delete env.TEST;
if (options.schedules === false) {
env[EVE_SCHEDULES_DISABLED_ENV] = "1";
}
@@ -277,7 +256,8 @@ export async function startProductionServer(
child,
getStartError: () => startError,
getOutput: () => output,
- knownUrl,
+ host,
+ port,
});
ready = true;
output = "";
diff --git a/packages/eve/src/public/next/index.integration.test.ts b/packages/eve/src/public/next/index.integration.test.ts
index 19c55d620..2cea1afad 100644
--- a/packages/eve/src/public/next/index.integration.test.ts
+++ b/packages/eve/src/public/next/index.integration.test.ts
@@ -128,6 +128,39 @@ describe("withEve Vercel config", () => {
]);
});
+ it("stops a managed agent that cannot bind its port instead of waiting for its URL", async () => {
+ const appRoot = await createTempAppRoot();
+ process.chdir(appRoot);
+ vi.stubEnv("NODE_ENV", "production");
+ await writeBuiltAgent(process.cwd());
+ const kill = vi.fn();
+ spawnMock.mockImplementation(() => {
+ const child = Object.assign(new EventEmitter(), {
+ killed: false,
+ kill,
+ stderr: new EventEmitter(),
+ stdout: new EventEmitter(),
+ });
+ setImmediate(() => {
+ child.stderr.emit(
+ "data",
+ Buffer.from(
+ "[srvx] Failed to start server: Error: listen EADDRINUSE: address already in use 127.0.0.1:4274\n",
+ ),
+ );
+ });
+ return child;
+ });
+ vi.spyOn(process.stderr, "write").mockImplementation(() => true);
+
+ await expect(
+ withEve<TestConfig>({})("phase-production-server", { defaultConfig: {} }),
+ ).rejects.toThrow(
+ "Port 4274 on 127.0.0.1 is already in use. Another process is listening there; stop it or set EVE_NEXT_PRODUCTION_PORT to another port.",
+ );
+ expect(kill).toHaveBeenCalledOnce();
+ });
+
it("does not start a managed agent on Vercel, for a hosted origin, or while building", async () => {
const appRoot = await createTempAppRoot();
process.chdir(appRoot);
diff --git a/packages/eve/src/public/next/server.ts b/packages/eve/src/public/next/server.ts
index 8031d0501..d6da8cf5c 100644
--- a/packages/eve/src/public/next/server.ts
+++ b/packages/eve/src/public/next/server.ts
@@ -56,6 +56,7 @@ export async function ensureEveProductionServer(input: {
appRoot: input.appRoot,
host: EVE_NEXT_HOST,
origin: input.origin,
+ portRetryHint: "set EVE_NEXT_PRODUCTION_PORT to another port",
}).catch((error: unknown) => {
state.servers.delete(key);
throw error;
diff --git a/packages/eve/src/shared/built-server-start-failure.ts b/packages/eve/src/shared/built-server-start-failure.ts
new file mode 100644
index 000000000..aff97c191
--- /dev/null
+++ b/packages/eve/src/shared/built-server-start-failure.ts
@@ -0,0 +1,36 @@
+const SRVX_START_FAILURE_MARKER = "[srvx] Failed to start server:";
+
+/**
+ * Detects a built eve server that reported a failed start in `output`.
+ *
+ * srvx only logs a failed bind and sets `process.exitCode`, so the process can
+ * stay alive without serving anything. Callers must treat this output as fatal
+ * and stop the process themselves.
+ */
+export function readBuiltServerStartFailure(
+ output: string,
+ listen: { readonly host: string; readonly port: number | string; readonly retryHint: string },
+): Error | undefined {
+ const failureIndex = output.indexOf(SRVX_START_FAILURE_MARKER);
+ // The error code is on the marker line; wait for the line to end so a
+ // partial read is not misclassified.
+ const failureLineEnd = failureIndex === -1 ? -1 : output.indexOf("\n", failureIndex);
+
+ if (failureLineEnd === -1) {
+ return undefined;
+ }
+
+ const failure = output.slice(failureIndex);
+
+ if (output.slice(failureIndex, failureLineEnd).includes("EADDRINUSE")) {
+ return new Error(
+ `Port ${String(listen.port)} on ${listen.host} is already in use. Another process is listening there; stop it or ${listen.retryHint}.`,
+ );
+ }
+
+ return new Error(
+ [`Built eve server failed to start on ${listen.host}:${String(listen.port)}.`, failure].join(
+ "\n",
+ ),
+ );
+}
diff --git a/packages/eve/src/shared/framework-eve-server.ts b/packages/eve/src/shared/framework-eve-server.ts
index 7e0ff858e..29b772bd2 100644
--- a/packages/eve/src/shared/framework-eve-server.ts
+++ b/packages/eve/src/shared/framework-eve-server.ts
@@ -5,6 +5,7 @@ import { join } from "node:path";
import { resolvePackageRoot } from "#internal/application/package.js";
import { readDevelopmentRuntimeArtifactsRevision } from "#services/dev-client/runtime-artifacts.js";
+import { readBuiltServerStartFailure } from "#shared/built-server-start-failure.js";
import { isLoopbackHostname } from "#shared/network-address.js";
/** Default time to wait for an eve server spawned by a framework integration. */
@@ -328,6 +329,7 @@ function startServerProcess(input: {
readonly command: string;
readonly cwd: string;
readonly env?: Record<string, string>;
+ readonly listen?: { readonly host: string; readonly port: string; readonly retryHint: string };
readonly logLabel?: string;
readonly timeoutMs?: number;
}): Promise<EveProcessHandle> {
@@ -355,7 +357,12 @@ function startServerProcess(input: {
reject(new Error(`Timed out after ${timeoutMs}ms waiting for eve to print its server URL.`));
}, timeoutMs);
+ let settled = false;
+ // Accumulated because a failure line can span several `data` chunks.
+ let startupOutput = "";
const cleanup = () => {
+ settled = true;
+ startupOutput = "";
clearTimeout(timeout);
child.off("error", handleError);
child.off("exit", handleEarlyExit);
@@ -379,7 +386,26 @@ function startServerProcess(input: {
);
};
const handleOutput = (chunk: Buffer) => {
- const origin = findLocalServerOrigin(chunk.toString("utf8"));
+ if (settled) {
+ return;
+ }
+
+ const text = chunk.toString("utf8");
+ startupOutput += text;
+ const startFailure =
+ input.listen === undefined
+ ? undefined
+ : readBuiltServerStartFailure(startupOutput, input.listen);
+
+ if (startFailure !== undefined) {
+ flushOutput();
+ cleanup();
+ child.kill();
+ reject(startFailure);
+ return;
+ }
+
+ const origin = findLocalServerOrigin(text);
if (origin === undefined) {
return;
@@ -456,6 +482,8 @@ export function startEveProductionServer(input: {
readonly appRoot: string;
readonly host: EveFrameworkHost;
readonly origin: string;
+ /** How to pick another port, completing "stop it or ..." when the port is taken. */
+ readonly portRetryHint: string;
}): Promise<EveProcessHandle> {
const parsedOrigin = new URL(input.origin);
const port = parsedOrigin.port;
@@ -477,6 +505,7 @@ export function startEveProductionServer(input: {
NITRO_PORT: port,
PORT: port,
},
+ listen: { host: parsedOrigin.hostname, port, retryHint: input.portRetryHint },
}).then(installProcessShutdown);
}