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
3 changes: 3 additions & 0 deletions apps/cli-docs/src/content/docs/exit-codes.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ react to failure categories without parsing stderr.
| 40–49 | Feature | Feature availability and billing issues |
| 50–59 | Operations | Upgrade and OAuth flow errors |
| 60–69 | Command | Command-specific non-standard exits |
| 124 | Shell convention | `sentry local run --timeout` stopped the app, as GNU `timeout` exits |
| 252 | Shell convention | An argument could not be parsed |

## Complete Reference

Expand Down Expand Up @@ -45,6 +47,7 @@ react to failure categories without parsing stderr.
| 51 | Device Flow Error | OAuth device authorization flow failed |
| 60 | Output Error | Command produced output but the operation failed |
| 64 | Verify Failed | `sentry local run --verify` received no events from the SDK |
| 124 | Run Timeout | `sentry local run --timeout` stopped the app (the GNU `timeout` convention) |
| 252 | Invalid Argument | An argument could not be parsed — see [Argument errors](#argument-errors) |

## Scripting Examples
Expand Down
4 changes: 4 additions & 0 deletions apps/cli-docs/src/fragments/commands/local.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@ The `<PREFIX>` variants put the URL where your bundler can inline it into browse

When `local run` sees `wrangler dev` and a `wrangler.json`, `wrangler.jsonc`, or `wrangler.toml`, it also adds `--var SENTRY_SPOTLIGHT:<url>`, because Wrangler does not pass process env vars to Worker code. An explicit `--var SENTRY_SPOTLIGHT:...` is kept. No project file is changed.

### Stop after a set time with `--timeout`

`sentry local run --timeout <seconds> -- <command>` stops your app after that many seconds and exits 124, as GNU `timeout` does, whatever exit code the app gives when it stops. If the app exits on its own first, `local run` exits with the app's code.

### Check your setup with `--verify`

`sentry local run --verify -- <command>` starts your app, waits for its first event, then stops it. It exits 0 once an event arrives. It fails if the app exits, crashes, or sends nothing within the timeout (30 seconds, or `--timeout <seconds>`). When port 8969 is busy, it verifies on a free port.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ Run a command with the local dev server enabled
- `--host <value> - Hostname for the local server - (default: "localhost")`
- `-f, --filter <value>... - Only show items of this type (repeatable: error, transaction, log, ai)`
- `-V, --verify - Verify SDK sends events, then exit`
- `-t, --timeout <value> - Kill the child after N seconds (0 = no timeout; defaults to 30 s in --verify mode) - (default: "0")`
- `-t, --timeout <value> - Stop the child after N seconds and exit 124 (0 = no timeout; defaults to 30 s in --verify mode, which exits 64) - (default: "0")`
- `-F, --format <value> - Output format: human (default) or json (NDJSON on stdout) - (default: "human")`
- `-a, --attributes - Also show SDK attributes, under each transaction, span and log or in JSON`
- `--open - Open Sentry Local UI in the browser`
Expand Down
16 changes: 14 additions & 2 deletions packages/cli/src/commands/local/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -592,7 +592,7 @@ export const runCommand = buildCommand({
kind: "parsed",
parse: textParser(parseTimeout),
brief:
"Kill the child after N seconds (0 = no timeout; defaults to 30 s in --verify mode)",
"Stop the child after N seconds and exit 124 (0 = no timeout; defaults to 30 s in --verify mode, which exits 64)",
default: "0",
},
format: {
Expand Down Expand Up @@ -766,7 +766,12 @@ export const runCommand = buildCommand({
let timeoutId: ReturnType<typeof setTimeout> | undefined;
if (flags.timeout > 0) {
timeoutId = setTimeout(() => {
logger.warn(`Timeout: killing child after ${flags.timeout}s`);
// The user already stopped the app, so it is shutting down: let it
// finish and keep its exit code.
if (interruptState.interrupted) {
return;
}
logger.info(`Stopping after ${flags.timeout}s (--timeout)…`);
interruptState.timedOut = true;
void gracefulKill(child, ownGroup);
}, flags.timeout * 1000);
Expand Down Expand Up @@ -811,6 +816,13 @@ export const runCommand = buildCommand({
}
}

// How the app ends once --timeout stops it depends on the app (0, 143,
// 137, ...), so report the timeout itself.
if (interruptState.timedOut) {
logger.info(`Stopped after ${flags.timeout}s (--timeout)`);
this.process.exitCode = EXIT.RUN_TIMEOUT;
return;
}
const exitCode = exit.signal
? signalExitCode(exit.signal)
: (exit.code ?? EXIT.GENERAL);
Expand Down
5 changes: 4 additions & 1 deletion packages/cli/src/lib/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export const EXIT = {
// 30–39: API & network (HTTP 502/503/504 family)
/** Sentry API returned an error */
API: 30,
/** Operation timed out */
/** API operation timed out */
TIMEOUT: 31,
/** Rate limited by the Sentry API — wait before retrying */
RATE_LIMITED: 32,
Expand Down Expand Up @@ -105,6 +105,9 @@ export const EXIT = {
OUTPUT_ERROR: 60,
/** `sentry local run --verify` received no events from the SDK */
VERIFY_FAILED: 64,

/** `sentry local run --timeout` stopped the app, as GNU `timeout` exits */
RUN_TIMEOUT: 124,
} as const;

/**
Expand Down
114 changes: 94 additions & 20 deletions packages/cli/test/commands/local/run.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -674,6 +674,28 @@ setInterval(() => {}, 1000);
},
);

test("keeps the app's exit code when --timeout fires during a Ctrl-C shutdown", async () => {
const ctx = { ...makeContext(), process: { exitCode: undefined } };
const func = (await runCommand.loader()) as unknown as RunFunc;
const ready = join(tmpDir, "ready");
// Takes 1.5s to shut down after SIGINT, so --timeout 1 fires meanwhile.
const run = func.call(
ctx,
{ port: 0, host: "127.0.0.1", verify: false, timeout: 1 },
process.execPath,
"-e",
// The ready file path comes in as an argument, not inside the code.
'process.on("SIGINT", () => setTimeout(() => process.exit(0), 1500));require("node:fs").writeFileSync(process.argv[1], "");setInterval(() => {}, 1000);',
ready,
);
await vi.waitFor(async () => {
await readFile(ready, "utf8");
});
signals.send("SIGINT");
await expect(run).resolves.toBeUndefined();
expect(ctx.process.exitCode).toBeUndefined();
}, 20_000);

describe("with an app behind a wrapper that ignores SIGINT", () => {
/**
* Like `go run`: ignores SIGINT, dies from SIGTERM without passing it
Expand Down Expand Up @@ -755,21 +777,21 @@ app.on("exit", (code, signal) => process.exit(signal ? 1 : (code ?? 1)));
}
}, 30_000);

test("--timeout leaves no app running", async () => {
test("--timeout leaves no app running and exits 124", async () => {
const { wrapper, appPidFile } = await wrappedApp();
const warn = vi.spyOn(logger, "warn").mockImplementation(() => {});
try {
const func = (await runCommand.loader()) as unknown as RunFunc;
await func
.call(
makeContext(),
{ port: 0, host: "127.0.0.1", verify: false, timeout: 2 },
process.execPath,
wrapper,
)
.catch(() => undefined);
const ctx = { ...makeContext(), process: { exitCode: undefined } };
await func.call(
ctx,
{ port: 0, host: "127.0.0.1", verify: false, timeout: 2 },
process.execPath,
wrapper,
);
const pid = await appPid(appPidFile);
expect(isRunning(pid)).toBe(false);
expect(ctx.process.exitCode).toBe(EXIT.RUN_TIMEOUT);
} finally {
warn.mockRestore();
}
Expand Down Expand Up @@ -898,24 +920,69 @@ setInterval(() => {}, 1000);
});
});

test("--timeout kills the child after N seconds", async () => {
const func = (await runCommand.loader()) as unknown as RunFunc;
const ctx = makeContext();
test.each([
{ app: "dies from SIGTERM", args: ["sleep", "60"] },
{
app: "exits 0 on SIGTERM",
args: [
process.execPath,
"-e",
"process.on('SIGTERM', () => process.exit(0)); setInterval(() => {}, 1000);",
],
},
])("--timeout exits 124 when it stops an app that $app", async ({ args }) => {
const info = vi.spyOn(logger, "info").mockImplementation(() => {});
try {
const func = (await runCommand.loader()) as unknown as RunFunc;
const ctx = { ...makeContext(), process: { exitCode: undefined } };
await func.call(
ctx,
{ port: 0, host: "127.0.0.1", verify: false, timeout: 1 },
...(args as [string, ...string[]]),
);
expect(ctx.process.exitCode).toBe(EXIT.RUN_TIMEOUT);
expect(info.mock.calls.map((c) => String(c[0]))).toContain(
"Stopped after 1s (--timeout)",
);
} finally {
info.mockRestore();
}
});

// "sleep 60" would take too long — timeout at 1s should kill it
test("--timeout exits 124 when the app ignores SIGTERM and gets SIGKILL", async () => {
const info = vi.spyOn(logger, "info").mockImplementation(() => {});
try {
const func = (await runCommand.loader()) as unknown as RunFunc;
const ctx = { ...makeContext(), process: { exitCode: undefined } };
await func.call(
ctx,
{ port: 0, host: "127.0.0.1", verify: false, timeout: 1 },
"sleep",
"60",
process.execPath,
"-e",
"process.on('SIGTERM', () => {}); setInterval(() => {}, 1000);",
);
expect.unreachable("should have thrown");
} catch (err) {
expect(err).toBeInstanceOf(CliError);
// The child is killed by SIGTERM, resulting in a non-zero exit
expect((err as CliError).message).toContain("exited with code");
expect(ctx.process.exitCode).toBe(EXIT.RUN_TIMEOUT);
const lines = info.mock.calls.map((c) => String(c[0]));
expect(lines).toContain("Stopping after 1s (--timeout)…");
expect(lines).toContain("Stopped after 1s (--timeout)");
} finally {
info.mockRestore();
}
}, 20_000);

test("--timeout keeps the exit code of an app that exits first", async () => {
const func = (await runCommand.loader()) as unknown as RunFunc;
const error = await func
.call(
makeContext(),
{ port: 0, host: "127.0.0.1", verify: false, timeout: 10 },
process.execPath,
"-e",
"process.exit(3)",
)
.catch((err: unknown) => err);
expect(error).toBeInstanceOf(CliError);
expect((error as CliError).exitCode).toBe(3);
});

test("--verify with a quick-exit process throws VERIFY_FAILED", async () => {
Expand All @@ -941,6 +1008,7 @@ setInterval(() => {}, 1000);
test("--verify with --timeout throws on timeout", async () => {
const func = (await runCommand.loader()) as unknown as RunFunc;
const ctx = makeContext();
const info = vi.spyOn(logger, "info").mockImplementation(() => {});

try {
await func.call(
Expand All @@ -954,6 +1022,12 @@ setInterval(() => {}, 1000);
expect(err).toBeInstanceOf(VerifyFailedError);
expect((err as CliError).message).toContain("Verification timed out");
expect((err as CliError).exitCode).toBe(64);
// The --verify timeout is not the plain-run --timeout.
expect(
info.mock.calls.some((c) => String(c[0]).includes("(--timeout)")),
).toBe(false);
} finally {
info.mockRestore();
}
});

Expand Down
Loading