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
use std::sync::Arc;
use std::time::Duration;

use crate::error::{Error, Result};
use crate::resources::{Batch, Chat, Emails, Events, Knowledge, Payments};
use crate::transport::{Async, Executor, Inner};

/// The API's address unless `HATANG_BASE_URL` or [`HatangBuilder::base_url`] says otherwise.
pub const DEFAULT_BASE_URL: &str = "https://api.hatang.dev";
/// How long one call may take unless [`HatangBuilder::timeout`] says otherwise.
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
/// This crate's version, sent in the User-Agent.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

/// Settings for a client. Start from [`Hatang::builder`] (or `blocking::Hatang::builder`).
#[derive(Debug, Default, Clone)]
pub struct HatangBuilder {
    api_key: Option<String>,
    base_url: Option<String>,
    environment: Option<String>,
    timeout: Option<Duration>,
    user_agent: Option<String>,
    http: Option<reqwest::Client>,
}

impl HatangBuilder {
    /// Your API key (`ht_…`). Without it, `HATANG_API_KEY` is read.
    pub fn api_key(mut self, key: impl Into<String>) -> Self {
        self.api_key = Some(key.into());
        self
    }
    /// The API's address. Without it, `HATANG_BASE_URL`, then `https://api.hatang.dev`.
    pub fn base_url(mut self, url: impl Into<String>) -> Self {
        self.base_url = Some(url.into());
        self
    }
    /// Sent as `Hatang-Environment` (`sandbox`…). Without it, `HATANG_ENVIRONMENT` is read.
    pub fn environment(mut self, environment: impl Into<String>) -> Self {
        self.environment = Some(environment.into());
        self
    }
    /// How long one call may take (30 seconds by default). Ignored with [`HatangBuilder::http_client`].
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }
    pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
        self.user_agent = Some(user_agent.into());
        self
    }
    /// Your own `reqwest::Client` (proxy, connection pool, middleware-free tests…).
    pub fn http_client(mut self, client: reqwest::Client) -> Self {
        self.http = Some(client);
        self
    }

    fn inner(self) -> Result<Inner> {
        let env = |k: &str| std::env::var(k).ok().filter(|v| !v.is_empty());
        let api_key = self
            .api_key
            .filter(|k| !k.is_empty())
            .or_else(|| env("HATANG_API_KEY"))
            .ok_or_else(|| {
                Error::Config(
                    r#"Missing API key. Pass it: Hatang::new("ht_123"), or set HATANG_API_KEY"#
                        .into(),
                )
            })?;
        let base_url = self
            .base_url
            .or_else(|| env("HATANG_BASE_URL"))
            .unwrap_or_else(|| DEFAULT_BASE_URL.into())
            .trim_end_matches('/')
            .to_string();
        let http = match self.http {
            Some(http) => http,
            None => reqwest::Client::builder()
                .timeout(self.timeout.unwrap_or(DEFAULT_TIMEOUT))
                .build()
                .map_err(|e| Error::Config(format!("HTTP client: {e}")))?,
        };
        Ok(Inner {
            http,
            api_key,
            base_url,
            environment: self.environment.or_else(|| env("HATANG_ENVIRONMENT")),
            user_agent: self
                .user_agent
                .unwrap_or_else(|| format!("hatang-sdk-rust/{VERSION} (rust)")),
        })
    }

    /// The async client.
    pub fn build(self) -> Result<Hatang> {
        Ok(Client::with(Async(Arc::new(self.inner()?))))
    }

    /// The blocking client. Do not use it inside an async runtime (it runs its own).
    #[cfg(feature = "blocking")]
    #[cfg_attr(docsrs, doc(cfg(feature = "blocking")))]
    pub fn build_blocking(self) -> Result<crate::blocking::Hatang> {
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .map_err(|e| Error::Config(format!("runtime: {e}")))?;
        Ok(Client::with(crate::transport::Blocking(
            Arc::new(self.inner()?),
            Arc::new(rt),
        )))
    }
}

/// A Ha Tang client. Use the aliases [`Hatang`] (async) and `blocking::Hatang`.
///
/// The namespaces are fields, as in the other SDKs: `hatang.emails.send(…)`, `hatang.chat.orders.get(…)`.
/// Cloning is cheap; clones share one connection pool.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Client<C> {
    /// Transactional email.
    pub emails: Emails<C>,
    /// Several emails in one call.
    pub batch: Batch<C>,
    /// The AI assistant's knowledge.
    pub knowledge: Knowledge<C>,
    /// Support: customers, conversations, plans and purchases, products, orders.
    pub chat: Chat<C>,
    /// VietQR payments.
    pub payments: Payments<C>,
    /// Events that trigger automations.
    pub events: Events<C>,
}

impl<C: Executor> Client<C> {
    fn with(c: C) -> Self {
        Client {
            emails: Emails::new(c.clone()),
            batch: Batch::new(c.clone()),
            knowledge: Knowledge::new(c.clone()),
            chat: Chat::new(c.clone()),
            payments: Payments::new(c.clone()),
            events: Events::new(c),
        }
    }
}

/// The async client: every call returns a future.
///
/// ```no_run
/// # async fn run() -> hatang::Result<()> {
/// let hatang = hatang::Hatang::from_env()?; // reads HATANG_API_KEY
/// let sent = hatang.emails.send(&hatang::SendEmail::new("hello@mochuong.vn", ["chi.ha@example.com"], "Xin chào"), None).await?;
/// println!("{}", sent.id);
/// # Ok(()) }
/// ```
pub type Hatang = Client<Async>;

impl Hatang {
    /// A client with this API key and the defaults (`HATANG_BASE_URL` and `HATANG_ENVIRONMENT` are still read).
    pub fn new(api_key: impl Into<String>) -> Result<Self> {
        Self::builder().api_key(api_key).build()
    }
    /// A client from `HATANG_API_KEY` (and `HATANG_BASE_URL`, `HATANG_ENVIRONMENT`).
    pub fn from_env() -> Result<Self> {
        Self::builder().build()
    }
    pub fn builder() -> HatangBuilder {
        HatangBuilder::default()
    }
}