use serde::Deserialize;
use thiserror::Error;
#[derive(Debug, Clone, Deserialize, Default)]
pub struct ApiErrorBody {
#[serde(default)]
pub code: String,
#[serde(default)]
pub message: String,
#[serde(default)]
pub request_id: Option<String>,
#[serde(default)]
pub docs: Option<String>,
#[serde(default)]
pub parameter: Option<String>,
#[serde(default)]
pub allowed: Option<Vec<serde_json::Value>>,
}
#[derive(Debug, Clone, Copy, Default)]
pub struct RateLimit {
pub limit: Option<u64>,
pub remaining: Option<u64>,
pub reset: Option<u64>,
}
#[derive(Debug, Error)]
pub enum Error {
#[error("bad request: {}{}", body.message, fmt_parameter(&body.parameter))]
BadRequest { body: ApiErrorBody, rate_limit: RateLimit },
#[error("authentication failed: {}", body.message)]
Authentication { body: ApiErrorBody, rate_limit: RateLimit },
#[error("forbidden: {}", body.message)]
Permission { body: ApiErrorBody, rate_limit: RateLimit },
#[error("insufficient credits: {}", body.message)]
InsufficientCredits { body: ApiErrorBody, rate_limit: RateLimit },
#[error("not found: {}", body.message)]
NotFound { body: ApiErrorBody, rate_limit: RateLimit },
#[error("rate limited: {} (retry after {:?}s)", body.message, retry_after)]
RateLimited {
body: ApiErrorBody,
rate_limit: RateLimit,
retry_after: Option<u64>,
},
#[error("server error {status}: {}", body.message)]
Server {
status: u16,
body: ApiErrorBody,
rate_limit: RateLimit,
},
#[error("unexpected status {status}: {}", body.message)]
Status {
status: u16,
body: ApiErrorBody,
rate_limit: RateLimit,
},
#[error("invalid request: {message}")]
InvalidRequest { message: String },
#[error("transport error: {0}")]
Transport(#[from] reqwest::Error),
#[error("could not decode response: {0}")]
Decode(String),
#[error("missing API key: pass it to the builder or set CABALSPY_API_KEY")]
MissingApiKey,
}
fn fmt_parameter(parameter: &Option<String>) -> String {
match parameter {
Some(name) => format!(" (parameter: {name})"),
None => String::new(),
}
}
impl Error {
pub fn code(&self) -> Option<&str> {
self.body().map(|b| b.code.as_str())
}
pub fn request_id(&self) -> Option<&str> {
self.body().and_then(|b| b.request_id.as_deref())
}
pub fn parameter(&self) -> Option<&str> {
self.body().and_then(|b| b.parameter.as_deref())
}
pub fn allowed(&self) -> Option<&[serde_json::Value]> {
self.body().and_then(|b| b.allowed.as_deref())
}
pub fn rate_limit(&self) -> Option<RateLimit> {
match self {
Error::BadRequest { rate_limit, .. }
| Error::Authentication { rate_limit, .. }
| Error::Permission { rate_limit, .. }
| Error::InsufficientCredits { rate_limit, .. }
| Error::NotFound { rate_limit, .. }
| Error::RateLimited { rate_limit, .. }
| Error::Server { rate_limit, .. }
| Error::Status { rate_limit, .. } => Some(*rate_limit),
_ => None,
}
}
pub fn is_retryable(&self) -> bool {
match self {
Error::RateLimited { .. } | Error::Server { .. } => true,
Error::Transport(err) => err.is_timeout() || err.is_connect() || err.is_request(),
_ => false,
}
}
fn body(&self) -> Option<&ApiErrorBody> {
match self {
Error::BadRequest { body, .. }
| Error::Authentication { body, .. }
| Error::Permission { body, .. }
| Error::InsufficientCredits { body, .. }
| Error::NotFound { body, .. }
| Error::RateLimited { body, .. }
| Error::Server { body, .. }
| Error::Status { body, .. } => Some(body),
_ => None,
}
}
}
pub(crate) fn error_from_status(
status: u16,
body: ApiErrorBody,
rate_limit: RateLimit,
retry_after: Option<u64>,
) -> Error {
match status {
400 => Error::BadRequest { body, rate_limit },
401 => Error::Authentication { body, rate_limit },
403 => {
if body.code == "insufficient_credits" {
Error::InsufficientCredits { body, rate_limit }
} else {
Error::Permission { body, rate_limit }
}
}
404 => Error::NotFound { body, rate_limit },
429 => Error::RateLimited {
body,
rate_limit,
retry_after,
},
s if s >= 500 => Error::Server {
status,
body,
rate_limit,
},
_ => Error::Status {
status,
body,
rate_limit,
},
}
}
pub type Result<T> = std::result::Result<T, Error>;