use std::time::Duration;
use serde::Deserialize;
#[derive(Debug)]
pub enum Error {
Api {
kind: ErrorKind,
message: String,
status: u16,
retry_after: Option<Duration>,
},
Network(reqwest::Error),
Io(std::io::Error),
Config(String),
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Api { kind, message, status: 0, .. } => {
write!(f, "internetdata: {kind}: {message}")
}
Self::Api { kind, message, status, .. } => {
write!(f, "internetdata: {kind} (HTTP {status}): {message}")
}
Self::Network(_) => write!(f, "internetdata: network: {}", self.message()),
Self::Io(e) => write!(f, "internetdata: io: {e}"),
Self::Config(m) => write!(f, "internetdata: {m}"),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Network(e) => Some(e),
Self::Io(e) => Some(e),
Self::Api { .. } | Self::Config(_) => None,
}
}
}
impl From<reqwest::Error> for Error {
fn from(e: reqwest::Error) -> Self {
Self::Network(e)
}
}
impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Self {
Self::Io(e)
}
}
#[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) if e.is_timeout() => format!("timed out: {e}"),
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, .. } if *status != 0 => 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_message(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 from_entry(status: u16, message: &str) -> Self {
Self::Api {
kind: kind_for_status(status, None),
message: message.to_owned(),
status,
retry_after: None,
}
}
pub(crate) fn restated(&self) -> Self {
Self::Api {
kind: self.kind(),
message: self.message(),
status: self.status().unwrap_or(0),
retry_after: self.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_message(body: &str) -> Option<String> {
#[derive(Deserialize)]
struct Envelope {
error: Option<String>,
rc: Option<String>,
}
let envelope: Envelope = serde_json::from_str(body).ok()?;
envelope.error.filter(|m| !m.is_empty()).or(envelope.rc.filter(|m| !m.is_empty()))
}