Skip to main content

logbrew_cli/
error.rs

1//! CLI error types and output rendering.
2
3use crate::ISSUE_STATUS_VALUES_NEXT_STEP;
4use std::borrow::Cow;
5
6/// CLI parsing error.
7#[derive(Debug, thiserror::Error, PartialEq, Eq)]
8pub enum CliError {
9    /// Command is missing or unsupported.
10    #[error("unknown or missing command")]
11    UnknownCommand,
12    /// Command name is unsupported.
13    #[error("unknown command: {command}")]
14    UnknownCommandName {
15        /// Unsupported command name.
16        command: String,
17        /// Suggested next step.
18        next: &'static str,
19    },
20    /// Required command argument is missing.
21    #[error("missing argument: {argument}")]
22    MissingArgument {
23        /// Missing argument name.
24        argument: &'static str,
25        /// Argument-specific next step.
26        next: &'static str,
27    },
28    /// Required flag value is missing.
29    #[error("missing value for {flag}")]
30    MissingFlagValue {
31        /// Flag missing a value.
32        flag: &'static str,
33        /// Flag-specific next step.
34        next: &'static str,
35    },
36    /// Flag is present more than once.
37    #[error("duplicate flag: {flag}")]
38    DuplicateFlag {
39        /// Duplicate flag value.
40        flag: &'static str,
41        /// Flag-specific next step.
42        next: &'static str,
43    },
44    /// Positional argument is unsupported for the selected command.
45    #[error("unexpected argument for {command}: {argument}")]
46    UnexpectedArgument {
47        /// Unexpected argument value.
48        argument: String,
49        /// Command name.
50        command: &'static str,
51        /// Command-specific next step.
52        next: &'static str,
53    },
54    /// Flag is unknown for the selected command.
55    #[error("unknown flag: {flag}")]
56    UnknownFlag {
57        /// Unknown flag value.
58        flag: String,
59        /// Command-specific next step.
60        next: &'static str,
61    },
62    /// Flag is known globally but unsupported for the selected command.
63    #[error("unsupported flag for {command}: {flag}")]
64    UnsupportedFlag {
65        /// Unsupported flag value.
66        flag: String,
67        /// Command name.
68        command: &'static str,
69        /// Command-specific next step.
70        next: &'static str,
71    },
72    /// Resource is unsupported for the selected command.
73    #[error("unknown resource: {resource}")]
74    UnknownResource {
75        /// Unsupported resource value.
76        resource: String,
77        /// Command-specific next step.
78        next: &'static str,
79    },
80    /// Issue status is unsupported.
81    #[error("unknown issue status: {0}")]
82    UnknownStatus(String),
83    /// Trace status is unsupported.
84    #[error("unknown trace status: {0}")]
85    UnknownTraceStatus(String),
86    /// Log level is unsupported.
87    #[error("unknown log level: {0}")]
88    UnknownLogLevel(String),
89    /// Row limit is malformed.
90    #[error("invalid limit: {0}")]
91    InvalidLimit(String),
92    /// Minimum trace duration is malformed.
93    #[error("invalid minimum duration: {0}")]
94    InvalidMinDuration(String),
95    /// Pagination mode is unsupported.
96    #[error("unknown pagination mode")]
97    UnknownPagination,
98    /// Action cursor fields are inconsistent.
99    #[error("invalid action cursor: {0}")]
100    InvalidActionCursor(String),
101    /// Log cursor fields are inconsistent.
102    #[error("invalid log cursor: {0}")]
103    InvalidLogCursor(String),
104    /// Issue cursor fields are inconsistent.
105    #[error("invalid issue cursor: {0}")]
106    InvalidIssueCursor(String),
107    /// Support-ticket cursor fields are inconsistent.
108    #[error("invalid support cursor: {0}")]
109    InvalidSupportCursor(String),
110    /// Support-ticket category is unsupported.
111    #[error("unknown support category")]
112    UnknownSupportCategory,
113    /// Support-ticket identifier is not in the public `sup_` form.
114    #[error("invalid support ticket id")]
115    InvalidSupportTicketId,
116    /// Support context retry key cannot be sent as an HTTP header value.
117    #[error("invalid support retry key")]
118    InvalidSupportRetryKey,
119    /// Support context reply syntax is malformed.
120    #[error("invalid support context reply")]
121    InvalidSupportContextReply,
122    /// Support context history syntax is malformed.
123    #[error("invalid support context command")]
124    InvalidSupportContextCommand,
125    /// Support context text is blank or exceeds the public limit.
126    #[error("invalid support context")]
127    InvalidSupportContext,
128    /// Issue investigation syntax is malformed.
129    #[error("invalid issue investigation command")]
130    InvalidInvestigationCommand,
131    /// Project-scoped doctor syntax is malformed.
132    #[error("invalid project doctor command")]
133    InvalidDoctorCommand,
134    /// Secure project creation syntax is malformed.
135    #[error("invalid project create command")]
136    InvalidProjectCreateCommand,
137    /// Authenticated project catalog syntax is malformed.
138    #[error("invalid projects command")]
139    InvalidProjectsCommand,
140    /// Account usage read syntax is malformed.
141    #[error("invalid usage command")]
142    InvalidUsageCommand,
143    /// Native debug-artifact command syntax is malformed.
144    #[error("invalid native debug-artifact command")]
145    InvalidNativeDebugCommand,
146    /// Native debug-artifact identity is not canonical.
147    #[error("invalid native debug-artifact identity")]
148    InvalidNativeDebugIdentity,
149    /// Project setup source is malformed.
150    #[error("invalid setup source: {0}")]
151    InvalidSetupSource(String),
152}
153
154/// Runtime error for command execution.
155#[derive(Debug, thiserror::Error)]
156pub enum RuntimeError {
157    /// Command-line parsing failed.
158    #[error(transparent)]
159    Cli(#[from] CliError),
160    /// Filesystem or process I/O failed.
161    #[error(transparent)]
162    Io(#[from] std::io::Error),
163    /// HTTP request failed.
164    #[error(transparent)]
165    Http(#[from] reqwest::Error),
166    /// Auth token was missing for an authenticated API call.
167    #[error("not logged in: run logbrew login")]
168    MissingToken,
169    /// API returned a non-success status.
170    #[error("api returned status {status}: {body}")]
171    Api {
172        /// HTTP status code.
173        status: u16,
174        /// Response body.
175        body: String,
176        /// Stable machine-readable auth source key.
177        auth_source: &'static str,
178        /// Concise human auth label.
179        auth_label: &'static str,
180    },
181    /// Status check could not prove API reachability.
182    #[error("LogBrew API unreachable: {message}")]
183    StatusUnavailable {
184        /// Base API URL checked by the CLI.
185        api_url: String,
186        /// Optional HTTP status code returned by `/health`.
187        status_code: Option<u16>,
188        /// Optional response body returned by `/health`.
189        body: Option<String>,
190        /// Whether a local credential is configured.
191        authenticated: bool,
192        /// Stable machine-readable auth source key.
193        auth_source: &'static str,
194        /// Concise human auth label.
195        auth_label: &'static str,
196        /// Human-readable reachability reason.
197        message: String,
198    },
199    /// Command is recognized but not available yet.
200    #[error("{message}")]
201    Unavailable {
202        /// Human-readable unavailable reason.
203        message: &'static str,
204        /// Suggested fallback action.
205        next: &'static str,
206    },
207    /// A successful investigation response violated the public contract.
208    #[error("issue investigation returned an invalid response")]
209    InvestigationResponseInvalid,
210    /// A local Apple native debug artifact failed validation.
211    #[error("native debug artifact is invalid")]
212    NativeDebugArtifactInvalid,
213    /// A native debug-artifact response violated the public contract.
214    #[error("native debug-artifact response is invalid")]
215    NativeDebugResponseInvalid,
216    /// Exact post-upload lookup verification did not match.
217    #[error("native debug-artifact verification failed")]
218    NativeDebugVerificationFailed,
219}
220
221/// Writes a command-line parsing error for humans or agents.
222///
223/// # Errors
224///
225/// Returns an I/O error if writing to the output stream fails.
226pub fn write_cli_error<W: std::io::Write>(
227    error: &CliError,
228    json: bool,
229    output: &mut W,
230) -> Result<(), std::io::Error> {
231    if json {
232        let body = serde_json::json!({
233            "ok": false,
234            "error": cli_error_code(error),
235            "message": error.to_string(),
236            "next": cli_error_next_step(error),
237        });
238        writeln!(output, "{body}")
239    } else {
240        writeln!(output, "{error}")?;
241        writeln!(output, "Next: {}", cli_error_next_step(error))
242    }
243}
244
245/// Writes a runtime error for humans or agents.
246///
247/// # Errors
248///
249/// Returns an I/O error if writing to the output stream fails.
250pub fn write_runtime_error<W: std::io::Write>(
251    error: &RuntimeError,
252    json: bool,
253    output: &mut W,
254) -> Result<(), std::io::Error> {
255    if json {
256        let body = runtime_error_json(error);
257        writeln!(output, "{body}")
258    } else {
259        write_human_runtime_error(error, output)
260    }
261}
262
263/// Writes a runtime error for human readers.
264fn write_human_runtime_error<W: std::io::Write>(
265    error: &RuntimeError,
266    output: &mut W,
267) -> Result<(), std::io::Error> {
268    match error {
269        RuntimeError::StatusUnavailable {
270            api_url,
271            status_code,
272            body,
273            auth_label,
274            message,
275            ..
276        } => {
277            writeln!(output, "LogBrew API unreachable.")?;
278            writeln!(output, "API: {api_url}")?;
279            writeln!(output, "Auth: {auth_label}")?;
280            if let Some(status_code) = status_code {
281                writeln!(output, "Status: {status_code}")?;
282            }
283            if let Some(body) = body.as_ref().filter(|body| !body.is_empty()) {
284                writeln!(output, "Body: {body}")?;
285            } else {
286                writeln!(output, "Reason: {message}")?;
287            }
288            writeln!(output, "Next: {STATUS_UNAVAILABLE_NEXT_STEP}")?;
289            Ok(())
290        }
291        RuntimeError::Api {
292            status,
293            body,
294            auth_label,
295            ..
296        } => {
297            let api_details = ApiErrorDetails::parse(body);
298            writeln!(output, "{error}")?;
299            if let Some(code) = api_details.code.as_deref() {
300                writeln!(output, "Code: {code}")?;
301            }
302            writeln!(output, "Auth: {auth_label}")?;
303            writeln!(output, "Next: {}", api_next_step(*status, &api_details))
304        }
305        RuntimeError::Cli(_)
306        | RuntimeError::Io(_)
307        | RuntimeError::Http(_)
308        | RuntimeError::MissingToken
309        | RuntimeError::InvestigationResponseInvalid
310        | RuntimeError::NativeDebugArtifactInvalid
311        | RuntimeError::NativeDebugResponseInvalid
312        | RuntimeError::NativeDebugVerificationFailed
313        | RuntimeError::Unavailable { .. } => {
314            writeln!(output, "{error}")?;
315            writeln!(output, "Next: {}", runtime_error_next_step(error))?;
316            Ok(())
317        }
318    }
319}
320
321/// Builds a JSON runtime error body for agents.
322fn runtime_error_json(error: &RuntimeError) -> serde_json::Value {
323    match error {
324        RuntimeError::MissingToken
325        | RuntimeError::Unavailable { .. }
326        | RuntimeError::InvestigationResponseInvalid
327        | RuntimeError::NativeDebugArtifactInvalid
328        | RuntimeError::NativeDebugResponseInvalid
329        | RuntimeError::NativeDebugVerificationFailed
330        | RuntimeError::Io(_)
331        | RuntimeError::Http(_) => serde_json::json!({
332            "ok": false,
333            "error": runtime_error_code(error),
334            "message": error.to_string(),
335            "next": runtime_error_next_step(error),
336        }),
337        RuntimeError::Api {
338            status,
339            body,
340            auth_source,
341            ..
342        } => {
343            let api_details = ApiErrorDetails::parse(body);
344            let next = api_next_step(*status, &api_details);
345            serde_json::json!({
346                "ok": false,
347                "error": runtime_error_code(error),
348                "message": error.to_string(),
349                "status": status,
350                "body": body,
351                "api_error": api_details.error.as_deref(),
352                "api_code": api_details.code.as_deref(),
353                "api_next": api_details.next.as_deref(),
354                "auth_source": auth_source,
355                "next": next,
356            })
357        }
358        RuntimeError::StatusUnavailable {
359            api_url,
360            status_code,
361            body,
362            authenticated,
363            auth_source,
364            message,
365            ..
366        } => serde_json::json!({
367            "ok": false,
368            "error": runtime_error_code(error),
369            "status": "unreachable",
370            "status_code": status_code,
371            "body": body,
372            "api_url": api_url,
373            "authenticated": authenticated,
374            "auth_source": auth_source,
375            "message": message,
376            "next": runtime_error_next_step(error),
377        }),
378        RuntimeError::Cli(error) => serde_json::json!({
379            "ok": false,
380            "error": cli_error_code(error),
381            "message": error.to_string(),
382            "next": cli_error_next_step(error),
383        }),
384    }
385}
386
387/// Returns a stable machine-readable parse error code.
388const fn cli_error_code(error: &CliError) -> &'static str {
389    match error {
390        CliError::UnknownCommand | CliError::UnknownCommandName { .. } => "unknown_command",
391        CliError::MissingArgument { .. } => "missing_argument",
392        CliError::MissingFlagValue { .. } => "missing_flag_value",
393        CliError::DuplicateFlag { .. } => "duplicate_flag",
394        CliError::UnexpectedArgument { .. } => "unexpected_argument",
395        CliError::UnknownFlag { .. } => "unknown_flag",
396        CliError::UnsupportedFlag { .. } => "unsupported_flag",
397        CliError::UnknownResource { .. } => "unknown_resource",
398        CliError::UnknownStatus(_) => "unknown_status",
399        CliError::UnknownTraceStatus(_) => "unknown_trace_status",
400        CliError::UnknownLogLevel(_) => "unknown_log_level",
401        CliError::InvalidLimit(_) => "invalid_limit",
402        CliError::InvalidMinDuration(_) => "invalid_min_duration",
403        CliError::UnknownPagination => "unknown_pagination",
404        CliError::InvalidActionCursor(_) => "invalid_action_cursor",
405        CliError::InvalidLogCursor(_) => "invalid_log_cursor",
406        CliError::InvalidIssueCursor(_) => "invalid_issue_cursor",
407        CliError::InvalidSupportCursor(_) => "invalid_support_cursor",
408        CliError::UnknownSupportCategory => "unknown_support_category",
409        CliError::InvalidSupportTicketId => "invalid_support_ticket_id",
410        CliError::InvalidSupportRetryKey => "invalid_support_retry_key",
411        CliError::InvalidSupportContextReply => "invalid_support_context_reply",
412        CliError::InvalidSupportContextCommand => "invalid_support_context_command",
413        CliError::InvalidSupportContext => "invalid_support_context",
414        CliError::InvalidInvestigationCommand => "invalid_investigation_command",
415        CliError::InvalidDoctorCommand => "invalid_doctor_command",
416        CliError::InvalidProjectCreateCommand => "invalid_project_create_command",
417        CliError::InvalidProjectsCommand => "invalid_projects_command",
418        CliError::InvalidUsageCommand => "invalid_usage_command",
419        CliError::InvalidNativeDebugCommand | CliError::InvalidNativeDebugIdentity => {
420            "invalid_native_debug_command"
421        }
422        CliError::InvalidSetupSource(_) => "invalid_setup_source",
423    }
424}
425
426/// Returns the next step for a parse error.
427const fn cli_error_next_step(error: &CliError) -> &'static str {
428    match error {
429        CliError::InvalidLimit(_) => "use --limit with a positive whole number",
430        CliError::InvalidMinDuration(_) => "use --min-duration-ms with a non-negative whole number",
431        CliError::UnknownPagination
432        | CliError::InvalidActionCursor(_)
433        | CliError::InvalidLogCursor(_)
434        | CliError::InvalidIssueCursor(_)
435        | CliError::InvalidSupportCursor(_) => {
436            "use --pagination cursor alone for the first page, then use --cursor-time and --cursor-id together from next_cursor"
437        }
438        CliError::UnknownSupportCategory => {
439            "use sdk_install_failure, ingest_failure, auth_failure, project_setup, dashboard_issue, docs_confusion, cli_issue, mobile_issue, billing_question, or other"
440        }
441        CliError::InvalidSupportTicketId => {
442            "use the ticket_id returned by logbrew support create or list"
443        }
444        CliError::InvalidSupportRetryKey => {
445            "use --retry-key with 1 to 128 visible ASCII characters and reuse it only for an exact retry"
446        }
447        CliError::InvalidSupportContextReply => {
448            "use support reply <ticket_id> --context <text> --retry-key <key>"
449        }
450        CliError::InvalidSupportContextCommand => {
451            "use support context <ticket_id> with optional --json"
452        }
453        CliError::InvalidSupportContext => {
454            "use --context with 1 to 4000 characters after trimming whitespace"
455        }
456        CliError::InvalidInvestigationCommand => {
457            "use logbrew investigate issue <issue_id> with optional --json"
458        }
459        CliError::InvalidDoctorCommand => {
460            "use logbrew doctor --project <project_id> with optional --json"
461        }
462        CliError::InvalidProjectCreateCommand => {
463            "use logbrew projects create <name> --ingest-key-file <path> with optional --runtime, --environment, --abandon-retry, and --json"
464        }
465        CliError::InvalidProjectsCommand => {
466            "use logbrew projects with optional --json, or logbrew projects --help"
467        }
468        CliError::InvalidUsageCommand => "use logbrew usage with optional --json",
469        CliError::InvalidNativeDebugCommand => {
470            "use logbrew debug-artifacts upload <path> --project <project_id> --release <release> --environment <environment> --service <service> with optional --expect-image-uuid, --dry-run, and --json"
471        }
472        CliError::InvalidNativeDebugIdentity => {
473            "use a lowercase UUID and architecture arm64, arm64e, or x86_64"
474        }
475        CliError::InvalidSetupSource(_) => "use --source api, cli, or sdk",
476        CliError::MissingArgument { next, .. }
477        | CliError::MissingFlagValue { next, .. }
478        | CliError::DuplicateFlag { next, .. }
479        | CliError::UnexpectedArgument { next, .. }
480        | CliError::UnsupportedFlag { next, .. }
481        | CliError::UnknownFlag { next, .. }
482        | CliError::UnknownResource { next, .. }
483        | CliError::UnknownCommandName { next, .. } => next,
484        CliError::UnknownCommand => "run logbrew --help",
485        CliError::UnknownStatus(_) => ISSUE_STATUS_VALUES_NEXT_STEP,
486        CliError::UnknownTraceStatus(_) => "use --status error or --status ok",
487        CliError::UnknownLogLevel(_) => "use one of info, warning, error, critical",
488    }
489}
490
491/// Returns a stable machine-readable runtime error code.
492const fn runtime_error_code(error: &RuntimeError) -> &'static str {
493    match error {
494        RuntimeError::Cli(error) => cli_error_code(error),
495        RuntimeError::Io(_) => "io_error",
496        RuntimeError::Http(_) => "http_error",
497        RuntimeError::MissingToken => "not_logged_in",
498        RuntimeError::Api { .. } => "api_error",
499        RuntimeError::StatusUnavailable { .. } => "status_unreachable",
500        RuntimeError::Unavailable { .. } => "unavailable",
501        RuntimeError::InvestigationResponseInvalid => "investigation_response_invalid",
502        RuntimeError::NativeDebugArtifactInvalid => "native_debug_artifact_invalid",
503        RuntimeError::NativeDebugResponseInvalid => "native_debug_response_invalid",
504        RuntimeError::NativeDebugVerificationFailed => "native_debug_verification_failed",
505    }
506}
507
508/// Next step for failed `status` reachability checks.
509const STATUS_UNAVAILABLE_NEXT_STEP: &str = "check LOGBREW_API_URL or network";
510
511/// Parsed public API error details.
512#[derive(Debug, Clone, Default, PartialEq, Eq)]
513struct ApiErrorDetails {
514    /// Human-readable backend error message.
515    error: Option<String>,
516    /// Stable backend error code.
517    code: Option<String>,
518    /// Backend-provided recovery step.
519    next: Option<String>,
520}
521
522impl ApiErrorDetails {
523    /// Parses additive backend error fields from an API response body.
524    fn parse(body: &str) -> Self {
525        let Ok(value) = serde_json::from_str::<serde_json::Value>(body) else {
526            return Self::default();
527        };
528
529        Self {
530            error: json_string_field(&value, "error"),
531            code: json_string_field(&value, "code"),
532            next: json_string_field(&value, "next"),
533        }
534    }
535}
536
537/// Extracts a non-empty string field from a JSON object.
538fn json_string_field(value: &serde_json::Value, key: &str) -> Option<String> {
539    value
540        .get(key)
541        .and_then(serde_json::Value::as_str)
542        .map(str::trim)
543        .filter(|value| !value.is_empty())
544        .map(ToOwned::to_owned)
545}
546
547/// Returns a useful next step for runtime errors when one is known.
548fn runtime_error_next_step(error: &RuntimeError) -> Cow<'static, str> {
549    match error {
550        RuntimeError::Api { status, body, .. } => {
551            let api_details = ApiErrorDetails::parse(body);
552            api_next_step(*status, &api_details)
553        }
554        RuntimeError::Cli(_)
555        | RuntimeError::Io(_)
556        | RuntimeError::Http(_)
557        | RuntimeError::MissingToken
558        | RuntimeError::InvestigationResponseInvalid
559        | RuntimeError::NativeDebugArtifactInvalid
560        | RuntimeError::NativeDebugResponseInvalid
561        | RuntimeError::NativeDebugVerificationFailed
562        | RuntimeError::StatusUnavailable { .. }
563        | RuntimeError::Unavailable { .. } => {
564            Cow::Borrowed(fallback_runtime_error_next_step(error))
565        }
566    }
567}
568
569/// Returns the API next step, preferring backend guidance when available.
570fn api_next_step(status: u16, api_details: &ApiErrorDetails) -> Cow<'static, str> {
571    api_details.next.as_ref().map_or_else(
572        || Cow::Borrowed(fallback_api_next_step(status)),
573        |next| Cow::Owned(next.clone()),
574    )
575}
576
577/// Returns the CLI fallback next step for an API status.
578const fn fallback_api_next_step(status: u16) -> &'static str {
579    match status {
580        401 | 403 => "run logbrew login",
581        400 | 422 => "check command arguments or filters",
582        404 => "check the resource id or filters",
583        429 => "retry later",
584        500..=599 => "check LOGBREW_API_URL or retry later",
585        _ => "check command arguments or retry later",
586    }
587}
588
589/// Returns a useful fallback next step for runtime errors when one is known.
590const fn fallback_runtime_error_next_step(error: &RuntimeError) -> &'static str {
591    match error {
592        RuntimeError::Cli(error) => cli_error_next_step(error),
593        RuntimeError::MissingToken => "run logbrew login",
594        RuntimeError::Api { status, .. } => fallback_api_next_step(*status),
595        RuntimeError::StatusUnavailable { .. } | RuntimeError::Http(_) => {
596            STATUS_UNAVAILABLE_NEXT_STEP
597        }
598        RuntimeError::Unavailable { next, .. } => next,
599        RuntimeError::InvestigationResponseInvalid => {
600            "retry the issue investigation; if it repeats, report the public response contract"
601        }
602        RuntimeError::NativeDebugArtifactInvalid => {
603            "provide one validated Apple dSYM, ZIP, or Mach-O object matching every --expect-image-uuid value"
604        }
605        RuntimeError::NativeDebugResponseInvalid => {
606            "retry the native debug-artifact request; if it repeats, report the public response contract"
607        }
608        RuntimeError::NativeDebugVerificationFailed => {
609            "retry exact native debug-artifact lookup before using native symbolication"
610        }
611        RuntimeError::Io(_) => "check local files and permissions",
612    }
613}