forked from vectordotdev/vector
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.rs
More file actions
266 lines (229 loc) · 7.99 KB
/
http.rs
File metadata and controls
266 lines (229 loc) · 7.99 KB
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
use crate::{
dns::Resolver,
internal_events::http_client,
tls::{tls_connector_builder, MaybeTlsSettings, TlsError},
};
use futures::future::BoxFuture;
use headers::{Authorization, HeaderMapExt};
use http::header::HeaderValue;
use http::request::Builder;
use http::HeaderMap;
use http::Request;
use hyper::{
body::{Body, HttpBody},
client::{Client, HttpConnector},
};
use hyper_openssl::HttpsConnector;
use serde::{Deserialize, Serialize};
use snafu::{ResultExt, Snafu};
use std::{
fmt,
task::{Context, Poll},
};
use tower::Service;
use tracing::Span;
use tracing_futures::Instrument;
#[derive(Debug, Snafu)]
pub enum HttpError {
#[snafu(display("Failed to build TLS connector"))]
BuildTlsConnector { source: TlsError },
#[snafu(display("Failed to build HTTPS connector"))]
MakeHttpsConnector { source: openssl::error::ErrorStack },
#[snafu(display("Failed to make HTTP(S) request"))]
CallRequest { source: hyper::Error },
}
pub type HttpClientFuture = <HttpClient as Service<http::Request<Body>>>::Future;
pub struct HttpClient<B = Body> {
client: Client<HttpsConnector<HttpConnector<Resolver>>, B>,
span: Span,
user_agent: HeaderValue,
}
impl<B> HttpClient<B>
where
B: fmt::Debug + HttpBody + Send + 'static,
B::Data: Send,
B::Error: Into<crate::Error>,
{
pub fn new(tls_settings: impl Into<MaybeTlsSettings>) -> Result<HttpClient<B>, HttpError> {
let mut http = HttpConnector::new_with_resolver(Resolver);
http.enforce_http(false);
let settings = tls_settings.into();
let tls = tls_connector_builder(&settings).context(BuildTlsConnector)?;
let mut https = HttpsConnector::with_connector(http, tls).context(MakeHttpsConnector)?;
let settings = settings.tls().cloned();
https.set_callback(move |c, _uri| {
if let Some(settings) = &settings {
settings.apply_connect_configuration(c);
}
Ok(())
});
let client = Client::builder().build(https);
let version = crate::get_version();
let user_agent = HeaderValue::from_str(&format!("Vector/{}", version))
.expect("Invalid header value for version!");
let span = tracing::info_span!("http");
Ok(HttpClient {
client,
span,
user_agent,
})
}
pub fn send(
&self,
mut request: Request<B>,
) -> BoxFuture<'static, Result<http::Response<Body>, HttpError>> {
let _enter = self.span.enter();
default_request_headers(&mut request, &self.user_agent);
emit!(http_client::AboutToSendHTTPRequest { request: &request });
let response = self.client.request(request);
let fut = async move {
// Capture the time right before we issue the request.
// Request doesn't start the processing until we start polling it.
let before = std::time::Instant::now();
// Send request and wait for the result.
let response_result = response.await;
// Compute the roundtrip time it took to send the request and get
// the response or error.
let roundtrip = before.elapsed();
// Handle the errors and extract the response.
let response = response_result
.map_err(|error| {
// Emit the error into the internal events system.
emit!(http_client::GotHTTPError {
error: &error,
roundtrip
});
error
})
.context(CallRequest)?;
// Emit the response into the internal events system.
emit!(http_client::GotHTTPResponse {
response: &response,
roundtrip
});
Ok(response)
}
.instrument(self.span.clone());
Box::pin(fut)
}
}
fn default_request_headers<B>(request: &mut Request<B>, user_agent: &HeaderValue) {
if !request.headers().contains_key("User-Agent") {
request
.headers_mut()
.insert("User-Agent", user_agent.clone());
}
if !request.headers().contains_key("Accept-Encoding") {
// hardcoding until we support compressed responses:
// https://github.com/timberio/vector/issues/5440
request
.headers_mut()
.insert("Accept-Encoding", HeaderValue::from_static("identity"));
}
}
impl<B> Service<Request<B>> for HttpClient<B>
where
B: fmt::Debug + HttpBody + Send + 'static,
B::Data: Send,
B::Error: Into<crate::Error>,
{
type Response = http::Response<Body>;
type Error = HttpError;
type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, request: Request<B>) -> Self::Future {
self.send(request)
}
}
impl<B> Clone for HttpClient<B> {
fn clone(&self) -> Self {
Self {
client: self.client.clone(),
span: self.span.clone(),
user_agent: self.user_agent.clone(),
}
}
}
impl<B> fmt::Debug for HttpClient<B> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("HttpClient")
.field("client", &self.client)
.field("user_agent", &self.user_agent)
.finish()
}
}
#[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq)]
#[serde(deny_unknown_fields, rename_all = "snake_case", tag = "strategy")]
pub enum Auth {
Basic { user: String, password: String },
Bearer { token: String },
}
pub trait MaybeAuth: Sized {
fn choose_one(&self, other: &Self) -> crate::Result<Self>;
}
impl MaybeAuth for Option<Auth> {
fn choose_one(&self, other: &Self) -> crate::Result<Self> {
if self.is_some() && other.is_some() {
Err("Two authorization credentials was provided.".into())
} else {
Ok(self.clone().or_else(|| other.clone()))
}
}
}
impl Auth {
pub fn apply<B>(&self, req: &mut Request<B>) {
self.apply_headers_map(req.headers_mut())
}
pub fn apply_builder(&self, mut builder: Builder) -> Builder {
if let Some(map) = builder.headers_mut() {
self.apply_headers_map(map)
}
builder
}
pub fn apply_headers_map(&self, map: &mut HeaderMap) {
match &self {
Auth::Basic { user, password } => {
let auth = Authorization::basic(&user, &password);
map.typed_insert(auth);
}
Auth::Bearer { token } => match Authorization::bearer(&token) {
Ok(auth) => map.typed_insert(auth),
Err(error) => error!(message = "Invalid bearer token.", token = %token, %error),
},
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_default_request_headers_defaults() {
let user_agent = HeaderValue::from_static("vector");
let mut request = Request::post("http://example.com").body(()).unwrap();
default_request_headers(&mut request, &user_agent);
assert_eq!(
request.headers().get("Accept-Encoding"),
Some(&HeaderValue::from_static("identity")),
);
assert_eq!(request.headers().get("User-Agent"), Some(&user_agent));
}
#[test]
fn test_default_request_headers_does_not_overwrite() {
let mut request = Request::post("http://example.com")
.header("Accept-Encoding", "gzip")
.header("User-Agent", "foo")
.body(())
.unwrap();
default_request_headers(&mut request, &HeaderValue::from_static("vector"));
assert_eq!(
request.headers().get("Accept-Encoding"),
Some(&HeaderValue::from_static("gzip")),
);
assert_eq!(
request.headers().get("User-Agent"),
Some(&HeaderValue::from_static("foo"))
);
}
}