1use std::fmt;
2use std::time::Duration;
3
4use reqwest::header::HeaderMap;
5use serde::Deserialize;
6
7use crate::models::Operation;
8use crate::Object;
9
10pub type Result<T, E = Error> = std::result::Result<T, E>;
12
13pub(crate) const KEYS_URL: &str = "https://wellfriend.dev/dashboard/developer-api/keys";
15
16#[derive(Debug, thiserror::Error)]
25#[non_exhaustive]
26pub enum Error {
27 #[error("{0}")]
29 BadRequest(Box<ApiError>),
30 #[error("{0}")]
32 Validation(Box<ApiError>),
33 #[error("{0}")]
35 Authentication(Box<ApiError>),
36 #[error("{0}")]
38 PermissionDenied(Box<ApiError>),
39 #[error("{0}")]
41 NotFound(Box<ApiError>),
42 #[error("{0}")]
44 Conflict(Box<ApiError>),
45 #[error("{0}")]
47 RateLimit(Box<ApiError>),
48 #[error("{0}")]
50 Server(Box<ApiError>),
51 #[error("{0}")]
53 Api(Box<ApiError>),
54 #[error("connection error: {0}")]
56 Connection(#[source] Box<dyn std::error::Error + Send + Sync>),
57 #[error("request timed out after {0:?}")]
59 Timeout(Duration),
60 #[error("{0}")]
62 OperationFailed(Box<OperationFailure>),
63 #[error("{kind} {id} did not finish within {waited:?}; it is still running and you can wait for it again")]
67 WaitTimeout {
68 kind: &'static str,
70 id: String,
72 waited: Duration,
74 },
75 #[error("webhook verification failed: {0}")]
77 WebhookVerification(String),
78 #[error("invalid input: {0}")]
80 InvalidInput(String),
81 #[error("file error: {0}")]
83 Io(#[from] std::io::Error),
84 #[error("unexpected response from the API: {0}")]
86 Decode(String),
87}
88
89impl Error {
90 pub fn status(&self) -> Option<u16> {
92 self.api_error().map(|error| error.status)
93 }
94
95 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 pub fn reference_id(&self) -> Option<&str> {
106 self.api_error()
107 .and_then(|error| error.reference_id.as_deref())
108 }
109
110 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 pub fn retry_after(&self) -> Option<Duration> {
128 self.api_error().and_then(|error| error.retry_after)
129 }
130
131 pub fn is_retryable(&self) -> bool {
133 match self {
134 Error::Connection(_) | Error::Timeout(_) => true,
135 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 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
186fn 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#[derive(Clone)]
196#[non_exhaustive]
197pub struct ApiError {
198 pub status: u16,
200 pub code: String,
202 pub message: String,
204 pub reference_id: Option<String>,
206 pub retryable: bool,
208 pub details: Option<Object>,
210 pub retry_after: Option<Duration>,
212 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 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#[derive(Debug, Clone)]
317#[non_exhaustive]
318pub struct OperationFailure {
319 pub code: String,
321 pub message: String,
323 pub id: String,
325 pub step: Option<usize>,
327 pub operation: Option<Box<Operation>>,
329 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}