Skip to main content

pain001_sdk/
client.rs

1// SPDX-License-Identifier: Apache-2.0 OR MIT
2//! The blocking client.
3
4use 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
20/// The timeout a new [`Client`] uses for a whole call (connect, send and
21/// read), until [`Client::timeout`] changes it.
22pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
23
24/// This crate's version, from `Cargo.toml`.
25pub const VERSION: &str = env!("CARGO_PKG_VERSION");
26
27/// The `User-Agent` every request sends: `pain001-sdk-rust/<VERSION>`, so a
28/// server's access log shows which client and release made a call.
29pub const USER_AGENT: &str = concat!("pain001-sdk-rust/", env!("CARGO_PKG_VERSION"));
30
31/// Largest response body read, in bytes. A generated document for the
32/// largest accepted input (10 MiB) fits with room to spare.
33const BODY_LIMIT: u64 = 64 * 1024 * 1024;
34
35/// A client for one pain001 server.
36///
37/// Cheap to clone; clones share the connection pool. `Debug` output never
38/// shows the API key.
39#[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
48/// One answer: the status, the `Retry-After` header and the parsed body.
49pub(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    /// A client for the server at `base_url`, for example
68    /// `http://127.0.0.1:8000`. A trailing `/` is ignored.
69    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    /// Sends `Authorization: Bearer <key>` on every call (the server's
81    /// `PAIN001_API_KEY`).
82    pub fn api_key(mut self, key: impl Into<String>) -> Self {
83        self.api_key = Some(key.into());
84        self
85    }
86
87    /// Sets the timeout for a whole call.
88    pub fn timeout(mut self, timeout: Duration) -> Self {
89        self.timeout = timeout;
90        self.agent = build_agent(timeout);
91        self
92    }
93
94    /// Retries `GET` calls under `policy`; without this, every call makes
95    /// exactly one attempt. `POST` calls are never retried. See
96    /// [`RetryPolicy`].
97    pub fn retry(mut self, policy: RetryPolicy) -> Self {
98        self.retry = Some(policy);
99        self
100    }
101
102    /// The base URL, without a trailing `/`.
103    pub fn base_url(&self) -> &str {
104        &self.base_url
105    }
106
107    /// `GET /api/v1/health`.
108    pub fn health(&self) -> Result<HealthResponse, Error> {
109        self.call("GET", "/api/v1/health", None::<&()>)
110    }
111
112    /// `POST /api/v1/ui/validate`: validates a CSV, JSON or JSONL payment
113    /// file's text. `filename`'s suffix picks the parser; `scheme` names
114    /// rulebooks, comma-separated (for example `sepa-sct`).
115    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    /// `POST /api/v1/ui/generate`: turns a payment file's text into XML.
132    ///
133    /// # Errors
134    ///
135    /// [`Error::Refused`] when the server refuses the rows or a scheme rule
136    /// (HTTP `422`), carrying the typed findings; [`Error::Api`] for any
137    /// other non-2xx reply, such as a `400` for an unreadable file;
138    /// [`Error::Decode`] for a 2xx reply without `success: true` and the
139    /// XML, so an `Ok` always carries the document.
140    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    /// `POST /api/v1/check`: runs the validation ladder on an existing
158    /// pain.001 or pain.008 document, adding scheme profiles and a
159    /// Schematron preset (`sepa`, `fednow`, `cbpr`) when given.
160    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    /// `GET /api/v1/faces`: the faces a document can be projected into.
175    pub fn faces(&self) -> Result<Vec<FaceInfo>, Error> {
176        self.call("GET", "/api/v1/faces", None::<&()>)
177    }
178
179    /// `POST /api/v1/faces/{face}`: projects a pain.001 document into
180    /// `face`. `version` is detected from the namespace when `None`.
181    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    /// Sends any request and returns the status with the parsed body,
198    /// whatever the status. An empty body parses as `null`; a body that is
199    /// not JSON becomes a JSON string. `path` starts with `/`.
200    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    /// [`Client::call`] with `on_error` building the error for a non-2xx
218    /// status from the parsed body.
219    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    /// Encodes `body` as JSON and sends the request.
235    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    /// Sends the request, once, or under the retry policy for a `GET`.
244    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    /// The request line and headers every call shares; an invalid method
258    /// or URL fails here, before anything is sent.
259    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    /// Sends `head` once, with `body` as JSON when there is one, and reads
272    /// the answer.
273    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
314/// Turns a status and its parsed body into the typed result: a 2xx body
315/// decodes as `T` (or fails with [`Error::Decode`]), any other status goes
316/// to `on_error`.
317pub(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
331/// A request body as JSON bytes; a body that cannot be encoded is
332/// [`Error::Decode`].
333pub(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
342/// The path of `POST /api/v1/faces/{face}`, with `face` percent-encoded.
343pub(crate) fn face_path(face: &str) -> String {
344    format!("/api/v1/faces/{}", encode_segment(face))
345}
346
347/// Parses a response body: empty is `null`, non-JSON is a JSON string.
348pub(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
355/// Percent-encodes one path segment, keeping RFC 3986 unreserved bytes.
356fn 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;