1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
use std::{
pin::Pin,
sync::{
atomic::{AtomicUsize, Ordering},
Arc,
},
};
use futures_core::{
task::{Context, Poll},
Future,
};
use futures_util::TryFutureExt;
pub use hyper::client::{connect::Connect, HttpConnector};
use hyper::{
body::to_bytes,
header::{AUTHORIZATION, CONTENT_TYPE},
Body, Client as HyperClient, Error as HyperError, Request as HttpRequest,
Response as HttpResponse,
};
pub use hyper_tls::HttpsConnector;
use tower_service::Service;
use tower_util::ServiceExt;
use super::{Error, RequestFactory};
use crate::objects::{Request, RequestBuilder, Response};
pub type HttpError = Error<ConnectionError<HyperError>>;
pub enum ConnectionError<E> {
Poll(E),
Service(E),
Body(HyperError),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Credentials {
url: String,
user: Option<String>,
password: Option<String>,
}
#[derive(Clone, Debug)]
pub struct Client<S> {
credentials: Arc<Credentials>,
nonce: Arc<AtomicUsize>,
inner_service: S,
}
impl Client<HyperClient<HttpConnector>> {
pub fn new(url: String, user: Option<String>, password: Option<String>) -> Self {
debug_assert!(password.is_none() || user.is_some());
let credentials = Arc::new(Credentials {
url,
user,
password,
});
Client {
credentials,
inner_service: HyperClient::new(),
nonce: Arc::new(AtomicUsize::new(0)),
}
}
}
impl<S> Client<S> {
pub fn next_nonce(&self) -> usize {
self.nonce.load(Ordering::AcqRel)
}
}
impl Client<HyperClient<HttpsConnector<HttpConnector>>> {
pub fn new_tls(url: String, user: Option<String>, password: Option<String>) -> Self {
debug_assert!(password.is_none() || user.is_some());
let https = HttpsConnector::new();
let inner_service = HyperClient::builder().build::<_, Body>(https);
let credentials = Arc::new(Credentials {
url,
user,
password,
});
Client {
credentials,
inner_service,
nonce: Arc::new(AtomicUsize::new(0)),
}
}
}
type FutResponse<R, E> = Pin<Box<dyn Future<Output = Result<R, E>> + 'static + Send>>;
impl<S> Service<Request> for Client<S>
where
S: Service<HttpRequest<Body>, Response = HttpResponse<Body>>,
S::Error: 'static,
S::Future: Send + 'static,
{
type Response = Response;
type Error = Error<ConnectionError<S::Error>>;
type Future = FutResponse<Self::Response, Self::Error>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner_service
.poll_ready(cx)
.map_err(ConnectionError::Poll)
.map_err(Error::Connection)
}
fn call(&mut self, request: Request) -> Self::Future {
let json_raw = serde_json::to_vec(&request).unwrap();
let body = Body::from(json_raw);
let mut builder = hyper::Request::post(&self.credentials.url);
if let Some(ref user) = self.credentials.user {
let pass_str = match &self.credentials.password {
Some(some) => some,
None => "",
};
builder = builder.header(
AUTHORIZATION,
format!(
"Basic {}",
base64::encode(&format!("{}:{}", user, pass_str))
),
)
};
let request = builder
.header(CONTENT_TYPE, "application/json")
.body(body)
.unwrap();
let fut = self
.inner_service
.call(request)
.map_err(ConnectionError::Service)
.map_err(Error::Connection)
.and_then(|response| async move {
let body = to_bytes(response.into_body())
.await
.map_err(ConnectionError::Body)
.map_err(Error::Connection)?;
Ok(serde_json::from_slice(&body).map_err(Error::Json)?)
});
Box::pin(fut)
}
}
impl<S> Client<S>
where
S: Service<HttpRequest<Body>, Response = HttpResponse<Body>> + Clone,
S::Error: 'static,
S::Future: Send + 'static,
{
pub async fn send(
&self,
request: Request,
) -> Result<Response, Error<ConnectionError<S::Error>>> {
self.clone().oneshot(request).await
}
}
impl<C> RequestFactory for Client<C> {
fn build_request(&self) -> RequestBuilder {
let id = serde_json::Value::Number(self.nonce.fetch_add(1, Ordering::AcqRel).into());
Request::build().id(id)
}
}