1use crate::ISSUE_STATUS_VALUES_NEXT_STEP;
4use std::borrow::Cow;
5
6#[derive(Debug, thiserror::Error, PartialEq, Eq)]
8pub enum CliError {
9 #[error("unknown or missing command")]
11 UnknownCommand,
12 #[error("unknown command: {command}")]
14 UnknownCommandName {
15 command: String,
17 next: &'static str,
19 },
20 #[error("missing argument: {argument}")]
22 MissingArgument {
23 argument: &'static str,
25 next: &'static str,
27 },
28 #[error("missing value for {flag}")]
30 MissingFlagValue {
31 flag: &'static str,
33 next: &'static str,
35 },
36 #[error("duplicate flag: {flag}")]
38 DuplicateFlag {
39 flag: &'static str,
41 next: &'static str,
43 },
44 #[error("unexpected argument for {command}: {argument}")]
46 UnexpectedArgument {
47 argument: String,
49 command: &'static str,
51 next: &'static str,
53 },
54 #[error("unknown flag: {flag}")]
56 UnknownFlag {
57 flag: String,
59 next: &'static str,
61 },
62 #[error("unsupported flag for {command}: {flag}")]
64 UnsupportedFlag {
65 flag: String,
67 command: &'static str,
69 next: &'static str,
71 },
72 #[error("unknown resource: {resource}")]
74 UnknownResource {
75 resource: String,
77 next: &'static str,
79 },
80 #[error("unknown issue status: {0}")]
82 UnknownStatus(String),
83 #[error("unknown trace status: {0}")]
85 UnknownTraceStatus(String),
86 #[error("unknown log level: {0}")]
88 UnknownLogLevel(String),
89 #[error("invalid limit: {0}")]
91 InvalidLimit(String),
92 #[error("invalid minimum duration: {0}")]
94 InvalidMinDuration(String),
95 #[error("unknown pagination mode")]
97 UnknownPagination,
98 #[error("invalid action cursor: {0}")]
100 InvalidActionCursor(String),
101 #[error("invalid log cursor: {0}")]
103 InvalidLogCursor(String),
104 #[error("invalid issue cursor: {0}")]
106 InvalidIssueCursor(String),
107 #[error("invalid support cursor: {0}")]
109 InvalidSupportCursor(String),
110 #[error("unknown support category")]
112 UnknownSupportCategory,
113 #[error("invalid support ticket id")]
115 InvalidSupportTicketId,
116 #[error("invalid support retry key")]
118 InvalidSupportRetryKey,
119 #[error("invalid support context reply")]
121 InvalidSupportContextReply,
122 #[error("invalid support context command")]
124 InvalidSupportContextCommand,
125 #[error("invalid support context")]
127 InvalidSupportContext,
128 #[error("invalid issue investigation command")]
130 InvalidInvestigationCommand,
131 #[error("invalid project doctor command")]
133 InvalidDoctorCommand,
134 #[error("invalid project create command")]
136 InvalidProjectCreateCommand,
137 #[error("invalid projects command")]
139 InvalidProjectsCommand,
140 #[error("invalid usage command")]
142 InvalidUsageCommand,
143 #[error("invalid native debug-artifact command")]
145 InvalidNativeDebugCommand,
146 #[error("invalid native debug-artifact identity")]
148 InvalidNativeDebugIdentity,
149 #[error("invalid setup source: {0}")]
151 InvalidSetupSource(String),
152}
153
154#[derive(Debug, thiserror::Error)]
156pub enum RuntimeError {
157 #[error(transparent)]
159 Cli(#[from] CliError),
160 #[error(transparent)]
162 Io(#[from] std::io::Error),
163 #[error(transparent)]
165 Http(#[from] reqwest::Error),
166 #[error("not logged in: run logbrew login")]
168 MissingToken,
169 #[error("api returned status {status}: {body}")]
171 Api {
172 status: u16,
174 body: String,
176 auth_source: &'static str,
178 auth_label: &'static str,
180 },
181 #[error("LogBrew API unreachable: {message}")]
183 StatusUnavailable {
184 api_url: String,
186 status_code: Option<u16>,
188 body: Option<String>,
190 authenticated: bool,
192 auth_source: &'static str,
194 auth_label: &'static str,
196 message: String,
198 },
199 #[error("{message}")]
201 Unavailable {
202 message: &'static str,
204 next: &'static str,
206 },
207 #[error("issue investigation returned an invalid response")]
209 InvestigationResponseInvalid,
210 #[error("native debug artifact is invalid")]
212 NativeDebugArtifactInvalid,
213 #[error("native debug-artifact response is invalid")]
215 NativeDebugResponseInvalid,
216 #[error("native debug-artifact verification failed")]
218 NativeDebugVerificationFailed,
219}
220
221pub 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
245pub 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
263fn 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
321fn 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
387const 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
426const 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
491const 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
508const STATUS_UNAVAILABLE_NEXT_STEP: &str = "check LOGBREW_API_URL or network";
510
511#[derive(Debug, Clone, Default, PartialEq, Eq)]
513struct ApiErrorDetails {
514 error: Option<String>,
516 code: Option<String>,
518 next: Option<String>,
520}
521
522impl ApiErrorDetails {
523 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
537fn 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
547fn 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
569fn 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
577const 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
589const 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}