Skip to main content

docsrs_cli/
error.rs

1//! Error types and exit-code mapping for docsrs-cli.
2//!
3//! # Model (Rules Rust — error handling)
4//!
5//! - Recoverable failures are [`AppError`] / [`AppResult`] (I/O, network, parse, validation).
6//! - [`ErrorKind`] is the stable discriminant for exit codes and JSON `error.kind`.
7//! - [`std::error::Error::source`] preserves the lower-level cause when present.
8//! - Display messages are technical English: lowercase, no trailing period, no secrets.
9//! - Panic is reserved for static invariants (hardcoded regex / CSS selectors).
10//! - Library API: typed `thiserror` enum, not `anyhow` / `Box<dyn Error>` as the public `E`.
11//!
12//! See `docs/decisions/0002-error-model.md`.
13//!
14//! # Errors
15//!
16//! | Kind | Exit | Retryable |
17//! |------|------|-----------|
18//! | usage | 64 | no |
19//! | invalid_input | 65 | no |
20//! | not_found | 66 | no |
21//! | rate_limited / unavailable | 69 | yes |
22//! | network | 74 | yes |
23//! | budget | 74 | no |
24//! | timeout | 124 | yes |
25//! | parse | 65 | no |
26//! | config | 78 | no |
27//! | internal | 70 | no |
28//! | interrupted (SIGINT) | 130 | no |
29//! | terminated (SIGTERM) | 143 | no |
30//! | broken_pipe (stdout EPIPE) | 141 | no |
31
32use std::process::ExitCode;
33use std::sync::Arc;
34
35use thiserror::Error;
36
37// ── Named process exit codes (sysexits-inspired + signal/convention) ─────────
38// Every `ExitCode::from(N)` / `process::exit(N)` in product code must use these
39// (or [`ErrorKind::exit_code`]) — never raw numeric literals for exit status.
40
41/// Clap / argv usage error (sysexits `EX_USAGE`).
42pub const EXIT_USAGE: u8 = 64;
43/// Domain validation failure (invalid crate name, path, pagination).
44pub const EXIT_INVALID_INPUT: u8 = 65;
45/// Remote resource missing (HTTP 404).
46pub const EXIT_NOT_FOUND: u8 = 66;
47/// Rate limit or temporary remote unavailability (HTTP 429/5xx).
48pub const EXIT_UNAVAILABLE: u8 = 69;
49/// Unexpected internal failure.
50pub const EXIT_INTERNAL: u8 = 70;
51/// Transport / network failure or local body budget.
52pub const EXIT_NETWORK: u8 = 74;
53/// Local configuration error (XDG TOML, origins).
54pub const EXIT_CONFIG: u8 = 78;
55/// Wall-clock deadline exceeded.
56pub const EXIT_TIMEOUT: u8 = 124;
57/// SIGINT / Ctrl-C cooperative cancel.
58pub const EXIT_INTERRUPTED: u8 = 130;
59/// stdout EPIPE / broken pipe.
60pub const EXIT_BROKEN_PIPE: u8 = 141;
61/// SIGTERM / SIGHUP terminate.
62pub const EXIT_TERMINATED: u8 = 143;
63
64/// Canonical error kinds exposed in JSON envelopes.
65///
66/// Marked `#[non_exhaustive]` so new kinds can ship without a SemVer major break
67/// for external `match` consumers of this library.
68#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
69#[serde(rename_all = "snake_case")]
70#[non_exhaustive]
71pub enum ErrorKind {
72    /// Clap usage / argv error (exit 64).
73    Usage,
74    /// Invalid domain input such as crate name or path (exit 65).
75    InvalidInput,
76    /// Remote resource missing (exit 66).
77    NotFound,
78    /// HTTP 429 rate limit (exit 69, retryable).
79    RateLimited,
80    /// Remote 5xx or temporary outage (exit 69, retryable).
81    Unavailable,
82    /// Wall-clock deadline exceeded (exit 124, retryable).
83    Timeout,
84    /// Transport / unexpected HTTP failure (exit 74, retryable).
85    Network,
86    /// Local body/output budget exceeded (exit 74, **not** retryable).
87    ///
88    /// Permanent for the same config: raising `--max-body-bytes` (or lowering
89    /// the remote payload) is required — agents must not auto-retry.
90    Budget,
91    /// Body parse failure (exit 65).
92    Parse,
93    /// Local configuration error (exit 78).
94    Config,
95    /// Unexpected internal failure (exit 70).
96    Internal,
97    /// SIGINT / Ctrl-C
98    Interrupted,
99    /// SIGTERM graceful cancel
100    Terminated,
101    /// stdout write hit a closed pipe (EPIPE / SIGPIPE)
102    BrokenPipe,
103}
104
105impl ErrorKind {
106    /// Stable snake_case identifier for JSON `error.kind`.
107    pub fn as_str(self) -> &'static str {
108        match self {
109            Self::Usage => "usage",
110            Self::InvalidInput => "invalid_input",
111            Self::NotFound => "not_found",
112            Self::RateLimited => "rate_limited",
113            Self::Unavailable => "unavailable",
114            Self::Timeout => "timeout",
115            Self::Network => "network",
116            Self::Budget => "budget",
117            Self::Parse => "parse",
118            Self::Config => "config",
119            Self::Internal => "internal",
120            Self::Interrupted => "interrupted",
121            Self::Terminated => "terminated",
122            Self::BrokenPipe => "broken_pipe",
123        }
124    }
125
126    /// Process exit code for this kind.
127    pub fn exit_code(self) -> u8 {
128        match self {
129            Self::Usage => EXIT_USAGE,
130            Self::InvalidInput => EXIT_INVALID_INPUT,
131            Self::NotFound => EXIT_NOT_FOUND,
132            Self::RateLimited | Self::Unavailable => EXIT_UNAVAILABLE,
133            Self::Network | Self::Budget => EXIT_NETWORK,
134            Self::Timeout => EXIT_TIMEOUT,
135            Self::Parse => EXIT_INVALID_INPUT,
136            Self::Config => EXIT_CONFIG,
137            Self::Internal => EXIT_INTERNAL,
138            Self::Interrupted => EXIT_INTERRUPTED,
139            Self::Terminated => EXIT_TERMINATED,
140            Self::BrokenPipe => EXIT_BROKEN_PIPE,
141        }
142    }
143
144    /// Whether an agent may retry the same invocation after backoff.
145    pub fn retryable(self) -> bool {
146        matches!(
147            self,
148            Self::RateLimited | Self::Unavailable | Self::Timeout | Self::Network
149        )
150    }
151
152    /// Alias of [`Self::retryable`] (Rules Rust checklist name `is_retryable`).
153    pub fn is_retryable(self) -> bool {
154        self.retryable()
155    }
156
157    /// Permanent for agent auto-retry (complement of [`Self::is_retryable`]).
158    ///
159    /// Cancel / broken-pipe kinds are permanent: do not re-issue the same command
160    /// as if the remote failed.
161    pub fn is_permanent(self) -> bool {
162        !self.retryable()
163    }
164
165    /// Detailed retry category (Rules Rust checklist `retry_kind`).
166    pub fn retry_kind(self) -> crate::retry::RetryKind {
167        use crate::retry::RetryKind;
168        match self {
169            Self::RateLimited => RetryKind::RateLimited,
170            Self::Unavailable => RetryKind::TransientServer,
171            Self::Timeout => RetryKind::Timeout,
172            Self::Network => RetryKind::TransientNetwork,
173            _ => RetryKind::Permanent,
174        }
175    }
176}
177
178/// Application error with structured kind for agents.
179///
180/// # Display
181///
182/// Prints only the technical English `message` field (lowercase, no trailing
183/// period). Walk [`std::error::Error::source`] for the cause chain; do not
184/// duplicate the cause text in `message`.
185///
186/// # Clone
187///
188/// Source is held in [`Arc`] so clones share the cause without re-boxing.
189#[derive(Debug, Error, Clone)]
190#[non_exhaustive]
191pub enum AppError {
192    /// Structured error used by all library and CLI paths.
193    #[error("{message}")]
194    Structured {
195        /// Canonical error kind for exit codes and JSON.
196        kind: ErrorKind,
197        /// Technical English message (never localized).
198        message: String,
199        /// Optional Retry-After hint from HTTP 429 / 503.
200        retry_after_secs: Option<u64>,
201        /// Optional lower-level cause (shared via [`Arc`] for [`Clone`]).
202        #[source]
203        source: Option<Arc<dyn std::error::Error + Send + Sync>>,
204    },
205}
206
207impl AppError {
208    /// Build a structured error without a source chain.
209    ///
210    /// # Errors
211    ///
212    /// This constructor never fails; the returned value is the error itself.
213    pub fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
214        Self::Structured {
215            kind,
216            message: message.into(),
217            retry_after_secs: None,
218            source: None,
219        }
220    }
221
222    /// Build a structured error with a source chain (cause preserved).
223    ///
224    /// The cause is available via [`std::error::Error::source`] and is not
225    /// duplicated in `message`.
226    pub fn with_source(
227        kind: ErrorKind,
228        message: impl Into<String>,
229        source: impl std::error::Error + Send + Sync + 'static,
230    ) -> Self {
231        Self::Structured {
232            kind,
233            message: message.into(),
234            retry_after_secs: None,
235            source: Some(Arc::new(source)),
236        }
237    }
238
239    /// Attach optional Retry-After seconds (HTTP 429 / 503).
240    pub fn with_retry_after(mut self, secs: u64) -> Self {
241        let Self::Structured {
242            retry_after_secs, ..
243        } = &mut self;
244        *retry_after_secs = Some(secs);
245        self
246    }
247
248    /// SIGINT cancel.
249    pub fn interrupted() -> Self {
250        Self::new(ErrorKind::Interrupted, "interrupted by SIGINT")
251    }
252
253    /// SIGTERM cancel.
254    pub fn terminated() -> Self {
255        Self::new(ErrorKind::Terminated, "terminated by SIGTERM")
256    }
257
258    /// stdout closed by the reader (pipe consumer exited).
259    pub fn broken_pipe() -> Self {
260        Self::new(ErrorKind::BrokenPipe, "broken pipe writing to stdout")
261    }
262
263    /// Returns the canonical error kind.
264    pub fn kind(&self) -> ErrorKind {
265        match self {
266            Self::Structured { kind, .. } => *kind,
267        }
268    }
269
270    /// Returns the technical English message.
271    pub fn message(&self) -> &str {
272        match self {
273            Self::Structured { message, .. } => message,
274        }
275    }
276
277    /// Returns optional Retry-After seconds when present.
278    pub fn retry_after_secs(&self) -> Option<u64> {
279        match self {
280            Self::Structured {
281                retry_after_secs, ..
282            } => *retry_after_secs,
283        }
284    }
285
286    /// Whether an agent may retry the same invocation after backoff.
287    pub fn retryable(&self) -> bool {
288        self.kind().retryable()
289    }
290
291    /// Alias of [`Self::retryable`] (Rules Rust checklist name `is_retryable`).
292    pub fn is_retryable(&self) -> bool {
293        self.retryable()
294    }
295
296    /// Permanent for agent auto-retry (complement of [`Self::is_retryable`]).
297    pub fn is_permanent(&self) -> bool {
298        self.kind().is_permanent()
299    }
300
301    /// Detailed retry category (Rules Rust checklist `retry_kind`).
302    pub fn retry_kind(&self) -> crate::retry::RetryKind {
303        self.kind().retry_kind()
304    }
305
306    /// Maps this error to a process [`ExitCode`].
307    pub fn exit_code(&self) -> ExitCode {
308        ExitCode::from(self.kind().exit_code())
309    }
310
311    /// Map remote HTTP status to a domain error.
312    ///
313    /// `body_hint` must be a short, non-sensitive context label (e.g. endpoint
314    /// name or `"retries exhausted"`), never a raw response body or credential.
315    pub fn from_http_status(status: u16, body_hint: &str) -> Self {
316        match status {
317            400 => Self::new(
318                ErrorKind::InvalidInput,
319                format!("bad request from remote: {body_hint}"),
320            ),
321            404 => Self::new(
322                ErrorKind::NotFound,
323                format!("resource not found: {body_hint}"),
324            ),
325            // 408 Request Timeout — transient; agent may retry with backoff.
326            408 => Self::new(
327                ErrorKind::Timeout,
328                format!("remote request timeout (HTTP 408): {body_hint}"),
329            ),
330            429 => Self::new(
331                ErrorKind::RateLimited,
332                format!("rate limited by remote: {body_hint}"),
333            ),
334            500 | 502 | 503 | 504 => Self::new(
335                ErrorKind::Unavailable,
336                format!("remote unavailable (HTTP {status}): {body_hint}"),
337            ),
338            other => Self::new(
339                ErrorKind::Network,
340                format!("unexpected HTTP status {other}: {body_hint}"),
341            ),
342        }
343    }
344}
345
346/// Result alias for library operations.
347pub type AppResult<T> = Result<T, AppError>;
348
349#[cfg(test)]
350mod tests {
351    use super::*;
352
353    #[test]
354    fn exit_codes_canonical() {
355        assert_eq!(ErrorKind::Usage.exit_code(), 64);
356        assert_eq!(ErrorKind::InvalidInput.exit_code(), 65);
357        assert_eq!(ErrorKind::NotFound.exit_code(), 66);
358        assert_eq!(ErrorKind::RateLimited.exit_code(), 69);
359        assert_eq!(ErrorKind::Network.exit_code(), 74);
360        assert_eq!(ErrorKind::Budget.exit_code(), 74);
361        assert_eq!(ErrorKind::Budget.as_str(), "budget");
362        assert!(!ErrorKind::Budget.retryable());
363        assert!(ErrorKind::Budget.is_permanent());
364        assert_eq!(ErrorKind::Timeout.exit_code(), 124);
365        assert_eq!(ErrorKind::Interrupted.exit_code(), 130);
366        assert_eq!(ErrorKind::Terminated.exit_code(), 143);
367        assert_eq!(ErrorKind::BrokenPipe.exit_code(), 141);
368        assert_eq!(ErrorKind::Config.exit_code(), 78);
369        assert_eq!(ErrorKind::Internal.exit_code(), 70);
370        assert_eq!(ErrorKind::BrokenPipe.as_str(), "broken_pipe");
371        assert!(!ErrorKind::BrokenPipe.retryable());
372    }
373
374    #[test]
375    fn cancel_helpers() {
376        assert_eq!(AppError::interrupted().kind(), ErrorKind::Interrupted);
377        assert_eq!(AppError::terminated().kind(), ErrorKind::Terminated);
378        assert_eq!(AppError::broken_pipe().kind(), ErrorKind::BrokenPipe);
379        assert_eq!(
380            AppError::broken_pipe().exit_code(),
381            ExitCode::from(EXIT_BROKEN_PIPE)
382        );
383    }
384
385    #[test]
386    fn from_http_status_matrix() {
387        assert_eq!(
388            AppError::from_http_status(400, "x").kind(),
389            ErrorKind::InvalidInput
390        );
391        assert_eq!(
392            AppError::from_http_status(404, "x").kind(),
393            ErrorKind::NotFound
394        );
395        assert_eq!(
396            AppError::from_http_status(429, "x").kind(),
397            ErrorKind::RateLimited
398        );
399        assert_eq!(
400            AppError::from_http_status(503, "x").kind(),
401            ErrorKind::Unavailable
402        );
403        assert_eq!(
404            AppError::from_http_status(418, "x").kind(),
405            ErrorKind::Network
406        );
407        let e = AppError::from_http_status(429, "slow").with_retry_after(7);
408        assert_eq!(e.retry_after_secs(), Some(7));
409        assert!(e.kind().retryable());
410        assert!(e.kind().is_retryable());
411        assert!(!ErrorKind::NotFound.retryable());
412        assert!(ErrorKind::NotFound.is_permanent());
413        assert!(ErrorKind::Interrupted.is_permanent());
414        assert_eq!(ErrorKind::Parse.as_str(), "parse");
415        assert_eq!(ErrorKind::Config.exit_code(), 78);
416    }
417
418    #[test]
419    fn with_source_preserves_kind() {
420        let e = AppError::with_source(ErrorKind::Parse, "bad", std::io::Error::other("inner"));
421        assert_eq!(e.kind(), ErrorKind::Parse);
422        assert_eq!(e.message(), "bad");
423    }
424
425    #[test]
426    fn source_chain_via_std_error() {
427        use std::error::Error as _;
428        let e = AppError::with_source(ErrorKind::Parse, "bad", std::io::Error::other("inner"));
429        let src = e.source().expect("source present");
430        assert!(src.to_string().contains("inner"));
431        // Display is message only — cause is not duplicated.
432        assert_eq!(e.to_string(), "bad");
433        assert!(!e.to_string().contains("inner"));
434    }
435
436    #[test]
437    fn app_error_clone_shares_source() {
438        use std::error::Error as _;
439        let e = AppError::with_source(
440            ErrorKind::Network,
441            "req failed",
442            std::io::Error::other("eof"),
443        );
444        let c = e.clone();
445        assert_eq!(c.kind(), ErrorKind::Network);
446        assert_eq!(c.message(), "req failed");
447        assert!(c.source().is_some());
448        assert!(c.is_retryable());
449        assert!(!c.is_permanent());
450        assert!(AppError::new(ErrorKind::NotFound, "missing").is_permanent());
451        assert_eq!(
452            c.retry_kind(),
453            crate::retry::RetryKind::TransientNetwork
454        );
455        assert_eq!(
456            AppError::new(ErrorKind::Budget, "cap").retry_kind(),
457            crate::retry::RetryKind::Permanent
458        );
459        assert_eq!(
460            ErrorKind::Timeout.retry_kind(),
461            crate::retry::RetryKind::Timeout
462        );
463    }
464
465    #[test]
466    fn display_message_style() {
467        let e = AppError::new(ErrorKind::Config, "invalid config.toml");
468        let s = e.to_string();
469        assert_eq!(s, "invalid config.toml");
470        assert!(!s.ends_with('.'));
471        assert_eq!(s, s.to_ascii_lowercase());
472    }
473
474    #[test]
475    fn with_source_display_does_not_embed_cause() {
476        use std::error::Error as _;
477        let e = AppError::with_source(
478            ErrorKind::Parse,
479            "html to markdown conversion failed",
480            std::io::Error::other("inner cause text"),
481        );
482        assert_eq!(e.to_string(), "html to markdown conversion failed");
483        assert!(!e.to_string().contains("inner cause text"));
484        assert!(e.source().is_some());
485        assert!(e.source().unwrap().to_string().contains("inner cause text"));
486        assert_eq!(e.to_string(), e.to_string().to_ascii_lowercase());
487    }
488}