hatang 0.2.0

Official Rust client for the Ha Tang (Hạ Tầng) API: transactional email, live chat and support CRM, VietQR payments, AI chatbot knowledge and webhook verification. Async (Tokio) and blocking.
Documentation
use std::fmt;
use std::time::Duration;

/// Everything a call or a signature check can fail with.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// The API answered with an error, or could not be reached.
    ///
    /// `status` is the HTTP status, or `0` when Ha Tang was not reached (network error, timeout).
    /// `name` is the API's error code (`validation_error`, `not_found`, `rate_limit_exceeded`…).
    /// `retry_after` is the API's `retry-after` header (sent with `429 rate_limit_exceeded`).
    /// Match it with `Error::Api { status, name, .. }`: more fields may come.
    #[error("{status} {name}: {message}")]
    #[non_exhaustive]
    Api {
        status: u16,
        name: String,
        message: String,
        retry_after: Option<Duration>,
    },
    /// A webhook delivery or IPN call whose signature (or timestamp) does not match.
    #[error("{0}")]
    Signature(String),
    /// The client could not be set up (no API key, an invalid base URL…).
    #[error("{0}")]
    Config(String),
    /// A request body could not be encoded, or a response did not have the expected shape.
    #[error("JSON: {0}")]
    Json(#[from] serde_json::Error),
}

impl Error {
    /// The HTTP status of an API error (`0` when Ha Tang was not reached); `None` for other errors.
    pub fn status(&self) -> Option<u16> {
        match self {
            Error::Api { status, .. } => Some(*status),
            _ => None,
        }
    }

    /// The API's error code (`validation_error`, `not_found`…); `None` for other errors.
    pub fn name(&self) -> Option<&str> {
        match self {
            Error::Api { name, .. } => Some(name),
            _ => None,
        }
    }

    /// True when the same call (with the same idempotency key) can succeed later: Ha Tang was
    /// unreachable, a rate limit (`429 rate_limit_exceeded`), a request still running with the same
    /// idempotency key (`409 concurrent_idempotent_requests`), or a server error. Wait
    /// [`Error::retry_after`] when it is set, otherwise back off.
    ///
    /// The daily email quota is not retryable this way: see [`Error::is_quota_exceeded`].
    pub fn retryable(&self) -> bool {
        match self {
            Error::Api { status, name, .. } => match status {
                0 => true,
                409 => name == "concurrent_idempotent_requests",
                429 => name != "daily_quota_exceeded",
                s => *s >= 500,
            },
            _ => false,
        }
    }

    /// How long the API asked to wait before retrying (its `retry-after` header), if it said.
    pub fn retry_after(&self) -> Option<Duration> {
        match self {
            Error::Api { retry_after, .. } => *retry_after,
            _ => None,
        }
    }

    /// True when the business reached its daily email quota (`429 daily_quota_exceeded`):
    /// sends work again after midnight UTC, or once the quota is raised.
    pub fn is_quota_exceeded(&self) -> bool {
        matches!(self, Error::Api { status: 429, name, .. } if name == "daily_quota_exceeded")
    }

    pub(crate) fn unreachable(err: impl fmt::Display) -> Self {
        Error::Api {
            status: 0,
            name: "application_error".into(),
            message: format!("Unable to reach the API: {err}"),
            retry_after: None,
        }
    }
}

/// `Result` with this crate's [`Error`].
pub type Result<T, E = Error> = std::result::Result<T, E>;