diff --git a/apps/cli-docs/src/content/docs/exit-codes.md b/apps/cli-docs/src/content/docs/exit-codes.md index b3beeaedd..3a9ba85ad 100644 --- a/apps/cli-docs/src/content/docs/exit-codes.md +++ b/apps/cli-docs/src/content/docs/exit-codes.md @@ -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 @@ -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 diff --git a/apps/cli-docs/src/fragments/commands/local.md b/apps/cli-docs/src/fragments/commands/local.md index a40d0a970..f0e4b0101 100644 --- a/apps/cli-docs/src/fragments/commands/local.md +++ b/apps/cli-docs/src/fragments/commands/local.md @@ -44,6 +44,10 @@ The `` 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:`, 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 -- ` 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 -- ` 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 `). When port 8969 is busy, it verifies on a free port. diff --git a/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/local.md b/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/local.md index b648fa4bc..8079869e9 100644 --- a/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/local.md +++ b/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/local.md @@ -193,7 +193,7 @@ Run a command with the local dev server enabled - `--host - Hostname for the local server - (default: "localhost")` - `-f, --filter ... - Only show items of this type (repeatable: error, transaction, log, ai)` - `-V, --verify - Verify SDK sends events, then exit` -- `-t, --timeout - Kill the child after N seconds (0 = no timeout; defaults to 30 s in --verify mode) - (default: "0")` +- `-t, --timeout - 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 - 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` diff --git a/packages/cli/src/commands/local/run.ts b/packages/cli/src/commands/local/run.ts index 3e0586f03..1091707af 100644 --- a/packages/cli/src/commands/local/run.ts +++ b/packages/cli/src/commands/local/run.ts @@ -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: { @@ -766,7 +766,12 @@ export const runCommand = buildCommand({ let timeoutId: ReturnType | 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); @@ -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); diff --git a/packages/cli/src/lib/errors.ts b/packages/cli/src/lib/errors.ts index d5b0f7b63..dcc8bd198 100644 --- a/packages/cli/src/lib/errors.ts +++ b/packages/cli/src/lib/errors.ts @@ -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, @@ -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; /** diff --git a/packages/cli/test/commands/local/run.test.ts b/packages/cli/test/commands/local/run.test.ts index c657437f0..2b8f14c58 100644 --- a/packages/cli/test/commands/local/run.test.ts +++ b/packages/cli/test/commands/local/run.test.ts @@ -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 @@ -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(); } @@ -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 () => { @@ -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( @@ -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(); } });