1use std::fmt;
5use std::thread;
6use std::time::Duration;
7
8use serde::de::DeserializeOwned;
9use serde::Serialize;
10use serde_json::{Map, Value};
11use ureq::http;
12
13use crate::error::{api_error, generate_error, generated, Error};
14use crate::retry::{self, RetryPolicy};
15use crate::types::{
16 CheckRequest, CheckResponse, FaceInfo, FaceRequest, FaceResponse, FilePayload,
17 GenerateResponse, HealthResponse, ValidationResponse,
18};
19
20pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
23
24pub const VERSION: &str = env!("CARGO_PKG_VERSION");
26
27pub const USER_AGENT: &str = concat!("pain001-sdk-rust/", env!("CARGO_PKG_VERSION"));
30
31const BODY_LIMIT: u64 = 64 * 1024 * 1024;
34
35#[derive(Clone)]
40pub struct Client {
41 base_url: String,
42 api_key: Option<String>,
43 timeout: Duration,
44 retry: Option<RetryPolicy>,
45 agent: ureq::Agent,
46}
47
48pub(crate) struct Reply {
50 pub(crate) status: u16,
51 pub(crate) retry_after: Option<String>,
52 pub(crate) value: Value,
53}
54
55impl fmt::Debug for Client {
56 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57 f.debug_struct("Client")
58 .field("base_url", &self.base_url)
59 .field("api_key", &self.api_key.as_ref().map(|_| "<redacted>"))
60 .field("timeout", &self.timeout)
61 .field("retry", &self.retry)
62 .finish()
63 }
64}
65
66impl Client {
67 pub fn new(base_url: impl Into<String>) -> Self {
70 let base_url = base_url.into().trim_end_matches('/').to_owned();
71 Client {
72 base_url,
73 api_key: None,
74 timeout: DEFAULT_TIMEOUT,
75 retry: None,
76 agent: build_agent(DEFAULT_TIMEOUT),
77 }
78 }
79
80 pub fn api_key(mut self, key: impl Into<String>) -> Self {
83 self.api_key = Some(key.into());
84 self
85 }
86
87 pub fn timeout(mut self, timeout: Duration) -> Self {
89 self.timeout = timeout;
90 self.agent = build_agent(timeout);
91 self
92 }
93
94 pub fn retry(mut self, policy: RetryPolicy) -> Self {
98 self.retry = Some(policy);
99 self
100 }
101
102 pub fn base_url(&self) -> &str {
104 &self.base_url
105 }
106
107 pub fn health(&self) -> Result<HealthResponse, Error> {
109 self.call("GET", "/api/v1/health", None::<&()>)
110 }
111
112 pub fn validate(
116 &self,
117 content: &str,
118 filename: &str,
119 message_type: impl AsRef<str>,
120 scheme: Option<&str>,
121 ) -> Result<ValidationResponse, Error> {
122 let body = FilePayload {
123 content,
124 filename,
125 message_type: message_type.as_ref(),
126 scheme,
127 };
128 self.call("POST", "/api/v1/ui/validate", Some(&body))
129 }
130
131 pub fn generate(
141 &self,
142 content: &str,
143 filename: &str,
144 message_type: impl AsRef<str>,
145 scheme: Option<&str>,
146 ) -> Result<GenerateResponse, Error> {
147 let body = FilePayload {
148 content,
149 filename,
150 message_type: message_type.as_ref(),
151 scheme,
152 };
153 self.call_with("POST", "/api/v1/ui/generate", Some(&body), generate_error)
154 .and_then(generated)
155 }
156
157 pub fn check(
161 &self,
162 xml: &str,
163 scheme: Option<&str>,
164 schematron: Option<&str>,
165 ) -> Result<CheckResponse, Error> {
166 let body = CheckRequest {
167 xml,
168 scheme,
169 schematron,
170 };
171 self.call("POST", "/api/v1/check", Some(&body))
172 }
173
174 pub fn faces(&self) -> Result<Vec<FaceInfo>, Error> {
176 self.call("GET", "/api/v1/faces", None::<&()>)
177 }
178
179 pub fn project_face(
182 &self,
183 face: &str,
184 xml: &str,
185 version: Option<&str>,
186 bindings: Option<&Map<String, Value>>,
187 ) -> Result<FaceResponse, Error> {
188 let path = face_path(face);
189 let body = FaceRequest {
190 xml,
191 version,
192 bindings,
193 };
194 self.call("POST", &path, Some(&body))
195 }
196
197 pub fn request(
201 &self,
202 method: &str,
203 path: &str,
204 body: Option<&Value>,
205 ) -> Result<(u16, Value), Error> {
206 self.exchange(method, path, body)
207 }
208
209 fn call<B, T>(&self, method: &str, path: &str, body: Option<&B>) -> Result<T, Error>
210 where
211 B: Serialize + ?Sized,
212 T: DeserializeOwned,
213 {
214 self.call_with(method, path, body, api_error)
215 }
216
217 fn call_with<B, T>(
220 &self,
221 method: &str,
222 path: &str,
223 body: Option<&B>,
224 on_error: fn(u16, Value) -> Error,
225 ) -> Result<T, Error>
226 where
227 B: Serialize + ?Sized,
228 T: DeserializeOwned,
229 {
230 let (status, value) = self.exchange(method, path, body)?;
231 decode(status, value, on_error)
232 }
233
234 fn exchange<B>(&self, method: &str, path: &str, body: Option<&B>) -> Result<(u16, Value), Error>
236 where
237 B: Serialize + ?Sized,
238 {
239 let bytes = encode(body)?;
240 self.send(method, path, bytes)
241 }
242
243 fn send(&self, method: &str, path: &str, body: Option<Vec<u8>>) -> Result<(u16, Value), Error> {
245 let head = self.head(method, path)?;
246 let reply = match self.retry.filter(|_| head.method() == http::Method::GET) {
247 Some(policy) => retry::run(
248 &policy,
249 || self.once(head.clone(), body.clone()),
250 thread::sleep,
251 ),
252 None => self.once(head, body),
253 }?;
254 Ok((reply.status, reply.value))
255 }
256
257 fn head(&self, method: &str, path: &str) -> Result<http::Request<()>, Error> {
260 let mut builder = http::Request::builder()
261 .method(method)
262 .uri(format!("{}{}", self.base_url, path))
263 .header("Accept", "application/json")
264 .header("User-Agent", USER_AGENT);
265 if let Some(key) = &self.api_key {
266 builder = builder.header("Authorization", format!("Bearer {key}"));
267 }
268 builder.body(()).map_err(Error::transport)
269 }
270
271 fn once(&self, head: http::Request<()>, body: Option<Vec<u8>>) -> Result<Reply, Error> {
274 let result = match body {
275 Some(bytes) => {
276 let (mut parts, ()) = head.into_parts();
277 parts.headers.insert(
278 http::header::CONTENT_TYPE,
279 http::HeaderValue::from_static("application/json"),
280 );
281 self.agent.run(http::Request::from_parts(parts, bytes))
282 }
283 None => self.agent.run(head),
284 };
285 let mut response = result.map_err(Error::transport)?;
286 let status = response.status().as_u16();
287 let retry_after = response
288 .headers()
289 .get(http::header::RETRY_AFTER)
290 .and_then(|value| value.to_str().ok())
291 .map(str::to_owned);
292 let text = response
293 .body_mut()
294 .with_config()
295 .limit(BODY_LIMIT)
296 .read_to_string()
297 .map_err(Error::transport)?;
298 Ok(Reply {
299 status,
300 retry_after,
301 value: parse_body(&text),
302 })
303 }
304}
305
306fn build_agent(timeout: Duration) -> ureq::Agent {
307 ureq::Agent::config_builder()
308 .http_status_as_error(false)
309 .timeout_global(Some(timeout))
310 .build()
311 .new_agent()
312}
313
314pub(crate) fn decode<T>(
318 status: u16,
319 value: Value,
320 on_error: fn(u16, Value) -> Error,
321) -> Result<T, Error>
322where
323 T: DeserializeOwned,
324{
325 if !(200..300).contains(&status) {
326 return Err(on_error(status, value));
327 }
328 serde_json::from_value(value).map_err(Error::Decode)
329}
330
331pub(crate) fn encode<B>(body: Option<&B>) -> Result<Option<Vec<u8>>, Error>
334where
335 B: Serialize + ?Sized,
336{
337 body.map(serde_json::to_vec)
338 .transpose()
339 .map_err(Error::Decode)
340}
341
342pub(crate) fn face_path(face: &str) -> String {
344 format!("/api/v1/faces/{}", encode_segment(face))
345}
346
347pub(crate) fn parse_body(text: &str) -> Value {
349 if text.trim().is_empty() {
350 return Value::Null;
351 }
352 serde_json::from_str(text).unwrap_or_else(|_| Value::String(text.to_owned()))
353}
354
355fn encode_segment(segment: &str) -> String {
357 let mut out = String::with_capacity(segment.len());
358 for byte in segment.bytes() {
359 if byte.is_ascii_alphanumeric() || b"-._~".contains(&byte) {
360 out.push(char::from(byte));
361 } else {
362 out.push_str(&format!("%{byte:02X}"));
363 }
364 }
365 out
366}
367
368#[cfg(test)]
369mod tests;