-
Notifications
You must be signed in to change notification settings - Fork 1
/
reqwest.rs
203 lines (179 loc) · 5.98 KB
/
reqwest.rs
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
//! Adapter for [`reqwest`] client.
//!
//! [`reqwest`]: https://crates.io/crates/reqwest
use std::{future::Future, task::Poll};
use pin_project::pin_project;
use tower::Service;
use crate::{HttpBody, HttpClientService, HttpResponse};
impl<S, ReqBody> Service<http::Request<ReqBody>> for HttpClientService<S>
where
S: Service<reqwest::Request>,
S::Future: Send + 'static,
S::Error: 'static,
crate::Error: From<S::Error>,
HttpResponse: From<S::Response>,
HttpBody: From<ReqBody>,
{
type Response = HttpResponse;
type Error = crate::Error;
type Future = ExecuteRequestFuture<S>;
fn poll_ready(
&mut self,
_cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, req: http::Request<ReqBody>) -> Self::Future {
let future = reqwest::Request::try_from(req).map(|reqw| self.0.call(reqw));
ExecuteRequestFuture::new(future)
}
}
#[pin_project]
/// Future that resolves to the response or failure to connect.
#[derive(Debug)]
pub struct ExecuteRequestFuture<S>
where
S: Service<reqwest::Request>,
{
#[pin]
inner: Inner<S::Future>,
}
#[pin_project(project = InnerProj)]
#[derive(Debug)]
enum Inner<F> {
Future {
#[pin]
fut: F,
},
Error {
error: Option<crate::Error>,
},
}
impl<S> ExecuteRequestFuture<S>
where
S: Service<reqwest::Request>,
{
fn new(future: Result<S::Future, reqwest::Error>) -> Self {
let inner = match future {
Ok(fut) => Inner::Future { fut },
Err(error) => Inner::Error {
error: Some(error.into()),
},
};
Self { inner }
}
}
impl<S> Future for ExecuteRequestFuture<S>
where
S: Service<reqwest::Request>,
crate::Error: From<S::Error>,
HttpResponse: From<S::Response>,
{
type Output = crate::Result<HttpResponse>;
fn poll(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Self::Output> {
let this = self.project();
match this.inner.project() {
InnerProj::Future { fut } => fut
.poll(cx)
.map_ok(HttpResponse::from)
.map_err(crate::Error::from),
InnerProj::Error { error } => {
let error = error.take().expect("Polled after ready");
Poll::Ready(Err(error))
}
}
}
}
#[cfg(test)]
mod tests {
use http::{header::USER_AGENT, HeaderName, HeaderValue};
use http_body_util::BodyExt;
use pretty_assertions::assert_eq;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use tower::{Service, ServiceBuilder, ServiceExt};
use tower_http::{request_id::MakeRequestUuid, ServiceBuilderExt};
use wiremock::{
matchers::{method, path},
Mock, MockServer, ResponseTemplate,
};
use crate::HttpClientLayer;
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
struct Info {
student: String,
answer: u32,
request_id: Option<String>,
}
impl Info {
async fn from_body(body: reqwest::Body) -> anyhow::Result<Self> {
let body_bytes = body.collect().await?.to_bytes();
let info: Info = serde_json::from_slice(&body_bytes)?;
Ok(info)
}
}
#[tokio::test]
async fn test_http_client_layer() -> anyhow::Result<()> {
// Start a background HTTP server on a random local port
let mock_server = MockServer::start().await;
// Get mock server base uri
let mock_uri = mock_server.uri();
// Arrange the behaviour of the MockServer adding a Mock:
// when it receives a GET request on '/hello' it will respond with a 200.
Mock::given(method("GET"))
.and(path("/hello"))
.respond_with(|req: &wiremock::Request| {
let request_id = req
.headers
.get(HeaderName::from_static("x-request-id"))
.map(|value| value.to_str().unwrap().to_owned());
ResponseTemplate::new(200).set_body_json(Info {
student: "Vasya Pupkin".to_owned(),
answer: 42,
request_id,
})
})
// Mounting the mock on the mock server - it's now effective!
.mount(&mock_server)
.await;
// Create HTTP client
let client = Client::new();
// Execute request without layers
let request = http::request::Builder::new()
.method(http::Method::GET)
.uri(format!("{mock_uri}/hello"))
// TODO Make in easy to create requests without body.
.body("")?;
let response = ServiceBuilder::new()
.layer(HttpClientLayer)
.service(client.clone())
.call(request.clone())
.await?;
assert!(response.status().is_success());
// Try to read body
let info = Info::from_body(response.into_body()).await?;
assert!(info.request_id.is_none());
// TODO Find the way to avoid cloning the service.
let service = ServiceBuilder::new()
.override_response_header(USER_AGENT, HeaderValue::from_static("tower-reqwest"))
.set_x_request_id(MakeRequestUuid)
.layer(HttpClientLayer)
.service(client)
.boxed_clone();
// Execute request with a several layers from the tower-http
let response = service.clone().call(request).await?;
assert!(response.status().is_success());
assert_eq!(
response.headers().get(USER_AGENT).unwrap(),
HeaderValue::from_static("tower-reqwest")
);
// Try to read body again.
let info = Info::from_body(response.into_body()).await?;
assert_eq!(info.student, "Vasya Pupkin");
assert_eq!(info.answer, 42);
assert!(info.request_id.is_some());
Ok(())
}
}