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
4 changes: 3 additions & 1 deletion apps/cli-docs/src/fragments/commands/local.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`

Expand All @@ -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 <name>` 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
Expand Down
17 changes: 9 additions & 8 deletions packages/cli/src/commands/local/daemon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -372,10 +372,9 @@ async function isStaleProbe(
probe: "ok" | "refused" | "failed",
): Promise<boolean> {
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";
}

/**
Expand Down Expand Up @@ -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(
Expand Down
50 changes: 26 additions & 24 deletions packages/cli/src/commands/local/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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<FilterValue>;
useJson: boolean;
Expand Down Expand Up @@ -322,7 +324,7 @@ function freePortNotice(
*/
async function openEventTail({
port,
freePortIfDaemon = false,
freePortIfHeld = false,
host,
activeFilters,
useJson,
Expand All @@ -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 <name> 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) {
Expand All @@ -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 <name> 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;
Expand Down Expand Up @@ -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,
Expand Down
45 changes: 27 additions & 18 deletions packages/cli/src/commands/local/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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://<host>:<port>/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://<host>:<port>/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).
*/
Expand Down Expand Up @@ -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`, {
Expand All @@ -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<boolean> {
const holder = await probeLocalHealth(url, 2000);
Expand All @@ -748,7 +754,10 @@ export async function isServerRunning(url: string): Promise<boolean> {
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. */
Expand Down
94 changes: 90 additions & 4 deletions packages/cli/test/commands/local/run.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down
Loading
Loading