use std::fmt;
use std::thread;
use std::time::Duration;
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::{Map, Value};
use ureq::http;
use crate::error::{api_error, generate_error, generated, Error};
use crate::retry::{self, RetryPolicy};
use crate::types::{
CheckRequest, CheckResponse, FaceInfo, FaceRequest, FaceResponse, FilePayload,
GenerateResponse, HealthResponse, ValidationResponse,
};
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
pub const USER_AGENT: &str = concat!("pain001-sdk-rust/", env!("CARGO_PKG_VERSION"));
const BODY_LIMIT: u64 = 64 * 1024 * 1024;
#[derive(Clone)]
pub struct Client {
base_url: String,
api_key: Option<String>,
timeout: Duration,
retry: Option<RetryPolicy>,
agent: ureq::Agent,
}
pub(crate) struct Reply {
pub(crate) status: u16,
pub(crate) retry_after: Option<String>,
pub(crate) value: Value,
}
impl fmt::Debug for Client {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Client")
.field("base_url", &self.base_url)
.field("api_key", &self.api_key.as_ref().map(|_| "<redacted>"))
.field("timeout", &self.timeout)
.field("retry", &self.retry)
.finish()
}
}
impl Client {
pub fn new(base_url: impl Into<String>) -> Self {
let base_url = base_url.into().trim_end_matches('/').to_owned();
Client {
base_url,
api_key: None,
timeout: DEFAULT_TIMEOUT,
retry: None,
agent: build_agent(DEFAULT_TIMEOUT),
}
}
pub fn api_key(mut self, key: impl Into<String>) -> Self {
self.api_key = Some(key.into());
self
}
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self.agent = build_agent(timeout);
self
}
pub fn retry(mut self, policy: RetryPolicy) -> Self {
self.retry = Some(policy);
self
}
pub fn base_url(&self) -> &str {
&self.base_url
}
pub fn health(&self) -> Result<HealthResponse, Error> {
self.call("GET", "/api/v1/health", None::<&()>)
}
pub fn validate(
&self,
content: &str,
filename: &str,
message_type: impl AsRef<str>,
scheme: Option<&str>,
) -> Result<ValidationResponse, Error> {
let body = FilePayload {
content,
filename,
message_type: message_type.as_ref(),
scheme,
};
self.call("POST", "/api/v1/ui/validate", Some(&body))
}
pub fn generate(
&self,
content: &str,
filename: &str,
message_type: impl AsRef<str>,
scheme: Option<&str>,
) -> Result<GenerateResponse, Error> {
let body = FilePayload {
content,
filename,
message_type: message_type.as_ref(),
scheme,
};
self.call_with("POST", "/api/v1/ui/generate", Some(&body), generate_error)
.and_then(generated)
}
pub fn check(
&self,
xml: &str,
scheme: Option<&str>,
schematron: Option<&str>,
) -> Result<CheckResponse, Error> {
let body = CheckRequest {
xml,
scheme,
schematron,
};
self.call("POST", "/api/v1/check", Some(&body))
}
pub fn faces(&self) -> Result<Vec<FaceInfo>, Error> {
self.call("GET", "/api/v1/faces", None::<&()>)
}
pub fn project_face(
&self,
face: &str,
xml: &str,
version: Option<&str>,
bindings: Option<&Map<String, Value>>,
) -> Result<FaceResponse, Error> {
let path = face_path(face);
let body = FaceRequest {
xml,
version,
bindings,
};
self.call("POST", &path, Some(&body))
}
pub fn request(
&self,
method: &str,
path: &str,
body: Option<&Value>,
) -> Result<(u16, Value), Error> {
self.exchange(method, path, body)
}
fn call<B, T>(&self, method: &str, path: &str, body: Option<&B>) -> Result<T, Error>
where
B: Serialize + ?Sized,
T: DeserializeOwned,
{
self.call_with(method, path, body, api_error)
}
fn call_with<B, T>(
&self,
method: &str,
path: &str,
body: Option<&B>,
on_error: fn(u16, Value) -> Error,
) -> Result<T, Error>
where
B: Serialize + ?Sized,
T: DeserializeOwned,
{
let (status, value) = self.exchange(method, path, body)?;
decode(status, value, on_error)
}
fn exchange<B>(&self, method: &str, path: &str, body: Option<&B>) -> Result<(u16, Value), Error>
where
B: Serialize + ?Sized,
{
let bytes = encode(body)?;
self.send(method, path, bytes)
}
fn send(&self, method: &str, path: &str, body: Option<Vec<u8>>) -> Result<(u16, Value), Error> {
let head = self.head(method, path)?;
let reply = match self.retry.filter(|_| head.method() == http::Method::GET) {
Some(policy) => retry::run(
&policy,
|| self.once(head.clone(), body.clone()),
thread::sleep,
),
None => self.once(head, body),
}?;
Ok((reply.status, reply.value))
}
fn head(&self, method: &str, path: &str) -> Result<http::Request<()>, Error> {
let mut builder = http::Request::builder()
.method(method)
.uri(format!("{}{}", self.base_url, path))
.header("Accept", "application/json")
.header("User-Agent", USER_AGENT);
if let Some(key) = &self.api_key {
builder = builder.header("Authorization", format!("Bearer {key}"));
}
builder.body(()).map_err(Error::transport)
}
fn once(&self, head: http::Request<()>, body: Option<Vec<u8>>) -> Result<Reply, Error> {
let result = match body {
Some(bytes) => {
let (mut parts, ()) = head.into_parts();
parts.headers.insert(
http::header::CONTENT_TYPE,
http::HeaderValue::from_static("application/json"),
);
self.agent.run(http::Request::from_parts(parts, bytes))
}
None => self.agent.run(head),
};
let mut response = result.map_err(Error::transport)?;
let status = response.status().as_u16();
let retry_after = response
.headers()
.get(http::header::RETRY_AFTER)
.and_then(|value| value.to_str().ok())
.map(str::to_owned);
let text = response
.body_mut()
.with_config()
.limit(BODY_LIMIT)
.read_to_string()
.map_err(Error::transport)?;
Ok(Reply {
status,
retry_after,
value: parse_body(&text),
})
}
}
fn build_agent(timeout: Duration) -> ureq::Agent {
ureq::Agent::config_builder()
.http_status_as_error(false)
.timeout_global(Some(timeout))
.build()
.new_agent()
}
pub(crate) fn decode<T>(
status: u16,
value: Value,
on_error: fn(u16, Value) -> Error,
) -> Result<T, Error>
where
T: DeserializeOwned,
{
if !(200..300).contains(&status) {
return Err(on_error(status, value));
}
serde_json::from_value(value).map_err(Error::Decode)
}
pub(crate) fn encode<B>(body: Option<&B>) -> Result<Option<Vec<u8>>, Error>
where
B: Serialize + ?Sized,
{
body.map(serde_json::to_vec)
.transpose()
.map_err(Error::Decode)
}
pub(crate) fn face_path(face: &str) -> String {
format!("/api/v1/faces/{}", encode_segment(face))
}
pub(crate) fn parse_body(text: &str) -> Value {
if text.trim().is_empty() {
return Value::Null;
}
serde_json::from_str(text).unwrap_or_else(|_| Value::String(text.to_owned()))
}
fn encode_segment(segment: &str) -> String {
let mut out = String::with_capacity(segment.len());
for byte in segment.bytes() {
if byte.is_ascii_alphanumeric() || b"-._~".contains(&byte) {
out.push(char::from(byte));
} else {
out.push_str(&format!("%{byte:02X}"));
}
}
out
}
#[cfg(test)]
mod tests;