crypto_service_sdk/
transport.rs1use std::fmt;
5use std::future::Future;
6use std::pin::Pin;
7
8use http::{HeaderMap, Method};
9
10use crate::error::TransportError;
11
12pub(crate) const BODY_LIMIT: usize = 64 * 1024 * 1024;
14
15pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
17
18pub trait Transport: Send + Sync + fmt::Debug {
27 fn send(&self, request: HttpRequest) -> BoxFuture<'_, Result<HttpResponse, TransportError>>;
30}
31
32#[derive(Clone)]
37pub struct HttpRequest {
38 pub method: Method,
40 pub url: String,
42 pub headers: HeaderMap,
44 pub body: Option<Vec<u8>>,
46}
47
48#[derive(Clone)]
52pub struct HttpResponse {
53 pub status: u16,
55 pub headers: HeaderMap,
57 pub body: Vec<u8>,
59}
60
61impl HttpResponse {
62 #[must_use]
65 pub fn media_type(&self) -> &str {
66 self.headers
67 .get(http::header::CONTENT_TYPE)
68 .and_then(|value| value.to_str().ok())
69 .and_then(|value| value.split(';').next())
70 .map_or("", str::trim)
71 }
72
73 #[must_use]
75 pub fn header(&self, name: &str) -> Option<&str> {
76 self.headers.get(name).and_then(|value| value.to_str().ok())
77 }
78}
79
80impl fmt::Debug for HttpRequest {
81 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82 f.debug_struct("HttpRequest")
83 .field("method", &self.method)
84 .field("url", &self.url)
85 .field("headers", &self.headers.keys().collect::<Vec<_>>())
86 .field("body", &self.body.as_ref().map(Vec::len))
87 .finish()
88 }
89}
90
91impl fmt::Debug for HttpResponse {
92 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93 f.debug_struct("HttpResponse")
94 .field("status", &self.status)
95 .field("headers", &self.headers.keys().collect::<Vec<_>>())
96 .field("body", &self.body.len())
97 .finish()
98 }
99}
100
101#[derive(Debug, Clone)]
106pub struct ReqwestTransport {
107 client: reqwest::Client,
108 limit: usize,
109}
110
111impl ReqwestTransport {
112 pub fn new() -> Result<Self, crate::Error> {
119 Self::with_limit(BODY_LIMIT)
120 }
121
122 pub(crate) fn with_limit(limit: usize) -> Result<Self, crate::Error> {
124 reqwest::Client::builder()
125 .redirect(reqwest::redirect::Policy::none())
128 .build()
129 .map(|client| ReqwestTransport { client, limit })
130 .map_err(build_failed)
131 }
132
133 async fn exchange(&self, request: HttpRequest) -> Result<HttpResponse, TransportError> {
134 let mut builder = self
135 .client
136 .request(request.method, request.url)
137 .headers(request.headers);
138 if let Some(body) = request.body {
139 builder = builder.body(body);
140 }
141 let mut response = builder.send().await.map_err(failure)?;
142 let status = response.status().as_u16();
143 let headers = std::mem::take(response.headers_mut());
144 let mut body = Vec::new();
145 while let Some(chunk) = response.chunk().await.map_err(failure)? {
146 if body.len() + chunk.len() > self.limit {
147 return Err(TransportError::new(
148 "response body over the size limit",
149 false,
150 ));
151 }
152 body.extend_from_slice(&chunk);
153 }
154 Ok(HttpResponse {
155 status,
156 headers,
157 body,
158 })
159 }
160}
161
162impl Transport for ReqwestTransport {
163 fn send(&self, request: HttpRequest) -> BoxFuture<'_, Result<HttpResponse, TransportError>> {
164 Box::pin(self.exchange(request))
165 }
166}
167
168pub(crate) fn build_failed(_: reqwest::Error) -> crate::Error {
170 crate::Error::Config("the HTTP client could not be built")
171}
172
173fn failure(error: reqwest::Error) -> TransportError {
175 let timed_out = error.is_timeout();
176 TransportError::new(error.without_url(), timed_out)
177}