use serde_json::{Map, Value};
use std::{error::Error as StdError, fmt, time::Duration};
macro_rules! error_codes {
($( $(#[$doc:meta])* $variant:ident = $id:literal, $status:literal; )*) => {
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorCode {
$( $(#[$doc])* $variant, )*
TransportError,
Timeout,
InvalidResponse,
HttpError,
InvalidArgument,
InvalidConfig,
ResponseTooLarge,
InvalidWebhookPayload,
InvalidWebhookSignature,
Other(String),
}
impl ErrorCode {
pub const API_CODES: &'static [(&'static str, u16)] = &[$(($id, $status),)*];
pub fn as_str(&self) -> &str {
match self {
$(Self::$variant => $id,)*
Self::TransportError => "sdk/transport-error",
Self::Timeout => "sdk/timeout",
Self::InvalidResponse => "sdk/invalid-response",
Self::HttpError => "sdk/http-error",
Self::InvalidArgument => "sdk/invalid-argument",
Self::InvalidConfig => "sdk/invalid-config",
Self::ResponseTooLarge => "sdk/response-too-large",
Self::InvalidWebhookPayload => "sdk/invalid-webhook-payload",
Self::InvalidWebhookSignature => "sdk/invalid-webhook-signature",
Self::Other(code) => code,
}
}
pub fn http_status(&self) -> Option<u16> {
match self {
$(Self::$variant => Some($status),)*
_ => None,
}
}
pub fn parse(code: &str) -> Self {
match code {
$($id => Self::$variant,)*
"sdk/transport-error" => Self::TransportError,
"sdk/timeout" => Self::Timeout,
"sdk/invalid-response" => Self::InvalidResponse,
"sdk/http-error" => Self::HttpError,
"sdk/invalid-argument" => Self::InvalidArgument,
"sdk/invalid-config" => Self::InvalidConfig,
"sdk/response-too-large" => Self::ResponseTooLarge,
"sdk/invalid-webhook-payload" => Self::InvalidWebhookPayload,
"sdk/invalid-webhook-signature" => Self::InvalidWebhookSignature,
other => Self::Other(other.to_owned()),
}
}
}
};
}
include!("codes.rs");
impl fmt::Display for ErrorCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl From<&str> for ErrorCode {
fn from(code: &str) -> Self {
Self::parse(code)
}
}
impl From<String> for ErrorCode {
fn from(code: String) -> Self {
Self::parse(&code)
}
}
impl PartialEq<str> for ErrorCode {
fn eq(&self, other: &str) -> bool {
self.as_str() == other
}
}
impl PartialEq<&str> for ErrorCode {
fn eq(&self, other: &&str) -> bool {
self.as_str() == *other
}
}
impl PartialEq<ErrorCode> for &str {
fn eq(&self, other: &ErrorCode) -> bool {
*self == other.as_str()
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct Error {
inner: Box<Inner>,
}
#[derive(Debug)]
struct Inner {
code: ErrorCode,
message: String,
details: Map<String, Value>,
status: Option<u16>,
request_id: Option<String>,
retry_after: Option<Duration>,
headers: Option<http::HeaderMap>,
source: Option<Box<dyn StdError + Send + Sync>>,
}
impl Error {
pub fn new(code: impl Into<ErrorCode>, message: impl Into<String>) -> Self {
Self {
inner: Box::new(Inner {
code: code.into(),
message: message.into(),
details: Map::new(),
status: None,
request_id: None,
retry_after: None,
headers: None,
source: None,
}),
}
}
pub fn with_status(mut self, status: u16) -> Self {
self.inner.status = Some(status);
self
}
pub fn with_details(mut self, details: Map<String, Value>) -> Self {
self.inner.details = details;
self
}
pub fn with_request_id(mut self, request_id: impl Into<String>) -> Self {
self.inner.request_id = Some(request_id.into());
self
}
pub fn with_retry_after(mut self, retry_after: Duration) -> Self {
self.inner.retry_after = Some(retry_after);
self
}
pub fn with_headers(mut self, headers: http::HeaderMap) -> Self {
self.inner.headers = Some(headers);
self
}
pub fn with_source(mut self, source: impl Into<Box<dyn StdError + Send + Sync>>) -> Self {
self.inner.source = Some(source.into());
self
}
pub fn code(&self) -> &ErrorCode {
&self.inner.code
}
pub fn message(&self) -> &str {
&self.inner.message
}
pub fn details(&self) -> &Map<String, Value> {
&self.inner.details
}
pub fn status(&self) -> Option<u16> {
self.inner.status
}
pub fn request_id(&self) -> Option<&str> {
self.inner.request_id.as_deref()
}
pub fn retry_after(&self) -> Option<Duration> {
self.inner.retry_after
}
pub fn headers(&self) -> Option<&http::HeaderMap> {
self.inner.headers.as_ref()
}
pub fn is_not_found(&self) -> bool {
self.inner.status == Some(404) || self.inner.code.as_str().ends_with("/not-found")
}
pub fn is_timeout(&self) -> bool {
self.inner.code == ErrorCode::Timeout
}
pub fn is_retryable(&self) -> bool {
matches!(
self.inner.code,
ErrorCode::TransportError | ErrorCode::Timeout | ErrorCode::IdempotentRequestInProgress
) || matches!(self.inner.status, Some(429 | 502 | 503 | 504))
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "[calmlens] {}", self.inner.message)
}
}
impl StdError for Error {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
self.inner.source.as_ref().map(|e| &**e as _)
}
}
pub type Result<T, E = Error> = std::result::Result<T, E>;
#[cfg(feature = "async")]
pub(crate) fn invalid_payload(message: impl Into<String>) -> Error {
Error::new(ErrorCode::InvalidUploadPayload, message)
}
#[cfg(feature = "async")]
pub(crate) fn invalid_argument(message: impl Into<String>) -> Error {
Error::new(ErrorCode::InvalidArgument, message)
}
#[cfg(feature = "async")]
pub(crate) fn invalid_config(message: impl Into<String>) -> Error {
Error::new(ErrorCode::InvalidConfig, message)
}