thaler 0.1.0

The Thaler API: financial data from SEC filings, with the source filing for every value.
Documentation
//! What can go wrong.
//!
//! Every error the client returns is an [`Error`]. An answer the API gave
//! is [`Error::Api`], carrying the problem as documented at
//! <https://thaler.sh/developers/errors>: its `code`, `status`, `detail`
//! and `request_id`, which support asks for. [`ApiError::kind`] tells the
//! cases apart without reading the code:
//!
//! ```no_run
//! # async fn example(client: thaler::Client) {
//! use thaler::{ApiErrorKind, Error};
//!
//! match client.profile("ZZZZ").send().await {
//!     Ok(profile) => println!("{}", profile.data.entity_name),
//!     Err(Error::Api(error)) if error.kind() == ApiErrorKind::NotFound => println!("not covered"),
//!     Err(Error::Api(error)) if error.kind() == ApiErrorKind::RateLimited => {
//!         println!("wait {:?}", error.retry_after)
//!     }
//!     Err(error) => println!("{error}"),
//! }
//! # }
//! ```

use std::fmt;
use std::time::Duration;

use reqwest::header::HeaderMap;

use crate::ratelimit::RateLimit;
use crate::types::{LimitPolicy, ProblemCode};

/// Every error the client returns.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// An error the API answered with. It is boxed because it carries the
    /// answer's headers; the box derefs, so `error.kind()` and
    /// `error.status` read as they would unboxed.
    #[error(transparent)]
    Api(Box<ApiError>),
    /// The request got no answer: a connection failed or timed out, after
    /// the retries.
    #[error("no answer from the API ({operation}): {source}")]
    Transport {
        /// The operation that was asked for.
        operation: &'static str,
        /// What reqwest reported.
        #[source]
        source: reqwest::Error,
    },
    /// An answer is not as the API documents it; the message says how.
    /// Write to support@thaler.sh with it, quoting the request ID.
    #[error("an answer is not as the API documents it ({operation}): {message}")]
    Decode {
        /// The operation that was asked for.
        operation: &'static str,
        /// What was wrong with the answer, naming the field.
        message: String,
    },
    /// The client could not be made (no key, or one of the wrong shape, or
    /// a base URL that is not one), or a request could not be built (an
    /// empty ticker, a Screener clause the API would refuse).
    #[error("{0}")]
    Config(String),
}

impl Error {
    /// The API's problem, when the error is one.
    pub fn api(&self) -> Option<&ApiError> {
        match self {
            Error::Api(error) => Some(error),
            _ => None,
        }
    }
}

impl From<ApiError> for Error {
    fn from(error: ApiError) -> Self {
        Error::Api(Box::new(error))
    }
}

/// What an [`ApiError`] is, by its status.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ApiErrorKind {
    /// 400: a parameter is missing, unknown or out of range; `detail`
    /// names it.
    BadRequest,
    /// 401: no key, or a key that is malformed, unknown, revoked or
    /// expired; `code` says which.
    Authentication,
    /// 404: no such endpoint, company, filing, holder or day. On a ticker
    /// route, Thaler doesn't cover the ticker.
    NotFound,
    /// 429: a limit was reached and the retries ran out, or `retry_after`
    /// was past what the client waits for. `violated_policies` names the
    /// limits; the request wasn't counted.
    RateLimited,
    /// A 5xx: Thaler failed to answer, is busy, or took too long. A 500,
    /// 502, 503 or 504 is returned only after the retries. The request
    /// wasn't counted.
    Server,
    /// Another status, such as 405.
    Other,
}

/// An error the API answered with, as an RFC 9457 problem.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ApiError {
    /// The HTTP status.
    pub status: u16,
    /// The problem's code, as the errors page lists them; `Unknown` for a
    /// code this version of the SDK does not know.
    pub code: ProblemCode,
    /// The code as the API spelled it, whether or not the SDK knows it.
    pub code_text: String,
    /// The problem's title.
    pub title: String,
    /// What went wrong and what to do, in a sentence or two.
    pub detail: String,
    /// The URL of the code's entry on the errors page.
    pub type_url: String,
    /// The request's ID; quote it when writing to support.
    pub request_id: String,
    /// How long to wait before trying again, when the API said.
    pub retry_after: Option<Duration>,
    /// On a 429, the limits the request would have broken.
    pub violated_policies: Vec<LimitPolicy>,
    /// The account's limits as the answer reported them.
    pub rate_limit: Option<RateLimit>,
    /// The answer's headers.
    pub headers: HeaderMap,
}

impl ApiError {
    /// What the error is, by its status.
    pub fn kind(&self) -> ApiErrorKind {
        match self.status {
            400 => ApiErrorKind::BadRequest,
            401 => ApiErrorKind::Authentication,
            404 => ApiErrorKind::NotFound,
            429 => ApiErrorKind::RateLimited,
            500.. => ApiErrorKind::Server,
            _ => ApiErrorKind::Other,
        }
    }
}

impl fmt::Display for ApiError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} ({}): {} [{}]",
            self.code_text, self.status, self.detail, self.request_id
        )
    }
}

impl std::error::Error for ApiError {}