taler-rust

GNU Taler code in Rust. Largely core banking integrations.
Log | Files | Refs | Submodules | README | LICENSE

builder.rs (9450B)


      1 /*
      2   This file is part of TALER
      3   Copyright (C) 2026 Taler Systems SA
      4 
      5   TALER is free software; you can redistribute it and/or modify it under the
      6   terms of the GNU Affero General Public License as published by the Free Software
      7   Foundation; either version 3, or (at your option) any later version.
      8 
      9   TALER is distributed in the hope that it will be useful, but WITHOUT ANY
     10   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
     11   A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
     12 
     13   You should have received a copy of the GNU Affero General Public License along with
     14   TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
     15 */
     16 
     17 use std::{
     18     borrow::Cow,
     19     fmt::{self},
     20 };
     21 
     22 use http::{
     23     HeaderMap, HeaderName, HeaderValue, StatusCode,
     24     header::{self},
     25 };
     26 use http_body_util::{BodyExt, Full, Limited};
     27 use hyper::{Method, body::Bytes};
     28 use serde::{Serialize, de::DeserializeOwned};
     29 use serde_path_to_error::Track;
     30 use taler_common::encoding::base64;
     31 use tracing::{Level, trace};
     32 use url::Url;
     33 
     34 use crate::{Client, ClientErr, Ctx, headers::HeaderParser, sse::SseClient};
     35 
     36 pub struct Req {
     37     client: Client,
     38     url: Url,
     39     body: Bytes,
     40     headers: HeaderMap,
     41     err: Option<ClientErr>,
     42     ctx: Ctx,
     43 }
     44 
     45 impl Req {
     46     pub fn new(
     47         client: &Client,
     48         method: Method,
     49         base_url: &Url,
     50         path: impl Into<Cow<'static, str>>,
     51     ) -> Self {
     52         let path = path.into();
     53         let url = base_url.join(&path).unwrap();
     54         Self {
     55             client: client.clone(),
     56             url,
     57             headers: HeaderMap::new(),
     58             body: Bytes::default(),
     59             err: None,
     60             ctx: Ctx {
     61                 path,
     62                 method,
     63                 status: None,
     64             },
     65         }
     66     }
     67 
     68     pub fn method(&self) -> &Method {
     69         &self.ctx.method
     70     }
     71 
     72     pub fn url(&self) -> &Url {
     73         &self.url
     74     }
     75 
     76     pub fn headers(&self) -> &HeaderMap {
     77         &self.headers
     78     }
     79 
     80     pub fn body(&self) -> &Bytes {
     81         &self.body
     82     }
     83 
     84     pub fn header<K, V>(mut self, key: K, value: V) -> Self
     85     where
     86         K: TryInto<HeaderName>,
     87         <K as TryInto<HeaderName>>::Error: Into<http::Error>,
     88         V: TryInto<HeaderValue>,
     89         <V as TryInto<HeaderValue>>::Error: Into<http::Error>,
     90     {
     91         let res = (|| {
     92             let name = key.try_into().map_err(Into::into)?;
     93             let value = value.try_into().map_err(Into::into)?;
     94             self.headers.insert(name, value);
     95             Ok(())
     96         })();
     97         if let Err(e) = res
     98             && self.err.is_none()
     99         {
    100             self.err = Some(e);
    101         }
    102         self
    103     }
    104 
    105     pub fn sensitive_header<K, V>(mut self, key: K, value: V) -> Self
    106     where
    107         K: TryInto<HeaderName>,
    108         <K as TryInto<HeaderName>>::Error: Into<http::Error>,
    109         V: TryInto<HeaderValue>,
    110         <V as TryInto<HeaderValue>>::Error: Into<http::Error>,
    111     {
    112         let res = (|| {
    113             let name = key.try_into().map_err(Into::into)?;
    114             let mut value = value.try_into().map_err(Into::into)?;
    115             value.set_sensitive(true);
    116             self.headers.insert(name, value);
    117             Ok(())
    118         })();
    119         if let Err(e) = res
    120             && self.err.is_none()
    121         {
    122             self.err = Some(e);
    123         }
    124         self
    125     }
    126 
    127     pub fn query<T: Serialize>(mut self, name: &str, value: T) -> Self {
    128         let mut pairs = self.url.query_pairs_mut();
    129         let serializer = serde_urlencoded::Serializer::new(&mut pairs);
    130         if let Err(e) = [(name, value)].serialize(serializer)
    131             && self.err.is_none()
    132         {
    133             self.err = Some(e.into());
    134         }
    135         drop(pairs);
    136         if self.url.query() == Some("") {
    137             self.url.set_query(None);
    138         }
    139         self
    140     }
    141 
    142     pub fn json<T: Serialize + ?Sized>(mut self, json: &T) -> Self {
    143         let mut buf = Vec::new();
    144         let serializer: &mut serde_json::Serializer<&mut Vec<u8>> =
    145             &mut serde_json::Serializer::new(&mut buf);
    146         if let Err(e) = serde_path_to_error::serialize(json, serializer).map_err(ClientErr::ReqJson)
    147             && self.err.is_none()
    148         {
    149             self.err = Some(e);
    150             return self;
    151         };
    152         self.content(buf.into(), HeaderValue::from_static("application/json"))
    153     }
    154 
    155     pub fn content(mut self, body: Bytes, ty: HeaderValue) -> Self {
    156         self.headers.insert(header::CONTENT_TYPE, ty);
    157         self.body = body;
    158         self
    159     }
    160 
    161     pub fn basic_auth<U, P>(self, username: U, password: P) -> Req
    162     where
    163         U: fmt::Display,
    164         P: fmt::Display,
    165     {
    166         let header = format!("Basic {}", base64::fmt(format!("{username}:{password}")),);
    167         self.sensitive_header(header::AUTHORIZATION, header)
    168     }
    169 
    170     pub fn bearer_auth<T>(self, token: T) -> Req
    171     where
    172         T: fmt::Display,
    173     {
    174         let header = format!("Bearer {token}");
    175         self.sensitive_header(header::AUTHORIZATION, header)
    176     }
    177 
    178     pub fn req_sse(mut self, client: &SseClient) -> Req {
    179         self = self
    180             .header(
    181                 header::ACCEPT,
    182                 HeaderValue::from_static("text/event-stream"),
    183             )
    184             .header(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
    185         if let Some(id) = &client.last_event_id()
    186             && let Ok(value) = HeaderValue::from_str(id)
    187         {
    188             self = self.header(HeaderName::from_static("last-event-id"), value);
    189         }
    190         self
    191     }
    192 
    193     pub async fn send(self) -> Result<(Ctx, Res), (Ctx, ClientErr)> {
    194         let Self {
    195             client,
    196             ctx,
    197             url,
    198             err,
    199             headers,
    200             body,
    201         } = self;
    202         if let Some(e) = err {
    203             return Err((ctx, e));
    204         }
    205         let req = match async {
    206             let mut builder = http::request::Request::builder()
    207                 .uri(url.as_str())
    208                 .method(ctx.method.clone());
    209             if let Some(headers_mut) = builder.headers_mut() {
    210                 *headers_mut = headers;
    211             }
    212             let req = builder.body(Full::new(body))?;
    213             Ok(req)
    214         }
    215         .await
    216         {
    217             Ok(it) => it,
    218             Err(e) => return Err((ctx, e)),
    219         };
    220         match client.request(req).await {
    221             Ok(res) => {
    222                 let (head, body) = res.into_parts();
    223                 Ok((ctx, Res { head, body }))
    224             }
    225             Err(e) => Err((ctx, ClientErr::ReqTransport(e.into()))),
    226         }
    227     }
    228 }
    229 
    230 pub struct Res {
    231     head: http::response::Parts,
    232     body: hyper::body::Incoming,
    233 }
    234 
    235 impl Res {
    236     pub fn status(&self) -> StatusCode {
    237         self.head.status
    238     }
    239 
    240     pub fn headers(&self) -> &HeaderMap {
    241         &self.head.headers
    242     }
    243 
    244     pub fn sse(self, client: &mut SseClient) -> Result<bool, ClientErr> {
    245         match self.status() {
    246             StatusCode::OK => {}
    247             StatusCode::NO_CONTENT => return Ok(false),
    248             status => return Err(ClientErr::Sse(format!("expected HTTP 200, got {status}"))),
    249         }
    250         let content_type = self.str_header(header::CONTENT_TYPE)?;
    251         if !content_type.eq_ignore_ascii_case("text/event-stream") {
    252             return Err(ClientErr::Sse(format!(
    253                 "expected text/event-stream, got {content_type}"
    254             )));
    255         }
    256         client.connect(self.body);
    257         Ok(true)
    258     }
    259 
    260     async fn full_body(self) -> Result<Bytes, ClientErr> {
    261         // Max 1 mb
    262         Limited::new(self.body, 1024 * 1024)
    263             .collect()
    264             .await
    265             .map(|it| it.to_bytes())
    266             .map_err(|e| ClientErr::ResTransport(e.to_string()))
    267     }
    268 
    269     /** Parse request body into a JSON type */
    270     pub async fn json<T: DeserializeOwned>(self) -> Result<T, ClientErr> {
    271         // TODO check content type?
    272         let body = self.full_body().await?;
    273         if tracing::enabled!(Level::TRACE) {
    274             let str = std::string::String::from_utf8_lossy(&body);
    275             trace!(target: "http", "JSON body: {str}");
    276         }
    277         let mut de = serde_json::Deserializer::from_slice(&body);
    278         let parsed = serde_path_to_error::deserialize(&mut de).map_err(ClientErr::ResJson)?;
    279         de.end().map_err(|e| {
    280             ClientErr::ResJson(serde_path_to_error::Error::new(Track::new().path(), e))
    281         })?;
    282         Ok(parsed)
    283     }
    284 
    285     /** Parse request body into a URL encoded type */
    286     pub async fn urlencoded<T: DeserializeOwned>(self) -> Result<T, ClientErr> {
    287         // TODO check content type?
    288         let body = self.full_body().await?;
    289         let parsed = serde_urlencoded::from_bytes(&body).map_err(ClientErr::Form)?;
    290         Ok(parsed)
    291     }
    292 
    293     /** Parse request body into as text */
    294     pub async fn text(self) -> Result<String, ClientErr> {
    295         let body = self.full_body().await?;
    296         let parsed =
    297             String::from_utf8(body.to_vec()).map_err(|e| ClientErr::Text(e.utf8_error()))?;
    298         Ok(parsed)
    299     }
    300 }
    301 
    302 impl HeaderParser<ClientErr> for Res {
    303     fn parse<T>(
    304         &self,
    305         name: impl Into<HeaderName>,
    306         kind: &'static str,
    307         transform: impl FnOnce(&str) -> Result<T, ()>,
    308     ) -> Result<T, ClientErr> {
    309         self.head
    310             .headers
    311             .parse(name, kind, transform)
    312             .map_err(ClientErr::Headers)
    313     }
    314 }