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};
const SEGMENT: &AsciiSet = &NON_ALPHANUMERIC
.remove(b'-')
.remove(b'.')
.remove(b'_')
.remove(b'~');
pub(crate) fn seg(value: &str) -> String {
utf8_percent_encode(value, SEGMENT).to_string()
}
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()),
}
}
#[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)>,
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
}
}
#[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
}
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 retry_after = retry_after(res.headers());
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(), retry_after));
}
Ok(serde_json::from_value(
body.unwrap_or_else(|| Value::Object(Default::default())),
)?)
}
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 retry_after = retry_after(res.headers());
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(),
retry_after,
));
}
Ok(text)
}
}
fn retry_after(headers: &reqwest::header::HeaderMap) -> Option<std::time::Duration> {
let secs: f64 = headers
.get(reqwest::header::RETRY_AFTER)?
.to_str()
.ok()?
.trim()
.parse()
.ok()?;
std::time::Duration::try_from_secs_f64(secs).ok()
}
fn api_error(
status: reqwest::StatusCode,
body: Option<&Value>,
retry_after: Option<std::time::Duration>,
) -> 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()),
retry_after,
}
}
pub type BoxFuture<T> = Pin<Box<dyn Future<Output = Result<T>> + Send + 'static>>;
mod sealed {
pub trait Sealed {}
}
pub trait Executor: Clone + sealed::Sealed {
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>;
}
#[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 })
}
}
#[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))
}
}