Skip to main content

rustai_core/
error.rs

1//! Error type for the whole pipeline.
2
3use std::fmt;
4
5/// Everything that can go wrong inside `rustai`.
6#[derive(Debug, thiserror::Error)]
7pub enum Error {
8    /// The remote host could not be reached, timed out, or returned a
9    /// transport-level failure.
10    #[error("network error for {url}: {source}")]
11    Network {
12        /// URL that was being fetched.
13        url: String,
14        /// Underlying transport error, stringified so the variant stays `Send`.
15        source: BoxError,
16    },
17
18    /// The server answered, but with a status we treat as a failure.
19    #[error("http {status} for {url}")]
20    Status {
21        /// URL that was being fetched.
22        url: String,
23        /// The status code returned.
24        status: u16,
25        /// Seconds the server asked us to wait, from its `Retry-After` header.
26        retry_after: Option<f64>,
27    },
28
29    /// Response body exceeded [`crate::http::FetchConfig::max_body_bytes`].
30    #[error("body for {url} exceeds the {limit} byte cap")]
31    BodyTooLarge {
32        /// URL that was being fetched.
33        url: String,
34        /// Configured cap in bytes.
35        limit: usize,
36    },
37
38    /// `robots.txt` disallows this path for our user-agent.
39    #[error("blocked by robots.txt: {0}")]
40    RobotsDenied(String),
41
42    /// A URL could not be parsed or was not http(s).
43    #[error("invalid url {0}")]
44    InvalidUrl(String),
45
46    /// The HTML could not be parsed.
47    #[error("html parse error: {0}")]
48    Parse(String),
49
50    /// A search or feed provider returned something we could not read.
51    #[error("provider `{provider}` failed: {message}")]
52    Provider {
53        /// Provider name, e.g. `duckduckgo`.
54        provider: String,
55        /// Human-readable reason.
56        message: String,
57    },
58
59    /// Headless-browser fallback failed or is not compiled in.
60    #[error("headless browser fallback unavailable: {0}")]
61    Browser(String),
62
63    /// Invalid configuration supplied by the caller.
64    #[error("invalid configuration: {0}")]
65    Config(String),
66}
67
68/// Boxed, thread-safe source error.
69pub type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
70
71/// Convenient result alias.
72pub type Result<T, E = Error> = std::result::Result<T, E>;
73
74impl Error {
75    pub(crate) fn network(url: impl fmt::Display, e: impl Into<BoxError>) -> Self {
76        Error::Network { url: url.to_string(), source: e.into() }
77    }
78
79    pub(crate) fn provider(provider: &'static str, message: impl fmt::Display) -> Self {
80        Error::Provider { provider: provider.to_string(), message: message.to_string() }
81    }
82
83    /// How long the server asked us to wait before trying again, if it said.
84    pub fn retry_after(&self) -> Option<std::time::Duration> {
85        match self {
86            Error::Status { retry_after: Some(secs), .. } if *secs >= 0.0 => {
87                Some(std::time::Duration::from_secs_f64(*secs))
88            }
89            _ => None,
90        }
91    }
92
93    /// Whether retrying the same request could plausibly succeed.
94    pub fn is_retryable(&self) -> bool {
95        match self {
96            Error::Network { .. } => true,
97            Error::Status { status, .. } => {
98                matches!(status, 408 | 425 | 429 | 500 | 502 | 503 | 504)
99            }
100            _ => false,
101        }
102    }
103}