hatang 0.1.1

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
//! The HTTP layer shared by the async and blocking clients: headers, query strings, errors.

use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use percent_encoding::{utf8_percent_encode, AsciiSet, NON_ALPHANUMERIC};
use reqwest::Method;
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::Value;

use crate::error::{Error, Result};

/// RFC 3986 unreserved characters stay as they are; everything else (`/` included) is escaped.
const SEGMENT: &AsciiSet = &NON_ALPHANUMERIC
    .remove(b'-')
    .remove(b'.')
    .remove(b'_')
    .remove(b'~');

/// One path segment: ids may hold `/` (Play purchase tokens, your own order ids).
pub(crate) fn seg(value: &str) -> String {
    utf8_percent_encode(value, SEGMENT).to_string()
}

/// Query parameters as the API reads them, from any serializable value with fields:
/// `null` dropped, booleans as `true`/`false`, arrays comma-joined.
pub(crate) fn query_of<Q: Serialize + ?Sized>(params: &Q) -> Result<Vec<(String, String)>> {
    let value = serde_json::to_value(params)?;
    let mut out = Vec::new();
    match value {
        Value::Null => {}
        Value::Object(map) => {
            for (key, v) in map {
                if let Some(s) = scalar(&v) {
                    out.push((key, s));
                }
            }
        }
        _ => {
            return Err(Error::Config(
                "query parameters must be a struct or a map".into(),
            ))
        }
    }
    Ok(out)
}

fn scalar(v: &Value) -> Option<String> {
    match v {
        Value::Null => None,
        Value::Bool(b) => Some(if *b { "true" } else { "false" }.into()),
        Value::String(s) => Some(s.clone()),
        Value::Number(n) => Some(n.to_string()),
        Value::Array(items) => Some(
            items
                .iter()
                .filter_map(scalar)
                .collect::<Vec<_>>()
                .join(","),
        ),
        Value::Object(_) => Some(v.to_string()),
    }
}

/// What a resource method asks for; an executor turns it into a call. Internal.
#[doc(hidden)]
#[derive(Debug)]
pub struct Req {
    pub(crate) method: Method,
    pub(crate) path: String,
    pub(crate) query: Vec<(String, String)>,
    pub(crate) body: Option<Value>,
    pub(crate) headers: Vec<(&'static str, String)>,
    /// An encoding problem found while building the request; reported when it runs.
    pub(crate) invalid: Option<Error>,
}

impl Req {
    pub(crate) fn new(method: Method, path: impl Into<String>) -> Self {
        Req {
            method,
            path: path.into(),
            query: Vec::new(),
            body: None,
            headers: Vec::new(),
            invalid: None,
        }
    }
    pub(crate) fn get(path: impl Into<String>) -> Self {
        Self::new(Method::GET, path)
    }
    pub(crate) fn post(path: impl Into<String>) -> Self {
        Self::new(Method::POST, path)
    }
    pub(crate) fn put(path: impl Into<String>) -> Self {
        Self::new(Method::PUT, path)
    }
    pub(crate) fn patch(path: impl Into<String>) -> Self {
        Self::new(Method::PATCH, path)
    }
    pub(crate) fn delete(path: impl Into<String>) -> Self {
        Self::new(Method::DELETE, path)
    }

    pub(crate) fn json<B: Serialize + ?Sized>(mut self, body: &B) -> Self {
        match serde_json::to_value(body) {
            Ok(v) => self.body = Some(v),
            Err(e) => self.invalid = Some(e.into()),
        }
        self
    }

    pub(crate) fn query<Q: Serialize + ?Sized>(mut self, params: &Q) -> Self {
        match query_of(params) {
            Ok(mut q) => self.query.append(&mut q),
            Err(e) => self.invalid = Some(e),
        }
        self
    }

    pub(crate) fn idempotency(mut self, key: Option<&str>) -> Self {
        if let Some(k) = key.filter(|k| !k.is_empty()) {
            self.headers.push(("Idempotency-Key", k.to_string()));
        }
        self
    }
}

/// Settings shared by every call of one client.
#[derive(Debug)]
pub(crate) struct Inner {
    pub http: reqwest::Client,
    pub api_key: String,
    pub base_url: String,
    pub environment: Option<String>,
    pub user_agent: String,
}

impl Inner {
    fn request(&self, req: &Req) -> reqwest::RequestBuilder {
        let mut b = self
            .http
            .request(req.method.clone(), format!("{}{}", self.base_url, req.path))
            .bearer_auth(&self.api_key)
            .header(reqwest::header::USER_AGENT, &self.user_agent)
            .header(reqwest::header::ACCEPT, "application/json");
        if !req.query.is_empty() {
            b = b.query(&req.query);
        }
        if let Some(env) = &self.environment {
            b = b.header("Hatang-Environment", env);
        }
        if let Some(body) = &req.body {
            b = b
                .header(reqwest::header::CONTENT_TYPE, "application/json")
                .body(body.to_string());
        }
        for (k, v) in &req.headers {
            b = b.header(*k, v);
        }
        b
    }

    /// Runs a call and parses its JSON (`{}` for an empty success).
    pub async fn call<T: DeserializeOwned>(&self, mut req: Req) -> Result<T> {
        if let Some(e) = req.invalid.take() {
            return Err(e);
        }
        let res = self
            .request(&req)
            .send()
            .await
            .map_err(Error::unreachable)?;
        let status = res.status();
        let bytes = res.bytes().await.map_err(Error::unreachable)?;
        let body: Option<Value> = if bytes.is_empty() {
            None
        } else {
            serde_json::from_slice(&bytes).ok()
        };
        if !status.is_success() {
            return Err(api_error(status, body.as_ref()));
        }
        Ok(serde_json::from_value(
            body.unwrap_or_else(|| Value::Object(Default::default())),
        )?)
    }

    /// Runs a call whose answer is text (CSV exports).
    pub async fn text(&self, mut req: Req) -> Result<String> {
        if let Some(e) = req.invalid.take() {
            return Err(e);
        }
        let res = self
            .request(&req)
            .send()
            .await
            .map_err(Error::unreachable)?;
        let status = res.status();
        let text = res.text().await.map_err(Error::unreachable)?;
        if !status.is_success() {
            return Err(api_error(status, serde_json::from_str(&text).ok().as_ref()));
        }
        Ok(text)
    }
}

fn api_error(status: reqwest::StatusCode, body: Option<&Value>) -> Error {
    let field = |k: &str| body.and_then(|b| b.get(k));
    Error::Api {
        status: field("statusCode")
            .and_then(Value::as_u64)
            .map(|s| s as u16)
            .unwrap_or(status.as_u16()),
        name: field("name")
            .and_then(Value::as_str)
            .unwrap_or("application_error")
            .to_string(),
        message: field("message")
            .and_then(Value::as_str)
            .map(str::to_string)
            .or_else(|| status.canonical_reason().map(str::to_string))
            .unwrap_or_else(|| "Request failed".into()),
    }
}

/// A future returned by the async client.
pub type BoxFuture<T> = Pin<Box<dyn Future<Output = Result<T>> + Send + 'static>>;

mod sealed {
    pub trait Sealed {}
}

/// How a client runs calls: the async client returns futures, the blocking client results.
///
/// Resource methods return `C::Out<T>`: a future of `Result<T>` to `.await` with [`crate::Hatang`], or the
/// `Result<T>` itself with `blocking::Hatang`. Not implementable outside this crate.
pub trait Executor: Clone + sealed::Sealed {
    /// What a call returns.
    type Out<T: Send + 'static>;
    #[doc(hidden)]
    fn run<T: DeserializeOwned + Send + 'static>(&self, req: Req) -> Self::Out<T>;
    #[doc(hidden)]
    fn run_text(&self, req: Req) -> Self::Out<String>;
}

/// The async executor behind [`crate::Hatang`].
#[derive(Debug, Clone)]
pub struct Async(pub(crate) Arc<Inner>);

impl sealed::Sealed for Async {}

impl Executor for Async {
    type Out<T: Send + 'static> = BoxFuture<T>;
    fn run<T: DeserializeOwned + Send + 'static>(&self, req: Req) -> BoxFuture<T> {
        let inner = self.0.clone();
        Box::pin(async move { inner.call(req).await })
    }
    fn run_text(&self, req: Req) -> BoxFuture<String> {
        let inner = self.0.clone();
        Box::pin(async move { inner.text(req).await })
    }
}

/// The executor behind `blocking::Hatang`.
#[cfg(feature = "blocking")]
#[derive(Debug, Clone)]
pub struct Blocking(
    pub(crate) Arc<Inner>,
    pub(crate) Arc<tokio::runtime::Runtime>,
);

#[cfg(feature = "blocking")]
impl sealed::Sealed for Blocking {}

#[cfg(feature = "blocking")]
impl Executor for Blocking {
    type Out<T: Send + 'static> = Result<T>;
    fn run<T: DeserializeOwned + Send + 'static>(&self, req: Req) -> Result<T> {
        self.1.block_on(self.0.call(req))
    }
    fn run_text(&self, req: Req) -> Result<String> {
        self.1.block_on(self.0.text(req))
    }
}