From 98a69f604ba8272ba059204f114deab2a837cc6f Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:27:47 +0000 Subject: [PATCH 1/6] fix(cli): Name each command's own refresh flag in the cached footer The cached-result footer hardcoded "use -f to refresh", but log list binds -f to --follow, so the hint pointed at the wrong flag. buildCommand now derives the flag from the command's final flags and aliases: the alias that maps to --fresh, else --fresh, else no refresh suggestion at all. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> Co-Authored-By: BYK --- packages/cli/src/lib/cache-hint.ts | 47 ++++++++- packages/cli/src/lib/command.ts | 10 +- packages/cli/test/lib/cache-hint.test.ts | 123 +++++++++++++++++++++-- packages/cli/test/lib/command.test.ts | 53 ++++++++++ 4 files changed, 220 insertions(+), 13 deletions(-) diff --git a/packages/cli/src/lib/cache-hint.ts b/packages/cli/src/lib/cache-hint.ts index b2b7161048..8d7e4df87a 100644 --- a/packages/cli/src/lib/cache-hint.ts +++ b/packages/cli/src/lib/cache-hint.ts @@ -6,6 +6,11 @@ * Applied automatically by `buildCommand` in `command.ts` — individual * commands don't need to call this themselves. * + * The refresh flag named in the hint is derived from each command's own + * parameters via {@link resolveRefreshFlag}, never hardcoded: commands + * like `log list` bind `-f` to `--follow`, so a fixed `-f` would point + * users at the wrong flag. + * * getsentry/cli#785 item #1 — `-f/--fresh` flag discoverability. * * @module @@ -44,6 +49,31 @@ export function formatAge(ms: number): string { return `${days}d ago`; } +/** + * Resolve the shortest spelling of a command's `--fresh` flag. + * + * Returns `-` when an alias maps to `fresh`, `--fresh` when the flag + * exists without an alias, and `undefined` when the command has no `fresh` + * flag at all (so the hint must not suggest one). + * + * @param flags - The command's final flag definitions + * @param aliases - The command's final alias map (short name → flag name) + */ +export function resolveRefreshFlag( + flags: Readonly>, + aliases: Readonly>, +): string | undefined { + if (!("fresh" in flags)) { + return; + } + for (const [short, target] of Object.entries(aliases)) { + if (target === "fresh") { + return `-${short}`; + } + } + return "--fresh"; +} + /** * Build a cache-age hint string, or `undefined` when the last request was * not served from cache. @@ -52,14 +82,19 @@ export function formatAge(ms: number): string { * displayed age corresponds to whichever resolves last — acceptable * since all hits share similar ages in practice. * - * Example output: `"cached · 3m ago · use -f to refresh"` + * Example output: `"cached · 3m ago · use -f to refresh"`, or + * `"cached · 3m ago"` when `refreshFlag` is omitted. + * + * @param refreshFlag - Flag that bypasses the cache for the running + * command, from {@link resolveRefreshFlag} */ -export function formatCacheHint(): string | undefined { +export function formatCacheHint(refreshFlag?: string): string | undefined { const ageMs = getLastCacheHitAge(); if (ageMs === undefined) { return; } - return `cached · ${formatAge(ageMs)} · use -f to refresh`; + const base = `cached · ${formatAge(ageMs)}`; + return refreshFlag ? `${base} · use ${refreshFlag} to refresh` : base; } /** @@ -69,11 +104,15 @@ export function formatCacheHint(): string | undefined { * - Only cache hint → `"cached · 3m ago · ..."` * - Only existing → `"existingHint"` (unchanged) * - Neither → `undefined` + * + * @param existingHint - Hint returned by the command, if any + * @param refreshFlag - Flag that bypasses the cache, see {@link formatCacheHint} */ export function appendCacheHint( existingHint: string | undefined, + refreshFlag?: string, ): string | undefined { - const cacheHint = formatCacheHint(); + const cacheHint = formatCacheHint(refreshFlag); if (existingHint && cacheHint) { return `${existingHint} | ${cacheHint}`; } diff --git a/packages/cli/src/lib/command.ts b/packages/cli/src/lib/command.ts index 0023ac43ba..52edfd2ccc 100644 --- a/packages/cli/src/lib/command.ts +++ b/packages/cli/src/lib/command.ts @@ -40,7 +40,7 @@ import { import type { GenericSchema } from "valibot"; import type { Writer } from "../types/index.js"; import { getInvocationCommand, sentry } from "./app-identity.js"; -import { appendCacheHint } from "./cache-hint.js"; +import { appendCacheHint, resolveRefreshFlag } from "./cache-hint.js"; import { type CommandExample, exampleSteps } from "./command-example.js"; import { choiceListParser, @@ -612,6 +612,10 @@ export function buildCommand< aliases: mergedAliases, }; + // Derive the cache-hint refresh flag from the final parameters so the + // footer can never name a flag the command binds to something else. + const refreshFlag = resolveRefreshFlag(mergedFlags, mergedAliases); + /** * If the yielded value is a {@link CommandOutput}, render it via * the output config. Void/undefined/Error/other values are ignored. @@ -909,14 +913,14 @@ export function buildCommand< // Render phase: output finalization. // Append cache-age hint automatically so every command gets - // "cached · 3m ago · use -f to refresh" when data was cached. + // "cached · 3m ago · use to refresh" when data was cached. // Skip bare `return;` paths (e.g. `--web` which opens a browser // without yielding) — no rendered output should mean no footer. // `Tip:` text is stripped first when tips are disabled // (`sentry cli defaults tips off` / SENTRY_DISABLE_TIPS); other // notices and the cache-age staleness indicator are kept. const finalHint = returned - ? appendCacheHint(applyTipsPreference(returned.hint)) + ? appendCacheHint(applyTipsPreference(returned.hint), refreshFlag) : undefined; await withTracing("render", "cli.command.render", () => { writeFinalization(stdout, finalHint, cleanFlags["json"], renderer); diff --git a/packages/cli/test/lib/cache-hint.test.ts b/packages/cli/test/lib/cache-hint.test.ts index 644579e656..02e49f19c1 100644 --- a/packages/cli/test/lib/cache-hint.test.ts +++ b/packages/cli/test/lib/cache-hint.test.ts @@ -6,12 +6,27 @@ * module is small and the formatting has specific boundary values. */ +import { + boolean, + constantFrom, + dictionary, + assert as fcAssert, + property, +} from "fast-check"; import { describe, expect, test } from "vitest"; +import { routes } from "../../src/app.js"; import { appendCacheHint, formatAge, formatCacheHint, + resolveRefreshFlag, } from "../../src/lib/cache-hint.js"; +import { + type Command, + isCommand, + isRouteMap, + type RouteMap, +} from "../../src/lib/introspect.js"; import { clearLastCacheHitAge, getLastCacheHitAge, @@ -50,6 +65,86 @@ describe("formatAge", () => { }); }); +describe("resolveRefreshFlag", () => { + test("prefers the short alias bound to --fresh", () => { + expect(resolveRefreshFlag({ fresh: {} }, { f: "fresh" })).toBe("-f"); + }); + + test("falls back to --fresh when -f is bound to another flag", () => { + expect(resolveRefreshFlag({ fresh: {}, follow: {} }, { f: "follow" })).toBe( + "--fresh", + ); + }); + + test("returns undefined when the command has no --fresh flag", () => { + expect(resolveRefreshFlag({ force: {} }, { f: "force" })).toBeUndefined(); + }); + + test("property: the result always parses back to --fresh", () => { + const names = constantFrom("fresh", "follow", "force", "filter", "web"); + fcAssert( + property( + boolean(), + dictionary(constantFrom("f", "F", "r", "w", "x"), names), + (hasFresh, aliases) => { + const flags: Record = hasFresh ? { fresh: {} } : {}; + const result = resolveRefreshFlag(flags, aliases); + if (!hasFresh) { + expect(result).toBeUndefined(); + } else if (result === "--fresh") { + expect(Object.values(aliases)).not.toContain("fresh"); + } else { + expect(result).toMatch(/^-[^-]$/); + expect(aliases[(result as string).slice(1)]).toBe("fresh"); + } + }, + ), + ); + }); +}); + +/** Collect every registered command with its full `sentry ...` path. */ +function collectCommands( + map: RouteMap, + prefix: string[], +): Array<{ path: string; command: Command }> { + return map.getAllEntries().flatMap((entry) => { + const path = [...prefix, entry.name.original]; + if (isRouteMap(entry.target)) { + return collectCommands(entry.target, path); + } + if (isCommand(entry.target)) { + return [{ path: path.join(" "), command: entry.target }]; + } + return []; + }); +} + +describe("cache hint refresh flag for registered commands", () => { + const commands = collectCommands(routes as unknown as RouteMap, []); + + /** Refresh flag named in a command's footer, from its final parameters. */ + function refreshFlagFor(path: string): string | undefined { + const found = commands.find((c) => c.path === path); + if (!found) { + throw new Error(`command not registered: ${path}`); + } + const { flags = {}, aliases = {} } = found.command.parameters as { + flags?: Record; + aliases?: Record; + }; + return resolveRefreshFlag(flags, aliases); + } + + test("log list names --fresh because -f is --follow", () => { + expect(refreshFlagFor("log list")).toBe("--fresh"); + }); + + test("issue list keeps the -f shorthand", () => { + expect(refreshFlagFor("issue list")).toBe("-f"); + }); +}); + describe("formatCacheHint", () => { test("returns undefined when no cache hit recorded", () => { clearLastCacheHitAge(); @@ -64,19 +159,33 @@ describe("formatCacheHint", () => { test("returns formatted hint when cache hit recorded (3m)", () => { setLastCacheHitAgeForTesting(180_000); - expect(formatCacheHint()).toBe("cached · 3m ago · use -f to refresh"); + expect(formatCacheHint("-f")).toBe("cached · 3m ago · use -f to refresh"); clearLastCacheHitAge(); }); test("returns formatted hint when cache hit recorded (just now)", () => { setLastCacheHitAgeForTesting(0); - expect(formatCacheHint()).toBe("cached · just now · use -f to refresh"); + expect(formatCacheHint("-f")).toBe("cached · just now · use -f to refresh"); clearLastCacheHitAge(); }); test("returns formatted hint when cache hit recorded (2h)", () => { setLastCacheHitAgeForTesting(2 * 60 * 60_000); - expect(formatCacheHint()).toBe("cached · 2h ago · use -f to refresh"); + expect(formatCacheHint("-f")).toBe("cached · 2h ago · use -f to refresh"); + clearLastCacheHitAge(); + }); + + test("names the given refresh flag", () => { + setLastCacheHitAgeForTesting(180_000); + expect(formatCacheHint("--fresh")).toBe( + "cached · 3m ago · use --fresh to refresh", + ); + clearLastCacheHitAge(); + }); + + test("omits the refresh suggestion when there is no refresh flag", () => { + setLastCacheHitAgeForTesting(180_000); + expect(formatCacheHint()).toBe("cached · 3m ago"); clearLastCacheHitAge(); }); }); @@ -94,7 +203,7 @@ describe("appendCacheHint", () => { test("returns just the cache hint when no existing hint", () => { setLastCacheHitAgeForTesting(180_000); - expect(appendCacheHint(undefined)).toBe( + expect(appendCacheHint(undefined, "-f")).toBe( "cached · 3m ago · use -f to refresh", ); clearLastCacheHitAge(); @@ -102,7 +211,7 @@ describe("appendCacheHint", () => { test("joins existing and cache hints with ' | ' separator", () => { setLastCacheHitAgeForTesting(180_000); - expect(appendCacheHint("Showing 5 issues")).toBe( + expect(appendCacheHint("Showing 5 issues", "-f")).toBe( "Showing 5 issues | cached · 3m ago · use -f to refresh", ); clearLastCacheHitAge(); @@ -111,7 +220,9 @@ describe("appendCacheHint", () => { test("treats empty existing hint as falsy (no separator)", () => { setLastCacheHitAgeForTesting(180_000); // Empty string is falsy — appendCacheHint returns just the cache hint. - expect(appendCacheHint("")).toBe("cached · 3m ago · use -f to refresh"); + expect(appendCacheHint("", "-f")).toBe( + "cached · 3m ago · use -f to refresh", + ); clearLastCacheHitAge(); }); }); diff --git a/packages/cli/test/lib/command.test.ts b/packages/cli/test/lib/command.test.ts index 6d106e1db4..877e6efcb2 100644 --- a/packages/cli/test/lib/command.test.ts +++ b/packages/cli/test/lib/command.test.ts @@ -44,6 +44,10 @@ import { import { LOG_LEVEL_NAMES, logger, setLogLevel } from "../../src/lib/logger.js"; import { DRY_RUN_FLAG, YES_FLAG } from "../../src/lib/mutate-command.js"; import { resolveOrgAndProject } from "../../src/lib/resolve-target.js"; +import { + clearLastCacheHitAge, + setLastCacheHitAgeForTesting, +} from "../../src/lib/response-cache.js"; import { buildRouteMap } from "../../src/lib/route-map.js"; /** Minimal context for test commands */ @@ -1338,6 +1342,55 @@ describe("buildCommand return-based output", () => { expect(output).not.toContain("Tip:"); }); + test("cache hint names the command's own refresh flag", async () => { + const makeCommand = (aliases: Record) => + buildCommand< + { fresh: boolean; follow: boolean }, + [], + TestContext, + { value: number } + >({ + auth: false, + docs: { brief: "Test" }, + output: { human: (d: { value: number }) => `Value: ${d.value}` }, + parameters: { + flags: { + fresh: { kind: "boolean", brief: "Fresh", default: false }, + follow: { kind: "boolean", brief: "Follow", default: false }, + }, + aliases, + }, + async *func(this: TestContext) { + yield new CommandOutput({ value: 42 }); + return {}; + }, + }); + const runWith = async (aliases: Record) => { + const app = buildApplication( + buildRouteMap({ + routes: { test: makeCommand(aliases) }, + docs: { brief: "Test app" }, + }), + { name: "test" }, + ); + const ctx = createTestContext(); + await run(app, ["test"], ctx as TestContext); + return ctx.output.join(""); + }; + + setLastCacheHitAgeForTesting(180_000); + try { + const followOwnsF = await runWith({ f: "follow" }); + expect(followOwnsF).toContain("cached · 3m ago · use --fresh to refresh"); + expect(followOwnsF).not.toContain("use -f"); + + const freshOwnsF = await runWith({ f: "fresh" }); + expect(freshOwnsF).toContain("cached · 3m ago · use -f to refresh"); + } finally { + clearLastCacheHitAge(); + } + }); + test("void return does nothing (no crash)", async () => { let executed = false; From f3015edcdd8e3ee45b324754aa415d779732106f Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 20:32:26 +0000 Subject: [PATCH 2/6] feat(cli): Stream logs with sentry log tail so -f always means --fresh `log list` bound `-f` to `--follow`, so the cached footer's "use -f to refresh" pointed at the wrong flag there, and `-f` meant something different in `log list` than in every other list command. Live output now has its own command, like `tail -f` and `heroku logs --tail`: `sentry log tail [target] [-i/--interval N]` covers project and trace mode. `log list` fetches once, and `-f` is `--fresh` there too. A hidden `--follow` on `log list` errors with a pointer to `log tail`. To keep the rule from drifting: - design/sentry-cli.md states it: `-f` is `--fresh` wherever a command can bypass the cache, and live output is its own command. It lists `dashboard view --refresh` as the remaining gap. - A route-tree test fails when a command with `--fresh` binds `-f` to anything else, when a new command streams through a flag, or when a visible `--follow` comes back. - `src/lib/streaming-commands.ts` is the one list of streaming commands and flags. The SDK generator types `sdk.log.tail()` as an AsyncIterable from it, and `sdk.run()` picks the same return shape from it. That also fixes `sdk.run(..., "-f")` streaming on commands where `-f` is `--fresh`. - `buildListCommand` drops its `noFreshAlias` opt-out. Co-Authored-By: BYK --- .../src/content/docs/agent-guidance.md | 2 +- .../cli-docs/src/content/docs/contributing.md | 2 +- .../src/content/docs/library-usage.md | 11 +- apps/cli-docs/src/fragments/commands/log.md | 2 +- design/sentry-cli.md | 7 +- packages/cli/README.md | 2 +- .../sentry-cli/skills/sentry-cli/SKILL.md | 3 +- .../skills/sentry-cli/references/log.md | 55 +- packages/cli/script/generate-sdk.ts | 71 +- packages/cli/src/commands/log/index.ts | 9 +- packages/cli/src/commands/log/list.ts | 752 +-------------- packages/cli/src/commands/log/shared.ts | 324 +++++++ packages/cli/src/commands/log/tail.ts | 472 ++++++++++ packages/cli/src/lib/cache-hint.ts | 6 +- packages/cli/src/lib/list-command.ts | 17 +- packages/cli/src/lib/sdk-invoke.ts | 17 +- packages/cli/src/lib/streaming-commands.ts | 40 + packages/cli/test/commands/log/list.test.ts | 764 +-------------- packages/cli/test/commands/log/tail.test.ts | 867 ++++++++++++++++++ packages/cli/test/e2e/log.test.ts | 17 +- packages/cli/test/lib/cache-hint.test.ts | 8 +- packages/cli/test/lib/index.test.ts | 12 +- packages/cli/test/lib/sdk-flag-types.test.ts | 9 +- .../test/lib/short-flag-conventions.test.ts | 79 ++ .../cli/test/lib/streaming-commands.test.ts | 34 + 25 files changed, 2032 insertions(+), 1550 deletions(-) create mode 100644 packages/cli/src/commands/log/shared.ts create mode 100644 packages/cli/src/commands/log/tail.ts create mode 100644 packages/cli/src/lib/streaming-commands.ts create mode 100644 packages/cli/test/commands/log/tail.test.ts create mode 100644 packages/cli/test/lib/short-flag-conventions.test.ts create mode 100644 packages/cli/test/lib/streaming-commands.test.ts diff --git a/apps/cli-docs/src/content/docs/agent-guidance.md b/apps/cli-docs/src/content/docs/agent-guidance.md index 6a72584ea9..6b68e268a5 100644 --- a/apps/cli-docs/src/content/docs/agent-guidance.md +++ b/apps/cli-docs/src/content/docs/agent-guidance.md @@ -117,7 +117,7 @@ sentry trace logs abc123def456... ```bash # Stream logs in real-time (auto-detects org/project) -sentry log list --follow +sentry log tail # Filter logs by severity sentry log list --query "severity:error" diff --git a/apps/cli-docs/src/content/docs/contributing.md b/apps/cli-docs/src/content/docs/contributing.md index d615d0205f..c10e6eb026 100644 --- a/apps/cli-docs/src/content/docs/contributing.md +++ b/apps/cli-docs/src/content/docs/contributing.md @@ -72,7 +72,7 @@ toolkit/ │ │ │ ├── integration/ # delete, list │ │ │ ├── issue/ # archive, events, explain, link, list, merge, plan, resolve, tags, unlink, unresolve, view │ │ │ ├── local/ # close, create, list, reset, restart, retention, run, serve, start, status, stop, view -│ │ │ ├── log/ # list, view +│ │ │ ├── log/ # list, tail, view │ │ │ ├── monitor/ # list, run │ │ │ ├── org/ # list, view │ │ │ ├── platform/ # list diff --git a/apps/cli-docs/src/content/docs/library-usage.md b/apps/cli-docs/src/content/docs/library-usage.md index 09506221ff..d784190615 100644 --- a/apps/cli-docs/src/content/docs/library-usage.md +++ b/apps/cli-docs/src/content/docs/library-usage.md @@ -277,14 +277,15 @@ The WASM SQLite fallback (Node.js 20–22.14) does not support [WAL mode](https: ## Streaming Commands -Two commands support real-time streaming: `log list --follow` and `dashboard view --refresh`. -When using streaming flags, methods return an `AsyncIterable` instead of a `Promise`: +Two commands support real-time streaming: `log tail` and `dashboard view --refresh`. +`sdk.log.tail()` always returns an `AsyncIterable`; `dashboard view` returns one when you +pass `--refresh`. Other methods return a `Promise`: ```typescript const sdk = createSentrySDK({ token: "sntrys_..." }); // Stream logs as they arrive (polls every 5 seconds) -for await (const log of sdk.log.list({ follow: "5" }, "acme/backend")) { +for await (const log of sdk.log.tail({ interval: 5 }, "acme/backend")) { console.log(log); } @@ -294,7 +295,7 @@ for await (const snapshot of sdk.run("dashboard", "view", "123", "--refresh", "3 } // Stop streaming by breaking out of the loop -for await (const log of sdk.log.list({ follow: "2" })) { +for await (const log of sdk.log.tail()) { if (someCondition) break; // Streaming stops immediately } ``` @@ -311,7 +312,7 @@ const sdk = createSentrySDK({ token: "...", signal: controller.signal }); // Cancel after 30 seconds setTimeout(() => controller.abort(), 30_000); -for await (const log of sdk.log.list({ follow: "5" })) { +for await (const log of sdk.log.tail({ interval: 5 })) { console.log(log); } // Loop exits when signal fires diff --git a/apps/cli-docs/src/fragments/commands/log.md b/apps/cli-docs/src/fragments/commands/log.md index 1d7d5048f1..a4dc41fa63 100644 --- a/apps/cli-docs/src/fragments/commands/log.md +++ b/apps/cli-docs/src/fragments/commands/log.md @@ -21,4 +21,4 @@ available scan accuracy. Use `--json` for machine-readable output. -In streaming mode with `--json`, each log entry is output as a separate JSON object (newline-delimited JSON), making it suitable for piping to other tools. +With `sentry log tail --json`, each log entry is output as a separate JSON object (newline-delimited JSON), making it suitable for piping to other tools. diff --git a/design/sentry-cli.md b/design/sentry-cli.md index e7c94929de..a407ff4d84 100644 --- a/design/sentry-cli.md +++ b/design/sentry-cli.md @@ -32,7 +32,12 @@ a terminal, with as little setup as the current project allows. - The CLI never prints a token in full. - Telemetry goes only to the Sentry CLI's own project, and `SENTRY_CLI_NO_TELEMETRY=1` or `DO_NOT_TRACK=1` turns it off. +- `-f` means `--fresh` in every command that can bypass the response cache, + and a cached result's footer names the flag that refreshes that command. +- Live output is its own command, such as `sentry log tail`, not a mode flag + on a list or view command. List and view commands return once. ## Gaps -None. +- `sentry dashboard view --refresh` keeps redrawing through a flag instead of + its own command. diff --git a/packages/cli/README.md b/packages/cli/README.md index 57a4151336..0fbc86249d 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -123,7 +123,7 @@ Options (all optional): - `text` — Return human-readable string instead of parsed JSON (affects `run()` only). - `cwd` — Working directory for DSN auto-detection. Defaults to `process.cwd()`. - `headers` — Extra HTTP headers for self-hosted instances behind a reverse proxy (same as `SENTRY_CUSTOM_HEADERS`). Ignored for sentry.io. -- `signal` — `AbortSignal` to cancel streaming commands (`--follow`, `--refresh`). +- `signal` — `AbortSignal` to cancel streaming commands (`log tail`, `dashboard view --refresh`). Streaming commands return `AsyncIterable` — use `for await...of` and `break` to stop. diff --git a/packages/cli/plugins/sentry-cli/skills/sentry-cli/SKILL.md b/packages/cli/plugins/sentry-cli/skills/sentry-cli/SKILL.md index c99c0b0000..aca9977978 100644 --- a/packages/cli/plugins/sentry-cli/skills/sentry-cli/SKILL.md +++ b/packages/cli/plugins/sentry-cli/skills/sentry-cli/SKILL.md @@ -127,7 +127,7 @@ sentry trace logs abc123def456... ```bash # Stream logs in real-time (auto-detects org/project) -sentry log list --follow +sentry log tail # Filter logs by severity sentry log list --query "severity:error" @@ -728,6 +728,7 @@ Manage User Feedback View Sentry logs - `sentry log list ` — List logs from a project +- `sentry log tail ` — Stream new logs from a project or trace - `sentry log view ` — View details of one or more log entries → Full flags and examples: `references/log.md` diff --git a/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/log.md b/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/log.md index 9b7590b48b..adeb66dd91 100644 --- a/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/log.md +++ b/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/log.md @@ -24,10 +24,9 @@ List logs from a project **Flags:** - `-n, --limit - Number of log entries (1-1000) - (default: "100")` - `-q, --query - Filter query (e.g., "severity:error", "project:backend", "project:[a,b]")` -- `-f, --follow - Stream logs (optionally specify poll interval in seconds)` - `-t, --period - Time range: "7d", "2024-01-01..2024-02-01", ">=2024-01-01"` - `-s, --sort - Sort order: "newest" (default) or "oldest" - (default: "newest")` -- `--fresh - Bypass cache, re-detect projects, and fetch fresh data` +- `-f, --fresh - Bypass cache, re-detect projects, and fetch fresh data` **JSON Fields** (use `--json --fields` to select specific fields): @@ -61,20 +60,56 @@ sentry log list --limit 50 # List logs for a trace sentry log list abc123def456abc123def456abc12345 +# Filter JSON output with jq +sentry log list --json | jq '.data[] | select(.severity == "error")' + +# Filter by trace in an explicit organization +sentry log list my-org/abc123def456abc123def456abc12345 +``` + +### `sentry log tail ` + +Stream new logs from a project or trace + +**Arguments:** + +| Argument | Description | +|----------|-------------| +| `` | [<org>/[<project>/]]<trace-id>, <org>/<project>, or <project> | + +**Flags:** +- `-n, --limit - Max log entries per poll (1-1000) - (default: "100")` +- `-q, --query - Filter query (e.g., "severity:error", "project:backend", "project:[a,b]")` +- `-i, --interval - Poll interval in seconds - (default: "2")` + +**JSON Fields** (use `--json --fields` to select specific fields): + +| Field | Type | Description | +|-------|------|-------------| +| `sentry.item_id` | string | Unique log entry ID | +| `timestamp` | string | Log timestamp (ISO 8601) | +| `timestamp_precise` | number | Nanosecond-precision timestamp | +| `message` | string \| null | Log message | +| `severity` | string \| null | Severity level (error, warning, info, debug) | +| `trace` | string \| null | Trace ID for correlation | + +**Examples:** + +```bash # Stream logs (2-second poll interval) -sentry log list -f +sentry log tail -# Stream logs (5-second poll interval) -sentry log list -f 5 +# Poll every 5 seconds +sentry log tail --interval 5 # Stream error logs from a specific project -sentry log list my-org/backend -f -q 'severity:error' +sentry log tail my-org/backend -q 'severity:error' -# Filter JSON output with jq -sentry log list --json | jq '.data[] | select(.severity == "error")' +# Stream the logs of a trace +sentry log tail abc123def456abc123def456abc12345 -# Filter by trace in an explicit organization -sentry log list my-org/abc123def456abc123def456abc12345 +# Stream JSONL for another tool +sentry log tail --json | jq 'select(.severity == "error")' ``` ### `sentry log view ` diff --git a/packages/cli/script/generate-sdk.ts b/packages/cli/script/generate-sdk.ts index 008f1d0c06..408238ad96 100644 --- a/packages/cli/script/generate-sdk.ts +++ b/packages/cli/script/generate-sdk.ts @@ -38,6 +38,10 @@ import { withJsDoc, } from "./ts-codegen.js"; import { logger } from "../src/lib/logger.js"; +import { + STREAMING_COMMANDS, + STREAMING_FLAGS, +} from "../src/lib/streaming-commands.js"; // --------------------------------------------------------------------------- // Configuration @@ -54,9 +58,6 @@ const INTERNAL_FLAGS = new Set([ "fields", ]); -/** Flags that trigger streaming mode — included in params but change return type */ -const STREAMING_FLAGS = new Set(["refresh", "follow"]); - /** Regex for stripping angle-bracket/ellipsis decorators from placeholder names */ const PLACEHOLDER_CLEAN_RE = /[<>.]/g; @@ -405,6 +406,8 @@ type SdkMethod = { flags: SdkFlagInfo[]; /** Flags that switch the command into streaming mode (`AsyncIterable` result). */ streamingFlags: SdkFlagInfo[]; + /** Whether the command always streams (`log tail`), whatever its flags. */ + alwaysStreams: boolean; /** Name of the params type, when the command has named params. */ paramsTypeName?: string | undefined; /** Whether a required flag makes the params object mandatory. */ @@ -413,6 +416,13 @@ type SdkMethod = { resultTypeName?: string | undefined; }; +/** `AsyncIterable`, the result of a streaming call. */ +function asyncIterableType(): ts.TypeNode { + return typeRef("AsyncIterable", [ + f.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword), + ]); +} + /** The method's result type (`FooResult`, or `unknown`). */ function resultType(method: SdkMethod): ts.TypeNode { return method.resultTypeName @@ -464,7 +474,7 @@ function methodParameters( /** * Params type for the streaming overload: the regular params with every streaming - * flag required (`LogListParams & { follow: string }`). + * flag required (`DashboardViewParams & { refresh: string }`). */ function streamingParamsType(method: SdkMethod): ts.TypeNode { const base = method.paramsTypeName @@ -487,6 +497,20 @@ function streamingParamsType(method: SdkMethod): ts.TypeNode { * signatures: passing a streaming flag returns an `AsyncIterable`, otherwise a `Promise`. */ function methodTypeMember(method: SdkMethod, name: string): ts.TypeElement { + if (method.alwaysStreams) { + return withJsDoc( + f.createMethodSignature( + undefined, + propertyName(name), + undefined, + undefined, + methodParameters(method), + asyncIterableType(), + ), + method.brief, + ); + } + const promise = typeRef("Promise", [resultType(method)]); if (method.streamingFlags.length === 0) { @@ -507,9 +531,7 @@ function methodTypeMember(method: SdkMethod, name: string): ts.TypeElement { f.createCallSignature( undefined, methodParameters(method, streamingParamsType(method)), - typeRef("AsyncIterable", [ - f.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword), - ]), + asyncIterableType(), ), f.createCallSignature(undefined, methodParameters(method), promise), ]); @@ -545,8 +567,15 @@ function positionalArgs(positional: PositionalInfo): ts.Expression { ); } -/** `invoke(path, flags, positional[, { streaming }])` */ -function invokeCall(method: SdkMethod, streaming: boolean): ts.CallExpression { +/** + * `invoke(path, flags, positional[, { streaming }])`. `streaming` picks + * `meta`: `"runtime"` passes the local `streaming` variable, `"always"` passes + * `true`, and omitting it passes no `meta` for commands that never stream. + */ +function invokeCall( + method: SdkMethod, + streaming?: "runtime" | "always", +): ts.CallExpression { const path = f.createArrayLiteralExpression( method.path.map((segment) => f.createStringLiteral(segment)), ); @@ -562,7 +591,9 @@ function invokeCall(method: SdkMethod, streaming: boolean): ts.CallExpression { if (streaming) { args.push( f.createObjectLiteralExpression([ - f.createShorthandPropertyAssignment("streaming"), + streaming === "always" + ? f.createPropertyAssignment("streaming", f.createTrue()) + : f.createShorthandPropertyAssignment("streaming"), ]), ); } @@ -589,11 +620,24 @@ function sdkMemberType(path: string[]): ts.TypeNode { * The method's implementation inside `createSDKMethods`. * * Regular commands narrow the invoker's `Promise | AsyncIterable` union to a `Promise`, - * since they never pass `meta.streaming`. Streaming commands decide at runtime whether a + * since they never pass `meta.streaming`; always-streaming commands narrow it to the + * `AsyncIterable`. Streaming commands decide at runtime whether a * streaming flag is present; a single arrow cannot express their overloads, so it is * asserted to the overloaded type declared in `SentrySDK`. */ function methodImplementation(method: SdkMethod): ts.Expression { + if (method.alwaysStreams) { + const iterable = asyncIterableType(); + return f.createArrowFunction( + undefined, + undefined, + methodParameters(method), + iterable, + undefined, + f.createAsExpression(invokeCall(method, "always"), iterable), + ); + } + const promise = typeRef("Promise", [resultType(method)]); if (method.streamingFlags.length === 0) { @@ -603,7 +647,7 @@ function methodImplementation(method: SdkMethod): ts.Expression { methodParameters(method), promise, undefined, - f.createAsExpression(invokeCall(method, false), promise), + f.createAsExpression(invokeCall(method), promise), ); } @@ -632,7 +676,7 @@ function methodImplementation(method: SdkMethod): ts.Expression { ts.NodeFlags.Const, ), ), - f.createReturnStatement(invokeCall(method, true)), + f.createReturnStatement(invokeCall(method, "runtime")), ], true, ); @@ -787,6 +831,7 @@ export async function emit(): Promise { positional, flags, streamingFlags: flags.filter((flag) => STREAMING_FLAGS.has(flag.name)), + alwaysStreams: STREAMING_COMMANDS.has(path.join(" ")), paramsTypeName: params?.name.text, paramsRequired: flags.some((flag) => !flag.optional), resultTypeName: returnType?.name.text, diff --git a/packages/cli/src/commands/log/index.ts b/packages/cli/src/commands/log/index.ts index d886987895..3d90120bd6 100644 --- a/packages/cli/src/commands/log/index.ts +++ b/packages/cli/src/commands/log/index.ts @@ -1,26 +1,29 @@ /** * sentry log * - * View and stream logs from Sentry projects. + * List, stream, and view logs from Sentry projects. */ import { buildRouteMap } from "../../lib/route-map.js"; import { topLevelBrief } from "../../top-level-briefs.js"; import { listCommand } from "./list.js"; +import { tailCommand } from "./tail.js"; import { viewCommand } from "./view.js"; export const logRoute = buildRouteMap({ routes: { list: listCommand, + tail: tailCommand, view: viewCommand, }, defaultCommand: "view", docs: { brief: topLevelBrief("log"), fullDescription: - "View and stream logs from your Sentry projects.\n\n" + + "List, stream, and view logs from your Sentry projects.\n\n" + "Commands:\n" + - " list List or stream logs from a project\n" + + " list List logs from a project\n" + + " tail Stream new logs from a project or trace\n" + " view View details of a specific log entry\n\n" + "Alias: `sentry logs` → `sentry log list`", hideRoute: {}, diff --git a/packages/cli/src/commands/log/list.ts b/packages/cli/src/commands/log/list.ts index 94d237a47c..9870c56d16 100644 --- a/packages/cli/src/commands/log/list.ts +++ b/packages/cli/src/commands/log/list.ts @@ -1,9 +1,8 @@ /** * sentry log list * - * List and stream logs from Sentry projects. - * Supports real-time streaming with --follow flag. - * Supports trace ID as a positional argument to filter logs by trace. + * List logs from Sentry projects, or the logs of a trace when the positional + * is a trace ID. `sentry log tail` streams new logs instead. */ import type { SentryContext } from "../../context.js"; @@ -15,34 +14,12 @@ import { import { sentry } from "../../lib/app-identity.js"; import { buildProjectQuery, - type ParsedOrgProject, parseLogSort, - parseOrgProjectInput, validateLimit, } from "../../lib/arg-parsing.js"; -import { ORG_PROJECT_TARGET, textParser } from "../../lib/completion-target.js"; -import { - AuthError, - stringifyUnknown, - toSearchQueryError, - ValidationError, -} from "../../lib/errors.js"; -import { - type LogLike as BaseLogLike, - buildLogRowCells, - createLogStreamingTable, - formatLogRow, - formatLogsHeader, - isPlainOutput, -} from "../../lib/formatters/index.js"; -import { filterFields } from "../../lib/formatters/json.js"; -import { renderInlineMarkdown } from "../../lib/formatters/markdown.js"; -import { - CommandOutput, - formatFooter, - type HumanRenderer, -} from "../../lib/formatters/output.js"; -import type { StreamingTable } from "../../lib/formatters/text-table.js"; +import { textParser } from "../../lib/completion-target.js"; +import { toSearchQueryError, ValidationError } from "../../lib/errors.js"; +import { CommandOutput } from "../../lib/formatters/output.js"; import { buildListCommand, LIST_MAX_LIMIT, @@ -50,16 +27,8 @@ import { TARGET_PATTERN_NOTE, } from "../../lib/list-command.js"; import { logger } from "../../lib/logger.js"; -import type { ListEnvelope } from "../../lib/org-list.js"; import { withProgress } from "../../lib/polling.js"; -import { - type BoundArguments, - boundArguments, -} from "../../lib/positional-parse.js"; -import { - resolveLogProjectId, - resolveProjectBoundTarget, -} from "../../lib/resolve-target.js"; +import { resolveLogProjectId } from "../../lib/resolve-target.js"; import { sanitizeQuery } from "../../lib/search-query.js"; import { PERIOD_BRIEF, @@ -69,22 +38,20 @@ import { type TimeRange, timeRangeToApiParams, } from "../../lib/time-range.js"; -import { applySentryUrlContext } from "../../lib/sentry-url-parser.js"; -import { - applyTraceTargetInput, - parseDualModeInput, - resolveTraceOrg, - type TraceTargetInput, - warnIfNormalized, -} from "../../lib/trace-target.js"; -import { getUpdateNotification } from "../../lib/version-check.js"; import { SentryLogSchema } from "../../generated/output-schemas/log.js"; -import { reportCliError } from "../../lib/error-reporting.js"; +import { + createLogRenderer, + jsonTransformLogOutput, + type LogListArguments, + type LogListResult, + logTargetArguments, +} from "./shared.js"; type ListFlags = { readonly limit: number; readonly query?: string; - readonly follow?: number; + /** Removed: streaming moved to `log tail`. Hidden, kept to say so. */ + readonly follow?: string; readonly period?: TimeRange; readonly sort: LogSortDirection; readonly json: boolean; @@ -92,35 +59,6 @@ type ListFlags = { readonly fields?: string[]; }; -/** - * Result yielded by the log list command in single-fetch mode. - * - * Contains the full array of logs and optional trace context. - * Follow mode yields bare {@link LogLike} items instead — see - * {@link LogOutput} for the union type. - */ -type LogListResult = { - logs: LogLike[]; - /** Trace ID, present for trace-filtered queries */ - traceId?: string; - /** Whether more results are available beyond the limit */ - hasMore: boolean; - /** Extra field names requested via `--fields`, used to render additional columns in human mode. */ - extraFields?: string[] | undefined; -}; - -/** Output yielded by log list: either a batch (single-fetch) or an individual item (follow). */ -type LogOutput = LogLike | LogListResult; - -/** Default poll interval in seconds for --follow mode */ -const DEFAULT_POLL_INTERVAL = 2; - -/** Command name used in resolver error messages */ -const COMMAND_NAME = "log list"; - -/** Usage hint for trace mode error messages */ -const traceUsageHint = () => sentry`log list [/[/]]`; - /** * Parse --limit flag, delegating range validation to shared utility. */ @@ -128,111 +66,12 @@ function parseLimit(value: string): number { return validateLimit(value, LIST_MIN_LIMIT, LIST_MAX_LIMIT); } -/** - * Parse --follow flag value. - * Supports: -f (empty string → default interval), -f 10 (explicit interval) - * - * @throws Error if value is not a positive integer - */ -function parseFollow(value: string): number { - if (value === "") { - return DEFAULT_POLL_INTERVAL; - } - const num = Number.parseInt(value, 10); - if (Number.isNaN(num) || num < 1) { - throw new Error("--follow interval must be a positive integer"); - } - return num; -} - -/** - * Extends the base {@link BaseLogLike} from formatters with the - * `timestamp_precise` field needed for follow-mode dedup tracking. - */ -type LogLike = BaseLogLike & { - /** Nanosecond-precision timestamp used for dedup in follow mode. - * Optional because TraceLog may omit it when the API response doesn't include it. */ - timestamp_precise?: number | undefined; -}; - /** Result from a single fetch: logs to yield + hint for the footer. */ type FetchResult = { result: LogListResult; hint: string; }; -// --------------------------------------------------------------------------- -// Positional argument disambiguation -// --------------------------------------------------------------------------- - -/** What `log list` lists, as parsed: a project's logs or a trace's. */ -type LogListInput = - | { - readonly mode: "project"; - readonly target: ParsedOrgProject; - /** Server of a pasted Sentry URL, for `applySentryUrlContext` */ - readonly baseUrl?: string | undefined; - } - | { readonly mode: "trace"; readonly trace: TraceTargetInput }; - -/** What `log list` lists, resolved. */ -type LogListTarget = - | { readonly mode: "project"; readonly org: string; readonly project: string } - | { - readonly mode: "trace"; - readonly org: string; - readonly traceId: string; - /** Project the user named, to filter the trace's logs by */ - readonly projectFilter?: string | undefined; - }; - -/** The arguments of `log list`. */ -type LogListArguments = BoundArguments; - -/** - * Disambiguate log list positional arguments with {@link parseDualModeInput} - * (trace mode when the arguments end in a trace ID). - */ -function parseLogListInput(args: readonly string[]): LogListInput { - const input = parseDualModeInput(args, traceUsageHint()); - if (input.mode === "trace") { - return input; - } - const { parsed, baseUrl } = parseOrgProjectInput(input.target); - return { mode: "project", target: parsed, baseUrl }; -} - -async function resolveLogListTarget( - input: LogListInput, - context: SentryContext, -): Promise { - if (input.mode === "trace") { - const parsed = applyTraceTargetInput(input.trace); - warnIfNormalized(parsed, "log.list"); - const { traceId, org } = await resolveTraceOrg( - parsed, - context.cwd, - "log list", - traceUsageHint(), - ); - return { - mode: "trace", - org, - traceId, - projectFilter: parsed.type === "explicit" ? parsed.project : undefined, - }; - } - if (input.baseUrl) { - applySentryUrlContext(input.baseUrl); - } - const { org, project } = await resolveProjectBoundTarget( - input.target, - context.cwd, - COMMAND_NAME, - ); - return { mode: "project", org, project }; -} - /** * Execute a single fetch of logs (non-streaming mode). * @@ -274,7 +113,9 @@ async function executeSingleFetch( const hasMore = logs.length >= flags.limit; const countText = `Showing ${logs.length} log${logs.length === 1 ? "" : "s"}.`; - const tip = hasMore ? " Use --limit to show more, or -f to follow." : ""; + const tip = hasMore + ? ` Use --limit to show more, or '${sentry`log tail`}' to stream new logs.` + : ""; return { result: { logs, hasMore, extraFields }, @@ -282,262 +123,6 @@ async function executeSingleFetch( }; } -// --------------------------------------------------------------------------- -// Streaming follow-mode infrastructure -// --------------------------------------------------------------------------- - -/** - * Sleep that resolves early when an AbortSignal fires. - * Resolves (not rejects) on abort for clean generator shutdown. - */ -function abortableSleep(ms: number, signal: AbortSignal): Promise { - return new Promise((resolve) => { - if (signal.aborted) { - resolve(); - return; - } - const onAbort = () => { - clearTimeout(timer); - resolve(); - }; - const timer = setTimeout(() => { - signal.removeEventListener("abort", onAbort); - resolve(); - }, ms); - signal.addEventListener("abort", onAbort, { once: true }); - }); -} - -/** - * Configuration for the follow-mode async generator. - * - * Parameterized over the log type to handle both project-scoped - * (`SentryLog`) and trace-scoped (`TraceLog`) streaming. - * - * Unlike the old callback-based approach, this does NOT include - * stdout/stderr. All stdout output flows through yielded chunks; - * diagnostics are reported via the `onDiagnostic` callback. - */ -type FollowGeneratorConfig = { - flags: ListFlags; - /** Report diagnostic/error messages (caller logs via logger) */ - onDiagnostic: (message: string) => void; - /** - * Fetch logs with the given time window. - * @param statsPeriod - Time window (e.g., "1m" for initial, "10m" for polls) - * @param afterTimestamp - Only return logs newer than this (nanoseconds). - * Standard mode passes this for server-side dedup; trace mode ignores it. - */ - fetch: (statsPeriod: string, afterTimestamp?: number) => Promise; - /** Extract only the genuinely new entries from a poll response */ - extractNew: (logs: T[], lastTimestamp: number) => T[]; - /** - * Called with the initial batch of logs before polling begins. - * Use this to seed dedup state (e.g., tracking seen log IDs). - */ - onInitialLogs?: (logs: T[]) => void; - /** - * External abort signal (library mode). When aborted, the follow - * generator stops on the next poll cycle. Complements SIGINT handling. - */ - abortSignal?: AbortSignal | undefined; -}; - -/** Find the highest timestamp_precise in a batch, or undefined if none have it. */ -function maxTimestamp(logs: LogLike[]): number | undefined { - let max: number | undefined; - for (const l of logs) { - if (l.timestamp_precise !== undefined) { - max = - max === undefined - ? l.timestamp_precise - : Math.max(max, l.timestamp_precise); - } - } - return max; -} - -/** - * Render a batch of log rows as a human-readable string. - * - * When a StreamingTable is provided (TTY mode), renders rows through the - * bordered table. Otherwise falls back to plain markdown rows. - * - * @param logs - Log entries to render - * @param includeTrace - Whether to append trace-ID suffix to messages - * @param table - Optional streaming table for TTY mode - * @param extraFields - Additional field names to render as extra columns - */ -function renderLogRows( - logs: LogLike[], - includeTrace: boolean, - table?: StreamingTable, - extraFields?: string[], -): string { - let text = ""; - for (const log of logs) { - if (table) { - text += table.row( - buildLogRowCells(log, true, includeTrace, extraFields).map( - renderInlineMarkdown, - ), - ); - } else { - text += formatLogRow(log, includeTrace, extraFields); - } - } - return text; -} - -/** - * Execute a single poll iteration in follow mode. - * - * Returns the new logs, or `undefined` if a transient error occurred - * (reported via `onDiagnostic`). Re-throws {@link AuthError} and - * {@link ValidationError} (a converted bad-`--query` 400). - */ -async function fetchPoll( - config: FollowGeneratorConfig, - lastTimestamp: number, -): Promise { - try { - const rawLogs = await config.fetch("10m", lastTimestamp); - return config.extractNew(rawLogs, lastTimestamp); - } catch (error) { - if (error instanceof AuthError) { - throw error; - } - // A ValidationError here is a converted search-query 400 (bad user - // --query). It is a user input mistake, not a transient fetch failure, so - // surface it and stop the stream rather than capturing it as a CLI bug. - if (error instanceof ValidationError) { - throw error; - } - reportCliError(error); - const message = stringifyUnknown(error); - config.onDiagnostic(`Error fetching logs: ${message}\n`); - return; - } -} - -/** - * Async generator that streams log entries via follow-mode polling. - * - * Yields batches of log entries (chronological order). The command - * unwraps each batch into individual {@link CommandOutput} yields so - * the OutputConfig formatters can handle incremental rendering and JSONL. - * - * The generator handles SIGINT via AbortController for clean shutdown. - * It never touches stdout — all data output flows through yielded batches - * and diagnostics use the `onDiagnostic` callback. - * - * @throws {AuthError} if the API returns an authentication error - */ -async function* generateFollowLogs( - config: FollowGeneratorConfig, -): AsyncGenerator { - const { flags } = config; - const pollInterval = flags.follow ?? DEFAULT_POLL_INTERVAL; - const pollIntervalMs = pollInterval * 1000; - - // timestamp_precise is nanoseconds; Date.now() is milliseconds → convert - let lastTimestamp = Date.now() * 1_000_000; - - // AbortController for clean SIGINT handling + library mode abort - const controller = new AbortController(); - const stop = () => controller.abort(); - process.once("SIGINT", stop); - - // Library mode: honor external abort signal (e.g., consumer break) - if (config.abortSignal) { - config.abortSignal.addEventListener("abort", stop, { once: true }); - } - - try { - // Initial fetch - const initialLogs = await config.fetch("1m"); - if (initialLogs.length > 0) { - yield [...initialLogs].reverse(); - } - lastTimestamp = maxTimestamp(initialLogs) ?? lastTimestamp; - config.onInitialLogs?.(initialLogs); - - // Poll loop — exits when SIGINT fires - for (;;) { - await abortableSleep(pollIntervalMs, controller.signal); - if (controller.signal.aborted) { - break; - } - - const newLogs = await fetchPoll(config, lastTimestamp); - if (newLogs && newLogs.length > 0) { - yield [...newLogs].reverse(); - lastTimestamp = maxTimestamp(newLogs) ?? lastTimestamp; - } - } - } finally { - process.removeListener("SIGINT", stop); - } -} - -/** - * Consume a project-scoped follow-mode generator, yielding items individually. - * - * When `extraFields` is provided, the first non-empty batch is yielded as a - * {@link LogListResult} so the human renderer can discover the extra columns - * and create a table with the right headers. Subsequent items are yielded - * bare for proper JSONL streaming. - */ -async function* yieldFollowItems( - generator: AsyncGenerator, - extraFields?: string[], -): AsyncGenerator, void, undefined> { - let contextSent = !extraFields?.length; - for await (const batch of generator) { - if (!contextSent && batch.length > 0) { - yield new CommandOutput({ - logs: batch, - hasMore: false, - extraFields, - }); - contextSent = true; - } else { - for (const item of batch) { - yield new CommandOutput(item); - } - } - } -} - -/** - * Consume a trace follow-mode generator, yielding items individually. - * - * The first non-empty batch is yielded as a {@link LogListResult} so - * the human renderer can detect `traceId` and hide the trace column. - * Subsequent items are yielded bare for proper JSONL streaming. - */ -async function* yieldTraceFollowItems( - generator: AsyncGenerator, - traceId: string, -): AsyncGenerator, void, undefined> { - let contextSent = false; - for await (const batch of generator) { - if (!contextSent && batch.length > 0) { - // First non-empty batch: yield as LogListResult to set trace context - yield new CommandOutput({ - logs: batch, - traceId, - hasMore: false, - }); - contextSent = true; - } else { - for (const item of batch) { - yield new CommandOutput(item); - } - } - } -} - /** Options for {@link executeTraceSingleFetch}. */ type TraceFetchOptions = { flags: ListFlags; @@ -605,174 +190,13 @@ async function executeTraceSingleFetch( }; } -/** - * Write the follow-mode banner via logger. Suppressed in JSON mode - * to avoid stderr noise when agents consume JSONL output. - */ -function writeFollowBanner( - pollInterval: number, - bannerText: string, - json: boolean, -): void { - if (json) { - return; - } - logger.info(`${bannerText} (poll interval: ${pollInterval}s)`); - logger.info("Press Ctrl+C to stop."); - const notification = getUpdateNotification(); - if (notification) { - logger.info(notification); - } -} - -// --------------------------------------------------------------------------- -// Output formatting -// --------------------------------------------------------------------------- - -/** - * Create a stateful human renderer for log list output. - * - * The factory is called once per command invocation. The returned renderer - * tracks streaming table state (header emitted, table instance) and cleans - * up via `finalize()`. - * - * All yields go through `render()` — both single-fetch and follow mode. - * The renderer emits the table header on the first non-empty batch, rows - * per batch, and the table footer + hint via `finalize()`. - * - * Discriminates between {@link LogListResult} (single-fetch or first trace - * follow batch) and bare {@link LogLike} items (follow mode). - */ -/** Shared discriminator for log output type. */ -function isLogListResult(data: LogOutput): data is LogListResult { - return "logs" in data && Array.isArray((data as LogListResult).logs); -} - -/** Mutable state for the log renderer, extracted to reduce cognitive complexity. */ -type LogRendererState = { - table: StreamingTable | undefined; - includeTrace: boolean; - headerEmitted: boolean; - extraFields: string[] | undefined; -}; - -/** Initialize table and column settings on the first non-empty render. */ -function initFirstRender( - state: LogRendererState, - data: LogOutput, - plain: boolean, -): void { - if (isLogListResult(data)) { - if (data.traceId) { - state.includeTrace = false; - } - state.extraFields = data.extraFields; - } - state.table = plain - ? undefined - : createLogStreamingTable({}, state.extraFields); - state.headerEmitted = true; -} - -function createLogRenderer(): HumanRenderer { - const plain = isPlainOutput(); - const state: LogRendererState = { - table: undefined, - includeTrace: true, - headerEmitted: false, - extraFields: undefined, - }; - - return { - render(data: LogOutput): string { - const logs: LogLike[] = isLogListResult(data) ? data.logs : [data]; - if (logs.length === 0) { - return ""; - } - - if (!state.headerEmitted) { - initFirstRender(state, data, plain); - let text = state.table - ? state.table.header() - : formatLogsHeader(state.extraFields); - text += renderLogRows( - logs, - state.includeTrace, - state.table, - state.extraFields, - ); - return text.trimEnd(); - } - - return renderLogRows( - logs, - state.includeTrace, - state.table, - state.extraFields, - ).trimEnd(); - }, - - finalize(hint?: string): string { - let text = ""; - - if (state.headerEmitted && state.table) { - text += state.table.footer(); - } - - if (hint) { - if (state.headerEmitted) { - text += `${text ? "\n" : ""}${formatFooter(hint)}`; - } else { - text += `${hint}\n`; - } - } - - return text; - }, - }; -} - -/** - * Transform log output into the JSON shape. - * - * Discriminates between {@link LogListResult} (single-fetch) and bare - * {@link LogLike} items (follow mode). Single-fetch yields a JSON envelope - * with `data` and `hasMore`; follow mode yields one JSON object per line (JSONL). - */ -function jsonTransformLogOutput( - data: LogOutput, - fields?: string[], -): ListEnvelope | Partial { - if (isLogListResult(data)) { - // Batch (single-fetch): return envelope with data + hasMore - const logList = data; - const items = - fields && fields.length > 0 - ? logList.logs.map((log) => filterFields(log, fields)) - : logList.logs; - return { data: items, hasMore: logList.hasMore }; - } - // Single item (follow mode): return bare object for JSONL - return fields && fields.length > 0 ? filterFields(data, fields) : data; -} - -/** Validate flag combinations that are invalid regardless of mode. */ -function validateFollowFlags(flags: ListFlags): void { - if (flags.follow && flags.sort === "oldest") { - throw new ValidationError( - '--sort "oldest" cannot be used with --follow. Follow mode streams new logs as they arrive.', - "sort", - ); - } -} - export const listCommand = buildListCommand( "log", { docs: { brief: "List logs from a project", fullDescription: - "List and stream logs from Sentry projects.\n\n" + + "List logs from Sentry projects. To stream new logs as they arrive, use `sentry log tail`.\n\n" + `${TARGET_PATTERN_NOTE}\n\n` + "Pass a 32-character trace ID instead of a project to filter by trace.\n\n" + "Alias: `sentry logs` → `sentry log list`", @@ -798,18 +222,6 @@ export const listCommand = buildListCommand( description: "List logs for a trace", run: "log list abc123def456abc123def456abc12345", }, - { - description: "Stream logs (2-second poll interval)", - run: "log list -f", - }, - { - description: "Stream logs (5-second poll interval)", - run: "log list -f 5", - }, - { - description: "Stream error logs from a specific project", - run: "log list my-org/backend -f -q 'severity:error'", - }, { description: "Filter JSON output with jq", run: "log list --json | jq '.data[] | select(.severity == \"error\")'", @@ -826,13 +238,7 @@ export const listCommand = buildListCommand( schema: SentryLogSchema, }, parameters: { - positional: boundArguments({ - placeholder: "org/project-or-trace-id", - brief: "[/[/]], /, or ", - kind: ORG_PROJECT_TARGET, - parse: parseLogListInput, - resolve: resolveLogListTarget, - }), + positional: logTargetArguments("log list"), flags: { limit: { kind: "parsed", @@ -849,10 +255,11 @@ export const listCommand = buildListCommand( }, follow: { kind: "parsed", - parse: textParser(parseFollow), - brief: "Stream logs (optionally specify poll interval in seconds)", + parse: textParser(String), + brief: "Removed: use `sentry log tail`", optional: true, inferEmpty: true, + hidden: true, }, period: { kind: "parsed", @@ -870,7 +277,6 @@ export const listCommand = buildListCommand( aliases: { n: "limit", q: "query", - f: "follow", t: "period", s: "sort", }, @@ -880,23 +286,19 @@ export const listCommand = buildListCommand( flags: ListFlags, target: LogListArguments, ) { - validateFollowFlags(flags); + if (flags.follow !== undefined) { + throw new ValidationError( + `--follow moved to its own command: ${sentry`log tail`}. ` + + "Pass the same target and --query; set the poll interval with --interval.", + "follow", + ); + } // Resolve mode-dependent default period const timeRange = flags.period ?? (target.parsed.mode === "trace" ? TIME_RANGE_14D : TIME_RANGE_30D); - // Follow mode streams live events via short polling intervals — - // absolute date ranges are silently ignored, so reject them entirely. - if (flags.follow && timeRange.type === "absolute") { - throw new ValidationError( - "--follow cannot be used with an absolute date range. " + - "Use a relative duration (e.g., --period 1h) or omit --period.", - "period", - ); - } - const resolved = await target.resolved; if (resolved.mode === "trace") { // Trace mode: use the org-scoped trace-logs endpoint. @@ -910,63 +312,6 @@ export const listCommand = buildListCommand( ); } - // Prepend project filter to the query when user explicitly specified a project - const traceQuery = buildProjectQuery(flags.query, projectFilter); - - if (flags.follow) { - // Banner (suppressed in JSON mode) - writeFollowBanner( - flags.follow ?? DEFAULT_POLL_INTERVAL, - `Streaming logs for trace ${traceId}...`, - flags.json, - ); - - // Track IDs of logs seen without timestamp_precise so they are - // shown once but not duplicated on subsequent polls. - const seenWithoutTs = new Set(); - const generator = generateFollowLogs({ - flags, - onDiagnostic: (msg) => logger.warn(msg), - abortSignal: (this.process as { abortSignal?: AbortSignal }) - .abortSignal, - fetch: (statsPeriod) => - listTraceLogs(org, traceId, { - query: traceQuery, - limit: flags.limit, - statsPeriod, - }).catch((error: unknown): never => { - // An unparseable user --query is a user input mistake, not a - // CLI bug — surface it as an actionable ValidationError. - throw toSearchQueryError(error, flags.query); - }), - extractNew: (logs, lastTs) => - logs.filter((l) => { - if (l.timestamp_precise !== undefined) { - return l.timestamp_precise > lastTs; - } - // No precise timestamp — deduplicate by id - if (!l.id) { - return true; // Can't dedup without id, include it - } - if (seenWithoutTs.has(l.id)) { - return false; - } - seenWithoutTs.add(l.id); - return true; - }), - onInitialLogs: (logs) => { - for (const l of logs) { - if (l.timestamp_precise === undefined && l.id) { - seenWithoutTs.add(l.id); - } - } - }, - }); - - yield* yieldTraceFollowItems(generator, traceId); - return; - } - const { result, hint } = await withProgress( { message: `Fetching logs (up to ${flags.limit})...`, @@ -990,38 +335,6 @@ export const listCommand = buildListCommand( // via the `project` param. The `project:` filter only matches // actively-selected projects and can otherwise return no logs (#1317). const projectId = await resolveLogProjectId(org, project); - if (flags.follow) { - writeFollowBanner( - flags.follow ?? DEFAULT_POLL_INTERVAL, - "Streaming logs...", - flags.json, - ); - - const generator = generateFollowLogs({ - flags, - onDiagnostic: (msg) => logger.warn(msg), - abortSignal: (this.process as { abortSignal?: AbortSignal }) - .abortSignal, - fetch: (statsPeriod, afterTimestamp) => - listLogs(org, project, { - query: flags.query, - limit: flags.limit, - statsPeriod, - afterTimestamp, - extraFields: flags.fields, - projectId, - }).catch((error: unknown): never => { - // An unparseable user --query is a user input mistake, not a - // CLI bug — surface it as an actionable ValidationError. - throw toSearchQueryError(error, flags.query); - }), - extractNew: (logs) => logs, - }); - - yield* yieldFollowItems(generator, flags.fields); - return; - } - const { result, hint } = await withProgress( { message: `Fetching logs (up to ${flags.limit})...`, @@ -1035,8 +348,5 @@ export const listCommand = buildListCommand( } }, }, - { - noCursorFlag: true, - noFreshAlias: true, - }, + { noCursorFlag: true }, ); diff --git a/packages/cli/src/commands/log/shared.ts b/packages/cli/src/commands/log/shared.ts new file mode 100644 index 0000000000..7370e4cf39 --- /dev/null +++ b/packages/cli/src/commands/log/shared.ts @@ -0,0 +1,324 @@ +/** + * Shared pieces of `sentry log list` and `sentry log tail`: the + * project-or-trace positional, the log output types, and their human and + * JSON renderers. + */ + +import type { SentryContext } from "../../context.js"; +import { sentry } from "../../lib/app-identity.js"; +import { + type ParsedOrgProject, + parseOrgProjectInput, +} from "../../lib/arg-parsing.js"; +import { ORG_PROJECT_TARGET } from "../../lib/completion-target.js"; +import { + type LogLike as BaseLogLike, + buildLogRowCells, + createLogStreamingTable, + formatLogRow, + formatLogsHeader, + isPlainOutput, +} from "../../lib/formatters/index.js"; +import { filterFields } from "../../lib/formatters/json.js"; +import { renderInlineMarkdown } from "../../lib/formatters/markdown.js"; +import { + formatFooter, + type HumanRenderer, +} from "../../lib/formatters/output.js"; +import type { StreamingTable } from "../../lib/formatters/text-table.js"; +import type { ListEnvelope } from "../../lib/org-list.js"; +import { + type BoundArguments, + boundArguments, +} from "../../lib/positional-parse.js"; +import { resolveProjectBoundTarget } from "../../lib/resolve-target.js"; +import { applySentryUrlContext } from "../../lib/sentry-url-parser.js"; +import { + applyTraceTargetInput, + parseDualModeInput, + resolveTraceOrg, + type TraceTargetInput, + warnIfNormalized, +} from "../../lib/trace-target.js"; + +/** + * Extends the base {@link BaseLogLike} from formatters with the + * `timestamp_precise` field needed for `log tail` dedup tracking. + */ +export type LogLike = BaseLogLike & { + /** Nanosecond-precision timestamp used for dedup in `log tail`. + * Optional because TraceLog may omit it when the API response doesn't include it. */ + timestamp_precise?: number | undefined; +}; + +/** + * A batch of logs: everything `log list` yields, and the first batch of + * `log tail` when the renderer needs its context. `log tail` yields bare + * {@link LogLike} items after that, see {@link LogOutput}. + */ +export type LogListResult = { + logs: LogLike[]; + /** Trace ID, present for trace-filtered queries */ + traceId?: string; + /** Whether more results are available beyond the limit */ + hasMore: boolean; + /** Extra field names requested via `--fields`, used to render additional columns in human mode. */ + extraFields?: string[] | undefined; +}; + +/** Output of a log command: a batch, or an individual item (`log tail`). */ +export type LogOutput = LogLike | LogListResult; + +/** Usage hint for trace mode error messages */ +const traceUsageHint = (commandName: string) => + sentry`${commandName} [/[/]]`; + +/** What a log command reads, as parsed: a project's logs or a trace's. */ +type LogListInput = + | { + readonly mode: "project"; + readonly target: ParsedOrgProject; + /** Server of a pasted Sentry URL, for `applySentryUrlContext` */ + readonly baseUrl?: string | undefined; + } + | { readonly mode: "trace"; readonly trace: TraceTargetInput }; + +/** What a log command reads, resolved. */ +type LogListTarget = + | { readonly mode: "project"; readonly org: string; readonly project: string } + | { + readonly mode: "trace"; + readonly org: string; + readonly traceId: string; + /** Project the user named, to filter the trace's logs by */ + readonly projectFilter?: string | undefined; + }; + +/** The arguments of `log list` and `log tail`. */ +export type LogListArguments = BoundArguments; + +/** The log commands that take a project-or-trace target. */ +type LogCommandName = "log list" | "log tail"; + +/** + * Disambiguate log list and log tail positional arguments with {@link parseDualModeInput} + * (trace mode when the arguments end in a trace ID). + */ +function parseLogListInput( + args: readonly string[], + commandName: LogCommandName, +): LogListInput { + const input = parseDualModeInput(args, traceUsageHint(commandName)); + if (input.mode === "trace") { + return input; + } + const { parsed, baseUrl } = parseOrgProjectInput(input.target); + return { mode: "project", target: parsed, baseUrl }; +} + +/** Resolve a parsed log target to an org and a project or trace. */ +async function resolveLogListTarget( + input: LogListInput, + context: SentryContext, + commandName: LogCommandName, +): Promise { + if (input.mode === "trace") { + const parsed = applyTraceTargetInput(input.trace); + warnIfNormalized(parsed, commandName.replace(" ", ".")); + const { traceId, org } = await resolveTraceOrg( + parsed, + context.cwd, + commandName, + traceUsageHint(commandName), + ); + return { + mode: "trace", + org, + traceId, + projectFilter: parsed.type === "explicit" ? parsed.project : undefined, + }; + } + if (input.baseUrl) { + applySentryUrlContext(input.baseUrl); + } + const { org, project } = await resolveProjectBoundTarget( + input.target, + context.cwd, + commandName, + ); + return { mode: "project", org, project }; +} + +/** + * The positional of `log list` and `log tail`: a project, or a trace ID with + * an optional `/[/]` prefix. + */ +export function logTargetArguments(commandName: LogCommandName) { + return boundArguments({ + placeholder: "org/project-or-trace-id", + brief: "[/[/]], /, or ", + kind: ORG_PROJECT_TARGET, + parse: (args: readonly string[]) => parseLogListInput(args, commandName), + resolve: (input: LogListInput, context: SentryContext) => + resolveLogListTarget(input, context, commandName), + }); +} + +/** + * Render a batch of log rows as a human-readable string. + * + * When a StreamingTable is provided (TTY mode), renders rows through the + * bordered table. Otherwise falls back to plain markdown rows. + * + * @param logs - Log entries to render + * @param includeTrace - Whether to append trace-ID suffix to messages + * @param table - Optional streaming table for TTY mode + * @param extraFields - Additional field names to render as extra columns + */ +function renderLogRows( + logs: LogLike[], + includeTrace: boolean, + table?: StreamingTable, + extraFields?: string[], +): string { + let text = ""; + for (const log of logs) { + if (table) { + text += table.row( + buildLogRowCells(log, true, includeTrace, extraFields).map( + renderInlineMarkdown, + ), + ); + } else { + text += formatLogRow(log, includeTrace, extraFields); + } + } + return text; +} + +/** Shared discriminator for log output type. */ +function isLogListResult(data: LogOutput): data is LogListResult { + return "logs" in data && Array.isArray((data as LogListResult).logs); +} + +/** Mutable state for the log renderer, extracted to reduce cognitive complexity. */ +type LogRendererState = { + table: StreamingTable | undefined; + includeTrace: boolean; + headerEmitted: boolean; + extraFields: string[] | undefined; +}; + +/** Initialize table and column settings on the first non-empty render. */ +function initFirstRender( + state: LogRendererState, + data: LogOutput, + plain: boolean, +): void { + if (isLogListResult(data)) { + if (data.traceId) { + state.includeTrace = false; + } + state.extraFields = data.extraFields; + } + state.table = plain + ? undefined + : createLogStreamingTable({}, state.extraFields); + state.headerEmitted = true; +} + +/** + * Create a stateful human renderer for log list and log tail output. + * + * The factory is called once per command invocation. The returned renderer + * tracks streaming table state (header emitted, table instance) and cleans + * up via `finalize()`. + * + * All yields go through `render()` — from both commands. + * The renderer emits the table header on the first non-empty batch, rows + * per batch, and the table footer + hint via `finalize()`. + * + * Discriminates between {@link LogListResult} (`log list`, or the first + * `log tail` batch) and bare {@link LogLike} items (`log tail`). + */ +export function createLogRenderer(): HumanRenderer { + const plain = isPlainOutput(); + const state: LogRendererState = { + table: undefined, + includeTrace: true, + headerEmitted: false, + extraFields: undefined, + }; + + return { + render(data: LogOutput): string { + const logs: LogLike[] = isLogListResult(data) ? data.logs : [data]; + if (logs.length === 0) { + return ""; + } + + if (!state.headerEmitted) { + initFirstRender(state, data, plain); + let text = state.table + ? state.table.header() + : formatLogsHeader(state.extraFields); + text += renderLogRows( + logs, + state.includeTrace, + state.table, + state.extraFields, + ); + return text.trimEnd(); + } + + return renderLogRows( + logs, + state.includeTrace, + state.table, + state.extraFields, + ).trimEnd(); + }, + + finalize(hint?: string): string { + let text = ""; + + if (state.headerEmitted && state.table) { + text += state.table.footer(); + } + + if (hint) { + if (state.headerEmitted) { + text += `${text ? "\n" : ""}${formatFooter(hint)}`; + } else { + text += `${hint}\n`; + } + } + + return text; + }, + }; +} + +/** + * Transform log output into the JSON shape. + * + * Discriminates between {@link LogListResult} (single-fetch) and bare + * {@link LogLike} items (follow mode). Single-fetch yields a JSON envelope + * with `data` and `hasMore`; follow mode yields one JSON object per line (JSONL). + */ +export function jsonTransformLogOutput( + data: LogOutput, + fields?: string[], +): ListEnvelope | Partial { + if (isLogListResult(data)) { + // Batch (single-fetch): return envelope with data + hasMore + const logList = data; + const items = + fields && fields.length > 0 + ? logList.logs.map((log) => filterFields(log, fields)) + : logList.logs; + return { data: items, hasMore: logList.hasMore }; + } + // Single item (follow mode): return bare object for JSONL + return fields && fields.length > 0 ? filterFields(data, fields) : data; +} diff --git a/packages/cli/src/commands/log/tail.ts b/packages/cli/src/commands/log/tail.ts new file mode 100644 index 0000000000..66fe4fe13b --- /dev/null +++ b/packages/cli/src/commands/log/tail.ts @@ -0,0 +1,472 @@ +/** + * sentry log tail + * + * Stream new logs from a Sentry project or trace as they arrive, like + * `tail -f`. `sentry log list` fetches one batch; this command keeps polling + * until Ctrl+C. + */ + +import type { SentryContext } from "../../context.js"; +import { listLogs, listTraceLogs } from "../../lib/api-client.js"; +import { buildProjectQuery, validateLimit } from "../../lib/arg-parsing.js"; +import { buildCommand } from "../../lib/command.js"; +import { textParser } from "../../lib/completion-target.js"; +import { + AuthError, + stringifyUnknown, + toSearchQueryError, + ValidationError, +} from "../../lib/errors.js"; +import { CommandOutput } from "../../lib/formatters/output.js"; +import { + LIST_MAX_LIMIT, + LIST_MIN_LIMIT, + TARGET_PATTERN_NOTE, +} from "../../lib/list-command.js"; +import { logger } from "../../lib/logger.js"; +import { resolveLogProjectId } from "../../lib/resolve-target.js"; +import { sanitizeQuery } from "../../lib/search-query.js"; +import { getUpdateNotification } from "../../lib/version-check.js"; +import { SentryLogSchema } from "../../generated/output-schemas/log.js"; +import { reportCliError } from "../../lib/error-reporting.js"; +import { + createLogRenderer, + jsonTransformLogOutput, + type LogLike, + type LogListArguments, + type LogOutput, + logTargetArguments, +} from "./shared.js"; + +type TailFlags = { + readonly limit: number; + readonly query?: string; + readonly interval: number; + readonly json: boolean; + readonly fields?: string[]; +}; + +/** Default poll interval in seconds */ +const DEFAULT_POLL_INTERVAL = 2; + +/** Parse --limit, delegating range validation to the shared utility. */ +function parseLimit(value: string): number { + return validateLimit(value, LIST_MIN_LIMIT, LIST_MAX_LIMIT); +} + +/** + * Parse the --interval flag: a poll interval in whole seconds. + * + * @throws Error if value is not a positive integer + */ +function parseInterval(value: string): number { + const num = Number(value); + if (!Number.isInteger(num) || num < 1) { + throw new Error("--interval must be a positive integer (seconds)"); + } + return num; +} + +/** + * Sleep that resolves early when an AbortSignal fires. + * Resolves (not rejects) on abort for clean generator shutdown. + */ +function abortableSleep(ms: number, signal: AbortSignal): Promise { + return new Promise((resolve) => { + if (signal.aborted) { + resolve(); + return; + } + const onAbort = () => { + clearTimeout(timer); + resolve(); + }; + const timer = setTimeout(() => { + signal.removeEventListener("abort", onAbort); + resolve(); + }, ms); + signal.addEventListener("abort", onAbort, { once: true }); + }); +} + +/** + * Configuration for the polling async generator. + * + * Parameterized over the log type to handle both project-scoped + * (`SentryLog`) and trace-scoped (`TraceLog`) streaming. + * + * Unlike the old callback-based approach, this does NOT include + * stdout/stderr. All stdout output flows through yielded chunks; + * diagnostics are reported via the `onDiagnostic` callback. + */ +type FollowGeneratorConfig = { + flags: TailFlags; + /** Report diagnostic/error messages (caller logs via logger) */ + onDiagnostic: (message: string) => void; + /** + * Fetch logs with the given time window. + * @param statsPeriod - Time window (e.g., "1m" for initial, "10m" for polls) + * @param afterTimestamp - Only return logs newer than this (nanoseconds). + * Standard mode passes this for server-side dedup; trace mode ignores it. + */ + fetch: (statsPeriod: string, afterTimestamp?: number) => Promise; + /** Extract only the genuinely new entries from a poll response */ + extractNew: (logs: T[], lastTimestamp: number) => T[]; + /** + * Called with the initial batch of logs before polling begins. + * Use this to seed dedup state (e.g., tracking seen log IDs). + */ + onInitialLogs?: (logs: T[]) => void; + /** + * External abort signal (library mode). When aborted, the + * generator stops on the next poll cycle. Complements SIGINT handling. + */ + abortSignal?: AbortSignal | undefined; +}; + +/** Find the highest timestamp_precise in a batch, or undefined if none have it. */ +function maxTimestamp(logs: LogLike[]): number | undefined { + let max: number | undefined; + for (const l of logs) { + if (l.timestamp_precise !== undefined) { + max = + max === undefined + ? l.timestamp_precise + : Math.max(max, l.timestamp_precise); + } + } + return max; +} + +/** + * Execute a single poll iteration. + * + * Returns the new logs, or `undefined` if a transient error occurred + * (reported via `onDiagnostic`). Re-throws {@link AuthError} and + * {@link ValidationError} (a converted bad-`--query` 400). + */ +async function fetchPoll( + config: FollowGeneratorConfig, + lastTimestamp: number, +): Promise { + try { + const rawLogs = await config.fetch("10m", lastTimestamp); + return config.extractNew(rawLogs, lastTimestamp); + } catch (error) { + if (error instanceof AuthError) { + throw error; + } + // A ValidationError here is a converted search-query 400 (bad user + // --query). It is a user input mistake, not a transient fetch failure, so + // surface it and stop the stream rather than capturing it as a CLI bug. + if (error instanceof ValidationError) { + throw error; + } + reportCliError(error); + const message = stringifyUnknown(error); + config.onDiagnostic(`Error fetching logs: ${message}\n`); + return; + } +} + +/** + * Async generator that streams log entries by polling. + * + * Yields batches of log entries (chronological order). The command + * unwraps each batch into individual {@link CommandOutput} yields so + * the OutputConfig formatters can handle incremental rendering and JSONL. + * + * The generator handles SIGINT via AbortController for clean shutdown. + * It never touches stdout — all data output flows through yielded batches + * and diagnostics use the `onDiagnostic` callback. + * + * @throws {AuthError} if the API returns an authentication error + */ +async function* generateFollowLogs( + config: FollowGeneratorConfig, +): AsyncGenerator { + const { flags } = config; + const pollIntervalMs = flags.interval * 1000; + + // timestamp_precise is nanoseconds; Date.now() is milliseconds → convert + let lastTimestamp = Date.now() * 1_000_000; + + // AbortController for clean SIGINT handling + library mode abort + const controller = new AbortController(); + const stop = () => controller.abort(); + process.once("SIGINT", stop); + + // Library mode: honor external abort signal (e.g., consumer break) + if (config.abortSignal) { + config.abortSignal.addEventListener("abort", stop, { once: true }); + } + + try { + // Initial fetch + const initialLogs = await config.fetch("1m"); + if (initialLogs.length > 0) { + yield [...initialLogs].reverse(); + } + lastTimestamp = maxTimestamp(initialLogs) ?? lastTimestamp; + config.onInitialLogs?.(initialLogs); + + // Poll loop — exits when SIGINT fires + for (;;) { + await abortableSleep(pollIntervalMs, controller.signal); + if (controller.signal.aborted) { + break; + } + + const newLogs = await fetchPoll(config, lastTimestamp); + if (newLogs && newLogs.length > 0) { + yield [...newLogs].reverse(); + lastTimestamp = maxTimestamp(newLogs) ?? lastTimestamp; + } + } + } finally { + process.removeListener("SIGINT", stop); + } +} + +/** + * Consume a project-scoped polling generator, yielding items individually. + * + * When `extraFields` is provided, the first non-empty batch is yielded as a + * {@link LogListResult} so the human renderer can discover the extra columns + * and create a table with the right headers. Subsequent items are yielded + * bare for proper JSONL streaming. + */ +async function* yieldFollowItems( + generator: AsyncGenerator, + extraFields?: string[], +): AsyncGenerator, void, undefined> { + let contextSent = !extraFields?.length; + for await (const batch of generator) { + if (!contextSent && batch.length > 0) { + yield new CommandOutput({ + logs: batch, + hasMore: false, + extraFields, + }); + contextSent = true; + } else { + for (const item of batch) { + yield new CommandOutput(item); + } + } + } +} + +/** + * Consume a trace polling generator, yielding items individually. + * + * The first non-empty batch is yielded as a {@link LogListResult} so + * the human renderer can detect `traceId` and hide the trace column. + * Subsequent items are yielded bare for proper JSONL streaming. + */ +async function* yieldTraceFollowItems( + generator: AsyncGenerator, + traceId: string, +): AsyncGenerator, void, undefined> { + let contextSent = false; + for await (const batch of generator) { + if (!contextSent && batch.length > 0) { + // First non-empty batch: yield as LogListResult to set trace context + yield new CommandOutput({ + logs: batch, + traceId, + hasMore: false, + }); + contextSent = true; + } else { + for (const item of batch) { + yield new CommandOutput(item); + } + } + } +} + +/** + * Write the streaming banner via logger. Suppressed in JSON mode + * to avoid stderr noise when agents consume JSONL output. + */ +function writeFollowBanner( + pollInterval: number, + bannerText: string, + json: boolean, +): void { + if (json) { + return; + } + logger.info(`${bannerText} (poll interval: ${pollInterval}s)`); + logger.info("Press Ctrl+C to stop."); + const notification = getUpdateNotification(); + if (notification) { + logger.info(notification); + } +} + +export const tailCommand = buildCommand({ + docs: { + brief: "Stream new logs from a project or trace", + fullDescription: + "Stream new logs as they arrive, like `tail -f`. Polls until Ctrl+C.\n\n" + + "Prints the logs of the last minute, then every new log on each poll. " + + "With --json, writes one JSON object per line (JSONL).\n\n" + + `${TARGET_PATTERN_NOTE}\n\n` + + "Pass a 32-character trace ID instead of a project to stream a trace's logs.", + examples: [ + { description: "Stream logs (2-second poll interval)", run: "log tail" }, + { + description: "Poll every 5 seconds", + run: "log tail --interval 5", + }, + { + description: "Stream error logs from a specific project", + run: "log tail my-org/backend -q 'severity:error'", + }, + { + description: "Stream the logs of a trace", + run: "log tail abc123def456abc123def456abc12345", + }, + { + description: "Stream JSONL for another tool", + run: "log tail --json | jq 'select(.severity == \"error\")'", + }, + ], + }, + output: { + human: createLogRenderer, + jsonTransform: jsonTransformLogOutput, + schema: SentryLogSchema, + }, + parameters: { + positional: logTargetArguments("log tail"), + flags: { + limit: { + kind: "parsed", + parse: textParser(parseLimit), + brief: `Max log entries per poll (${LIST_MIN_LIMIT}-${LIST_MAX_LIMIT})`, + default: "100", + }, + query: { + kind: "parsed", + parse: sanitizeQuery, + brief: + 'Filter query (e.g., "severity:error", "project:backend", "project:[a,b]")', + optional: true, + }, + interval: { + kind: "parsed", + parse: textParser(parseInterval), + brief: "Poll interval in seconds", + default: String(DEFAULT_POLL_INTERVAL), + }, + }, + aliases: { + n: "limit", + q: "query", + i: "interval", + }, + }, + async *func(this: SentryContext, flags: TailFlags, target: LogListArguments) { + const abortSignal = (this.process as { abortSignal?: AbortSignal }) + .abortSignal; + const resolved = await target.resolved; + + if (resolved.mode === "trace") { + // Trace mode: use the org-scoped trace-logs endpoint. + const { traceId, org, projectFilter } = resolved; + + // The trace-logs endpoint has a fixed field set and doesn't support + // arbitrary extra fields. + if (flags.fields?.length) { + logger.warn( + "--fields is not supported for trace-scoped log queries. Use project-scoped mode instead.", + ); + } + + // Prepend project filter to the query when user explicitly specified a project + const traceQuery = buildProjectQuery(flags.query, projectFilter); + + writeFollowBanner( + flags.interval, + `Streaming logs for trace ${traceId}...`, + flags.json, + ); + + // Track IDs of logs seen without timestamp_precise so they are + // shown once but not duplicated on subsequent polls. + const seenWithoutTs = new Set(); + const generator = generateFollowLogs({ + flags, + onDiagnostic: (msg) => logger.warn(msg), + abortSignal, + fetch: (statsPeriod) => + listTraceLogs(org, traceId, { + query: traceQuery, + limit: flags.limit, + statsPeriod, + }).catch((error: unknown): never => { + // An unparseable user --query is a user input mistake, not a + // CLI bug — surface it as an actionable ValidationError. + throw toSearchQueryError(error, flags.query); + }), + extractNew: (logs, lastTs) => + logs.filter((l) => { + if (l.timestamp_precise !== undefined) { + return l.timestamp_precise > lastTs; + } + // No precise timestamp — deduplicate by id + if (!l.id) { + return true; // Can't dedup without id, include it + } + if (seenWithoutTs.has(l.id)) { + return false; + } + seenWithoutTs.add(l.id); + return true; + }), + onInitialLogs: (logs) => { + for (const l of logs) { + if (l.timestamp_precise === undefined && l.id) { + seenWithoutTs.add(l.id); + } + } + }, + }); + + yield* yieldTraceFollowItems(generator, traceId); + return; + } + + const { org, project } = resolved; + // Resolve the slug to a numeric project ID so the Events query scopes + // via the `project` param. The `project:` filter only matches + // actively-selected projects and can otherwise return no logs (#1317). + const projectId = await resolveLogProjectId(org, project); + writeFollowBanner(flags.interval, "Streaming logs...", flags.json); + + const generator = generateFollowLogs({ + flags, + onDiagnostic: (msg) => logger.warn(msg), + abortSignal, + fetch: (statsPeriod, afterTimestamp) => + listLogs(org, project, { + query: flags.query, + limit: flags.limit, + statsPeriod, + afterTimestamp, + extraFields: flags.fields, + projectId, + }).catch((error: unknown): never => { + // An unparseable user --query is a user input mistake, not a + // CLI bug — surface it as an actionable ValidationError. + throw toSearchQueryError(error, flags.query); + }), + extractNew: (logs) => logs, + }); + + yield* yieldFollowItems(generator, flags.fields); + }, +}); diff --git a/packages/cli/src/lib/cache-hint.ts b/packages/cli/src/lib/cache-hint.ts index 8d7e4df87a..8576a7b096 100644 --- a/packages/cli/src/lib/cache-hint.ts +++ b/packages/cli/src/lib/cache-hint.ts @@ -7,9 +7,9 @@ * commands don't need to call this themselves. * * The refresh flag named in the hint is derived from each command's own - * parameters via {@link resolveRefreshFlag}, never hardcoded: commands - * like `log list` bind `-f` to `--follow`, so a fixed `-f` would point - * users at the wrong flag. + * parameters via {@link resolveRefreshFlag}, never hardcoded, so the hint + * names `--fresh` when a command has no `-f` for it and drops the + * suggestion when the command cannot bypass the cache at all. * * getsentry/cli#785 item #1 — `-f/--fresh` flag discoverability. * diff --git a/packages/cli/src/lib/list-command.ts b/packages/cli/src/lib/list-command.ts index f190d4043d..375faa22f5 100644 --- a/packages/cli/src/lib/list-command.ts +++ b/packages/cli/src/lib/list-command.ts @@ -208,8 +208,8 @@ export const FRESH_FLAG = { * aliases: { ...FRESH_ALIASES, w: "web" } * ``` * - * **Note**: Commands that use `-f` for a different flag (e.g. `log list` - * uses `-f` for `--follow`) should NOT spread this constant. + * A command with `--fresh` must not bind `-f` to anything else; see + * `design/sentry-cli.md` and `test/lib/short-flag-conventions.test.ts`. */ export const FRESH_ALIASES = { f: "fresh" } as const; @@ -498,13 +498,12 @@ type BaseFlags = Readonly>>; * Options for controlling which flags {@link buildListCommand} auto-injects. * * By default, `buildListCommand` adds `--fresh`, `--cursor`, and their aliases - * (`-f`, `-c`). Use these options to opt out when a command has conflicts. + * (`-f`, `-c`). `-f` always means `--fresh` (see `design/sentry-cli.md`), so + * only the cursor flag can be opted out. */ export type ListCommandOptions = { - /** Skip injecting `--cursor` flag and `-c` alias (e.g., log list uses streaming). */ + /** Skip injecting `--cursor` flag and `-c` alias (e.g., log list has no pagination). */ noCursorFlag?: boolean; - /** Skip injecting `-f` alias for `--fresh` (e.g., log list uses `-f` for `--follow`). */ - noFreshAlias?: boolean; }; /** @@ -514,7 +513,7 @@ export type ListCommandOptions = { * This is a drop-in replacement for `buildCommand` that: * 1. Intercepts subcommand names passed through plural aliases * 2. Auto-injects `--fresh` and `--cursor` flags (unless already defined) - * 3. Auto-injects `-f` and `-c` aliases (with opt-outs via `options`) + * 3. Auto-injects `-f` and `-c` aliases (`-c` can be opted out via `options`) * 4. Auto-calls `applyFreshFlag(flags)` before the command function runs * * Commands that define their own `cursor` or `fresh` flags (e.g., with a @@ -563,8 +562,8 @@ export function buildListCommand< mergedFlags["cursor"] = LIST_CURSOR_FLAG; } - // Inject -f alias unless opted out or already defined - if (!(options?.noFreshAlias || "f" in mergedAliases)) { + // Inject -f alias unless already defined + if (!("f" in mergedAliases)) { mergedAliases["f"] = "fresh"; } diff --git a/packages/cli/src/lib/sdk-invoke.ts b/packages/cli/src/lib/sdk-invoke.ts index b53e34145c..49e3d09271 100644 --- a/packages/cli/src/lib/sdk-invoke.ts +++ b/packages/cli/src/lib/sdk-invoke.ts @@ -21,14 +21,7 @@ import { type AsyncChannel, createAsyncChannel } from "./async-channel.js"; import { NO_PERSISTENCE_ENV_VAR, withInvocation } from "./env.js"; import { stringifyUnknown } from "./errors.js"; import { SentryError, type SentryOptions } from "./sdk-types.js"; - -/** CLI flag names/aliases that trigger infinite streaming output. */ -const STREAMING_FLAG_NAMES = new Set(["--refresh", "--follow", "-f"]); - -/** Check if CLI args contain any streaming flag. */ -function hasStreamingFlag(args: string[]): boolean { - return args.some((arg) => STREAMING_FLAG_NAMES.has(arg)); -} +import { isStreamingInvocation } from "./streaming-commands.js"; /** * Build an isolated env from options, starting from `options.env` or the @@ -560,7 +553,7 @@ function executeWithStream( * zero-copy capture, and error wrapping — used by the typed SDK methods. * * When `meta.streaming` is true, returns an AsyncIterable that yields - * values as the command produces them (for `--follow`/`--refresh` commands). + * values as the command produces them (`log tail`, `dashboard view --refresh`). */ export function buildInvoker(options?: SentryOptions) { return function invokeCommand( @@ -614,14 +607,14 @@ export function buildInvoker(options?: SentryOptions) { * typed SDK methods (or for passing raw CLI flags). * * Returns parsed JSON by default, or trimmed text for commands - * without JSON support. When streaming flags are detected, returns - * an AsyncIterable instead. + * without JSON support. Returns an AsyncIterable instead for a streaming + * command or flag (see `streaming-commands.ts`). */ export function buildRunner(options?: SentryOptions) { return function run( ...args: string[] ): Promise | AsyncIterable { - if (hasStreamingFlag(args)) { + if (isStreamingInvocation(args)) { return executeWithStream(options, async (ctx, span) => { const { run: stricliRun } = await import("@stricli/core"); const { loadSdkApp } = await import("../sdk-app.js"); diff --git a/packages/cli/src/lib/streaming-commands.ts b/packages/cli/src/lib/streaming-commands.ts new file mode 100644 index 0000000000..3782e69929 --- /dev/null +++ b/packages/cli/src/lib/streaming-commands.ts @@ -0,0 +1,40 @@ +/** + * Which commands stream output until stopped, for the library SDK. + * + * A streaming command returns an `AsyncIterable` from the SDK instead of a + * `Promise`. `script/generate-sdk.ts` reads this module to type the generated + * methods, and `sdk.run()` reads it to pick the same return shape at runtime, + * so the two cannot disagree. + * + * Live output gets its own command (`log tail`), not a mode flag on a list + * command; see `design/sentry-cli.md`. `--refresh` on `dashboard view` is the + * one flag that still switches a command into streaming. + * + * @module + */ + +/** Flag names that switch a command into streaming mode. */ +export const STREAMING_FLAGS: ReadonlySet = new Set(["refresh"]); + +/** Commands, as space-separated route paths, that always stream. */ +export const STREAMING_COMMANDS: ReadonlySet = new Set(["log tail"]); + +/** + * Whether raw CLI arguments run a streaming command or pass a streaming flag. + * + * Matches the route path against the leading arguments, so `log tail ...` + * streams while `log list ...` does not. + */ +export function isStreamingInvocation(args: readonly string[]): boolean { + for (const path of STREAMING_COMMANDS) { + const segments = path.split(" "); + if (segments.every((segment, index) => args[index] === segment)) { + return true; + } + } + return args.some( + (arg) => + arg.startsWith("--") && + STREAMING_FLAGS.has(arg.slice(2).split("=")[0] ?? ""), + ); +} diff --git a/packages/cli/test/commands/log/list.test.ts b/packages/cli/test/commands/log/list.test.ts index 824c03415b..606f81f605 100644 --- a/packages/cli/test/commands/log/list.test.ts +++ b/packages/cli/test/commands/log/list.test.ts @@ -6,19 +6,13 @@ * - Trace-filtered mode (positional 32-char hex trace-id) * - Positional argument disambiguation (trace vs project) * - Period flag behavior - * - Follow/streaming mode for both standard and trace modes + * - The removed --follow flag pointing at `sentry log tail` * * Uses spyOn mocking to avoid real HTTP calls or database access. - * Follow-mode tests use SIGINT to cleanly stop the setTimeout-based - * poll loop — the promise resolves on SIGINT (normal termination). - * AuthError tests verify that fetch failures reject the promise. - * - * Non-follow (single-fetch) tests mock `withProgress` from `polling.ts` - * to bypass the spinner. Follow-mode tests do NOT mock `withProgress` - * because follow mode uses its own streaming banner, not the spinner. + * Tests mock `withProgress` from `polling.ts` to bypass the spinner. + * Streaming lives in `sentry log tail`, tested in tail.test.ts. */ -import { setTimeout as sleep } from "node:timers/promises"; import { afterEach, beforeEach, @@ -51,23 +45,10 @@ vi.mock("../../../src/lib/db/auth.js", async (importOriginal) => { import * as dbAuth from "../../../src/lib/db/auth.js"; import { ApiError, - AuthError, ContextError, ValidationError, } from "../../../src/lib/errors.js"; -vi.mock("../../../src/lib/formatters/index.js", async (importOriginal) => { - const actual = - await importOriginal< - typeof import("../../../src/lib/formatters/index.js") - >(); - const { mockFunctionExports } = await import("../../mock-exports.js"); - return mockFunctionExports(actual); -}); - -// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking -import * as formatters from "../../../src/lib/formatters/index.js"; - vi.mock("../../../src/lib/polling.js", async (importOriginal) => { const actual = await importOriginal(); @@ -99,22 +80,8 @@ vi.mock("../../../src/lib/trace-target.js", async (importOriginal) => { // oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking import * as traceTarget from "../../../src/lib/trace-target.js"; -vi.mock("../../../src/lib/version-check.js", async (importOriginal) => { - const actual = - await importOriginal(); - const { mockFunctionExports } = await import("../../mock-exports.js"); - return mockFunctionExports(actual); -}); - -// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking -import * as versionCheck from "../../../src/lib/version-check.js"; import type { SentryLog, TraceLog } from "../../../src/types/sentry.js"; -import { - loadCommand, - at, - must, - passthroughWithProgress, -} from "../../helpers.js"; +import { loadCommand, passthroughWithProgress } from "../../helpers.js"; import type { Writer } from "../../../src/types/index.js"; // ============================================================================ @@ -125,59 +92,6 @@ const TRACE_ID = "aaaa1111bbbb2222cccc3333dddd4444"; const ORG = "test-org"; const PROJECT = "test-project"; -/** - * Intercept `process.once("SIGINT", handler)` registrations so tests can - * invoke the handler directly without sending a real signal (which would - * kill the Bun test runner). - * - * Must be created BEFORE the code under test runs. Call `trigger()` to - * simulate SIGINT, and `restore()` in afterEach. - */ -function interceptSigint() { - let handler: ((...args: unknown[]) => void) | null = null; - const originalOnce = process.once.bind(process); - const spy = vi.spyOn(process, "once").mockImplementation((( - event: string, - fn: (...args: unknown[]) => void, - ) => { - if (event === "SIGINT") { - handler = fn; - return process; - } - return originalOnce(event, fn); - }) as typeof process.once); - - // Also intercept removeListener so AuthError path works - const originalRemoveListener = process.removeListener.bind(process); - const removeSpy = vi.spyOn(process, "removeListener").mockImplementation((( - event: string, - fn: (...args: unknown[]) => void, - ) => { - if (event === "SIGINT" && fn === handler) { - handler = null; - return process; - } - return originalRemoveListener(event, fn); - }) as typeof process.removeListener); - - return { - /** Invoke the captured SIGINT handler (simulates Ctrl+C) */ - trigger() { - if (handler) { - const h = handler; - handler = null; - h(); - } - }, - /** Restore original process.once and process.removeListener */ - restore() { - spy.mockRestore(); - removeSpy.mockRestore(); - handler = null; - }, - }; -} - function createMockContext() { const stdoutWrite = vi.fn(() => true); const stderrWrite = vi.fn(() => true); @@ -193,14 +107,14 @@ function createMockContext() { }; } -/** Standard flags for non-follow batch mode (period omitted = use mode default) */ +/** Standard flags for batch mode (period omitted = use mode default) */ const BATCH_FLAGS = { json: true, limit: 100, sort: "newest", } as const; -/** Human-mode flags for non-follow batch mode (period omitted = use mode default) */ +/** Human-mode flags for batch mode (period omitted = use mode default) */ const HUMAN_FLAGS = { json: false, limit: 100, @@ -269,32 +183,6 @@ const sampleTraceLogs: TraceLog[] = [ }, ]; -/** Newer trace logs for polling tests — uses far-future timestamp to always be "newer" */ -const newerTraceLogs: TraceLog[] = [ - { - id: "log004", - "project.id": 1, - trace: TRACE_ID, - severity_number: 9, - severity: "info", - timestamp: "2099-01-30T14:32:20+00:00", - timestamp_precise: 4_073_000_000_000_000_000, - message: "New poll result", - }, -]; - -/** Newer project logs for polling tests — uses far-future timestamp */ -const newerLogs: SentryLog[] = [ - { - "sentry.item_id": "item004", - timestamp: "2099-01-30T14:32:20+00:00", - timestamp_precise: 4_073_000_000_000_000_000, - severity: "info", - message: "New poll result", - trace: "aaaa1111bbbb2222cccc3333dddd4444", - }, -]; - // ============================================================================ // Auth setup — mock getAuthConfig for all tests (auth guard added in #611) // ============================================================================ @@ -934,638 +822,20 @@ describe("listCommand.func — trace mode org resolution failure", () => { }); // ============================================================================ -// Follow mode — standard (--follow, project-scoped) -// -// Strategy: SIGINT resolves the promise (normal termination). AuthError -// from fetch rejects the promise. Tests use interceptSigint() to capture -// the SIGINT handler and invoke it directly (process.emit("SIGINT") -// kills the Bun test runner). -// -// Follow mode does NOT use withProgress (it has its own streaming banner), -// so withProgress is NOT mocked here. -// ============================================================================ - -/** - * Collect all output written to a `process.stderr.write` spy. - * Handles both string and Buffer arguments from the logger. - */ -function collectProcessStderr( - spy: MockInstance<(typeof process.stderr)["write"]>, -): string { - return spy.mock.calls - .map((c) => { - const arg = c[0]; - if (typeof arg === "string") { - return arg; - } - if (arg instanceof Uint8Array) { - return new TextDecoder().decode(arg); - } - return String(arg); - }) - .join(""); -} - -// ============================================================================ -// Flag validation +// Removed --follow flag // ============================================================================ -describe("listCommand.func — flag validation", () => { - test("rejects --sort oldest with --follow", async () => { - const { context } = createMockContext(); - const func = await loadCommand(listCommand); - await expect( - func.call( - context, - { json: false, limit: 100, follow: 2, sort: "oldest" }, - "my-org/my-project", - ), - ).rejects.toThrow(ValidationError); - }); - - test("allows --sort newest with --follow", async () => { - // Should not throw ValidationError — the error (if any) comes from - // downstream resolution, not flag validation. Mock resolution to reject - // with a non-ValidationError so we can verify flag validation passed. - const resolveOrgProjectSpy = vi - .spyOn(resolveTarget, "resolveProjectBoundTarget") - .mockRejectedValueOnce( - new ContextError("Organization", "sentry log list"), - ); +describe("listCommand.func — removed --follow", () => { + test("points at sentry log tail before resolving anything", async () => { + const resolveSpy = vi.spyOn(resolveTarget, "resolveProjectBoundTarget"); const { context } = createMockContext(); const func = await loadCommand(listCommand); - await expect( - func.call( - context, - { json: false, limit: 100, follow: 2, sort: "newest" }, - "my-org/my-project", - ), - ).rejects.not.toThrow(ValidationError); - resolveOrgProjectSpy.mockRestore(); - }); -}); - -// ============================================================================ -// Follow mode — standard (project-scoped) -// ============================================================================ - -describe("listCommand.func — follow mode (standard)", () => { - let listLogsSpy: MockInstance<(typeof apiClient)["listLogs"]>; - let resolveOrgProjectSpy: MockInstance< - (typeof resolveTarget)["resolveProjectBoundTarget"] - >; - let isPlainSpy: MockInstance<(typeof formatters)["isPlainOutput"]>; - let updateNotifSpy: MockInstance< - (typeof versionCheck)["getUpdateNotification"] - >; - let sigint: ReturnType; - let stderrSpy: MockInstance<(typeof process.stderr)["write"]>; - - beforeEach(() => { - sigint = interceptSigint(); - listLogsSpy = vi.spyOn(apiClient, "listLogs"); - resolveOrgProjectSpy = vi.spyOn(resolveTarget, "resolveProjectBoundTarget"); - vi.spyOn(resolveTarget, "resolveLogProjectId").mockResolvedValue(undefined); - isPlainSpy = vi.spyOn(formatters, "isPlainOutput").mockReturnValue(true); - updateNotifSpy = vi - .spyOn(versionCheck, "getUpdateNotification") - .mockReturnValue(null); - stderrSpy = vi - .spyOn(process.stderr, "write") - .mockImplementation(() => true); - }); - - afterEach(() => { - listLogsSpy.mockRestore(); - resolveOrgProjectSpy.mockRestore(); - isPlainSpy.mockRestore(); - updateNotifSpy.mockRestore(); - stderrSpy.mockRestore(); - sigint.restore(); - }); - - /** Follow flags with 1-second interval (minimum real-world value) */ - const followFlags = { - json: false, - limit: 100, - follow: 1, - sort: "newest", - } as const; - - test("writes initial logs then resolves on SIGINT", async () => { - listLogsSpy.mockResolvedValueOnce(sampleLogs); - resolveOrgProjectSpy.mockResolvedValue({ org: ORG, project: PROJECT }); - - const { context, stdoutWrite } = createMockContext(); - const func = await loadCommand(listCommand); - - const promise = func.call(context, followFlags, `${ORG}/${PROJECT}`); - await sleep(50); - sigint.trigger(); - await promise; - - const output = stdoutWrite.mock.calls.map((c) => c[0]).join(""); - expect(output).toContain("Request received"); - }); - - test("converts a bad --query 400 to a ValidationError in follow mode", async () => { - // The follow-mode fetch closure wraps listLogs with toSearchQueryError, so - // a bad user --query surfaces as a ValidationError on the initial fetch and - // terminates the stream instead of being reported as a CLI bug. - listLogsSpy.mockRejectedValueOnce( - new ApiError("bad", 400, "Error parsing search query: bad field"), - ); - resolveOrgProjectSpy.mockResolvedValue({ org: ORG, project: PROJECT }); - - const { context } = createMockContext(); - const func = await loadCommand(listCommand); - - await expect( - func.call( - context, - { ...followFlags, query: "bad:::query" }, - `${ORG}/${PROJECT}`, - ), - ).rejects.toBeInstanceOf(ValidationError); - }); - - test("SIGINT during initial fetch does not start poll loop", async () => { - // fetchInitial will hang until we resolve it manually - let resolveFetch!: (logs: typeof sampleLogs) => void; - listLogsSpy.mockReturnValueOnce( - new Promise((resolve) => { - resolveFetch = resolve; - }), - ); - resolveOrgProjectSpy.mockResolvedValue({ org: ORG, project: PROJECT }); - - const { context } = createMockContext(); - const func = await loadCommand(listCommand); - - const promise = func.call(context, followFlags, `${ORG}/${PROJECT}`); - await sleep(10); - - // SIGINT fires while fetchInitial is still pending - sigint.trigger(); - await sleep(10); - - // Now resolve the fetch — the .then() should NOT schedule a poll - resolveFetch(sampleLogs); - await promise; - - // If the bug existed, a timer would be scheduled. Wait to confirm none fires. - await sleep(50); - - // Only 1 call to listLogs (the initial fetch). No poll calls. - expect(listLogsSpy).toHaveBeenCalledTimes(1); - }); - - test("writes stderr banner in human follow mode", async () => { - listLogsSpy.mockResolvedValueOnce([]); - resolveOrgProjectSpy.mockResolvedValue({ org: ORG, project: PROJECT }); - - const { context } = createMockContext(); - const func = await loadCommand(listCommand); - - const promise = func.call(context, followFlags, `${ORG}/${PROJECT}`); - await sleep(50); - sigint.trigger(); - await promise; - - // Banner now goes through logger → process.stderr - const stderr = collectProcessStderr(stderrSpy); - expect(stderr).toContain("Streaming logs"); - expect(stderr).toContain("Ctrl+C"); - }); - - test("skips stderr banner in JSON follow mode", async () => { - listLogsSpy.mockResolvedValueOnce([]); - resolveOrgProjectSpy.mockResolvedValue({ org: ORG, project: PROJECT }); - - const { context } = createMockContext(); - const func = await loadCommand(listCommand); - - const promise = func.call( - context, - { ...followFlags, json: true }, - `${ORG}/${PROJECT}`, - ); - await sleep(50); - sigint.trigger(); - await promise; - - // Banner now goes through logger → process.stderr - const stderr = collectProcessStderr(stderrSpy); - expect(stderr).not.toContain("Streaming logs"); - }); - - test("writes new logs from poll iteration", async () => { - // Initial: sampleLogs, first poll: newerLogs - listLogsSpy - .mockResolvedValueOnce(sampleLogs) - .mockResolvedValueOnce(newerLogs); - resolveOrgProjectSpy.mockResolvedValue({ org: ORG, project: PROJECT }); - - const { context, stdoutWrite } = createMockContext(); - const func = await loadCommand(listCommand); - - const promise = func.call(context, followFlags, `${ORG}/${PROJECT}`); - // Wait for initial fetch + poll timer (1s) + poll execution - await sleep(1200); - sigint.trigger(); - await promise; - - const output = stdoutWrite.mock.calls.map((c) => c[0]).join(""); - // Both initial and polled logs should appear - expect(output).toContain("Request received"); - expect(output).toContain("New poll result"); - }); - - test("streams JSON objects per-line in follow mode", async () => { - listLogsSpy.mockResolvedValueOnce(sampleLogs); - resolveOrgProjectSpy.mockResolvedValue({ org: ORG, project: PROJECT }); - - const { context, stdoutWrite } = createMockContext(); - const func = await loadCommand(listCommand); - - const promise = func.call( - context, - { ...followFlags, json: true }, - `${ORG}/${PROJECT}`, - ); - await sleep(50); - sigint.trigger(); - await promise; - - // Each log should be written as a separate JSON object (streaming NDJSON) - const calls = stdoutWrite.mock.calls.map((c) => String(c[0])); - const jsonObjects = calls.filter((s: string) => { - try { - JSON.parse(s); - return true; - } catch { - return false; - } - }); - expect(jsonObjects.length).toBe(3); - }); - - test("rejects with AuthError from initial fetch", async () => { - listLogsSpy.mockRejectedValueOnce(new AuthError("expired")); - resolveOrgProjectSpy.mockResolvedValue({ org: ORG, project: PROJECT }); - - const { context } = createMockContext(); - const func = await loadCommand(listCommand); - - await expect( - func.call(context, followFlags, `${ORG}/${PROJECT}`), - ).rejects.toThrow(AuthError); - }); - - test("rejects with AuthError from poll", async () => { - listLogsSpy - .mockResolvedValueOnce([]) - .mockRejectedValueOnce(new AuthError("expired")); - resolveOrgProjectSpy.mockResolvedValue({ org: ORG, project: PROJECT }); - - const { context } = createMockContext(); - const func = await loadCommand(listCommand); - - await expect( - func.call(context, followFlags, `${ORG}/${PROJECT}`), - ).rejects.toThrow(AuthError); - }); - - test("continues polling after transient error (non-auth)", async () => { - // Initial: empty, poll 1: transient error, then SIGINT - listLogsSpy - .mockResolvedValueOnce([]) - .mockRejectedValueOnce(new Error("network timeout")); - resolveOrgProjectSpy.mockResolvedValue({ org: ORG, project: PROJECT }); - - const { context } = createMockContext(); - const func = await loadCommand(listCommand); - - const promise = func.call(context, followFlags, `${ORG}/${PROJECT}`); - // Wait for initial fetch + poll timer (1s) + poll execution - await sleep(1200); - sigint.trigger(); - await promise; - - // Transient error now goes through logger → process.stderr - const stderr = collectProcessStderr(stderrSpy); - expect(stderr).toContain("Error fetching logs"); - expect(stderr).toContain("network timeout"); - }); - - test("uses 1m statsPeriod for initial follow fetch", async () => { - listLogsSpy.mockResolvedValueOnce([]); - resolveOrgProjectSpy.mockResolvedValue({ org: ORG, project: PROJECT }); - - const { context } = createMockContext(); - const func = await loadCommand(listCommand); - - const promise = func.call(context, followFlags, `${ORG}/${PROJECT}`); - await sleep(50); - sigint.trigger(); - await promise; - - // Initial fetch should use "1m" (short window for follow mode) - expect(listLogsSpy.mock.calls[0]).toEqual([ - ORG, - PROJECT, - { query: undefined, limit: 100, statsPeriod: "1m" }, - ]); - }); - - test("passes afterTimestamp to poll calls", async () => { - // maxTimestamp scans the entire batch for the highest timestamp_precise - const maxTs = Math.max(...sampleLogs.map((l) => l.timestamp_precise)); - listLogsSpy.mockResolvedValueOnce(sampleLogs).mockResolvedValueOnce([]); - resolveOrgProjectSpy.mockResolvedValue({ org: ORG, project: PROJECT }); - - const { context } = createMockContext(); - const func = await loadCommand(listCommand); - - const promise = func.call(context, followFlags, `${ORG}/${PROJECT}`); - // Wait for initial fetch + poll timer (1s) + poll execution - await sleep(1200); - sigint.trigger(); - await promise; - - // Poll call (index 1) should include afterTimestamp from max in batch - const pollCall = at(listLogsSpy.mock.calls, 1); - expect(pollCall).toBeDefined(); - expect(must(pollCall[2]).afterTimestamp).toBe(maxTs); - expect(must(pollCall[2]).statsPeriod).toBe("10m"); - }); - - test("shows update notification when available", async () => { - updateNotifSpy.mockReturnValue("Update available: v2.0.0\n"); - listLogsSpy.mockResolvedValueOnce([]); - resolveOrgProjectSpy.mockResolvedValue({ org: ORG, project: PROJECT }); - - const { context } = createMockContext(); - const func = await loadCommand(listCommand); - - const promise = func.call(context, followFlags, `${ORG}/${PROJECT}`); - await sleep(50); - sigint.trigger(); - await promise; - - // Update notification now goes through logger → process.stderr - const stderr = collectProcessStderr(stderrSpy); - expect(stderr).toContain("Update available: v2.0.0"); - }); -}); - -// ============================================================================ -// Follow mode — trace (--follow + positional trace-id) -// ============================================================================ - -describe("listCommand.func — follow mode (trace)", () => { - let listTraceLogsSpy: MockInstance<(typeof apiClient)["listTraceLogs"]>; - let resolveTraceOrgSpy: MockInstance<(typeof traceTarget)["resolveTraceOrg"]>; - let warnIfNormalizedSpy: MockInstance< - (typeof traceTarget)["warnIfNormalized"] - >; - let isPlainSpy: MockInstance<(typeof formatters)["isPlainOutput"]>; - let updateNotifSpy: MockInstance< - (typeof versionCheck)["getUpdateNotification"] - >; - let sigint: ReturnType; - let stderrSpy: MockInstance<(typeof process.stderr)["write"]>; - - beforeEach(() => { - sigint = interceptSigint(); - listTraceLogsSpy = vi.spyOn(apiClient, "listTraceLogs"); - resolveTraceOrgSpy = vi.spyOn(traceTarget, "resolveTraceOrg"); - warnIfNormalizedSpy = vi - .spyOn(traceTarget, "warnIfNormalized") - .mockReturnValue(undefined); - isPlainSpy = vi.spyOn(formatters, "isPlainOutput").mockReturnValue(true); - updateNotifSpy = vi - .spyOn(versionCheck, "getUpdateNotification") - .mockReturnValue(null); - stderrSpy = vi - .spyOn(process.stderr, "write") - .mockImplementation(() => true); - }); - - afterEach(() => { - listTraceLogsSpy.mockRestore(); - resolveTraceOrgSpy.mockRestore(); - warnIfNormalizedSpy.mockRestore(); - isPlainSpy.mockRestore(); - updateNotifSpy.mockRestore(); - stderrSpy.mockRestore(); - sigint.restore(); - }); - - const traceFollowFlags = { - json: false, - limit: 100, - follow: 1, - sort: "newest", - } as const; - - test("writes initial trace logs then resolves on SIGINT", async () => { - listTraceLogsSpy.mockResolvedValueOnce(sampleTraceLogs); - resolveTraceOrgSpy.mockResolvedValue({ traceId: TRACE_ID, org: ORG }); - - const { context, stdoutWrite } = createMockContext(); - const func = await loadCommand(listCommand); - - const promise = func.call(context, traceFollowFlags, TRACE_ID); - await sleep(50); - sigint.trigger(); - await promise; - - const output = stdoutWrite.mock.calls.map((c) => c[0]).join(""); - expect(output).toContain("Request received"); - }); - - test("writes stderr banner with trace ID in follow mode", async () => { - listTraceLogsSpy.mockResolvedValueOnce([]); - resolveTraceOrgSpy.mockResolvedValue({ traceId: TRACE_ID, org: ORG }); - - const { context } = createMockContext(); - const func = await loadCommand(listCommand); - - const promise = func.call(context, traceFollowFlags, TRACE_ID); - await sleep(50); - sigint.trigger(); - await promise; - - // Banner now goes through logger → process.stderr - const stderr = collectProcessStderr(stderrSpy); - expect(stderr).toContain("Streaming logs"); - expect(stderr).toContain(TRACE_ID); - expect(stderr).toContain("Ctrl+C"); - }); - - test("filters new logs by timestamp_precise (dedup)", async () => { - // Initial fetch returns logs, poll returns mix of old+new - const mixedLogs: TraceLog[] = [ - ...sampleTraceLogs, // old — should be filtered out - ...newerTraceLogs, // new — should pass filter - ]; - listTraceLogsSpy - .mockResolvedValueOnce(sampleTraceLogs) - .mockResolvedValueOnce(mixedLogs); - resolveTraceOrgSpy.mockResolvedValue({ traceId: TRACE_ID, org: ORG }); - - const { context, stdoutWrite } = createMockContext(); - const func = await loadCommand(listCommand); - - const promise = func.call(context, traceFollowFlags, TRACE_ID); - // Wait for initial fetch + poll timer (1s) + poll execution - await sleep(1200); - sigint.trigger(); - await promise; - - const output = stdoutWrite.mock.calls.map((c) => c[0]).join(""); - // New log should appear - expect(output).toContain("New poll result"); - // Count total log writes — initial 3 + 1 new from poll - // (old logs from poll are filtered by timestamp_precise) - }); - - test("streams JSON in trace follow mode: first batch as array, then bare items", async () => { - listTraceLogsSpy - .mockResolvedValueOnce(sampleTraceLogs) - .mockResolvedValueOnce(newerTraceLogs); - resolveTraceOrgSpy.mockResolvedValue({ traceId: TRACE_ID, org: ORG }); - - const { context, stdoutWrite } = createMockContext(); - const func = await loadCommand(listCommand); - - const promise = func.call( - context, - { ...traceFollowFlags, json: true }, - TRACE_ID, - ); - // Wait for initial fetch + poll timer (1s) + poll execution - await sleep(1200); - sigint.trigger(); - await promise; - - const calls = stdoutWrite.mock.calls.map((c) => String(c[0])); - const jsonLines = calls.filter((s: string) => { - try { - JSON.parse(s); - return true; - } catch { - return false; - } - }); - // First batch: 1 JSON line (envelope with data array from LogListResult) - // Poll batch: 1 JSON line per item (bare JSONL) - expect(jsonLines.length).toBe(2); - // First line is an envelope with data array (the initial trace batch) - const firstBatch = JSON.parse(at(jsonLines, 0)); - expect(firstBatch).toHaveProperty("data"); - expect(Array.isArray(firstBatch.data)).toBe(true); - expect(firstBatch.data).toHaveLength(3); - // Second line is a bare object (polled item) - const pollItem = JSON.parse(at(jsonLines, 1)); - expect(pollItem.message).toBe("New poll result"); - }); - - test("rejects with AuthError from poll", async () => { - listTraceLogsSpy - .mockResolvedValueOnce([]) - .mockRejectedValueOnce(new AuthError("expired")); - resolveTraceOrgSpy.mockResolvedValue({ traceId: TRACE_ID, org: ORG }); - - const { context } = createMockContext(); - const func = await loadCommand(listCommand); - - await expect( - func.call(context, traceFollowFlags, TRACE_ID), - ).rejects.toThrow(AuthError); - }); - - test("continues polling after transient error (trace mode)", async () => { - listTraceLogsSpy - .mockResolvedValueOnce([]) - .mockRejectedValueOnce(new Error("server error")); - resolveTraceOrgSpy.mockResolvedValue({ traceId: TRACE_ID, org: ORG }); - - const { context } = createMockContext(); - const func = await loadCommand(listCommand); - - const promise = func.call(context, traceFollowFlags, TRACE_ID); - // Wait for initial fetch + poll timer (1s) + poll execution - await sleep(1200); - sigint.trigger(); - await promise; - - // Transient error now goes through logger → process.stderr - const stderr = collectProcessStderr(stderrSpy); - expect(stderr).toContain("Error fetching logs"); - expect(stderr).toContain("server error"); - }); - - test("uses 1m statsPeriod for initial trace follow fetch", async () => { - listTraceLogsSpy.mockResolvedValueOnce([]); - resolveTraceOrgSpy.mockResolvedValue({ traceId: TRACE_ID, org: ORG }); - - const { context } = createMockContext(); - const func = await loadCommand(listCommand); - - const promise = func.call(context, traceFollowFlags, TRACE_ID); - await sleep(50); - sigint.trigger(); - await promise; - - expect(listTraceLogsSpy.mock.calls[0]).toEqual([ - ORG, - TRACE_ID, - { query: undefined, limit: 100, statsPeriod: "1m" }, - ]); - }); - - test("does not pass afterTimestamp to trace poll calls (dedup via filter)", async () => { - listTraceLogsSpy - .mockResolvedValueOnce(sampleTraceLogs) - .mockResolvedValueOnce([]); - resolveTraceOrgSpy.mockResolvedValue({ traceId: TRACE_ID, org: ORG }); - - const { context } = createMockContext(); - const func = await loadCommand(listCommand); - - const promise = func.call(context, traceFollowFlags, TRACE_ID); - // Wait for initial fetch + poll timer (1s) + poll execution - await sleep(1200); - sigint.trigger(); - await promise; - - // Poll call (index 1) should NOT have afterTimestamp - // (trace-logs endpoint doesn't support it) - const pollCall = at(listTraceLogsSpy.mock.calls, 1); - expect(pollCall).toBeDefined(); - expect(Reflect.get(must(pollCall[2]), "afterTimestamp")).toBeUndefined(); - expect(must(pollCall[2]).statsPeriod).toBe("10m"); - }); - - test("handles empty initial fetch then new logs in poll", async () => { - // Initial: empty, poll: new logs - listTraceLogsSpy - .mockResolvedValueOnce([]) - .mockResolvedValueOnce(newerTraceLogs); - resolveTraceOrgSpy.mockResolvedValue({ traceId: TRACE_ID, org: ORG }); - - const { context, stdoutWrite } = createMockContext(); - const func = await loadCommand(listCommand); - - const promise = func.call(context, traceFollowFlags, TRACE_ID); - // Wait for initial fetch + poll timer (1s) + poll execution - await sleep(1200); - sigint.trigger(); - await promise; - - const output = stdoutWrite.mock.calls.map((c) => c[0]).join(""); - expect(output).toContain("New poll result"); + const error = await func + .call(context, { ...HUMAN_FLAGS, follow: "" }, `${ORG}/${PROJECT}`) + .catch((e: unknown) => e); + expect(error).toBeInstanceOf(ValidationError); + expect((error as ValidationError).message).toContain("log tail"); + expect(resolveSpy).not.toHaveBeenCalled(); + resolveSpy.mockRestore(); }); }); diff --git a/packages/cli/test/commands/log/tail.test.ts b/packages/cli/test/commands/log/tail.test.ts new file mode 100644 index 0000000000..65ee519ad6 --- /dev/null +++ b/packages/cli/test/commands/log/tail.test.ts @@ -0,0 +1,867 @@ +/** + * Log Tail Command Tests + * + * Tests for the `sentry log tail` command func() body, for both + * project-scoped and trace-scoped streaming. + * + * Uses spyOn mocking to avoid real HTTP calls or database access. + * Tests use SIGINT to cleanly stop the setTimeout-based poll loop — the + * promise resolves on SIGINT (normal termination). AuthError tests verify + * that fetch failures reject the promise. + * + * Strategy: tests use interceptSigint() to capture the SIGINT handler and + * invoke it directly (process.emit("SIGINT") kills the test runner). + */ + +import { setTimeout as sleep } from "node:timers/promises"; +import { + afterEach, + beforeEach, + describe, + expect, + test, + vi, + type MockInstance, +} from "vitest"; +import { tailCommand } from "../../../src/commands/log/tail.js"; + +vi.mock("../../../src/lib/api-client.js", async (importOriginal) => { + const actual = + await importOriginal(); + const { mockFunctionExports } = await import("../../mock-exports.js"); + return mockFunctionExports(actual); +}); + +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as apiClient from "../../../src/lib/api-client.js"; + +vi.mock("../../../src/lib/db/auth.js", async (importOriginal) => { + const actual = + await importOriginal(); + const { mockFunctionExports } = await import("../../mock-exports.js"); + return mockFunctionExports(actual); +}); + +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as dbAuth from "../../../src/lib/db/auth.js"; +import { + ApiError, + AuthError, + ValidationError, +} from "../../../src/lib/errors.js"; + +vi.mock("../../../src/lib/formatters/index.js", async (importOriginal) => { + const actual = + await importOriginal< + typeof import("../../../src/lib/formatters/index.js") + >(); + const { mockFunctionExports } = await import("../../mock-exports.js"); + return mockFunctionExports(actual); +}); + +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as formatters from "../../../src/lib/formatters/index.js"; + +vi.mock("../../../src/lib/resolve-target.js", async (importOriginal) => { + const actual = + await importOriginal(); + const { mockFunctionExports } = await import("../../mock-exports.js"); + return mockFunctionExports(actual); +}); + +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as resolveTarget from "../../../src/lib/resolve-target.js"; + +vi.mock("../../../src/lib/trace-target.js", async (importOriginal) => { + const actual = + await importOriginal(); + const { mockFunctionExports } = await import("../../mock-exports.js"); + return mockFunctionExports(actual); +}); + +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as traceTarget from "../../../src/lib/trace-target.js"; + +vi.mock("../../../src/lib/version-check.js", async (importOriginal) => { + const actual = + await importOriginal(); + const { mockFunctionExports } = await import("../../mock-exports.js"); + return mockFunctionExports(actual); +}); + +// oxlint-disable-next-line sentry-cli/no-namespace-import -- needed for spyOn mocking +import * as versionCheck from "../../../src/lib/version-check.js"; +import type { SentryLog, TraceLog } from "../../../src/types/sentry.js"; +import { at, loadCommand, must } from "../../helpers.js"; +import type { Writer } from "../../../src/types/index.js"; + +// ============================================================================ +// Helpers +// ============================================================================ + +const TRACE_ID = "aaaa1111bbbb2222cccc3333dddd4444"; +const ORG = "test-org"; +const PROJECT = "test-project"; + +/** + * Intercept `process.once("SIGINT", handler)` registrations so tests can + * invoke the handler directly without sending a real signal (which would + * kill the Bun test runner). + * + * Must be created BEFORE the code under test runs. Call `trigger()` to + * simulate SIGINT, and `restore()` in afterEach. + */ +function interceptSigint() { + let handler: ((...args: unknown[]) => void) | null = null; + const originalOnce = process.once.bind(process); + const spy = vi.spyOn(process, "once").mockImplementation((( + event: string, + fn: (...args: unknown[]) => void, + ) => { + if (event === "SIGINT") { + handler = fn; + return process; + } + return originalOnce(event, fn); + }) as typeof process.once); + + // Also intercept removeListener so AuthError path works + const originalRemoveListener = process.removeListener.bind(process); + const removeSpy = vi.spyOn(process, "removeListener").mockImplementation((( + event: string, + fn: (...args: unknown[]) => void, + ) => { + if (event === "SIGINT" && fn === handler) { + handler = null; + return process; + } + return originalRemoveListener(event, fn); + }) as typeof process.removeListener); + + return { + /** Invoke the captured SIGINT handler (simulates Ctrl+C) */ + trigger() { + if (handler) { + const h = handler; + handler = null; + h(); + } + }, + /** Restore original process.once and process.removeListener */ + restore() { + spy.mockRestore(); + removeSpy.mockRestore(); + handler = null; + }, + }; +} + +function createMockContext() { + const stdoutWrite = vi.fn(() => true); + const stderrWrite = vi.fn(() => true); + return { + context: { + stdout: { write: stdoutWrite }, + stderr: { write: stderrWrite }, + cwd: "/tmp", + process: {}, + }, + stdoutWrite, + stderrWrite, + }; +} + +/** Sample project-scoped logs (SentryLog) */ +const sampleLogs: SentryLog[] = [ + { + "sentry.item_id": "item001", + timestamp: "2025-01-30T14:32:15+00:00", + timestamp_precise: 1_738_247_535_123_456_000, + severity: "info", + message: "Request received", + trace: "aaaa1111bbbb2222cccc3333dddd4444", + }, + { + "sentry.item_id": "item002", + timestamp: "2025-01-30T14:32:16+00:00", + timestamp_precise: 1_738_247_536_456_789_000, + severity: "warn", + message: "Slow query detected", + trace: "aaaa1111bbbb2222cccc3333dddd4444", + }, + { + "sentry.item_id": "item003", + timestamp: "2025-01-30T14:32:17+00:00", + timestamp_precise: 1_738_247_537_789_012_000, + severity: "error", + message: "Database connection failed", + trace: "aaaa1111bbbb2222cccc3333dddd4444", + }, +]; + +/** Sample trace-scoped logs (TraceLog) */ +const sampleTraceLogs: TraceLog[] = [ + { + id: "log001", + "project.id": 1, + trace: TRACE_ID, + severity_number: 9, + severity: "info", + timestamp: "2025-01-30T14:32:15+00:00", + timestamp_precise: 1_738_247_535_123_456_000, + message: "Request received", + }, + { + id: "log002", + "project.id": 1, + trace: TRACE_ID, + severity_number: 13, + severity: "warn", + timestamp: "2025-01-30T14:32:16+00:00", + timestamp_precise: 1_738_247_536_456_789_000, + message: "Slow query detected", + }, + { + id: "log003", + "project.id": 1, + trace: TRACE_ID, + severity_number: 17, + severity: "error", + timestamp: "2025-01-30T14:32:17+00:00", + timestamp_precise: 1_738_247_537_789_012_000, + message: "Database connection failed", + }, +]; + +/** Newer trace logs for polling tests — uses far-future timestamp to always be "newer" */ +const newerTraceLogs: TraceLog[] = [ + { + id: "log004", + "project.id": 1, + trace: TRACE_ID, + severity_number: 9, + severity: "info", + timestamp: "2099-01-30T14:32:20+00:00", + timestamp_precise: 4_073_000_000_000_000_000, + message: "New poll result", + }, +]; + +/** Newer project logs for polling tests — uses far-future timestamp */ +const newerLogs: SentryLog[] = [ + { + "sentry.item_id": "item004", + timestamp: "2099-01-30T14:32:20+00:00", + timestamp_precise: 4_073_000_000_000_000_000, + severity: "info", + message: "New poll result", + trace: "aaaa1111bbbb2222cccc3333dddd4444", + }, +]; + +// ============================================================================ +// Auth setup — mock getAuthConfig for all tests (auth guard added in #611) +// ============================================================================ + +let getAuthConfigSpy: MockInstance<(typeof dbAuth)["getAuthConfig"]>; + +beforeEach(() => { + getAuthConfigSpy = vi.spyOn(dbAuth, "getAuthConfig").mockReturnValue({ + token: "sntrys_test", + source: "oauth" as const, + }); +}); + +afterEach(() => { + getAuthConfigSpy.mockRestore(); +}); + +// ============================================================================ +// Standard mode (project-scoped, no trace-id positional) +// ============================================================================ + +// ============================================================================ + +/** + * Collect all output written to a `process.stderr.write` spy. + * Handles both string and Buffer arguments from the logger. + */ +function collectProcessStderr( + spy: MockInstance<(typeof process.stderr)["write"]>, +): string { + return spy.mock.calls + .map((c) => { + const arg = c[0]; + if (typeof arg === "string") { + return arg; + } + if (arg instanceof Uint8Array) { + return new TextDecoder().decode(arg); + } + return String(arg); + }) + .join(""); +} + +// ============================================================================ +// Project-scoped streaming +// ============================================================================ + +describe("tailCommand.func — project", () => { + let listLogsSpy: MockInstance<(typeof apiClient)["listLogs"]>; + let resolveOrgProjectSpy: MockInstance< + (typeof resolveTarget)["resolveProjectBoundTarget"] + >; + let isPlainSpy: MockInstance<(typeof formatters)["isPlainOutput"]>; + let updateNotifSpy: MockInstance< + (typeof versionCheck)["getUpdateNotification"] + >; + let sigint: ReturnType; + let stderrSpy: MockInstance<(typeof process.stderr)["write"]>; + + beforeEach(() => { + sigint = interceptSigint(); + listLogsSpy = vi.spyOn(apiClient, "listLogs"); + resolveOrgProjectSpy = vi.spyOn(resolveTarget, "resolveProjectBoundTarget"); + vi.spyOn(resolveTarget, "resolveLogProjectId").mockResolvedValue(undefined); + isPlainSpy = vi.spyOn(formatters, "isPlainOutput").mockReturnValue(true); + updateNotifSpy = vi + .spyOn(versionCheck, "getUpdateNotification") + .mockReturnValue(null); + stderrSpy = vi + .spyOn(process.stderr, "write") + .mockImplementation(() => true); + }); + + afterEach(() => { + listLogsSpy.mockRestore(); + resolveOrgProjectSpy.mockRestore(); + isPlainSpy.mockRestore(); + updateNotifSpy.mockRestore(); + stderrSpy.mockRestore(); + sigint.restore(); + }); + + /** Follow flags with 1-second interval (minimum real-world value) */ + const followFlags = { + json: false, + limit: 100, + interval: 1, + } as const; + + test("writes initial logs then resolves on SIGINT", async () => { + listLogsSpy.mockResolvedValueOnce(sampleLogs); + resolveOrgProjectSpy.mockResolvedValue({ org: ORG, project: PROJECT }); + + const { context, stdoutWrite } = createMockContext(); + const func = await loadCommand(tailCommand); + + const promise = func.call(context, followFlags, `${ORG}/${PROJECT}`); + await sleep(50); + sigint.trigger(); + await promise; + + const output = stdoutWrite.mock.calls.map((c) => c[0]).join(""); + expect(output).toContain("Request received"); + }); + + test("converts a bad --query 400 to a ValidationError in follow mode", async () => { + // The follow-mode fetch closure wraps listLogs with toSearchQueryError, so + // a bad user --query surfaces as a ValidationError on the initial fetch and + // terminates the stream instead of being reported as a CLI bug. + listLogsSpy.mockRejectedValueOnce( + new ApiError("bad", 400, "Error parsing search query: bad field"), + ); + resolveOrgProjectSpy.mockResolvedValue({ org: ORG, project: PROJECT }); + + const { context } = createMockContext(); + const func = await loadCommand(tailCommand); + + await expect( + func.call( + context, + { ...followFlags, query: "bad:::query" }, + `${ORG}/${PROJECT}`, + ), + ).rejects.toBeInstanceOf(ValidationError); + }); + + test("SIGINT during initial fetch does not start poll loop", async () => { + // fetchInitial will hang until we resolve it manually + let resolveFetch!: (logs: typeof sampleLogs) => void; + listLogsSpy.mockReturnValueOnce( + new Promise((resolve) => { + resolveFetch = resolve; + }), + ); + resolveOrgProjectSpy.mockResolvedValue({ org: ORG, project: PROJECT }); + + const { context } = createMockContext(); + const func = await loadCommand(tailCommand); + + const promise = func.call(context, followFlags, `${ORG}/${PROJECT}`); + await sleep(10); + + // SIGINT fires while fetchInitial is still pending + sigint.trigger(); + await sleep(10); + + // Now resolve the fetch — the .then() should NOT schedule a poll + resolveFetch(sampleLogs); + await promise; + + // If the bug existed, a timer would be scheduled. Wait to confirm none fires. + await sleep(50); + + // Only 1 call to listLogs (the initial fetch). No poll calls. + expect(listLogsSpy).toHaveBeenCalledTimes(1); + }); + + test("writes stderr banner in human follow mode", async () => { + listLogsSpy.mockResolvedValueOnce([]); + resolveOrgProjectSpy.mockResolvedValue({ org: ORG, project: PROJECT }); + + const { context } = createMockContext(); + const func = await loadCommand(tailCommand); + + const promise = func.call(context, followFlags, `${ORG}/${PROJECT}`); + await sleep(50); + sigint.trigger(); + await promise; + + // Banner now goes through logger → process.stderr + const stderr = collectProcessStderr(stderrSpy); + expect(stderr).toContain("Streaming logs"); + expect(stderr).toContain("Ctrl+C"); + }); + + test("skips stderr banner in JSON follow mode", async () => { + listLogsSpy.mockResolvedValueOnce([]); + resolveOrgProjectSpy.mockResolvedValue({ org: ORG, project: PROJECT }); + + const { context } = createMockContext(); + const func = await loadCommand(tailCommand); + + const promise = func.call( + context, + { ...followFlags, json: true }, + `${ORG}/${PROJECT}`, + ); + await sleep(50); + sigint.trigger(); + await promise; + + // Banner now goes through logger → process.stderr + const stderr = collectProcessStderr(stderrSpy); + expect(stderr).not.toContain("Streaming logs"); + }); + + test("writes new logs from poll iteration", async () => { + // Initial: sampleLogs, first poll: newerLogs + listLogsSpy + .mockResolvedValueOnce(sampleLogs) + .mockResolvedValueOnce(newerLogs); + resolveOrgProjectSpy.mockResolvedValue({ org: ORG, project: PROJECT }); + + const { context, stdoutWrite } = createMockContext(); + const func = await loadCommand(tailCommand); + + const promise = func.call(context, followFlags, `${ORG}/${PROJECT}`); + // Wait for initial fetch + poll timer (1s) + poll execution + await sleep(1200); + sigint.trigger(); + await promise; + + const output = stdoutWrite.mock.calls.map((c) => c[0]).join(""); + // Both initial and polled logs should appear + expect(output).toContain("Request received"); + expect(output).toContain("New poll result"); + }); + + test("streams JSON objects per-line in follow mode", async () => { + listLogsSpy.mockResolvedValueOnce(sampleLogs); + resolveOrgProjectSpy.mockResolvedValue({ org: ORG, project: PROJECT }); + + const { context, stdoutWrite } = createMockContext(); + const func = await loadCommand(tailCommand); + + const promise = func.call( + context, + { ...followFlags, json: true }, + `${ORG}/${PROJECT}`, + ); + await sleep(50); + sigint.trigger(); + await promise; + + // Each log should be written as a separate JSON object (streaming NDJSON) + const calls = stdoutWrite.mock.calls.map((c) => String(c[0])); + const jsonObjects = calls.filter((s: string) => { + try { + JSON.parse(s); + return true; + } catch { + return false; + } + }); + expect(jsonObjects.length).toBe(3); + }); + + test("rejects with AuthError from initial fetch", async () => { + listLogsSpy.mockRejectedValueOnce(new AuthError("expired")); + resolveOrgProjectSpy.mockResolvedValue({ org: ORG, project: PROJECT }); + + const { context } = createMockContext(); + const func = await loadCommand(tailCommand); + + await expect( + func.call(context, followFlags, `${ORG}/${PROJECT}`), + ).rejects.toThrow(AuthError); + }); + + test("rejects with AuthError from poll", async () => { + listLogsSpy + .mockResolvedValueOnce([]) + .mockRejectedValueOnce(new AuthError("expired")); + resolveOrgProjectSpy.mockResolvedValue({ org: ORG, project: PROJECT }); + + const { context } = createMockContext(); + const func = await loadCommand(tailCommand); + + await expect( + func.call(context, followFlags, `${ORG}/${PROJECT}`), + ).rejects.toThrow(AuthError); + }); + + test("continues polling after transient error (non-auth)", async () => { + // Initial: empty, poll 1: transient error, then SIGINT + listLogsSpy + .mockResolvedValueOnce([]) + .mockRejectedValueOnce(new Error("network timeout")); + resolveOrgProjectSpy.mockResolvedValue({ org: ORG, project: PROJECT }); + + const { context } = createMockContext(); + const func = await loadCommand(tailCommand); + + const promise = func.call(context, followFlags, `${ORG}/${PROJECT}`); + // Wait for initial fetch + poll timer (1s) + poll execution + await sleep(1200); + sigint.trigger(); + await promise; + + // Transient error now goes through logger → process.stderr + const stderr = collectProcessStderr(stderrSpy); + expect(stderr).toContain("Error fetching logs"); + expect(stderr).toContain("network timeout"); + }); + + test("uses 1m statsPeriod for initial follow fetch", async () => { + listLogsSpy.mockResolvedValueOnce([]); + resolveOrgProjectSpy.mockResolvedValue({ org: ORG, project: PROJECT }); + + const { context } = createMockContext(); + const func = await loadCommand(tailCommand); + + const promise = func.call(context, followFlags, `${ORG}/${PROJECT}`); + await sleep(50); + sigint.trigger(); + await promise; + + // Initial fetch should use "1m" (short window for follow mode) + expect(listLogsSpy.mock.calls[0]).toEqual([ + ORG, + PROJECT, + { query: undefined, limit: 100, statsPeriod: "1m" }, + ]); + }); + + test("passes afterTimestamp to poll calls", async () => { + // maxTimestamp scans the entire batch for the highest timestamp_precise + const maxTs = Math.max(...sampleLogs.map((l) => l.timestamp_precise)); + listLogsSpy.mockResolvedValueOnce(sampleLogs).mockResolvedValueOnce([]); + resolveOrgProjectSpy.mockResolvedValue({ org: ORG, project: PROJECT }); + + const { context } = createMockContext(); + const func = await loadCommand(tailCommand); + + const promise = func.call(context, followFlags, `${ORG}/${PROJECT}`); + // Wait for initial fetch + poll timer (1s) + poll execution + await sleep(1200); + sigint.trigger(); + await promise; + + // Poll call (index 1) should include afterTimestamp from max in batch + const pollCall = at(listLogsSpy.mock.calls, 1); + expect(pollCall).toBeDefined(); + expect(must(pollCall[2]).afterTimestamp).toBe(maxTs); + expect(must(pollCall[2]).statsPeriod).toBe("10m"); + }); + + test("shows update notification when available", async () => { + updateNotifSpy.mockReturnValue("Update available: v2.0.0\n"); + listLogsSpy.mockResolvedValueOnce([]); + resolveOrgProjectSpy.mockResolvedValue({ org: ORG, project: PROJECT }); + + const { context } = createMockContext(); + const func = await loadCommand(tailCommand); + + const promise = func.call(context, followFlags, `${ORG}/${PROJECT}`); + await sleep(50); + sigint.trigger(); + await promise; + + // Update notification now goes through logger → process.stderr + const stderr = collectProcessStderr(stderrSpy); + expect(stderr).toContain("Update available: v2.0.0"); + }); +}); + +// ============================================================================ +// Trace-scoped streaming (positional trace-id) +// ============================================================================ + +describe("tailCommand.func — trace", () => { + let listTraceLogsSpy: MockInstance<(typeof apiClient)["listTraceLogs"]>; + let resolveTraceOrgSpy: MockInstance<(typeof traceTarget)["resolveTraceOrg"]>; + let warnIfNormalizedSpy: MockInstance< + (typeof traceTarget)["warnIfNormalized"] + >; + let isPlainSpy: MockInstance<(typeof formatters)["isPlainOutput"]>; + let updateNotifSpy: MockInstance< + (typeof versionCheck)["getUpdateNotification"] + >; + let sigint: ReturnType; + let stderrSpy: MockInstance<(typeof process.stderr)["write"]>; + + beforeEach(() => { + sigint = interceptSigint(); + listTraceLogsSpy = vi.spyOn(apiClient, "listTraceLogs"); + resolveTraceOrgSpy = vi.spyOn(traceTarget, "resolveTraceOrg"); + warnIfNormalizedSpy = vi + .spyOn(traceTarget, "warnIfNormalized") + .mockReturnValue(undefined); + isPlainSpy = vi.spyOn(formatters, "isPlainOutput").mockReturnValue(true); + updateNotifSpy = vi + .spyOn(versionCheck, "getUpdateNotification") + .mockReturnValue(null); + stderrSpy = vi + .spyOn(process.stderr, "write") + .mockImplementation(() => true); + }); + + afterEach(() => { + listTraceLogsSpy.mockRestore(); + resolveTraceOrgSpy.mockRestore(); + warnIfNormalizedSpy.mockRestore(); + isPlainSpy.mockRestore(); + updateNotifSpy.mockRestore(); + stderrSpy.mockRestore(); + sigint.restore(); + }); + + const traceFollowFlags = { + json: false, + limit: 100, + interval: 1, + } as const; + + test("writes initial trace logs then resolves on SIGINT", async () => { + listTraceLogsSpy.mockResolvedValueOnce(sampleTraceLogs); + resolveTraceOrgSpy.mockResolvedValue({ traceId: TRACE_ID, org: ORG }); + + const { context, stdoutWrite } = createMockContext(); + const func = await loadCommand(tailCommand); + + const promise = func.call(context, traceFollowFlags, TRACE_ID); + await sleep(50); + sigint.trigger(); + await promise; + + const output = stdoutWrite.mock.calls.map((c) => c[0]).join(""); + expect(output).toContain("Request received"); + }); + + test("writes stderr banner with trace ID in follow mode", async () => { + listTraceLogsSpy.mockResolvedValueOnce([]); + resolveTraceOrgSpy.mockResolvedValue({ traceId: TRACE_ID, org: ORG }); + + const { context } = createMockContext(); + const func = await loadCommand(tailCommand); + + const promise = func.call(context, traceFollowFlags, TRACE_ID); + await sleep(50); + sigint.trigger(); + await promise; + + // Banner now goes through logger → process.stderr + const stderr = collectProcessStderr(stderrSpy); + expect(stderr).toContain("Streaming logs"); + expect(stderr).toContain(TRACE_ID); + expect(stderr).toContain("Ctrl+C"); + }); + + test("filters new logs by timestamp_precise (dedup)", async () => { + // Initial fetch returns logs, poll returns mix of old+new + const mixedLogs: TraceLog[] = [ + ...sampleTraceLogs, // old — should be filtered out + ...newerTraceLogs, // new — should pass filter + ]; + listTraceLogsSpy + .mockResolvedValueOnce(sampleTraceLogs) + .mockResolvedValueOnce(mixedLogs); + resolveTraceOrgSpy.mockResolvedValue({ traceId: TRACE_ID, org: ORG }); + + const { context, stdoutWrite } = createMockContext(); + const func = await loadCommand(tailCommand); + + const promise = func.call(context, traceFollowFlags, TRACE_ID); + // Wait for initial fetch + poll timer (1s) + poll execution + await sleep(1200); + sigint.trigger(); + await promise; + + const output = stdoutWrite.mock.calls.map((c) => c[0]).join(""); + // New log should appear + expect(output).toContain("New poll result"); + // Count total log writes — initial 3 + 1 new from poll + // (old logs from poll are filtered by timestamp_precise) + }); + + test("streams JSON in trace follow mode: first batch as array, then bare items", async () => { + listTraceLogsSpy + .mockResolvedValueOnce(sampleTraceLogs) + .mockResolvedValueOnce(newerTraceLogs); + resolveTraceOrgSpy.mockResolvedValue({ traceId: TRACE_ID, org: ORG }); + + const { context, stdoutWrite } = createMockContext(); + const func = await loadCommand(tailCommand); + + const promise = func.call( + context, + { ...traceFollowFlags, json: true }, + TRACE_ID, + ); + // Wait for initial fetch + poll timer (1s) + poll execution + await sleep(1200); + sigint.trigger(); + await promise; + + const calls = stdoutWrite.mock.calls.map((c) => String(c[0])); + const jsonLines = calls.filter((s: string) => { + try { + JSON.parse(s); + return true; + } catch { + return false; + } + }); + // First batch: 1 JSON line (envelope with data array from LogListResult) + // Poll batch: 1 JSON line per item (bare JSONL) + expect(jsonLines.length).toBe(2); + // First line is an envelope with data array (the initial trace batch) + const firstBatch = JSON.parse(at(jsonLines, 0)); + expect(firstBatch).toHaveProperty("data"); + expect(Array.isArray(firstBatch.data)).toBe(true); + expect(firstBatch.data).toHaveLength(3); + // Second line is a bare object (polled item) + const pollItem = JSON.parse(at(jsonLines, 1)); + expect(pollItem.message).toBe("New poll result"); + }); + + test("rejects with AuthError from poll", async () => { + listTraceLogsSpy + .mockResolvedValueOnce([]) + .mockRejectedValueOnce(new AuthError("expired")); + resolveTraceOrgSpy.mockResolvedValue({ traceId: TRACE_ID, org: ORG }); + + const { context } = createMockContext(); + const func = await loadCommand(tailCommand); + + await expect( + func.call(context, traceFollowFlags, TRACE_ID), + ).rejects.toThrow(AuthError); + }); + + test("continues polling after transient error (trace mode)", async () => { + listTraceLogsSpy + .mockResolvedValueOnce([]) + .mockRejectedValueOnce(new Error("server error")); + resolveTraceOrgSpy.mockResolvedValue({ traceId: TRACE_ID, org: ORG }); + + const { context } = createMockContext(); + const func = await loadCommand(tailCommand); + + const promise = func.call(context, traceFollowFlags, TRACE_ID); + // Wait for initial fetch + poll timer (1s) + poll execution + await sleep(1200); + sigint.trigger(); + await promise; + + // Transient error now goes through logger → process.stderr + const stderr = collectProcessStderr(stderrSpy); + expect(stderr).toContain("Error fetching logs"); + expect(stderr).toContain("server error"); + }); + + test("uses 1m statsPeriod for initial trace follow fetch", async () => { + listTraceLogsSpy.mockResolvedValueOnce([]); + resolveTraceOrgSpy.mockResolvedValue({ traceId: TRACE_ID, org: ORG }); + + const { context } = createMockContext(); + const func = await loadCommand(tailCommand); + + const promise = func.call(context, traceFollowFlags, TRACE_ID); + await sleep(50); + sigint.trigger(); + await promise; + + expect(listTraceLogsSpy.mock.calls[0]).toEqual([ + ORG, + TRACE_ID, + { query: undefined, limit: 100, statsPeriod: "1m" }, + ]); + }); + + test("does not pass afterTimestamp to trace poll calls (dedup via filter)", async () => { + listTraceLogsSpy + .mockResolvedValueOnce(sampleTraceLogs) + .mockResolvedValueOnce([]); + resolveTraceOrgSpy.mockResolvedValue({ traceId: TRACE_ID, org: ORG }); + + const { context } = createMockContext(); + const func = await loadCommand(tailCommand); + + const promise = func.call(context, traceFollowFlags, TRACE_ID); + // Wait for initial fetch + poll timer (1s) + poll execution + await sleep(1200); + sigint.trigger(); + await promise; + + // Poll call (index 1) should NOT have afterTimestamp + // (trace-logs endpoint doesn't support it) + const pollCall = at(listTraceLogsSpy.mock.calls, 1); + expect(pollCall).toBeDefined(); + expect(Reflect.get(must(pollCall[2]), "afterTimestamp")).toBeUndefined(); + expect(must(pollCall[2]).statsPeriod).toBe("10m"); + }); + + test("handles empty initial fetch then new logs in poll", async () => { + // Initial: empty, poll: new logs + listTraceLogsSpy + .mockResolvedValueOnce([]) + .mockResolvedValueOnce(newerTraceLogs); + resolveTraceOrgSpy.mockResolvedValue({ traceId: TRACE_ID, org: ORG }); + + const { context, stdoutWrite } = createMockContext(); + const func = await loadCommand(tailCommand); + + const promise = func.call(context, traceFollowFlags, TRACE_ID); + // Wait for initial fetch + poll timer (1s) + poll execution + await sleep(1200); + sigint.trigger(); + await promise; + + const output = stdoutWrite.mock.calls.map((c) => c[0]).join(""); + expect(output).toContain("New poll result"); + }); +}); diff --git a/packages/cli/test/e2e/log.test.ts b/packages/cli/test/e2e/log.test.ts index da03416e3b..fe93ff048c 100644 --- a/packages/cli/test/e2e/log.test.ts +++ b/packages/cli/test/e2e/log.test.ts @@ -134,16 +134,19 @@ describe("sentry log list", () => { expect(result.stderr + result.stdout).toMatch(/must be between|1.*1000/i); }); - test("supports -f flag for follow mode", async () => { + test("-f is --fresh, and streaming lives in log tail", async () => { await ctx.setAuthToken(TEST_TOKEN); - // We can't actually test follow mode in e2e since it runs forever, - // but we can verify the flag is accepted by checking --help - const result = await ctx.run(["log", "list", "--help"]); + const list = await ctx.run(["log", "list", "--help"]); + expect(list.exitCode).toBe(0); + expect(list.stdout).toMatch(/-f.*--fresh/); + expect(list.stdout).not.toMatch(/--follow/); - expect(result.exitCode).toBe(0); - expect(result.stdout).toMatch(/-f.*--follow/); - expect(result.stdout).toMatch(/poll interval/i); + // log tail runs until Ctrl+C, so check its flags through --help + const tail = await ctx.run(["log", "tail", "--help"]); + expect(tail.exitCode).toBe(0); + expect(tail.stdout).toMatch(/-i.*--interval/); + expect(tail.stdout).toMatch(/poll interval/i); }); }); diff --git a/packages/cli/test/lib/cache-hint.test.ts b/packages/cli/test/lib/cache-hint.test.ts index 02e49f19c1..68b1aa9448 100644 --- a/packages/cli/test/lib/cache-hint.test.ts +++ b/packages/cli/test/lib/cache-hint.test.ts @@ -136,8 +136,12 @@ describe("cache hint refresh flag for registered commands", () => { return resolveRefreshFlag(flags, aliases); } - test("log list names --fresh because -f is --follow", () => { - expect(refreshFlagFor("log list")).toBe("--fresh"); + test("log list names -f, the regression from getsentry/toolkit#2442", () => { + expect(refreshFlagFor("log list")).toBe("-f"); + }); + + test("log tail streams live data and suggests no refresh flag", () => { + expect(refreshFlagFor("log tail")).toBeUndefined(); }); test("issue list keeps the -f shorthand", () => { diff --git a/packages/cli/test/lib/index.test.ts b/packages/cli/test/lib/index.test.ts index 81c818142d..68da63113f 100644 --- a/packages/cli/test/lib/index.test.ts +++ b/packages/cli/test/lib/index.test.ts @@ -157,10 +157,10 @@ describe("createSentrySDK() library API", () => { expect(authorizationHeaders).not.toContain("Bearer stored-oauth-token"); }); - test("sdk.run returns AsyncIterable for streaming flag --follow", () => { + test("sdk.run returns AsyncIterable for the streaming command log tail", () => { const sdk = createSentrySDK(); - const result = sdk.run("log", "list", "--follow"); - // Streaming flags return an AsyncIterable, not a Promise + const result = sdk.run("log", "tail"); + // Streaming commands return an AsyncIterable, not a Promise expect(Symbol.asyncIterator in (result as object)).toBe(true); }); @@ -169,12 +169,6 @@ describe("createSentrySDK() library API", () => { const result = sdk.run("issue", "list", "--refresh"); expect(Symbol.asyncIterator in (result as object)).toBe(true); }); - - test("sdk.run returns AsyncIterable for streaming short flag -f", () => { - const sdk = createSentrySDK(); - const result = sdk.run("log", "list", "-f"); - expect(Symbol.asyncIterator in (result as object)).toBe(true); - }); }); describe("v3 static helpers", () => { diff --git a/packages/cli/test/lib/sdk-flag-types.test.ts b/packages/cli/test/lib/sdk-flag-types.test.ts index fafd5b9abe..cccc968dc6 100644 --- a/packages/cli/test/lib/sdk-flag-types.test.ts +++ b/packages/cli/test/lib/sdk-flag-types.test.ts @@ -40,12 +40,15 @@ describe("generated SDK flag types", () => { test("streaming overloads accept the target positional", () => { // Streaming calls still take their target as trailing positionals, e.g. - // `sdk.log.list({ follow: "5" }, "org/project")` must type as an AsyncIterable. + // `sdk.dashboard.view({ refresh: "30" }, "org/123")` must type as an AsyncIterable. expect(declarations).toContain( - "(params: LogListParams & { follow: string; }, ...positional: string[]): AsyncIterable;", + "(params: DashboardViewParams & { refresh: string; }, ...positional: string[]): AsyncIterable;", ); + }); + + test("always-streaming commands return an AsyncIterable without a flag", () => { expect(declarations).toContain( - "(params: DashboardViewParams & { refresh: string; }, ...positional: string[]): AsyncIterable;", + "tail(params?: LogTailParams, ...positional: string[]): AsyncIterable;", ); }); }); diff --git a/packages/cli/test/lib/short-flag-conventions.test.ts b/packages/cli/test/lib/short-flag-conventions.test.ts new file mode 100644 index 0000000000..6897aa57fb --- /dev/null +++ b/packages/cli/test/lib/short-flag-conventions.test.ts @@ -0,0 +1,79 @@ +/** + * Short-flag and streaming conventions across the real route tree. + * + * `-f` means `--fresh` in every command that can bypass the cache, so the + * cached footer's "use -f to refresh" and users' muscle memory hold + * everywhere. Live output is its own command (`log tail`), not a mode flag on + * a list command. See the "Flags" rules in `design/sentry-cli.md`. + */ + +import { describe, expect, test } from "vitest"; +import { routes } from "../../src/app.js"; +import { + type CommandInfo, + extractAllRoutes, + type RouteMap, +} from "../../src/lib/introspect.js"; +import { + STREAMING_COMMANDS, + STREAMING_FLAGS, +} from "../../src/lib/streaming-commands.js"; + +/** + * Commands that still stream through a mode flag. Each entry is a known gap + * listed in `design/sentry-cli.md`; do not add to it. + */ +const STREAMING_FLAG_COMMANDS = ["dashboard view"]; + +const commands: CommandInfo[] = extractAllRoutes( + routes as unknown as RouteMap, +).flatMap((route) => route.commands); + +/** `sentry log list` → `log list` */ +function routePath(command: CommandInfo): string { + return command.path.replace(/^sentry /, ""); +} + +describe("-f means --fresh", () => { + test("every command with --fresh binds -f to it", () => { + const offenders = commands + .filter((cmd) => cmd.flags.some((flag) => flag.name === "fresh")) + .filter((cmd) => cmd.aliases["f"] !== "fresh") + .map((cmd) => `${routePath(cmd)}: -f → ${cmd.aliases["f"] ?? "(none)"}`); + expect(offenders).toEqual([]); + }); + + test("log list is one of them", () => { + const logList = commands.find((cmd) => routePath(cmd) === "log list"); + expect(logList?.aliases["f"]).toBe("fresh"); + }); +}); + +describe("live output is its own command", () => { + test("only the listed gaps switch to streaming with a flag", () => { + const withStreamingFlag = commands + .filter((cmd) => + cmd.flags.some( + (flag) => !flag.hidden && STREAMING_FLAGS.has(flag.name), + ), + ) + .map(routePath); + expect(withStreamingFlag).toEqual(STREAMING_FLAG_COMMANDS); + }); + + test("no command has a visible --follow flag", () => { + const withFollow = commands + .filter((cmd) => + cmd.flags.some((flag) => flag.name === "follow" && !flag.hidden), + ) + .map(routePath); + expect(withFollow).toEqual([]); + }); + + test("every streaming command is registered", () => { + const registered = new Set(commands.map(routePath)); + for (const path of STREAMING_COMMANDS) { + expect(registered.has(path), path).toBe(true); + } + }); +}); diff --git a/packages/cli/test/lib/streaming-commands.test.ts b/packages/cli/test/lib/streaming-commands.test.ts new file mode 100644 index 0000000000..c36a56bbf8 --- /dev/null +++ b/packages/cli/test/lib/streaming-commands.test.ts @@ -0,0 +1,34 @@ +/** + * Tests for which raw `sdk.run()` arguments stream. + */ + +import { describe, expect, test } from "vitest"; +import { isStreamingInvocation } from "../../src/lib/streaming-commands.js"; + +describe("isStreamingInvocation", () => { + test("a streaming command streams with any arguments", () => { + expect(isStreamingInvocation(["log", "tail"])).toBe(true); + expect(isStreamingInvocation(["log", "tail", "acme/api", "-i", "5"])).toBe( + true, + ); + }); + + test("a streaming flag streams in long or --flag=value form", () => { + expect(isStreamingInvocation(["dashboard", "view", "1", "--refresh"])).toBe( + true, + ); + expect( + isStreamingInvocation(["dashboard", "view", "1", "--refresh=30"]), + ).toBe(true); + }); + + test("-f is --fresh, not a stream", () => { + expect(isStreamingInvocation(["log", "list", "-f"])).toBe(false); + expect(isStreamingInvocation(["issue", "list", "-f"])).toBe(false); + }); + + test("the command path must lead the arguments", () => { + expect(isStreamingInvocation(["log", "list", "tail"])).toBe(false); + expect(isStreamingInvocation(["log"])).toBe(false); + }); +}); From ecfff50a1bc6b47157279d1220d0f4a7ca460b28 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 20:41:49 +0000 Subject: [PATCH 3/6] fix(cli): Detect log tail in sdk.run() when global flags come first The route scanner accepts global flags before or between route segments (`--json log tail`, `log --json tail`), but the streaming check only looked at the first two arguments, so those layouts returned a Promise for a command that never ends. Skip global flags the same way, from `buildTopLevelFlags()`. --- packages/cli/src/lib/streaming-commands.ts | 37 +++++++++++++++++-- .../cli/test/lib/streaming-commands.test.ts | 10 +++++ 2 files changed, 44 insertions(+), 3 deletions(-) diff --git a/packages/cli/src/lib/streaming-commands.ts b/packages/cli/src/lib/streaming-commands.ts index 3782e69929..7aa7654620 100644 --- a/packages/cli/src/lib/streaming-commands.ts +++ b/packages/cli/src/lib/streaming-commands.ts @@ -13,22 +13,53 @@ * @module */ +import { buildTopLevelFlags } from "./global-flags.js"; + /** Flag names that switch a command into streaming mode. */ export const STREAMING_FLAGS: ReadonlySet = new Set(["refresh"]); /** Commands, as space-separated route paths, that always stream. */ export const STREAMING_COMMANDS: ReadonlySet = new Set(["log tail"]); +/** + * The leading route segments of raw CLI arguments, skipping global flags the + * way the route scanner does (`sentry --json log tail`, `sentry log + * --log-level debug tail`). Stops at the first other flag. + */ +function routeSegments(args: readonly string[], depth: number): string[] { + const { booleanFlags, valueFlags } = buildTopLevelFlags(); + const segments: string[] = []; + for (let i = 0; i < args.length && segments.length < depth; i++) { + const arg = args[i] ?? ""; + if (booleanFlags.has(arg)) { + continue; + } + if (valueFlags.has(arg)) { + i++; // the flag's value + continue; + } + if (valueFlags.has(arg.split("=")[0] ?? "")) { + continue; + } + if (arg.startsWith("-")) { + break; + } + segments.push(arg); + } + return segments; +} + /** * Whether raw CLI arguments run a streaming command or pass a streaming flag. * - * Matches the route path against the leading arguments, so `log tail ...` + * Matches the route path against the leading route segments, so `log tail ...` * streams while `log list ...` does not. */ export function isStreamingInvocation(args: readonly string[]): boolean { for (const path of STREAMING_COMMANDS) { - const segments = path.split(" "); - if (segments.every((segment, index) => args[index] === segment)) { + const expected = path.split(" "); + const actual = routeSegments(args, expected.length); + if (expected.every((segment, index) => actual[index] === segment)) { return true; } } diff --git a/packages/cli/test/lib/streaming-commands.test.ts b/packages/cli/test/lib/streaming-commands.test.ts index c36a56bbf8..55b97b5bbe 100644 --- a/packages/cli/test/lib/streaming-commands.test.ts +++ b/packages/cli/test/lib/streaming-commands.test.ts @@ -27,6 +27,16 @@ describe("isStreamingInvocation", () => { expect(isStreamingInvocation(["issue", "list", "-f"])).toBe(false); }); + test("global flags before or between route segments are skipped", () => { + expect(isStreamingInvocation(["--json", "log", "tail"])).toBe(true); + expect(isStreamingInvocation(["log", "--json", "tail"])).toBe(true); + expect(isStreamingInvocation(["--log-level", "debug", "log", "tail"])).toBe( + true, + ); + expect(isStreamingInvocation(["log", "--org=acme", "tail"])).toBe(true); + expect(isStreamingInvocation(["--json", "log", "list"])).toBe(false); + }); + test("the command path must lead the arguments", () => { expect(isStreamingInvocation(["log", "list", "tail"])).toBe(false); expect(isStreamingInvocation(["log"])).toBe(false); From 3cd24d5cc9ce0c851488bd271e5ccaa00f25d227 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 20:59:11 +0000 Subject: [PATCH 4/6] fix(cli): Check streaming detection against every command's flags sdk.run() decided streaming from a global flag-name list, so a streaming flag's short alias could collide with another command's alias. It also missed `dashboard view -r`, which returned a Promise for a command that never finishes. STREAMING_COMMANDS is now a per-command table (always, or one flag plus its alias). A test walks the whole route tree, hidden aliases included, and checks every flag and alias of every command against isStreamingInvocation(), and checks each table entry against the command's own flag and alias definitions. Also share the poll-interval parser and abortableSleep between log tail and dashboard view, merge the two log tail item yielders, and name the backfill and poll windows. --- design/sentry-cli.md | 2 + packages/cli/script/generate-sdk.ts | 12 +- packages/cli/src/commands/dashboard/view.ts | 37 ++---- packages/cli/src/commands/log/tail.ts | 112 +++++------------- packages/cli/src/lib/polling.ts | 44 +++++++ packages/cli/src/lib/streaming-commands.ts | 59 ++++++--- packages/cli/test/lib/polling.test.ts | 41 ++++++- .../test/lib/short-flag-conventions.test.ts | 33 ++++-- .../cli/test/lib/streaming-commands.test.ts | 91 +++++++++++++- 9 files changed, 289 insertions(+), 142 deletions(-) diff --git a/design/sentry-cli.md b/design/sentry-cli.md index a407ff4d84..006c813604 100644 --- a/design/sentry-cli.md +++ b/design/sentry-cli.md @@ -36,6 +36,8 @@ a terminal, with as little setup as the current project allows. and a cached result's footer names the flag that refreshes that command. - Live output is its own command, such as `sentry log tail`, not a mode flag on a list or view command. List and view commands return once. +- The library SDK returns an `AsyncIterable` for exactly the invocations that + stream, in its typed methods and in `sdk.run()` alike. ## Gaps diff --git a/packages/cli/script/generate-sdk.ts b/packages/cli/script/generate-sdk.ts index 408238ad96..27d944e95a 100644 --- a/packages/cli/script/generate-sdk.ts +++ b/packages/cli/script/generate-sdk.ts @@ -38,10 +38,7 @@ import { withJsDoc, } from "./ts-codegen.js"; import { logger } from "../src/lib/logger.js"; -import { - STREAMING_COMMANDS, - STREAMING_FLAGS, -} from "../src/lib/streaming-commands.js"; +import { STREAMING_COMMANDS } from "../src/lib/streaming-commands.js"; // --------------------------------------------------------------------------- // Configuration @@ -809,6 +806,7 @@ export async function emit(): Promise { for (const { path, command } of allCommands) { const flags = extractSdkFlags(command); + const streaming = STREAMING_COMMANDS[path.join(" ")]; const positional = derivePositional(command); const returnType = buildReturnType(command, `${buildTypeName(path)}Result`); @@ -830,8 +828,10 @@ export async function emit(): Promise { brief: command.brief || path.join(" "), positional, flags, - streamingFlags: flags.filter((flag) => STREAMING_FLAGS.has(flag.name)), - alwaysStreams: STREAMING_COMMANDS.has(path.join(" ")), + streamingFlags: flags.filter( + (flag) => streaming?.kind === "flag" && flag.name === streaming.flag, + ), + alwaysStreams: streaming?.kind === "always", paramsTypeName: params?.name.text, paramsRequired: flags.some((flag) => !flag.optional), resultTypeName: returnType?.name.text, diff --git a/packages/cli/src/commands/dashboard/view.ts b/packages/cli/src/commands/dashboard/view.ts index e15dad0d1b..6fff19a225 100644 --- a/packages/cli/src/commands/dashboard/view.ts +++ b/packages/cli/src/commands/dashboard/view.ts @@ -19,7 +19,11 @@ import { FRESH_FLAG, } from "../../lib/list-command.js"; import { logger } from "../../lib/logger.js"; -import { withProgress } from "../../lib/polling.js"; +import { + abortableSleep, + parsePollInterval, + withProgress, +} from "../../lib/polling.js"; import { resolveOrgRegion } from "../../lib/region.js"; import { buildDashboardUrl } from "../../lib/sentry-web-urls.js"; import type { GraphicsRendererPreference } from "../../lib/sixel.js"; @@ -65,34 +69,9 @@ function parseRefresh(value: string): number { if (value === "") { return DEFAULT_REFRESH_INTERVAL; } - const num = Number.parseInt(value, 10); - if (Number.isNaN(num) || num < MIN_REFRESH_INTERVAL) { - throw new Error( - `--refresh interval must be at least ${MIN_REFRESH_INTERVAL} seconds`, - ); - } - return num; -} - -/** - * Sleep that resolves early when an AbortSignal fires. - * Resolves (not rejects) on abort for clean generator shutdown. - */ -function abortableSleep(ms: number, signal: AbortSignal): Promise { - return new Promise((resolve) => { - if (signal.aborted) { - resolve(); - return; - } - const onAbort = () => { - clearTimeout(timer); - resolve(); - }; - const timer = setTimeout(() => { - signal.removeEventListener("abort", onAbort); - resolve(); - }, ms); - signal.addEventListener("abort", onAbort, { once: true }); + return parsePollInterval(value, { + flag: "--refresh", + min: MIN_REFRESH_INTERVAL, }); } diff --git a/packages/cli/src/commands/log/tail.ts b/packages/cli/src/commands/log/tail.ts index 66fe4fe13b..0ea7c8315f 100644 --- a/packages/cli/src/commands/log/tail.ts +++ b/packages/cli/src/commands/log/tail.ts @@ -24,6 +24,7 @@ import { TARGET_PATTERN_NOTE, } from "../../lib/list-command.js"; import { logger } from "../../lib/logger.js"; +import { abortableSleep, parsePollInterval } from "../../lib/polling.js"; import { resolveLogProjectId } from "../../lib/resolve-target.js"; import { sanitizeQuery } from "../../lib/search-query.js"; import { getUpdateNotification } from "../../lib/version-check.js"; @@ -34,6 +35,7 @@ import { jsonTransformLogOutput, type LogLike, type LogListArguments, + type LogListResult, type LogOutput, logTargetArguments, } from "./shared.js"; @@ -49,44 +51,27 @@ type TailFlags = { /** Default poll interval in seconds */ const DEFAULT_POLL_INTERVAL = 2; +/** + * Window of the first fetch: the logs of the last minute, so the stream + * opens with recent context instead of a blank screen. + */ +const BACKFILL_PERIOD = "1m"; + +/** + * Window of each poll. `afterTimestamp` already filters to logs newer than + * the last one shown, so this only bounds the scan. It is wider than any poll + * interval so logs that arrive late from ingestion still show up. + */ +const POLL_PERIOD = "10m"; + /** Parse --limit, delegating range validation to the shared utility. */ function parseLimit(value: string): number { return validateLimit(value, LIST_MIN_LIMIT, LIST_MAX_LIMIT); } -/** - * Parse the --interval flag: a poll interval in whole seconds. - * - * @throws Error if value is not a positive integer - */ +/** Parse --interval: whole seconds, at least 1. */ function parseInterval(value: string): number { - const num = Number(value); - if (!Number.isInteger(num) || num < 1) { - throw new Error("--interval must be a positive integer (seconds)"); - } - return num; -} - -/** - * Sleep that resolves early when an AbortSignal fires. - * Resolves (not rejects) on abort for clean generator shutdown. - */ -function abortableSleep(ms: number, signal: AbortSignal): Promise { - return new Promise((resolve) => { - if (signal.aborted) { - resolve(); - return; - } - const onAbort = () => { - clearTimeout(timer); - resolve(); - }; - const timer = setTimeout(() => { - signal.removeEventListener("abort", onAbort); - resolve(); - }, ms); - signal.addEventListener("abort", onAbort, { once: true }); - }); + return parsePollInterval(value, { flag: "--interval" }); } /** @@ -105,7 +90,8 @@ type FollowGeneratorConfig = { onDiagnostic: (message: string) => void; /** * Fetch logs with the given time window. - * @param statsPeriod - Time window (e.g., "1m" for initial, "10m" for polls) + * @param statsPeriod - Time window: {@link BACKFILL_PERIOD} for the first + * fetch, {@link POLL_PERIOD} for polls * @param afterTimestamp - Only return logs newer than this (nanoseconds). * Standard mode passes this for server-side dedup; trace mode ignores it. */ @@ -150,7 +136,7 @@ async function fetchPoll( lastTimestamp: number, ): Promise { try { - const rawLogs = await config.fetch("10m", lastTimestamp); + const rawLogs = await config.fetch(POLL_PERIOD, lastTimestamp); return config.extractNew(rawLogs, lastTimestamp); } catch (error) { if (error instanceof AuthError) { @@ -202,8 +188,7 @@ async function* generateFollowLogs( } try { - // Initial fetch - const initialLogs = await config.fetch("1m"); + const initialLogs = await config.fetch(BACKFILL_PERIOD); if (initialLogs.length > 0) { yield [...initialLogs].reverse(); } @@ -229,54 +214,21 @@ async function* generateFollowLogs( } /** - * Consume a project-scoped polling generator, yielding items individually. - * - * When `extraFields` is provided, the first non-empty batch is yielded as a - * {@link LogListResult} so the human renderer can discover the extra columns - * and create a table with the right headers. Subsequent items are yielded - * bare for proper JSONL streaming. - */ -async function* yieldFollowItems( - generator: AsyncGenerator, - extraFields?: string[], -): AsyncGenerator, void, undefined> { - let contextSent = !extraFields?.length; - for await (const batch of generator) { - if (!contextSent && batch.length > 0) { - yield new CommandOutput({ - logs: batch, - hasMore: false, - extraFields, - }); - contextSent = true; - } else { - for (const item of batch) { - yield new CommandOutput(item); - } - } - } -} - -/** - * Consume a trace polling generator, yielding items individually. + * Consume a polling generator, yielding log items individually for JSONL + * streaming. * - * The first non-empty batch is yielded as a {@link LogListResult} so - * the human renderer can detect `traceId` and hide the trace column. - * Subsequent items are yielded bare for proper JSONL streaming. + * When the renderer needs context, the first non-empty batch is yielded as a + * {@link LogListResult} instead: `traceId` hides the trace column, and + * `extraFields` adds the `--fields` columns to the table header. */ -async function* yieldTraceFollowItems( +async function* yieldLogItems( generator: AsyncGenerator, - traceId: string, + context: Pick, ): AsyncGenerator, void, undefined> { - let contextSent = false; + let contextSent = !(context.traceId || context.extraFields?.length); for await (const batch of generator) { if (!contextSent && batch.length > 0) { - // First non-empty batch: yield as LogListResult to set trace context - yield new CommandOutput({ - logs: batch, - traceId, - hasMore: false, - }); + yield new CommandOutput({ ...context, logs: batch, hasMore: false }); contextSent = true; } else { for (const item of batch) { @@ -436,7 +388,7 @@ export const tailCommand = buildCommand({ }, }); - yield* yieldTraceFollowItems(generator, traceId); + yield* yieldLogItems(generator, { traceId }); return; } @@ -467,6 +419,6 @@ export const tailCommand = buildCommand({ extractNew: (logs) => logs, }); - yield* yieldFollowItems(generator, flags.fields); + yield* yieldLogItems(generator, { extraFields: flags.fields }); }, }); diff --git a/packages/cli/src/lib/polling.ts b/packages/cli/src/lib/polling.ts index c8878171b0..e3b6545d01 100644 --- a/packages/cli/src/lib/polling.ts +++ b/packages/cli/src/lib/polling.ts @@ -262,3 +262,47 @@ export async function withProgress( process.stdout.write("\r\x1b[K"); } } + +/** + * Parse a poll-interval flag value: a whole number of seconds, at least `min`. + * Shared by the commands that stream until Ctrl+C (`log tail --interval`, + * `dashboard view --refresh`). + * + * @param flag - Flag spelling for the error message, e.g. `"--interval"` + * @throws Error when the value is not a whole number of seconds `>= min` + */ +export function parsePollInterval( + value: string, + options: { flag: string; min?: number }, +): number { + const min = options.min ?? 1; + const seconds = Number(value); + if (!Number.isInteger(seconds) || seconds < min) { + throw new Error( + `${options.flag} must be a whole number of seconds, at least ${min}`, + ); + } + return seconds; +} + +/** + * Sleep that resolves early when an AbortSignal fires. + * Resolves (not rejects) on abort for clean generator shutdown. + */ +export function abortableSleep(ms: number, signal: AbortSignal): Promise { + return new Promise((resolve) => { + if (signal.aborted) { + resolve(); + return; + } + const onAbort = () => { + clearTimeout(timer); + resolve(); + }; + const timer = setTimeout(() => { + signal.removeEventListener("abort", onAbort); + resolve(); + }, ms); + signal.addEventListener("abort", onAbort, { once: true }); + }); +} diff --git a/packages/cli/src/lib/streaming-commands.ts b/packages/cli/src/lib/streaming-commands.ts index 7aa7654620..6b97eea3d6 100644 --- a/packages/cli/src/lib/streaming-commands.ts +++ b/packages/cli/src/lib/streaming-commands.ts @@ -10,16 +10,32 @@ * command; see `design/sentry-cli.md`. `--refresh` on `dashboard view` is the * one flag that still switches a command into streaming. * + * Streaming is per command: a flag or alias streams only in the command + * listed with it, so `-r` on `dashboard view` streams and `-f` never does. + * * @module */ import { buildTopLevelFlags } from "./global-flags.js"; -/** Flag names that switch a command into streaming mode. */ -export const STREAMING_FLAGS: ReadonlySet = new Set(["refresh"]); +/** + * How a command streams: on every run, or only when one of its flags is + * passed. `alias` is that flag's short alias in the command, if any. + */ +export type StreamingMode = + | { readonly kind: "always" } + | { readonly kind: "flag"; readonly flag: string; readonly alias?: string }; -/** Commands, as space-separated route paths, that always stream. */ -export const STREAMING_COMMANDS: ReadonlySet = new Set(["log tail"]); +/** + * Every command that can stream, keyed by space-separated route path. + * `test/lib/streaming-commands.test.ts` checks this table against the real + * route tree: each flag and alias here must match the command's own + * definition, and no other flag or alias of any command may stream. + */ +export const STREAMING_COMMANDS: Readonly> = { + "log tail": { kind: "always" }, + "dashboard view": { kind: "flag", flag: "refresh", alias: "r" }, +}; /** * The leading route segments of raw CLI arguments, skipping global flags the @@ -49,23 +65,34 @@ function routeSegments(args: readonly string[], depth: number): string[] { return segments; } +/** Whether `arg` passes the streaming flag of `mode`. */ +function passesStreamingFlag( + arg: string, + mode: Extract, +): boolean { + return ( + arg === `--${mode.flag}` || + arg.startsWith(`--${mode.flag}=`) || + (mode.alias !== undefined && arg === `-${mode.alias}`) + ); +} + /** - * Whether raw CLI arguments run a streaming command or pass a streaming flag. - * - * Matches the route path against the leading route segments, so `log tail ...` - * streams while `log list ...` does not. + * Whether raw CLI arguments run a streaming command, or pass the streaming + * flag of the command they run. Matches route paths against the leading route + * segments, so `log tail ...` streams while `log list ...` does not. */ export function isStreamingInvocation(args: readonly string[]): boolean { - for (const path of STREAMING_COMMANDS) { + for (const [path, mode] of Object.entries(STREAMING_COMMANDS)) { const expected = path.split(" "); const actual = routeSegments(args, expected.length); - if (expected.every((segment, index) => actual[index] === segment)) { - return true; + if (!expected.every((segment, index) => actual[index] === segment)) { + continue; } + return ( + mode.kind === "always" || + args.some((arg) => passesStreamingFlag(arg, mode)) + ); } - return args.some( - (arg) => - arg.startsWith("--") && - STREAMING_FLAGS.has(arg.slice(2).split("=")[0] ?? ""), - ); + return false; } diff --git a/packages/cli/test/lib/polling.test.ts b/packages/cli/test/lib/polling.test.ts index 9a592f4750..2dd8ef6d7f 100644 --- a/packages/cli/test/lib/polling.test.ts +++ b/packages/cli/test/lib/polling.test.ts @@ -1,5 +1,9 @@ import { afterEach, describe, expect, test, vi } from "vitest"; -import { withProgress } from "../../src/lib/polling.js"; +import { + abortableSleep, + parsePollInterval, + withProgress, +} from "../../src/lib/polling.js"; const originalIsTTY = process.stdout.isTTY; @@ -151,3 +155,38 @@ describe("withProgress", () => { expect(stdoutWrite).not.toHaveBeenCalled(); }); }); + +describe("parsePollInterval", () => { + test("accepts whole seconds at or above the minimum", () => { + expect(parsePollInterval("5", { flag: "--interval" })).toBe(5); + expect(parsePollInterval("10", { flag: "--refresh", min: 10 })).toBe(10); + }); + + test("rejects fractions, junk, and values below the minimum", () => { + for (const value of ["0", "1.5", "5s", "", "-3"]) { + expect(() => parsePollInterval(value, { flag: "--interval" })).toThrow( + "--interval must be a whole number of seconds, at least 1", + ); + } + expect(() => + parsePollInterval("9", { flag: "--refresh", min: 10 }), + ).toThrow("--refresh must be a whole number of seconds, at least 10"); + }); +}); + +describe("abortableSleep", () => { + test("resolves at once when the signal is already aborted", async () => { + const controller = new AbortController(); + controller.abort(); + await expect(abortableSleep(60_000, controller.signal)).resolves.toBe( + undefined, + ); + }); + + test("resolves early when the signal aborts mid-sleep", async () => { + const controller = new AbortController(); + const sleeping = abortableSleep(60_000, controller.signal); + controller.abort(); + await expect(sleeping).resolves.toBe(undefined); + }); +}); diff --git a/packages/cli/test/lib/short-flag-conventions.test.ts b/packages/cli/test/lib/short-flag-conventions.test.ts index 6897aa57fb..b6f818a26b 100644 --- a/packages/cli/test/lib/short-flag-conventions.test.ts +++ b/packages/cli/test/lib/short-flag-conventions.test.ts @@ -14,10 +14,7 @@ import { extractAllRoutes, type RouteMap, } from "../../src/lib/introspect.js"; -import { - STREAMING_COMMANDS, - STREAMING_FLAGS, -} from "../../src/lib/streaming-commands.js"; +import { STREAMING_COMMANDS } from "../../src/lib/streaming-commands.js"; /** * Commands that still stream through a mode flag. Each entry is a known gap @@ -25,6 +22,21 @@ import { */ const STREAMING_FLAG_COMMANDS = ["dashboard view"]; +/** + * Flag names that usually mean "keep running and stream". A command that adds + * one must be a listed gap, which forces the change through review here and + * in `STREAMING_COMMANDS`. + */ +const STREAM_LIKE_FLAG_NAMES = new Set([ + "follow", + "live", + "poll", + "refresh", + "stream", + "tail", + "watch", +]); + const commands: CommandInfo[] = extractAllRoutes( routes as unknown as RouteMap, ).flatMap((route) => route.commands); @@ -51,14 +63,19 @@ describe("-f means --fresh", () => { describe("live output is its own command", () => { test("only the listed gaps switch to streaming with a flag", () => { - const withStreamingFlag = commands + const withStreamLikeFlag = commands .filter((cmd) => cmd.flags.some( - (flag) => !flag.hidden && STREAMING_FLAGS.has(flag.name), + (flag) => !flag.hidden && STREAM_LIKE_FLAG_NAMES.has(flag.name), ), ) .map(routePath); - expect(withStreamingFlag).toEqual(STREAMING_FLAG_COMMANDS); + expect(withStreamLikeFlag).toEqual(STREAMING_FLAG_COMMANDS); + + const flagModeCommands = Object.entries(STREAMING_COMMANDS) + .filter(([, mode]) => mode.kind === "flag") + .map(([path]) => path); + expect(flagModeCommands).toEqual(STREAMING_FLAG_COMMANDS); }); test("no command has a visible --follow flag", () => { @@ -72,7 +89,7 @@ describe("live output is its own command", () => { test("every streaming command is registered", () => { const registered = new Set(commands.map(routePath)); - for (const path of STREAMING_COMMANDS) { + for (const path of Object.keys(STREAMING_COMMANDS)) { expect(registered.has(path), path).toBe(true); } }); diff --git a/packages/cli/test/lib/streaming-commands.test.ts b/packages/cli/test/lib/streaming-commands.test.ts index 55b97b5bbe..f79da12ae2 100644 --- a/packages/cli/test/lib/streaming-commands.test.ts +++ b/packages/cli/test/lib/streaming-commands.test.ts @@ -1,9 +1,90 @@ /** * Tests for which raw `sdk.run()` arguments stream. + * + * The route-tree section checks every flag and alias of every registered + * command, so a short alias that collides with a streaming flag (the `-f` + * bug: `-f` was `--follow` in `sdk.run()` but `--fresh` in `issue list`) + * fails here instead of hanging an SDK caller. */ import { describe, expect, test } from "vitest"; -import { isStreamingInvocation } from "../../src/lib/streaming-commands.js"; +import { routes } from "../../src/app.js"; +import { + isCommand, + isRouteMap, + type Command, + type RouteMap, +} from "../../src/lib/introspect.js"; +import { + isStreamingInvocation, + STREAMING_COMMANDS, +} from "../../src/lib/streaming-commands.js"; + +type RegisteredCommand = { path: string[]; command: Command }; + +/** Every command in the route tree, hidden aliases included. */ +function allCommands( + map: RouteMap, + prefix: string[] = [], +): RegisteredCommand[] { + return map.getAllEntries().flatMap((entry) => { + const path = [...prefix, entry.name.original]; + if (isRouteMap(entry.target)) { + return allCommands(entry.target, path); + } + return isCommand(entry.target) ? [{ path, command: entry.target }] : []; + }); +} + +const registered = allCommands(routes as unknown as RouteMap); + +describe("STREAMING_COMMANDS matches the route tree", () => { + test("every entry is a registered command whose flag and alias match", () => { + for (const [path, mode] of Object.entries(STREAMING_COMMANDS)) { + const found = registered.find((cmd) => cmd.path.join(" ") === path); + expect(found, path).toBeDefined(); + if (mode.kind !== "flag" || !found) { + continue; + } + const { flags = {}, aliases = {} } = found.command.parameters; + expect(Object.keys(flags), path).toContain(mode.flag); + const commandAlias = Object.entries(aliases).find( + ([, target]) => target === mode.flag, + )?.[0]; + expect(mode.alias, `${path}: alias of --${mode.flag}`).toBe(commandAlias); + } + }); + + test("a flag or alias streams only where the table says so", () => { + const wrong: string[] = []; + for (const { path, command } of registered) { + const mode = STREAMING_COMMANDS[path.join(" ")]; + const { flags = {}, aliases = {} } = command.parameters; + const tokens: [string, string][] = [ + ...Object.keys(flags).map((name): [string, string] => [ + `--${name}`, + name, + ]), + ...Object.entries(aliases).map(([alias, name]): [string, string] => [ + `-${alias}`, + name, + ]), + ]; + for (const [token, flagName] of tokens) { + const expected = + mode?.kind === "always" || + (mode?.kind === "flag" && mode.flag === flagName); + if (isStreamingInvocation([...path, token]) !== expected) { + wrong.push(`${path.join(" ")} ${token}: expected ${expected}`); + } + } + if (isStreamingInvocation(path) !== (mode?.kind === "always")) { + wrong.push(`${path.join(" ")}: expected ${mode?.kind === "always"}`); + } + } + expect(wrong).toEqual([]); + }); +}); describe("isStreamingInvocation", () => { test("a streaming command streams with any arguments", () => { @@ -13,7 +94,8 @@ describe("isStreamingInvocation", () => { ); }); - test("a streaming flag streams in long or --flag=value form", () => { + test("a streaming flag streams in long, --flag=value, or alias form", () => { + expect(isStreamingInvocation(["dashboard", "view", "1", "-r"])).toBe(true); expect(isStreamingInvocation(["dashboard", "view", "1", "--refresh"])).toBe( true, ); @@ -27,6 +109,11 @@ describe("isStreamingInvocation", () => { expect(isStreamingInvocation(["issue", "list", "-f"])).toBe(false); }); + test("a streaming flag streams only in its own command", () => { + expect(isStreamingInvocation(["issue", "list", "--refresh"])).toBe(false); + expect(isStreamingInvocation(["log", "list", "-r"])).toBe(false); + }); + test("global flags before or between route segments are skipped", () => { expect(isStreamingInvocation(["--json", "log", "tail"])).toBe(true); expect(isStreamingInvocation(["log", "--json", "tail"])).toBe(true); From 84f46d546127c17734457103d39b94821e104e45 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 21:02:37 +0000 Subject: [PATCH 5/6] test(cli): Point the sdk.run streaming-flag test at dashboard view --refresh streams only on dashboard view now, so issue list --refresh no longer returns an AsyncIterable. Cover both --refresh and -r there. --- packages/cli/test/lib/index.test.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/cli/test/lib/index.test.ts b/packages/cli/test/lib/index.test.ts index 68da63113f..55d7467436 100644 --- a/packages/cli/test/lib/index.test.ts +++ b/packages/cli/test/lib/index.test.ts @@ -164,10 +164,12 @@ describe("createSentrySDK() library API", () => { expect(Symbol.asyncIterator in (result as object)).toBe(true); }); - test("sdk.run returns AsyncIterable for streaming flag --refresh", () => { + test("sdk.run returns AsyncIterable for dashboard view's streaming flag", () => { const sdk = createSentrySDK(); - const result = sdk.run("issue", "list", "--refresh"); - expect(Symbol.asyncIterator in (result as object)).toBe(true); + for (const flag of ["--refresh", "-r"]) { + const result = sdk.run("dashboard", "view", "1", flag); + expect(Symbol.asyncIterator in (result as object), flag).toBe(true); + } }); }); From f5a29e27f3ed88c9b2e9aa80f7ff66db13c0dc0c Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 21:11:54 +0000 Subject: [PATCH 6/6] fix(cli): Declare streaming on the command instead of a list Commands now mark themselves with `streams` in buildCommand: `true` for log tail, `{ flag: "refresh" }` for dashboard view. The SDK generator reads the marker directly. sdk.run() must choose a return shape before it loads any command, so a new generator step writes the markers, with each flag's alias read from the command, to src/generated/streaming-commands.json. The hand-kept STREAMING_COMMANDS table is gone. The route-tree test now checks sdk.run()'s answer for every flag and alias of every command against that command's own marker, and that the generated file is current. --- packages/cli/script/generate-sdk.ts | 8 +- .../cli/script/generate-streaming-commands.ts | 36 ++++++ packages/cli/script/generate.ts | 4 + packages/cli/src/commands/dashboard/view.ts | 1 + packages/cli/src/commands/log/tail.ts | 1 + packages/cli/src/lib/command.ts | 15 +++ packages/cli/src/lib/sdk-invoke.ts | 11 +- packages/cli/src/lib/streaming-commands.ts | 95 ++++++++++----- .../test/lib/short-flag-conventions.test.ts | 20 ++- .../cli/test/lib/streaming-commands.test.ts | 115 ++++++++++-------- 10 files changed, 208 insertions(+), 98 deletions(-) create mode 100644 packages/cli/script/generate-streaming-commands.ts diff --git a/packages/cli/script/generate-sdk.ts b/packages/cli/script/generate-sdk.ts index 27d944e95a..631b1de30d 100644 --- a/packages/cli/script/generate-sdk.ts +++ b/packages/cli/script/generate-sdk.ts @@ -38,7 +38,7 @@ import { withJsDoc, } from "./ts-codegen.js"; import { logger } from "../src/lib/logger.js"; -import { STREAMING_COMMANDS } from "../src/lib/streaming-commands.js"; +import { streamingModeOf } from "../src/lib/streaming-commands.js"; // --------------------------------------------------------------------------- // Configuration @@ -806,7 +806,7 @@ export async function emit(): Promise { for (const { path, command } of allCommands) { const flags = extractSdkFlags(command); - const streaming = STREAMING_COMMANDS[path.join(" ")]; + const streaming = streamingModeOf(command); const positional = derivePositional(command); const returnType = buildReturnType(command, `${buildTypeName(path)}Result`); @@ -829,9 +829,9 @@ export async function emit(): Promise { positional, flags, streamingFlags: flags.filter( - (flag) => streaming?.kind === "flag" && flag.name === streaming.flag, + (flag) => streaming?.flag !== undefined && flag.name === streaming.flag, ), - alwaysStreams: streaming?.kind === "always", + alwaysStreams: streaming !== undefined && streaming.flag === undefined, paramsTypeName: params?.name.text, paramsRequired: flags.some((flag) => !flag.optional), resultTypeName: returnType?.name.text, diff --git a/packages/cli/script/generate-streaming-commands.ts b/packages/cli/script/generate-streaming-commands.ts new file mode 100644 index 0000000000..1cf715b863 --- /dev/null +++ b/packages/cli/script/generate-streaming-commands.ts @@ -0,0 +1,36 @@ +/** + * Generate Which Commands Stream, for `sdk.run()` + * + * `sdk.run()` takes raw CLI arguments and must decide between a `Promise` + * and an `AsyncIterable` before it loads any command. This script reads the + * `streams` marker of every command in the loaded route tree and writes them + * out, so the runtime check comes from the command definitions instead of a + * hand-kept list. + * + * The output is gitignored and regenerated by `generate:docs`, which runs as + * part of `dev`, `build`, `bundle`, `typecheck`, and `test`. + * + * Usage: pnpm ts script/generate.ts streaming-commands + * Output: src/generated/streaming-commands.json + */ + +import { mkdirSync } from "node:fs"; +import { writeFile } from "node:fs/promises"; +import { routes } from "../src/app.js"; +import type { RouteMap } from "../src/lib/introspect.js"; +import { logger } from "../src/lib/logger.js"; +import { collectStreamingCommands } from "../src/lib/streaming-commands.js"; + +const OUTPUT_PATH = "src/generated/streaming-commands.json"; + +/** Write the streaming mode of every streaming command. */ +export async function emit(): Promise { + const commands = collectStreamingCommands(routes as unknown as RouteMap); + + mkdirSync("src/generated", { recursive: true }); + await writeFile(OUTPUT_PATH, `${JSON.stringify(commands, null, 2)}\n`); + + logger.success( + `Generated ${OUTPUT_PATH} (${Object.keys(commands).length} commands)`, + ); +} diff --git a/packages/cli/script/generate.ts b/packages/cli/script/generate.ts index 3a14479a82..74723249f8 100644 --- a/packages/cli/script/generate.ts +++ b/packages/cli/script/generate.ts @@ -195,6 +195,10 @@ const TREE_STEPS: readonly Step[] = [ name: "top-level-routes", load: () => import("./generate-top-level-routes.js"), }, + { + name: "streaming-commands", + load: () => import("./generate-streaming-commands.js"), + }, { name: "command-docs", load: () => import("./generate-command-docs.js") }, { name: "docs-sections", load: () => import("./generate-docs-sections.js") }, { name: "skill", load: () => import("./generate-skill.js") }, diff --git a/packages/cli/src/commands/dashboard/view.ts b/packages/cli/src/commands/dashboard/view.ts index 6fff19a225..0079568d51 100644 --- a/packages/cli/src/commands/dashboard/view.ts +++ b/packages/cli/src/commands/dashboard/view.ts @@ -138,6 +138,7 @@ function resolveViewTimeRange( } export const viewCommand = buildCommand({ + streams: { flag: "refresh" }, docs: { brief: "View a dashboard", fullDescription: diff --git a/packages/cli/src/commands/log/tail.ts b/packages/cli/src/commands/log/tail.ts index 0ea7c8315f..4a9bec685b 100644 --- a/packages/cli/src/commands/log/tail.ts +++ b/packages/cli/src/commands/log/tail.ts @@ -259,6 +259,7 @@ function writeFollowBanner( } export const tailCommand = buildCommand({ + streams: true, docs: { brief: "Stream new logs from a project or trace", fullDescription: diff --git a/packages/cli/src/lib/command.ts b/packages/cli/src/lib/command.ts index 52edfd2ccc..9b91d3207c 100644 --- a/packages/cli/src/lib/command.ts +++ b/packages/cli/src/lib/command.ts @@ -226,6 +226,17 @@ type LocalCommandBuilderArguments< * `issue merge`, `trial start`). */ readonly destructive?: boolean; + /** + * Mark the command as streaming until stopped: `true` when every run + * streams (`log tail`), or `{ flag }` when passing that flag switches it + * into streaming (`dashboard view --refresh`). + * + * The library SDK returns an `AsyncIterable` for streaming invocations. + * The SDK generator and `sdk.run()` both derive that from this marker + * through `streaming-commands.ts`, so nothing else lists streaming + * commands. + */ + readonly streams?: true | { readonly flag: string }; }; // --------------------------------------------------------------------------- @@ -979,6 +990,10 @@ export function buildCommand< if (builderArgs.destructive) { (cmd as unknown as Record)["__destructive"] = true; } + if (builderArgs.streams) { + (cmd as unknown as Record)["__streams"] = + builderArgs.streams; + } // Attach the JSON fields to the built command as a non-standard property. // introspect.ts reads this to populate CommandInfo.jsonFields for help diff --git a/packages/cli/src/lib/sdk-invoke.ts b/packages/cli/src/lib/sdk-invoke.ts index 49e3d09271..b0216b2038 100644 --- a/packages/cli/src/lib/sdk-invoke.ts +++ b/packages/cli/src/lib/sdk-invoke.ts @@ -21,7 +21,14 @@ import { type AsyncChannel, createAsyncChannel } from "./async-channel.js"; import { NO_PERSISTENCE_ENV_VAR, withInvocation } from "./env.js"; import { stringifyUnknown } from "./errors.js"; import { SentryError, type SentryOptions } from "./sdk-types.js"; -import { isStreamingInvocation } from "./streaming-commands.js"; +import generatedStreamingCommands from "../generated/streaming-commands.json" with { type: "json" }; +import { + isStreamingInvocation, + type StreamingCommands, +} from "./streaming-commands.js"; + +/** Streaming commands, generated from the commands' `streams` markers. */ +const STREAMING_COMMANDS: StreamingCommands = generatedStreamingCommands; /** * Build an isolated env from options, starting from `options.env` or the @@ -614,7 +621,7 @@ export function buildRunner(options?: SentryOptions) { return function run( ...args: string[] ): Promise | AsyncIterable { - if (isStreamingInvocation(args)) { + if (isStreamingInvocation(args, STREAMING_COMMANDS)) { return executeWithStream(options, async (ctx, span) => { const { run: stricliRun } = await import("@stricli/core"); const { loadSdkApp } = await import("../sdk-app.js"); diff --git a/packages/cli/src/lib/streaming-commands.ts b/packages/cli/src/lib/streaming-commands.ts index 6b97eea3d6..5760a5d0ba 100644 --- a/packages/cli/src/lib/streaming-commands.ts +++ b/packages/cli/src/lib/streaming-commands.ts @@ -2,40 +2,77 @@ * Which commands stream output until stopped, for the library SDK. * * A streaming command returns an `AsyncIterable` from the SDK instead of a - * `Promise`. `script/generate-sdk.ts` reads this module to type the generated - * methods, and `sdk.run()` reads it to pick the same return shape at runtime, - * so the two cannot disagree. + * `Promise`. Commands declare it with `streams` in `buildCommand`. The SDK + * generator reads that marker through {@link streamingModeOf}, and + * `script/generate-streaming-commands.ts` writes + * {@link collectStreamingCommands} to `src/generated/streaming-commands.json` + * for `sdk.run()`, which must pick a return shape before it loads any + * command. Both come from the command definitions, so there is no list to + * keep in sync. * - * Live output gets its own command (`log tail`), not a mode flag on a list - * command; see `design/sentry-cli.md`. `--refresh` on `dashboard view` is the - * one flag that still switches a command into streaming. - * - * Streaming is per command: a flag or alias streams only in the command - * listed with it, so `-r` on `dashboard view` streams and `-f` never does. + * Streaming is per command: a flag or alias streams only in the command that + * declares it, so `-r` on `dashboard view` streams and `-f` never does. * * @module */ import { buildTopLevelFlags } from "./global-flags.js"; +import type { Command, RouteMap } from "./introspect.js"; /** - * How a command streams: on every run, or only when one of its flags is - * passed. `alias` is that flag's short alias in the command, if any. + * How a command streams. Without `flag`, every run streams. With `flag`, only + * runs that pass `--` or its short `alias` do. */ -export type StreamingMode = - | { readonly kind: "always" } - | { readonly kind: "flag"; readonly flag: string; readonly alias?: string }; +export type StreamingMode = { + readonly flag?: string; + readonly alias?: string; +}; + +/** Streaming commands keyed by space-separated route path. */ +export type StreamingCommands = Readonly>; /** - * Every command that can stream, keyed by space-separated route path. - * `test/lib/streaming-commands.test.ts` checks this table against the real - * route tree: each flag and alias here must match the command's own - * definition, and no other flag or alias of any command may stream. + * The streaming mode a command declares with `streams` in `buildCommand`, + * with the flag's short alias read from the command's own aliases. + * `undefined` for commands that never stream. */ -export const STREAMING_COMMANDS: Readonly> = { - "log tail": { kind: "always" }, - "dashboard view": { kind: "flag", flag: "refresh", alias: "r" }, -}; +export function streamingModeOf(command: Command): StreamingMode | undefined { + const streams = (command as { __streams?: true | { flag: string } }) + .__streams; + if (!streams) { + return; + } + if (streams === true) { + return {}; + } + const alias = Object.entries(command.parameters.aliases ?? {}).find( + ([, target]) => target === streams.flag, + )?.[0]; + return alias ? { flag: streams.flag, alias } : { flag: streams.flag }; +} + +/** + * Every streaming command in a route tree, hidden alias routes included, + * keyed by route path. + */ +export function collectStreamingCommands( + map: RouteMap, + prefix: readonly string[] = [], +): Record { + const found: Record = {}; + for (const entry of map.getAllEntries()) { + const path = [...prefix, entry.name.original]; + if ("getAllEntries" in entry.target) { + Object.assign(found, collectStreamingCommands(entry.target, path)); + continue; + } + const mode = streamingModeOf(entry.target); + if (mode) { + found[path.join(" ")] = mode; + } + } + return found; +} /** * The leading route segments of raw CLI arguments, skipping global flags the @@ -66,10 +103,7 @@ function routeSegments(args: readonly string[], depth: number): string[] { } /** Whether `arg` passes the streaming flag of `mode`. */ -function passesStreamingFlag( - arg: string, - mode: Extract, -): boolean { +function passesStreamingFlag(arg: string, mode: StreamingMode): boolean { return ( arg === `--${mode.flag}` || arg.startsWith(`--${mode.flag}=`) || @@ -82,15 +116,18 @@ function passesStreamingFlag( * flag of the command they run. Matches route paths against the leading route * segments, so `log tail ...` streams while `log list ...` does not. */ -export function isStreamingInvocation(args: readonly string[]): boolean { - for (const [path, mode] of Object.entries(STREAMING_COMMANDS)) { +export function isStreamingInvocation( + args: readonly string[], + commands: StreamingCommands, +): boolean { + for (const [path, mode] of Object.entries(commands)) { const expected = path.split(" "); const actual = routeSegments(args, expected.length); if (!expected.every((segment, index) => actual[index] === segment)) { continue; } return ( - mode.kind === "always" || + mode.flag === undefined || args.some((arg) => passesStreamingFlag(arg, mode)) ); } diff --git a/packages/cli/test/lib/short-flag-conventions.test.ts b/packages/cli/test/lib/short-flag-conventions.test.ts index b6f818a26b..e6bc7ab9e2 100644 --- a/packages/cli/test/lib/short-flag-conventions.test.ts +++ b/packages/cli/test/lib/short-flag-conventions.test.ts @@ -14,7 +14,7 @@ import { extractAllRoutes, type RouteMap, } from "../../src/lib/introspect.js"; -import { STREAMING_COMMANDS } from "../../src/lib/streaming-commands.js"; +import { collectStreamingCommands } from "../../src/lib/streaming-commands.js"; /** * Commands that still stream through a mode flag. Each entry is a known gap @@ -24,8 +24,7 @@ const STREAMING_FLAG_COMMANDS = ["dashboard view"]; /** * Flag names that usually mean "keep running and stream". A command that adds - * one must be a listed gap, which forces the change through review here and - * in `STREAMING_COMMANDS`. + * one must be a listed gap and declare it with `streams` in `buildCommand`. */ const STREAM_LIKE_FLAG_NAMES = new Set([ "follow", @@ -41,6 +40,10 @@ const commands: CommandInfo[] = extractAllRoutes( routes as unknown as RouteMap, ).flatMap((route) => route.commands); +const streamingCommands = collectStreamingCommands( + routes as unknown as RouteMap, +); + /** `sentry log list` → `log list` */ function routePath(command: CommandInfo): string { return command.path.replace(/^sentry /, ""); @@ -72,8 +75,8 @@ describe("live output is its own command", () => { .map(routePath); expect(withStreamLikeFlag).toEqual(STREAMING_FLAG_COMMANDS); - const flagModeCommands = Object.entries(STREAMING_COMMANDS) - .filter(([, mode]) => mode.kind === "flag") + const flagModeCommands = Object.entries(streamingCommands) + .filter(([, mode]) => mode.flag !== undefined) .map(([path]) => path); expect(flagModeCommands).toEqual(STREAMING_FLAG_COMMANDS); }); @@ -86,11 +89,4 @@ describe("live output is its own command", () => { .map(routePath); expect(withFollow).toEqual([]); }); - - test("every streaming command is registered", () => { - const registered = new Set(commands.map(routePath)); - for (const path of Object.keys(STREAMING_COMMANDS)) { - expect(registered.has(path), path).toBe(true); - } - }); }); diff --git a/packages/cli/test/lib/streaming-commands.test.ts b/packages/cli/test/lib/streaming-commands.test.ts index f79da12ae2..f10685bddd 100644 --- a/packages/cli/test/lib/streaming-commands.test.ts +++ b/packages/cli/test/lib/streaming-commands.test.ts @@ -1,14 +1,18 @@ /** * Tests for which raw `sdk.run()` arguments stream. * - * The route-tree section checks every flag and alias of every registered - * command, so a short alias that collides with a streaming flag (the `-f` - * bug: `-f` was `--follow` in `sdk.run()` but `--fresh` in `issue list`) - * fails here instead of hanging an SDK caller. + * Commands declare streaming with `streams` in `buildCommand`, and + * `sdk.run()` reads the generated `streaming-commands.json`. The route-tree + * section runs every flag and alias of every registered command through the + * generated table and compares the answer with the command's own marker, so + * a short alias that collides with a streaming flag (the `-f` bug: `-f` was + * `--follow` in `sdk.run()` but `--fresh` in `issue list`) or a stale + * generated file fails here instead of hanging an SDK caller. */ import { describe, expect, test } from "vitest"; import { routes } from "../../src/app.js"; +import generated from "../../src/generated/streaming-commands.json" with { type: "json" }; import { isCommand, isRouteMap, @@ -16,10 +20,19 @@ import { type RouteMap, } from "../../src/lib/introspect.js"; import { + collectStreamingCommands, isStreamingInvocation, - STREAMING_COMMANDS, + type StreamingCommands, + streamingModeOf, } from "../../src/lib/streaming-commands.js"; +const STREAMING_COMMANDS: StreamingCommands = generated; + +/** What `sdk.run()` decides for these raw arguments. */ +function streams(args: readonly string[]): boolean { + return isStreamingInvocation(args, STREAMING_COMMANDS); +} + type RegisteredCommand = { path: string[]; command: Command }; /** Every command in the route tree, hidden aliases included. */ @@ -36,29 +49,39 @@ function allCommands( }); } -const registered = allCommands(routes as unknown as RouteMap); +const routeMap = routes as unknown as RouteMap; +const registered = allCommands(routeMap); + +describe("streaming comes from the commands' streams markers", () => { + test("log tail always streams, dashboard view streams on -r/--refresh", () => { + expect(STREAMING_COMMANDS["log tail"]).toEqual({}); + expect(STREAMING_COMMANDS["dashboard view"]).toEqual({ + flag: "refresh", + alias: "r", + }); + }); + + test("the generated table is current", () => { + expect(STREAMING_COMMANDS).toEqual(collectStreamingCommands(routeMap)); + }); -describe("STREAMING_COMMANDS matches the route tree", () => { - test("every entry is a registered command whose flag and alias match", () => { - for (const [path, mode] of Object.entries(STREAMING_COMMANDS)) { - const found = registered.find((cmd) => cmd.path.join(" ") === path); - expect(found, path).toBeDefined(); - if (mode.kind !== "flag" || !found) { - continue; + test("a declared streaming flag exists on its command", () => { + for (const { path, command } of registered) { + const flag = streamingModeOf(command)?.flag; + if (flag !== undefined) { + expect( + Object.keys(command.parameters.flags ?? {}), + path.join(" "), + ).toContain(flag); } - const { flags = {}, aliases = {} } = found.command.parameters; - expect(Object.keys(flags), path).toContain(mode.flag); - const commandAlias = Object.entries(aliases).find( - ([, target]) => target === mode.flag, - )?.[0]; - expect(mode.alias, `${path}: alias of --${mode.flag}`).toBe(commandAlias); } }); - test("a flag or alias streams only where the table says so", () => { + test("a flag or alias streams in sdk.run() only where its command says so", () => { const wrong: string[] = []; for (const { path, command } of registered) { - const mode = STREAMING_COMMANDS[path.join(" ")]; + const mode = streamingModeOf(command); + const always = mode !== undefined && mode.flag === undefined; const { flags = {}, aliases = {} } = command.parameters; const tokens: [string, string][] = [ ...Object.keys(flags).map((name): [string, string] => [ @@ -71,15 +94,13 @@ describe("STREAMING_COMMANDS matches the route tree", () => { ]), ]; for (const [token, flagName] of tokens) { - const expected = - mode?.kind === "always" || - (mode?.kind === "flag" && mode.flag === flagName); - if (isStreamingInvocation([...path, token]) !== expected) { + const expected = always || mode?.flag === flagName; + if (streams([...path, token]) !== expected) { wrong.push(`${path.join(" ")} ${token}: expected ${expected}`); } } - if (isStreamingInvocation(path) !== (mode?.kind === "always")) { - wrong.push(`${path.join(" ")}: expected ${mode?.kind === "always"}`); + if (streams(path) !== always) { + wrong.push(`${path.join(" ")}: expected ${always}`); } } expect(wrong).toEqual([]); @@ -88,44 +109,36 @@ describe("STREAMING_COMMANDS matches the route tree", () => { describe("isStreamingInvocation", () => { test("a streaming command streams with any arguments", () => { - expect(isStreamingInvocation(["log", "tail"])).toBe(true); - expect(isStreamingInvocation(["log", "tail", "acme/api", "-i", "5"])).toBe( - true, - ); + expect(streams(["log", "tail"])).toBe(true); + expect(streams(["log", "tail", "acme/api", "-i", "5"])).toBe(true); }); test("a streaming flag streams in long, --flag=value, or alias form", () => { - expect(isStreamingInvocation(["dashboard", "view", "1", "-r"])).toBe(true); - expect(isStreamingInvocation(["dashboard", "view", "1", "--refresh"])).toBe( - true, - ); - expect( - isStreamingInvocation(["dashboard", "view", "1", "--refresh=30"]), - ).toBe(true); + expect(streams(["dashboard", "view", "1", "-r"])).toBe(true); + expect(streams(["dashboard", "view", "1", "--refresh"])).toBe(true); + expect(streams(["dashboard", "view", "1", "--refresh=30"])).toBe(true); }); test("-f is --fresh, not a stream", () => { - expect(isStreamingInvocation(["log", "list", "-f"])).toBe(false); - expect(isStreamingInvocation(["issue", "list", "-f"])).toBe(false); + expect(streams(["log", "list", "-f"])).toBe(false); + expect(streams(["issue", "list", "-f"])).toBe(false); }); test("a streaming flag streams only in its own command", () => { - expect(isStreamingInvocation(["issue", "list", "--refresh"])).toBe(false); - expect(isStreamingInvocation(["log", "list", "-r"])).toBe(false); + expect(streams(["issue", "list", "--refresh"])).toBe(false); + expect(streams(["log", "list", "-r"])).toBe(false); }); test("global flags before or between route segments are skipped", () => { - expect(isStreamingInvocation(["--json", "log", "tail"])).toBe(true); - expect(isStreamingInvocation(["log", "--json", "tail"])).toBe(true); - expect(isStreamingInvocation(["--log-level", "debug", "log", "tail"])).toBe( - true, - ); - expect(isStreamingInvocation(["log", "--org=acme", "tail"])).toBe(true); - expect(isStreamingInvocation(["--json", "log", "list"])).toBe(false); + expect(streams(["--json", "log", "tail"])).toBe(true); + expect(streams(["log", "--json", "tail"])).toBe(true); + expect(streams(["--log-level", "debug", "log", "tail"])).toBe(true); + expect(streams(["log", "--org=acme", "tail"])).toBe(true); + expect(streams(["--json", "log", "list"])).toBe(false); }); test("the command path must lead the arguments", () => { - expect(isStreamingInvocation(["log", "list", "tail"])).toBe(false); - expect(isStreamingInvocation(["log"])).toBe(false); + expect(streams(["log", "list", "tail"])).toBe(false); + expect(streams(["log"])).toBe(false); }); });