sqlload 0.37.0

SQL data loading tooling.
use crate::http::constants::{FIRST_SERVER_ERROR, TOO_MANY_REQUESTS};

/// A failed call to a warehouse or object-store endpoint.
#[derive(Debug, Clone, thiserror::Error)]
pub enum ApiError {
    #[error("request failed: {0}")]
    Transport(String),
    #[error("HTTP {status} {code}: {message}")]
    Status {
        status: u16,
        code: String,
        message: String,
    },
    #[error("unexpected response: {0}")]
    Protocol(String),
    #[error("{0}")]
    Auth(String),
}

impl ApiError {
    /// True for failures worth retrying unchanged: transport errors, throttling and server errors.
    pub fn is_retryable(&self) -> bool {
        match self {
            Self::Transport(_) => true,
            Self::Status { status, .. } => {
                *status == TOO_MANY_REQUESTS || *status >= FIRST_SERVER_ERROR
            }
            Self::Protocol(_) | Self::Auth(_) => false,
        }
    }

    /// The HTTP status, when the server answered.
    pub fn status(&self) -> Option<u16> {
        match self {
            Self::Status { status, .. } => Some(*status),
            _ => None,
        }
    }

    /// The service error code, when the server sent one.
    pub fn code(&self) -> Option<&str> {
        match self {
            Self::Status { code, .. } => Some(code.as_str()),
            _ => None,
        }
    }
}

impl From<reqwest::Error> for ApiError {
    /// A request that could not be built, or an answer that is not the JSON expected, is a protocol error, which retrying would not change; anything else is transport, including a body cut off mid-read (which reqwest also calls a decode error).
    fn from(error: reqwest::Error) -> Self {
        let not_json = error.is_decode()
            && std::error::Error::source(&error)
                .is_some_and(|source| source.is::<serde_json::Error>());
        let protocol = error.is_builder() || not_json;
        let text = error.without_url().to_string();
        match protocol {
            true => Self::Protocol(text),
            false => Self::Transport(text),
        }
    }
}