use std::fmt;
use std::time::Duration;
use reqwest::header::HeaderMap;
use serde::Deserialize;
use crate::models::Operation;
use crate::Object;
pub type Result<T, E = Error> = std::result::Result<T, E>;
pub(crate) const KEYS_URL: &str = "https://wellfriend.dev/dashboard/developer-api/keys";
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error("{0}")]
BadRequest(Box<ApiError>),
#[error("{0}")]
Validation(Box<ApiError>),
#[error("{0}")]
Authentication(Box<ApiError>),
#[error("{0}")]
PermissionDenied(Box<ApiError>),
#[error("{0}")]
NotFound(Box<ApiError>),
#[error("{0}")]
Conflict(Box<ApiError>),
#[error("{0}")]
RateLimit(Box<ApiError>),
#[error("{0}")]
Server(Box<ApiError>),
#[error("{0}")]
Api(Box<ApiError>),
#[error("connection error: {0}")]
Connection(#[source] Box<dyn std::error::Error + Send + Sync>),
#[error("request timed out after {0:?}")]
Timeout(Duration),
#[error("{0}")]
OperationFailed(Box<OperationFailure>),
#[error("{kind} {id} did not finish within {waited:?}; it is still running and you can wait for it again")]
WaitTimeout {
kind: &'static str,
id: String,
waited: Duration,
},
#[error("webhook verification failed: {0}")]
WebhookVerification(String),
#[error("invalid input: {0}")]
InvalidInput(String),
#[error("file error: {0}")]
Io(#[from] std::io::Error),
#[error("unexpected response from the API: {0}")]
Decode(String),
}
impl Error {
pub fn status(&self) -> Option<u16> {
self.api_error().map(|error| error.status)
}
pub fn code(&self) -> Option<&str> {
match self {
Error::OperationFailed(failure) => Some(failure.code.as_str()),
other => other.api_error().map(|error| error.code.as_str()),
}
}
pub fn reference_id(&self) -> Option<&str> {
self.api_error()
.and_then(|error| error.reference_id.as_deref())
}
pub fn api_error(&self) -> Option<&ApiError> {
match self {
Error::BadRequest(error)
| Error::Validation(error)
| Error::Authentication(error)
| Error::PermissionDenied(error)
| Error::NotFound(error)
| Error::Conflict(error)
| Error::RateLimit(error)
| Error::Server(error)
| Error::Api(error) => Some(error),
_ => None,
}
}
pub fn retry_after(&self) -> Option<Duration> {
self.api_error().and_then(|error| error.retry_after)
}
pub fn is_retryable(&self) -> bool {
match self {
Error::Connection(_) | Error::Timeout(_) => true,
Error::RateLimit(error) | Error::Server(error) => {
error.retryable || error.retry_after.is_some() || error.code.starts_with("HTTP_")
}
other => other
.api_error()
.is_some_and(|error| error.retryable || matches!(error.status, 408)),
}
}
pub(crate) fn connection(error: impl std::error::Error + Send + Sync + 'static) -> Self {
Error::Connection(Box::new(error))
}
pub(crate) fn decode(context: &str, error: impl fmt::Display) -> Self {
Error::Decode(format!("{context}: {error}"))
}
pub(crate) fn missing_api_key() -> Self {
Error::Authentication(Box::new(ApiError {
status: 401,
code: "API_KEY_MISSING".into(),
message: format!(
"No API key is configured. Set WELLFRIEND_API_KEY or call Wellfriend::builder().api_key(..). Create a key at {KEYS_URL}"
),
reference_id: None,
retryable: false,
details: None,
retry_after: None,
headers: HeaderMap::new(),
}))
}
pub(crate) fn from_api(error: ApiError) -> Self {
let error = Box::new(error);
match error.status {
400 if is_validation_code(&error.code) => Error::Validation(error),
400 => Error::BadRequest(error),
401 => Error::Authentication(error),
403 => Error::PermissionDenied(error),
404 => Error::NotFound(error),
409 => Error::Conflict(error),
422 => Error::Validation(error),
429 => Error::RateLimit(error),
500..=599 => Error::Server(error),
_ => Error::Api(error),
}
}
}
fn is_validation_code(code: &str) -> bool {
code.ends_with("_INPUT_INVALID")
|| code.ends_with("_PARAMETERS_INVALID")
|| code.contains("VALIDATION")
}
#[derive(Clone)]
#[non_exhaustive]
pub struct ApiError {
pub status: u16,
pub code: String,
pub message: String,
pub reference_id: Option<String>,
pub retryable: bool,
pub details: Option<Object>,
pub retry_after: Option<Duration>,
pub headers: HeaderMap,
}
impl fmt::Debug for ApiError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ApiError")
.field("status", &self.status)
.field("code", &self.code)
.field("message", &self.message)
.field("reference_id", &self.reference_id)
.field("retryable", &self.retryable)
.field("details", &self.details)
.field("retry_after", &self.retry_after)
.finish_non_exhaustive()
}
}
impl fmt::Display for ApiError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)?;
if let Some(reference) = &self.reference_id {
write!(f, " (reference {reference})")?;
}
Ok(())
}
}
#[derive(Deserialize)]
struct Envelope {
error: Option<Body>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Body {
#[serde(default)]
code: String,
#[serde(default)]
message: String,
reference_id: Option<String>,
#[serde(default)]
retryable: bool,
details: Option<Object>,
}
impl ApiError {
pub(crate) fn from_parts(status: u16, headers: HeaderMap, body: &[u8]) -> Self {
let retry_after = crate::retry::parse_retry_after(&headers);
match serde_json::from_slice::<Envelope>(body)
.ok()
.and_then(|envelope| envelope.error)
{
Some(parsed) => ApiError {
status,
code: if parsed.code.is_empty() {
format!("HTTP_{status}")
} else {
parsed.code
},
message: if parsed.message.is_empty() {
default_message(status)
} else {
parsed.message
},
reference_id: parsed.reference_id.filter(|value| !value.is_empty()),
retryable: parsed.retryable,
details: parsed.details,
retry_after,
headers,
},
None => {
let text = String::from_utf8_lossy(body);
let snippet: String = text.trim().chars().take(200).collect();
ApiError {
status,
code: format!("HTTP_{status}"),
message: if snippet.is_empty() || snippet.starts_with('<') {
default_message(status)
} else {
format!("{}: {snippet}", default_message(status))
},
reference_id: None,
retryable: false,
details: None,
retry_after,
headers,
}
}
}
}
}
fn default_message(status: u16) -> String {
let reason = reqwest::StatusCode::from_u16(status)
.ok()
.and_then(|code| code.canonical_reason())
.unwrap_or("error");
format!("The API answered {status} {reason}")
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct OperationFailure {
pub code: String,
pub message: String,
pub id: String,
pub step: Option<usize>,
pub operation: Option<Box<Operation>>,
pub run: Option<Box<crate::models::WorkflowRun>>,
}
impl fmt::Display for OperationFailure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.message.is_empty() {
write!(f, "{} failed with {}", self.id, self.code)
} else {
write!(f, "{} failed with {}: {}", self.id, self.code, self.message)
}
}
}