Skip to main content

fetchium_core/
error.rs

1//! Error types for Fetchium (PRD §44).
2//!
3//! Structured errors with retry info, suggested actions, and fallback alternatives.
4
5use serde::{Deserialize, Serialize};
6
7/// Categorized error type for structured error handling.
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
9#[serde(rename_all = "snake_case")]
10pub enum ErrorKind {
11    NetworkTimeout,
12    DnsFailure,
13    Http403,
14    Http429,
15    Http5xx,
16    AntiBot,
17    Paywall,
18    ContentNotFound,
19    ExtractionFailed,
20    BrowserCrash,
21    AiUnavailable,
22    ValidationFailed,
23    BudgetExceeded,
24    ConfigError,
25    CacheError,
26    IndexError,
27    ParseError,
28    IoError,
29    Unknown,
30}
31
32/// Structured error with context for automated fallback handling.
33#[derive(Debug, Clone, Serialize, Deserialize)]
34pub struct StructuredError {
35    pub kind: ErrorKind,
36    pub retryable: bool,
37    pub message: String,
38    #[serde(skip_serializing_if = "Option::is_none")]
39    pub source_url: Option<String>,
40    pub suggested_action: String,
41    #[serde(default)]
42    pub alternatives: Vec<String>,
43}
44
45impl std::fmt::Display for StructuredError {
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        write!(f, "[{:?}] {}", self.kind, self.message)?;
48        if let Some(url) = &self.source_url {
49            write!(f, " (url: {url})")?;
50        }
51        Ok(())
52    }
53}
54
55impl std::error::Error for StructuredError {}
56
57/// Main error type for fetchium-core.
58#[derive(Debug, thiserror::Error)]
59pub enum FetchiumError {
60    #[error("Network error: {0}")]
61    Network(#[from] reqwest::Error),
62
63    #[error("I/O error: {0}")]
64    Io(#[from] std::io::Error),
65
66    #[error("JSON error: {0}")]
67    Json(#[from] serde_json::Error),
68
69    #[error("Config error: {0}")]
70    Config(String),
71
72    #[error("Cache error: {0}")]
73    Cache(String),
74
75    #[error("Extraction error: {0}")]
76    Extraction(String),
77
78    #[error("Search error: {0}")]
79    Search(String),
80
81    #[error("Validation error: {0}")]
82    Validation(String),
83
84    #[error("Token budget exceeded: used {used}, budget {budget}")]
85    BudgetExceeded { used: u32, budget: u32 },
86
87    #[error("Database error: {0}")]
88    Database(#[from] rusqlite::Error),
89
90    #[error("URL parse error: {0}")]
91    UrlParse(#[from] url::ParseError),
92
93    #[error("{0}")]
94    Structured(StructuredError),
95
96    #[error("AI engine unavailable: {0}")]
97    AiUnavailable(String),
98
99    #[error("Internal error: {0}")]
100    Internal(String),
101
102    #[error("Not found: {0}")]
103    NotFound(String),
104
105    #[error("External tool error: {0}")]
106    ExternalTool(String),
107
108    #[error("Insecure connection to {url}: {suggestion}")]
109    InsecureConnection { url: String, suggestion: String },
110
111    #[error("Invalid URL: {0}")]
112    InvalidUrl(String),
113
114    #[error("YouTube error: {0}")]
115    YouTube(String),
116
117    #[error("Operation '{operation}' timed out after {timeout_ms}ms: {suggestion}")]
118    OperationTimeout {
119        operation: String,
120        timeout_ms: u64,
121        suggestion: String,
122    },
123
124    #[error("{0}")]
125    Other(#[from] anyhow::Error),
126}
127
128/// Convenience alias.
129pub type FetchiumResult<T> = Result<T, FetchiumError>;
130
131/// Wrap any async operation with a timeout (PRD SS44: "Never hang").
132///
133/// # Example
134/// ```rust,no_run
135/// use fetchium_core::error::with_timeout;
136/// use tokio::time::Duration;
137/// # async fn example() -> fetchium_core::error::FetchiumResult<()> {
138/// let result = with_timeout(Duration::from_secs(10), "fetch", async {
139///     Ok(())
140/// }).await;
141/// # result
142/// # }
143/// ```
144pub async fn with_timeout<F, T>(
145    duration: tokio::time::Duration,
146    op_name: &str,
147    future: F,
148) -> FetchiumResult<T>
149where
150    F: std::future::Future<Output = FetchiumResult<T>>,
151{
152    match tokio::time::timeout(duration, future).await {
153        Ok(result) => result,
154        Err(_) => Err(FetchiumError::OperationTimeout {
155            operation: op_name.to_string(),
156            timeout_ms: duration.as_millis() as u64,
157            suggestion: format!(
158                "{op_name} timed out after {}ms. Try increasing the timeout.",
159                duration.as_millis()
160            ),
161        }),
162    }
163}
164
165impl FetchiumError {
166    /// Whether this error is retryable.
167    pub fn is_retryable(&self) -> bool {
168        match self {
169            Self::Network(_) => true,
170            Self::Structured(e) => e.retryable,
171            Self::Database(_) => false,
172            _ => false,
173        }
174    }
175
176    /// A human-readable suggestion for how to resolve this error.
177    pub fn suggested_action(&self) -> &str {
178        match self {
179            Self::Network(_) => "Retry the request or check network connectivity",
180            Self::InsecureConnection { .. } => "Use HTTPS instead of HTTP for remote hosts",
181            Self::InvalidUrl(_) => "Check the URL format (must start with https:// or http://)",
182            Self::OperationTimeout { suggestion, .. } => suggestion.as_str(),
183            Self::AiUnavailable(_) => "Start Ollama with: ollama serve",
184            Self::BudgetExceeded { .. } => "Increase --budget or use a lower PDS tier",
185            _ => "Check error details and try again",
186        }
187    }
188
189    /// Convert to a structured error for serialized output.
190    pub fn to_structured(&self) -> StructuredError {
191        match self {
192            Self::Network(e) => StructuredError {
193                kind: if e.is_timeout() {
194                    ErrorKind::NetworkTimeout
195                } else {
196                    ErrorKind::Http5xx
197                },
198                retryable: true,
199                message: e.to_string(),
200                source_url: e.url().map(|u| u.to_string()),
201                suggested_action: "Retry the request or check network connectivity".into(),
202                alternatives: vec![],
203            },
204            Self::BudgetExceeded { used, budget } => StructuredError {
205                kind: ErrorKind::BudgetExceeded,
206                retryable: false,
207                message: format!("Token budget exceeded: {used}/{budget}"),
208                source_url: None,
209                suggested_action: "Increase --budget or use a lower PDS tier".into(),
210                alternatives: vec![],
211            },
212            Self::Structured(e) => e.clone(),
213            other => StructuredError {
214                kind: ErrorKind::Unknown,
215                retryable: false,
216                message: other.to_string(),
217                source_url: None,
218                suggested_action: "Check logs for details".into(),
219                alternatives: vec![],
220            },
221        }
222    }
223}
224
225#[cfg(test)]
226mod tests {
227    use super::*;
228
229    #[test]
230    fn structured_error_display() {
231        let err = StructuredError {
232            kind: ErrorKind::Http429,
233            retryable: true,
234            message: "Rate limited".into(),
235            source_url: Some("https://example.com".into()),
236            suggested_action: "Wait and retry".into(),
237            alternatives: vec!["Use cache".into()],
238        };
239        let s = err.to_string();
240        assert!(s.contains("Rate limited"));
241        assert!(s.contains("example.com"));
242    }
243
244    #[test]
245    fn budget_exceeded_structured() {
246        let err = FetchiumError::BudgetExceeded {
247            used: 5000,
248            budget: 4000,
249        };
250        assert!(!err.is_retryable());
251        let structured = err.to_structured();
252        assert_eq!(structured.kind, ErrorKind::BudgetExceeded);
253    }
254
255    #[test]
256    fn error_kind_serialization() {
257        let kind = ErrorKind::AntiBot;
258        let json = serde_json::to_string(&kind).unwrap();
259        assert_eq!(json, "\"anti_bot\"");
260    }
261}