diff --git a/packages/cli/src/commands/local/run.ts b/packages/cli/src/commands/local/run.ts index c63bc7be3..b2de5d731 100644 --- a/packages/cli/src/commands/local/run.ts +++ b/packages/cli/src/commands/local/run.ts @@ -175,6 +175,36 @@ async function startBackgroundServer( }; } +/** + * Get a live event tail on `host:port`, whichever way is available. + * + * Prefers attaching to whatever already holds the port so we never compete + * with it, and falls back to attaching if the bind loses a race. `run` wraps + * the user's dev command, so a busy port must never be fatal here. + */ +async function openEventTail(port: number, host: string): Promise { + const url = `http://${host}:${port}`; + + if (await isServerRunning(url)) { + logger.info(`Connected to existing server at ${bold(url)}`); + return attachToExistingServer(url); + } + + logger.info("No server detected, starting one in the background..."); + try { + const bg = await startBackgroundServer(port, host); + logger.info(`Background server listening on ${bold(bg.url)}`); + return bg; + } catch (err) { + if (!(err instanceof ValidationError && err.field === "port")) { + throw err; + } + // Something grabbed the port between the probe and the bind. + logger.warn(`${err.message}; attaching to it instead`); + return attachToExistingServer(url); + } +} + /** Augment PATH with `./node_modules/.bin` for Node project scripts. */ function augmentPathForNode( env: Record, @@ -310,17 +340,9 @@ export const runCommand = buildCommand({ } let url = `http://${flags.host}:${flags.port}`; - let tail: EventTail; - - if (await isServerRunning(url)) { - logger.info(`Connected to existing server at ${bold(url)}`); - tail = attachToExistingServer(url); - } else { - logger.info("No server detected, starting one in the background..."); - tail = await startBackgroundServer(flags.port, flags.host); - url = tail.url; - logger.info(`Background server listening on ${bold(url)}`); - } + + const tail = await openEventTail(flags.port, flags.host); + url = tail.url; const spotlightUrl = `${url}/stream`; logger.info(`Starting: ${bold(args.join(" "))}`); diff --git a/packages/cli/src/commands/local/server.ts b/packages/cli/src/commands/local/server.ts index ab2209181..777e1d931 100644 --- a/packages/cli/src/commands/local/server.ts +++ b/packages/cli/src/commands/local/server.ts @@ -376,15 +376,30 @@ export function tryListen( } /** - * Check whether a server is already running on the given URL. - * Returns `true` if the health endpoint responds successfully. + * Check whether something is already serving on the given URL. + * + * Any HTTP reply — including an error status — means the port is taken, so + * this deliberately does not require a 2xx. Spotlight's own sidecar can + * answer `/health` with a 5xx while still holding the port and ingesting + * envelopes; treating that as "nothing there" made the CLI try to bind the + * port anyway and abort with `Port 8969 is in use after 3 retries`, killing + * the user's dev command instead of attaching to the sidecar. + * + * Only a transport-level failure (connection refused, timeout) counts as + * "no server". If the responder turns out not to speak the envelope + * protocol, {@link consumeSSE} reports that when the stream fails to open. */ export async function isServerRunning(url: string): Promise { try { const res = await fetch(`${url}/health`, { signal: AbortSignal.timeout(2000), }); - return res.ok; + if (!res.ok) { + logger.debug( + `Server at ${url} answered /health with HTTP ${res.status}; treating the port as occupied` + ); + } + return true; } catch (err) { logger.debug( `No existing server at ${url}`, diff --git a/packages/cli/test/commands/local/server.test.ts b/packages/cli/test/commands/local/server.test.ts index e550c46db..0d17b431d 100644 --- a/packages/cli/test/commands/local/server.test.ts +++ b/packages/cli/test/commands/local/server.test.ts @@ -6,6 +6,7 @@ */ import { createSpotlightBuffer } from "@spotlightjs/spotlight/sdk"; +import { Hono } from "hono"; import { describe, expect, test } from "vitest"; import { buildApp, @@ -13,6 +14,7 @@ import { isServerRunning, parsePort, SERVER_IDENTIFIER, + tryListen, } from "../../../src/commands/local/server.js"; import { ValidationError } from "../../../src/lib/errors.js"; import { SENTRY_CONTENT_TYPE } from "../../../src/lib/formatters/local.js"; @@ -315,6 +317,31 @@ describe("buildApp", () => { }); describe("isServerRunning", () => { + test("returns true when /health answers with an error status", async () => { + // Spotlight's sidecar can 5xx on /health while still holding the port and + // ingesting envelopes. Reporting "no server" made the CLI try to bind the + // port anyway and abort with "Port 8969 is in use after 3 retries". + const unhealthy = new Hono(); + unhealthy.get("/health", (c) => c.text("Internal Server Error", 500)); + const { server, port } = await tryListen(unhealthy, 0, "127.0.0.1"); + + const savedFetch = globalThis.fetch; + const realFetch = (globalThis as { __originalFetch?: typeof fetch }) + .__originalFetch; + if (realFetch) { + globalThis.fetch = realFetch; + } + + try { + await expect(isServerRunning(`http://127.0.0.1:${port}`)).resolves.toBe( + true + ); + } finally { + globalThis.fetch = savedFetch; + await new Promise((done) => server.close(() => done())); + } + }); + test("returns false when no server is running", async () => { // isServerRunning uses global fetch which is mocked in tests. // Verify the function handles connection errors gracefully.