Skip to main content

wellfriend/
error.rs

1use std::fmt;
2use std::time::Duration;
3
4use reqwest::header::HeaderMap;
5use serde::Deserialize;
6
7use crate::models::Operation;
8use crate::Object;
9
10/// The result type of every fallible call in this crate.
11pub type Result<T, E = Error> = std::result::Result<T, E>;
12
13/// Where to create an API key, quoted in the missing-key error.
14pub(crate) const KEYS_URL: &str = "https://wellfriend.dev/dashboard/developer-api/keys";
15
16/// Every error this SDK returns.
17///
18/// HTTP errors from the API are split by status into [`Error::BadRequest`], [`Error::Validation`],
19/// [`Error::Authentication`], [`Error::PermissionDenied`], [`Error::NotFound`],
20/// [`Error::Conflict`], [`Error::RateLimit`] and [`Error::Server`]; any other status is
21/// [`Error::Api`]. Each carries an [`ApiError`] with the status, code, message, reference id,
22/// details and response headers. Use [`Error::status`], [`Error::code`] and
23/// [`Error::reference_id`] to inspect any variant without matching.
24#[derive(Debug, thiserror::Error)]
25#[non_exhaustive]
26pub enum Error {
27    /// 400: the request was malformed.
28    #[error("{0}")]
29    BadRequest(Box<ApiError>),
30    /// 422, or a 400 that reports invalid input (for example an invalid tool parameter).
31    #[error("{0}")]
32    Validation(Box<ApiError>),
33    /// 401: the API key is missing, invalid, expired or revoked.
34    #[error("{0}")]
35    Authentication(Box<ApiError>),
36    /// 403: the key lacks a scope, or the plan does not include the feature.
37    #[error("{0}")]
38    PermissionDenied(Box<ApiError>),
39    /// 404: the resource does not exist in this workspace and environment.
40    #[error("{0}")]
41    NotFound(Box<ApiError>),
42    /// 409: the request conflicts with the resource's current state.
43    #[error("{0}")]
44    Conflict(Box<ApiError>),
45    /// 429: too many requests. [`ApiError::retry_after`] says how long to wait.
46    #[error("{0}")]
47    RateLimit(Box<ApiError>),
48    /// 5xx: the API failed. These are retried automatically before they reach you.
49    #[error("{0}")]
50    Server(Box<ApiError>),
51    /// Any other HTTP error status (for example 413 for a file above the size limit).
52    #[error("{0}")]
53    Api(Box<ApiError>),
54    /// The request could not be sent or the response could not be read (DNS, TCP, TLS).
55    #[error("connection error: {0}")]
56    Connection(#[source] Box<dyn std::error::Error + Send + Sync>),
57    /// The server did not answer within the request timeout.
58    #[error("request timed out after {0:?}")]
59    Timeout(Duration),
60    /// An operation or workflow run ended failed or cancelled.
61    #[error("{0}")]
62    OperationFailed(Box<OperationFailure>),
63    /// Waiting for an operation or run took longer than the wait limit. The work goes on
64    /// server-side; resume with [`DocumentOperations::wait`](crate::DocumentOperations::wait)
65    /// or [`WorkflowRuns::wait`](crate::WorkflowRuns::wait).
66    #[error("{kind} {id} did not finish within {waited:?}; it is still running and you can wait for it again")]
67    WaitTimeout {
68        /// `operation` or `workflow run`.
69        kind: &'static str,
70        /// The id to resume waiting on.
71        id: String,
72        /// How long this call waited.
73        waited: Duration,
74    },
75    /// A webhook delivery failed signature or timestamp verification.
76    #[error("webhook verification failed: {0}")]
77    WebhookVerification(String),
78    /// The arguments cannot be sent as given (checked before any request is made).
79    #[error("invalid input: {0}")]
80    InvalidInput(String),
81    /// Reading or writing a local file failed.
82    #[error("file error: {0}")]
83    Io(#[from] std::io::Error),
84    /// A response body could not be decoded into the expected type.
85    #[error("unexpected response from the API: {0}")]
86    Decode(String),
87}
88
89impl Error {
90    /// The HTTP status of an API error.
91    pub fn status(&self) -> Option<u16> {
92        self.api_error().map(|error| error.status)
93    }
94
95    /// The machine-readable error code: the API's `error.code`, or the code an operation
96    /// failed with.
97    pub fn code(&self) -> Option<&str> {
98        match self {
99            Error::OperationFailed(failure) => Some(failure.code.as_str()),
100            other => other.api_error().map(|error| error.code.as_str()),
101        }
102    }
103
104    /// The reference id to quote to support.
105    pub fn reference_id(&self) -> Option<&str> {
106        self.api_error()
107            .and_then(|error| error.reference_id.as_deref())
108    }
109
110    /// The API error behind any HTTP error variant.
111    pub fn api_error(&self) -> Option<&ApiError> {
112        match self {
113            Error::BadRequest(error)
114            | Error::Validation(error)
115            | Error::Authentication(error)
116            | Error::PermissionDenied(error)
117            | Error::NotFound(error)
118            | Error::Conflict(error)
119            | Error::RateLimit(error)
120            | Error::Server(error)
121            | Error::Api(error) => Some(error),
122            _ => None,
123        }
124    }
125
126    /// How long the API asked to wait before retrying (429 and some 503 responses).
127    pub fn retry_after(&self) -> Option<Duration> {
128        self.api_error().and_then(|error| error.retry_after)
129    }
130
131    /// Whether the same call may succeed if sent again later.
132    pub fn is_retryable(&self) -> bool {
133        match self {
134            Error::Connection(_) | Error::Timeout(_) => true,
135            // Unless the API says otherwise (an exhausted balance is a final 429).
136            Error::RateLimit(error) | Error::Server(error) => {
137                error.retryable || error.retry_after.is_some() || error.code.starts_with("HTTP_")
138            }
139            other => other
140                .api_error()
141                .is_some_and(|error| error.retryable || matches!(error.status, 408)),
142        }
143    }
144
145    pub(crate) fn connection(error: impl std::error::Error + Send + Sync + 'static) -> Self {
146        Error::Connection(Box::new(error))
147    }
148
149    pub(crate) fn decode(context: &str, error: impl fmt::Display) -> Self {
150        Error::Decode(format!("{context}: {error}"))
151    }
152
153    pub(crate) fn missing_api_key() -> Self {
154        Error::Authentication(Box::new(ApiError {
155            status: 401,
156            code: "API_KEY_MISSING".into(),
157            message: format!(
158                "No API key is configured. Set WELLFRIEND_API_KEY or call Wellfriend::builder().api_key(..). Create a key at {KEYS_URL}"
159            ),
160            reference_id: None,
161            retryable: false,
162            details: None,
163            retry_after: None,
164            headers: HeaderMap::new(),
165        }))
166    }
167
168    /// Builds the error for an HTTP error response.
169    pub(crate) fn from_api(error: ApiError) -> Self {
170        let error = Box::new(error);
171        match error.status {
172            400 if is_validation_code(&error.code) => Error::Validation(error),
173            400 => Error::BadRequest(error),
174            401 => Error::Authentication(error),
175            403 => Error::PermissionDenied(error),
176            404 => Error::NotFound(error),
177            409 => Error::Conflict(error),
178            422 => Error::Validation(error),
179            429 => Error::RateLimit(error),
180            500..=599 => Error::Server(error),
181            _ => Error::Api(error),
182        }
183    }
184}
185
186/// A 400 whose code says the input itself is invalid counts as a validation error, so a bad
187/// tool parameter is an [`Error::Validation`] whichever of 400 or 422 the endpoint uses.
188fn is_validation_code(code: &str) -> bool {
189    code.ends_with("_INPUT_INVALID")
190        || code.ends_with("_PARAMETERS_INVALID")
191        || code.contains("VALIDATION")
192}
193
194/// An error response from the API.
195#[derive(Clone)]
196#[non_exhaustive]
197pub struct ApiError {
198    /// The HTTP status.
199    pub status: u16,
200    /// The machine-readable code, for example `OPERATION_INPUT_INVALID`.
201    pub code: String,
202    /// The human-readable message.
203    pub message: String,
204    /// The reference id to quote to support.
205    pub reference_id: Option<String>,
206    /// Whether the API says the same request may succeed later.
207    pub retryable: bool,
208    /// Structured details, when the API sends them.
209    pub details: Option<Object>,
210    /// The parsed `Retry-After` header.
211    pub retry_after: Option<Duration>,
212    /// The response headers.
213    pub headers: HeaderMap,
214}
215
216impl fmt::Debug for ApiError {
217    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
218        f.debug_struct("ApiError")
219            .field("status", &self.status)
220            .field("code", &self.code)
221            .field("message", &self.message)
222            .field("reference_id", &self.reference_id)
223            .field("retryable", &self.retryable)
224            .field("details", &self.details)
225            .field("retry_after", &self.retry_after)
226            .finish_non_exhaustive()
227    }
228}
229
230impl fmt::Display for ApiError {
231    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
232        f.write_str(&self.message)?;
233        if let Some(reference) = &self.reference_id {
234            write!(f, " (reference {reference})")?;
235        }
236        Ok(())
237    }
238}
239
240#[derive(Deserialize)]
241struct Envelope {
242    error: Option<Body>,
243}
244
245#[derive(Deserialize)]
246#[serde(rename_all = "camelCase")]
247struct Body {
248    #[serde(default)]
249    code: String,
250    #[serde(default)]
251    message: String,
252    reference_id: Option<String>,
253    #[serde(default)]
254    retryable: bool,
255    details: Option<Object>,
256}
257
258impl ApiError {
259    /// Parses an error response body. Bodies that are not the API's error envelope (for example
260    /// an HTML page from a proxy) still give a useful error.
261    pub(crate) fn from_parts(status: u16, headers: HeaderMap, body: &[u8]) -> Self {
262        let retry_after = crate::retry::parse_retry_after(&headers);
263        match serde_json::from_slice::<Envelope>(body)
264            .ok()
265            .and_then(|envelope| envelope.error)
266        {
267            Some(parsed) => ApiError {
268                status,
269                code: if parsed.code.is_empty() {
270                    format!("HTTP_{status}")
271                } else {
272                    parsed.code
273                },
274                message: if parsed.message.is_empty() {
275                    default_message(status)
276                } else {
277                    parsed.message
278                },
279                reference_id: parsed.reference_id.filter(|value| !value.is_empty()),
280                retryable: parsed.retryable,
281                details: parsed.details,
282                retry_after,
283                headers,
284            },
285            None => {
286                let text = String::from_utf8_lossy(body);
287                let snippet: String = text.trim().chars().take(200).collect();
288                ApiError {
289                    status,
290                    code: format!("HTTP_{status}"),
291                    message: if snippet.is_empty() || snippet.starts_with('<') {
292                        default_message(status)
293                    } else {
294                        format!("{}: {snippet}", default_message(status))
295                    },
296                    reference_id: None,
297                    retryable: false,
298                    details: None,
299                    retry_after,
300                    headers,
301                }
302            }
303        }
304    }
305}
306
307fn default_message(status: u16) -> String {
308    let reason = reqwest::StatusCode::from_u16(status)
309        .ok()
310        .and_then(|code| code.canonical_reason())
311        .unwrap_or("error");
312    format!("The API answered {status} {reason}")
313}
314
315/// Why an operation or workflow run failed.
316#[derive(Debug, Clone)]
317#[non_exhaustive]
318pub struct OperationFailure {
319    /// The error code, for example `PDF_DANGEROUS_CONTENT`.
320    pub code: String,
321    /// The error message.
322    pub message: String,
323    /// The operation id (for a pipeline, the step that failed), or the workflow run id.
324    pub id: String,
325    /// For a pipeline, the step that failed (1-based).
326    pub step: Option<usize>,
327    /// The final state of the operation, when it was an operation.
328    pub operation: Option<Box<Operation>>,
329    /// The final workflow run, when it was a pipeline or workflow.
330    pub run: Option<Box<crate::models::WorkflowRun>>,
331}
332
333impl fmt::Display for OperationFailure {
334    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
335        if self.message.is_empty() {
336            write!(f, "{} failed with {}", self.id, self.code)
337        } else {
338            write!(f, "{} failed with {}: {}", self.id, self.code, self.message)
339        }
340    }
341}