diff --git a/apps/cli-docs/src/fragments/commands/local.md b/apps/cli-docs/src/fragments/commands/local.md index a40d0a970..e90675957 100644 --- a/apps/cli-docs/src/fragments/commands/local.md +++ b/apps/cli-docs/src/fragments/commands/local.md @@ -4,7 +4,7 @@ Most apps don't need a DSN either. If your app has no DSN configured, events flow **only** to the local server — nothing reaches your Sentry organization and no production quota is used. If a DSN *is* set, the SDK sends to both Sentry and the local server. A few features need a DSN to work; see [SDK setup](#sdk-setup). -If a server is already running on the port, the command attaches as an SSE consumer instead of starting a duplicate. +If a Local or Spotlight server is already running on the port, the command attaches as an SSE consumer instead of starting a duplicate. It never attaches to any other process on the port, because events sent there would be lost. ## `sentry local run` @@ -14,6 +14,8 @@ If nothing is listening on the port, a server is started in the background and s The Local daemon behind `--session` is the exception: it only takes session traffic. When it holds port 8969, a plain `local run` captures on a free port and says so. An SDK that hard-codes 8969 won't reach that port, so make sure it reads `SENTRY_SPOTLIGHT`. Add `--session ` to capture into the daemon instead. With an explicit `--port` that the daemon holds, the command stops with an error. +The same goes for a port held by another process that isn't a Local or Spotlight server, such as `python -m http.server 8969`: a plain `local run` captures on a free port and says so, and with an explicit `--port`, or with `local serve`, the command stops with an error that names the port. + With no command, `local run` picks one from the project, in this order: 1. An `artisan` file (Laravel): `composer run dev` when `composer.json` has a `dev` script, as the Laravel skeleton does to start the server, queue, logs, and Vite together, or else `php artisan serve`. A `Gemfile` with `bin/rails` (Rails): `ruby bin/dev` when the app has a Ruby `bin/dev`, `sh bin/dev` for a shell one (not on Windows), or else `ruby bin/rails server`. Both come before `package.json`, whose `dev` script in these apps only starts Vite diff --git a/packages/cli/src/commands/local/daemon.ts b/packages/cli/src/commands/local/daemon.ts index 293bed47a..84c277f05 100644 --- a/packages/cli/src/commands/local/daemon.ts +++ b/packages/cli/src/commands/local/daemon.ts @@ -372,10 +372,9 @@ async function isStaleProbe( probe: "ok" | "refused" | "failed", ): Promise { if (probe === "refused") return true; - return ( - probe === "failed" && - (await probeLocalHealth(daemonBaseUrl(state), 500)) === "other" - ); + if (probe !== "failed") return false; + const holder = await probeLocalHealth(daemonBaseUrl(state), 500); + return holder === "receiver" || holder === "foreign"; } /** @@ -576,10 +575,12 @@ export async function ensureLocalDaemon({ // A daemon child would only wait out the listener retries behind a // server that is not a Local daemon. A Local daemon there may be a // foreground owner still publishing discovery, so startup waits for it. - if ( - (await probeLocalHealth(formatLocalServerUrl(host, port), 500)) === - "other" - ) { + const holder = await probeLocalHealth( + formatLocalServerUrl(host, port), + 500, + ); + if (holder === "foreign") throw portInUseError(port); + if (holder === "receiver") { // A plain receiver answers /health like Spotlight's sidecar does, so // the probe cannot tell `local serve` from `local run`; name both. throw portInUseError( diff --git a/packages/cli/src/commands/local/run.ts b/packages/cli/src/commands/local/run.ts index 3e0586f03..dd94fda74 100644 --- a/packages/cli/src/commands/local/run.ts +++ b/packages/cli/src/commands/local/run.ts @@ -11,8 +11,9 @@ * * If no server is already running on the target port, one is started * automatically in the background and shut down when the child exits. - * If one is already running, this command attaches to it as an SSE consumer - * so events still tail to the terminal. + * If a Local or Spotlight receiver is already running, this command attaches + * to it as an SSE consumer so events still tail to the terminal. Another + * process on the default port makes it capture on a free port instead. */ import type { ChildProcess, StdioOptions } from "node:child_process"; @@ -172,10 +173,11 @@ type EventTail = { type EventTailOptions = { port: number; /** - * Capture on a free port when the daemon holds `port`. Only for the default - * port: a `--port` the user chose stays an error. + * Capture on a free port when the daemon or a server that is not a receiver + * holds `port`. Only for the default port: a `--port` the user chose stays + * an error. */ - freePortIfDaemon?: boolean; + freePortIfHeld?: boolean; host: string; activeFilters: ReadonlySet; useJson: boolean; @@ -322,7 +324,7 @@ function freePortNotice( */ async function openEventTail({ port, - freePortIfDaemon = false, + freePortIfHeld = false, host, activeFilters, useJson, @@ -332,22 +334,24 @@ async function openEventTail({ const url = formatLocalServerUrl(host, port); let running = false; - let heldByDaemon = false; + // Why this run captures on a free port instead of `port`, if it does. + let heldNotice: ((boundPort: number) => string) | undefined; try { running = await isServerRunning(url); } catch (err) { - if ( - !( - freePortIfDaemon && - err instanceof ValidationError && - err.field === PORT_HELD_BY_DAEMON_FIELD - ) - ) { + if (!(freePortIfHeld && err instanceof ValidationError)) throw err; + if (err.field === PORT_HELD_BY_DAEMON_FIELD) { + // The daemon's receiver only takes session traffic, and it stays up + // while it retains sessions, so a plain run gets its own receiver. + heldNotice = (bound) => + `${freePortNotice(port, bound, "is held by the Local daemon")} Add --session to capture into the daemon instead.`; + } else if (err.field === PORT_IN_USE_FIELD) { + // A server that is not a receiver would drop every event. + heldNotice = (bound) => + freePortNotice(port, bound, "is held by another process"); + } else { throw err; } - // The daemon's receiver only takes session traffic, and it stays up while - // it retains sessions, so a plain run gets its own receiver instead. - heldByDaemon = true; } if (running) { @@ -361,22 +365,20 @@ async function openEventTail({ }); } - if (!heldByDaemon) { + if (!heldNotice) { logger.info("No server detected, starting one in the background..."); } try { const bg = await startBackgroundServer({ maxEnvelopes, - port: heldByDaemon ? 0 : port, + port: heldNotice ? 0 : port, host, activeFilters, useJson, showAttributes, }); - if (heldByDaemon) { - logger.info( - `${freePortNotice(port, Number(new URL(bg.url).port), "is held by the Local daemon")} Add --session to capture into the daemon instead.`, - ); + if (heldNotice) { + logger.info(heldNotice(Number(new URL(bg.url).port))); } logger.info(`Background server listening on ${bold(bg.url)}`); return bg; @@ -683,7 +685,7 @@ export const runCommand = buildCommand({ : await openEventTail({ maxEnvelopes: flags["max-envelopes"], port, - freePortIfDaemon: flags.port === undefined, + freePortIfHeld: flags.port === undefined, host: flags.host, activeFilters, useJson, diff --git a/packages/cli/src/commands/local/server.ts b/packages/cli/src/commands/local/server.ts index f4ead07b3..2cde72ca4 100644 --- a/packages/cli/src/commands/local/server.ts +++ b/packages/cli/src/commands/local/server.ts @@ -18,9 +18,10 @@ import { isLoopbackHost } from "./loopback.js"; * Start a local development server that captures Sentry SDK envelopes, * or attach to one already running on the same port. * - * On startup the command probes `http://:/health`. If a server - * is already listening, the command attaches as an SSE consumer and tails - * events from it. Otherwise it starts its own Hono HTTP server. + * On startup the command probes `http://:/health`. If a Local or + * Spotlight receiver is already listening, the command attaches as an SSE + * consumer and tails events from it. Any other server there is an error. + * Otherwise it starts its own Hono HTTP server. * * The command runs until interrupted (Ctrl-C / SIGTERM). */ @@ -697,13 +698,15 @@ export function tryListen( /** * Ask `${url}/health` who holds the port: `none` for a transport failure - * (connection refused, timeout), `daemon` for a Sentry Local daemon, and - * `other` for any other HTTP reply, including an error status. + * (connection refused, timeout), `daemon` for a Sentry Local daemon, + * `receiver` for a Local or Spotlight receiver, which sends the + * {@link SERVER_IDENTIFIER} header even on an error status, and `foreign` for + * any other HTTP server. */ export async function probeLocalHealth( url: string, timeoutMs: number, -): Promise<"none" | "daemon" | "other"> { +): Promise<"none" | "daemon" | "receiver" | "foreign"> { let res: Response; try { res = await fetch(`${url}/health`, { @@ -718,27 +721,30 @@ export async function probeLocalHealth( } await res.body?.cancel(); if (res.headers.get("X-Sentry-Local-Mode") === "daemon") return "daemon"; + if (res.headers.get("X-Powered-By") !== SERVER_IDENTIFIER) { + logger.debug( + `Server at ${url} answered /health with HTTP ${res.status} and is not a receiver`, + ); + return "foreign"; + } if (!res.ok) { logger.debug( - `Server at ${url} answered /health with HTTP ${res.status}; treating the port as occupied`, + `Receiver at ${url} answered /health with HTTP ${res.status}; attaching anyway`, ); } - return "other"; + return "receiver"; } /** - * Check whether something is already serving on the given URL. + * Check whether a receiver to attach to 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 already in use`, killing - * the user's dev command instead of attaching to the sidecar. + * A receiver is recognized by its {@link SERVER_IDENTIFIER} header, not by a + * 2xx: Spotlight's own sidecar can answer `/health` with a 5xx while still + * holding the port and ingesting envelopes, and attaching to it is right. * * 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. + * "no server". Any other HTTP server, such as `python -m http.server`, throws + * a port-in-use error: attaching to it would lose every event. */ export async function isServerRunning(url: string): Promise { const holder = await probeLocalHealth(url, 2000); @@ -748,7 +754,10 @@ export async function isServerRunning(url: string): Promise { PORT_HELD_BY_DAEMON_FIELD, ); } - return holder === "other"; + if (holder === "foreign") { + throw portInUseError(Number(new URL(url).port || 80)); + } + return holder === "receiver"; } /** Apply only an explicitly requested limit when attaching to an existing receiver. */ diff --git a/packages/cli/test/commands/local/run.test.ts b/packages/cli/test/commands/local/run.test.ts index c657437f0..dbcfa74e4 100644 --- a/packages/cli/test/commands/local/run.test.ts +++ b/packages/cli/test/commands/local/run.test.ts @@ -1159,11 +1159,14 @@ setInterval(() => {}, 1000); }); test("warns when the existing server's stream cannot be attached", async () => { - // `/health` answers but `/stream` does not — e.g. an unrelated service - // squatting on the port. Attaching fails, and since `run` keeps the child - // alive the user would otherwise get no hint that events are missing. + // `/health` answers like a receiver but `/stream` does not. Attaching + // fails, and since `run` keeps the child alive the user would otherwise + // get no hint that events are missing. const brokenApp = new Hono(); - brokenApp.get("/health", (c) => c.text("OK")); + brokenApp.get("/health", (c) => { + c.header("X-Powered-By", serverModule.SERVER_IDENTIFIER); + return c.text("OK"); + }); const { server, port } = await tryListen(brokenApp, 0, "127.0.0.1"); const savedFetch = globalThis.fetch; @@ -1471,6 +1474,89 @@ describe("sentry local run messages", () => { } }, 30_000); + test("plain run captures on a free port while another process holds the default port", async () => { + // Something that isn't a receiver, such as `python -m http.server 8969`, + // answers /health without the receiver header. + const realFetch = (globalThis as { __originalFetch?: typeof fetch }) + .__originalFetch; + if (!realFetch) throw new Error("Expected the native fetch"); + vi.stubGlobal( + "fetch", + vi.fn(async (input: string | URL | Request, init?: RequestInit) => { + const url = new URL(input instanceof Request ? input.url : input); + return url.port === String(DEFAULT_PORT) + ? new Response("Not Found", { status: 404 }) + : await realFetch(input, init); + }), + ); + const info = vi.spyOn(logger, "info").mockImplementation(() => {}); + const context = makeParsedRunContext(); + try { + await run( + app, + [ + "local", + "run", + "--host", + "127.0.0.1", + "--", + process.execPath, + "-e", + "", + ], + context, + ); + expect(context.process.exitCode ?? 0).toBe(0); + const receiver = new URL(spawnCapture.env?.["SENTRY_SPOTLIGHT"] ?? ""); + expect(Number(receiver.port)).not.toBe(DEFAULT_PORT); + expect(Number(receiver.port)).toBeGreaterThan(0); + expect(info).toHaveBeenCalledWith( + `Port ${DEFAULT_PORT} is held by another process, so this run listens on port ${receiver.port} instead. SDKs that hard-code ${DEFAULT_PORT} won't reach it; make sure they read SENTRY_SPOTLIGHT.`, + ); + expect(info).not.toHaveBeenCalledWith( + expect.stringContaining("Connected to existing server"), + ); + } finally { + info.mockRestore(); + vi.unstubAllGlobals(); + } + }, 30_000); + + test("plain run fails when another process holds an explicit --port", async () => { + const holder = await holdPort(0, "127.0.0.1"); + const address = holder?.address(); + if (!address || typeof address === "string") + throw new Error("Expected a TCP address"); + const savedFetch = globalThis.fetch; + const realFetch = (globalThis as { __originalFetch?: typeof fetch }) + .__originalFetch; + if (realFetch) { + globalThis.fetch = realFetch; + } + spawnCapture.env = undefined; + try { + const func = (await runCommand.loader()) as unknown as RunFunc; + const error = await func + .call( + makeContext(), + { port: address.port, host: "127.0.0.1", verify: false, timeout: 0 }, + "true", + ) + .catch((err: unknown) => err); + expect(error).toBeInstanceOf(ValidationError); + expect(error).toMatchObject({ + field: PORT_IN_USE_FIELD, + message: expect.stringContaining( + `Port ${address.port} is already in use by another process`, + ), + }); + expect(spawnCapture.env).toBeUndefined(); + } finally { + globalThis.fetch = savedFetch; + await closeServer(holder); + } + }); + test("plain run still fails when the daemon holds an explicit --port", async () => { const daemonPort = makeDaemonHoldPort(45_678); spawnCapture.env = undefined; diff --git a/packages/cli/test/commands/local/server.test.ts b/packages/cli/test/commands/local/server.test.ts index 6c20fe88e..16bb80222 100644 --- a/packages/cli/test/commands/local/server.test.ts +++ b/packages/cli/test/commands/local/server.test.ts @@ -33,6 +33,7 @@ import { import { openBrowser } from "../../../src/lib/browser.js"; import { PORT_HELD_BY_DAEMON_FIELD, + PORT_IN_USE_FIELD, ValidationError, } from "../../../src/lib/errors.js"; import { SENTRY_CONTENT_TYPE } from "../../../src/lib/formatters/local.js"; @@ -1053,6 +1054,21 @@ describe("buildApp", () => { expect(res.headers.get("x-powered-by")).toBe(SERVER_IDENTIFIER); }); + test("sets X-Powered-By on unknown routes and errors", async () => { + // isServerRunning recognizes a receiver by this header on /health, which + // must hold even when the response is an error. + const app = buildApp(createLocalRetentionBuffer(10).buffer); + app.get("/boom", () => { + throw new Error("boom"); + }); + const notFound = await app.request("/no-such-route"); + expect(notFound.status).toBe(404); + expect(notFound.headers.get("x-powered-by")).toBe(SERVER_IDENTIFIER); + const failed = await app.request("/boom"); + expect(failed.status).toBe(500); + expect(failed.headers.get("x-powered-by")).toBe(SERVER_IDENTIFIER); + }); + test("SSE event type carries no base64 suffix by default", async () => { const chunk = await readFirstSSEEvent("/stream"); expect(chunk).toContain(`event: ${SENTRY_CONTENT_TYPE}\n`); @@ -1064,13 +1080,60 @@ describe("buildApp", () => { }); }); +describe("sentry local serve on a port held by another process", () => { + test("fails instead of attaching", async () => { + const foreign = new Hono(); + foreign.get("/health", (c) => c.text("Not Found", 404)); + const { server, port } = await tryListen(foreign, 0, "127.0.0.1"); + const savedFetch = globalThis.fetch; + const realFetch = (globalThis as { __originalFetch?: typeof fetch }) + .__originalFetch; + if (realFetch) { + globalThis.fetch = realFetch; + } + const func = (await serverCommand.loader()) as unknown as ServeFunc; + + try { + const error = await func + .call( + {}, + { + port, + host: "127.0.0.1", + quiet: true, + filter: [], + format: "human", + attributes: false, + open: false, + }, + ) + .catch((err: unknown) => err); + expect(error).toBeInstanceOf(ValidationError); + expect(error).toMatchObject({ + field: PORT_IN_USE_FIELD, + message: expect.stringContaining( + `Port ${port} is already in use by another process`, + ), + }); + } finally { + globalThis.fetch = savedFetch; + await new Promise((done) => server.close(() => done())); + } + }); +}); + 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 already in use". + // The sidecar sets X-Powered-By in middleware, so the header comes back + // with the error too. const unhealthy = new Hono(); - unhealthy.get("/health", (c) => c.text("Internal Server Error", 500)); + unhealthy.get("/health", (c) => { + c.header("X-Powered-By", SERVER_IDENTIFIER); + return c.text("Internal Server Error", 500); + }); const { server, port } = await tryListen(unhealthy, 0, "127.0.0.1"); const savedFetch = globalThis.fetch; @@ -1090,6 +1153,34 @@ describe("isServerRunning", () => { } }); + test("rejects a port that an HTTP server other than a receiver holds", async () => { + // e.g. `python -m http.server 8969`: attaching to it loses every event. + const foreign = new Hono(); + foreign.get("/health", (c) => c.text("Not Found", 404)); + const { server, port } = await tryListen(foreign, 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}`), + ).rejects.toMatchObject({ + name: "ValidationError", + field: PORT_IN_USE_FIELD, + message: expect.stringContaining( + `Port ${port} is already in use by another process`, + ), + }); + } finally { + globalThis.fetch = savedFetch; + await new Promise((done) => server.close(() => done())); + } + }); + test("rejects a port that a Sentry Local daemon holds", async () => { vi.stubGlobal( "fetch",