use std::time::Duration;
use serde::Deserialize;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("internetdata: {kind} (HTTP {status}): {message}")]
Api {
kind: ErrorKind,
message: String,
status: u16,
retry_after: Option<Duration>,
},
#[error("internetdata: network: {0}")]
Network(#[from] reqwest::Error),
#[error("internetdata: io: {0}")]
Io(#[from] std::io::Error),
#[error("internetdata: {0}")]
Config(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ErrorKind {
BadRequest,
Unauthorized,
Forbidden,
RateLimited,
QuotaExceeded,
ServerError,
Network,
Io,
}
impl ErrorKind {
pub fn as_str(self) -> &'static str {
match self {
Self::BadRequest => "bad_request",
Self::Unauthorized => "unauthorized",
Self::Forbidden => "forbidden",
Self::RateLimited => "rate_limited",
Self::QuotaExceeded => "quota_exceeded",
Self::ServerError => "server_error",
Self::Network => "network",
Self::Io => "io",
}
}
}
impl std::fmt::Display for ErrorKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
impl Error {
pub fn kind(&self) -> ErrorKind {
match self {
Self::Api { kind, .. } => *kind,
Self::Network(_) => ErrorKind::Network,
Self::Io(_) => ErrorKind::Io,
Self::Config(_) => ErrorKind::BadRequest,
}
}
pub fn retryable(&self) -> bool {
match self {
Self::Io(e) => e.kind() == std::io::ErrorKind::UnexpectedEof,
_ => matches!(
self.kind(),
ErrorKind::RateLimited | ErrorKind::ServerError | ErrorKind::Network
),
}
}
pub fn message(&self) -> String {
match self {
Self::Api { message, .. } => message.clone(),
Self::Network(e) => e.to_string(),
Self::Io(e) => e.to_string(),
Self::Config(m) => m.clone(),
}
}
pub fn status(&self) -> Option<u16> {
match self {
Self::Api { status, .. } => Some(*status),
_ => None,
}
}
pub fn retry_after(&self) -> Option<Duration> {
match self {
Self::Api { retry_after, .. } => *retry_after,
_ => None,
}
}
pub(crate) fn from_response(status: u16, retry_after: Option<Duration>, body: &str) -> Self {
let message =
envelope_rc(body).unwrap_or_else(|| format!("request failed with status {status}"));
Self::Api { kind: kind_for_status(status, retry_after), message, status, retry_after }
}
}
pub(crate) fn kind_for_status(status: u16, retry_after: Option<Duration>) -> ErrorKind {
match status {
429 if retry_after.is_some() => ErrorKind::RateLimited,
429 => ErrorKind::QuotaExceeded,
401 => ErrorKind::Unauthorized,
403 => ErrorKind::Forbidden,
400..=499 => ErrorKind::BadRequest,
_ => ErrorKind::ServerError,
}
}
fn envelope_rc(body: &str) -> Option<String> {
#[derive(Deserialize)]
struct Envelope {
rc: Option<String>,
}
let envelope: Envelope = serde_json::from_str(body).ok()?;
envelope.rc.filter(|rc| !rc.is_empty())
}