Repository navigation
Expand file tree
/
Copy pathhttp.rs
517 lines (455 loc) · 15.5 KB
/
Copy pathhttp.rs
File metadata and controls
517 lines (455 loc) · 15.5 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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
use super::{
retries::{RetryAction, RetryLogic},
sink, Batch, Partition, TowerBatchedSink, TowerPartitionSink, TowerRequestConfig,
TowerRequestSettings,
};
use crate::{
buffers::Acker,
http::{HttpClient, HttpError},
Event,
};
use bytes::{Buf, Bytes};
use futures::{future::BoxFuture, ready, Sink};
use http::StatusCode;
use hyper::{body, Body};
use indexmap::IndexMap;
use pin_project::pin_project;
use serde::{Deserialize, Serialize};
use std::{
fmt,
future::Future,
hash::Hash,
pin::Pin,
sync::Arc,
task::{Context, Poll},
time::Duration,
};
use tower::Service;
#[async_trait::async_trait]
pub trait HttpSink: Send + Sync + 'static {
type Input;
type Output;
fn encode_event(&self, event: Event) -> Option<Self::Input>;
async fn build_request(&self, events: Self::Output) -> crate::Result<http::Request<Vec<u8>>>;
}
/// Provides a simple wrapper around internal tower and
/// batching sinks for http.
///
/// This type wraps some `HttpSink` and some `Batch` type
/// and will apply request, batch and tls settings. Internally,
/// it holds an Arc reference to the `HttpSink`. It then exposes
/// a `Sink` interface that can be returned from `SinkConfig`.
///
/// Implementation details we require to buffer a single item due
/// to how `Sink` works. This is because we must "encode" the type
/// to be able to send it to the inner batch type and sink. Because of
/// this we must provide a single buffer slot. To ensure the buffer is
/// fully flushed make sure `poll_flush` returns ready.
#[pin_project]
pub struct BatchedHttpSink<T, B, L = HttpRetryLogic>
where
B: Batch,
B::Output: Clone + Send + 'static,
L: RetryLogic<Response = http::Response<Bytes>> + Send + 'static,
{
sink: Arc<T>,
#[pin]
inner: TowerBatchedSink<
HttpBatchService<BoxFuture<'static, crate::Result<hyper::Request<Vec<u8>>>>, B::Output>,
B,
L,
B::Output,
>,
// An empty slot is needed to buffer an item where we encoded it but
// the inner sink is applying back pressure. This trick is used in the `WithFlatMap`
// sink combinator. https://docs.rs/futures/0.1.29/src/futures/sink/with_flat_map.rs.html#20
slot: Option<B::Input>,
}
impl<T, B> BatchedHttpSink<T, B, HttpRetryLogic>
where
B: Batch,
B::Output: Clone + Send + 'static,
T: HttpSink<Input = B::Input, Output = B::Output>,
{
pub fn new(
sink: T,
batch: B,
request_settings: TowerRequestSettings,
batch_timeout: Duration,
client: HttpClient,
acker: Acker,
) -> Self {
Self::with_retry_logic(
sink,
batch,
HttpRetryLogic,
request_settings,
batch_timeout,
client,
acker,
)
}
}
impl<T, B, L> BatchedHttpSink<T, B, L>
where
B: Batch,
B::Output: Clone + Send + 'static,
L: RetryLogic<Response = http::Response<Bytes>, Error = HttpError> + Send + 'static,
T: HttpSink<Input = B::Input, Output = B::Output>,
{
pub fn with_retry_logic(
sink: T,
batch: B,
logic: L,
request_settings: TowerRequestSettings,
batch_timeout: Duration,
client: HttpClient,
acker: Acker,
) -> Self {
let sink = Arc::new(sink);
let sink1 = Arc::clone(&sink);
let request_builder =
move |b| -> BoxFuture<'static, crate::Result<http::Request<Vec<u8>>>> {
let sink = Arc::clone(&sink1);
Box::pin(async move { sink.build_request(b).await })
};
let svc = HttpBatchService::new(client, request_builder);
let inner = request_settings.batch_sink(logic, svc, batch, batch_timeout, acker);
Self {
sink,
inner,
slot: None,
}
}
}
impl<T, B, L> Sink<Event> for BatchedHttpSink<T, B, L>
where
B: Batch,
B::Output: Clone + Send + 'static,
T: HttpSink<Input = B::Input, Output = B::Output>,
L: RetryLogic<Response = http::Response<Bytes>> + Send + 'static,
{
type Error = crate::Error;
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
if self.slot.is_some() {
match self.as_mut().poll_flush(cx) {
Poll::Ready(Ok(())) => {}
Poll::Ready(Err(error)) => return Poll::Ready(Err(error)),
Poll::Pending => {
if self.slot.is_some() {
return Poll::Pending;
}
}
}
}
Poll::Ready(Ok(()))
}
fn start_send(self: Pin<&mut Self>, item: Event) -> Result<(), Self::Error> {
if let Some(item) = self.sink.encode_event(item) {
*self.project().slot = Some(item);
}
Ok(())
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
let mut this = self.project();
if this.slot.is_some() {
ready!(this.inner.as_mut().poll_ready(cx))?;
this.inner.as_mut().start_send(this.slot.take().unwrap())?;
}
this.inner.poll_flush(cx)
}
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
ready!(self.as_mut().poll_flush(cx))?;
self.project().inner.poll_close(cx)
}
}
#[pin_project]
pub struct PartitionHttpSink<T, B, K, L = HttpRetryLogic>
where
B: Batch,
B::Output: Clone + Send + 'static,
B::Input: Partition<K>,
K: Hash + Eq + Clone + Send + 'static,
L: RetryLogic<Response = http::Response<Bytes>> + Send + 'static,
T: HttpSink<Input = B::Input, Output = B::Output>,
{
sink: Arc<T>,
#[pin]
inner: TowerPartitionSink<
HttpBatchService<BoxFuture<'static, crate::Result<hyper::Request<Vec<u8>>>>, B::Output>,
B,
L,
K,
B::Output,
>,
slot: Option<B::Input>,
}
impl<T, B, K> PartitionHttpSink<T, B, K, HttpRetryLogic>
where
B: Batch,
B::Output: Clone + Send + 'static,
B::Input: Partition<K>,
K: Hash + Eq + Clone + Send + 'static,
T: HttpSink<Input = B::Input, Output = B::Output>,
{
pub fn new(
sink: T,
batch: B,
request_settings: TowerRequestSettings,
batch_timeout: Duration,
client: HttpClient,
acker: Acker,
) -> Self {
Self::with_retry_logic(
sink,
batch,
HttpRetryLogic,
request_settings,
batch_timeout,
client,
acker,
)
}
}
impl<T, B, K, L> PartitionHttpSink<T, B, K, L>
where
B: Batch,
B::Output: Clone + Send + 'static,
B::Input: Partition<K>,
K: Hash + Eq + Clone + Send + 'static,
L: RetryLogic<Response = http::Response<Bytes>, Error = HttpError> + Send + 'static,
T: HttpSink<Input = B::Input, Output = B::Output>,
{
pub fn with_retry_logic(
sink: T,
batch: B,
logic: L,
request_settings: TowerRequestSettings,
batch_timeout: Duration,
client: HttpClient,
acker: Acker,
) -> Self {
let sink = Arc::new(sink);
let sink1 = Arc::clone(&sink);
let request_builder =
move |b| -> BoxFuture<'static, crate::Result<http::Request<Vec<u8>>>> {
let sink = Arc::clone(&sink1);
Box::pin(async move { sink.build_request(b).await })
};
let svc = HttpBatchService::new(client, request_builder);
let inner = request_settings.partition_sink(logic, svc, batch, batch_timeout, acker);
Self {
sink,
inner,
slot: None,
}
}
}
impl<T, B, K, L> Sink<Event> for PartitionHttpSink<T, B, K, L>
where
B: Batch,
B::Output: Clone + Send + 'static,
B::Input: Partition<K>,
K: Hash + Eq + Clone + Send + 'static,
T: HttpSink<Input = B::Input, Output = B::Output>,
L: RetryLogic<Response = http::Response<Bytes>> + Send + 'static,
{
type Error = crate::Error;
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
if self.slot.is_some() {
match self.as_mut().poll_flush(cx) {
Poll::Ready(Ok(())) => {}
Poll::Ready(Err(error)) => return Poll::Ready(Err(error)),
Poll::Pending => {
if self.slot.is_some() {
return Poll::Pending;
}
}
}
}
Poll::Ready(Ok(()))
}
fn start_send(self: Pin<&mut Self>, item: Event) -> Result<(), Self::Error> {
if let Some(item) = self.sink.encode_event(item) {
*self.project().slot = Some(item);
}
Ok(())
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
let mut this = self.project();
if this.slot.is_some() {
ready!(this.inner.as_mut().poll_ready(cx))?;
this.inner.as_mut().start_send(this.slot.take().unwrap())?;
}
this.inner.poll_flush(cx)
}
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
ready!(self.as_mut().poll_flush(cx))?;
self.project().inner.poll_close(cx)
}
}
pub struct HttpBatchService<F, B = Vec<u8>> {
inner: HttpClient<Body>,
request_builder: Arc<dyn Fn(B) -> F + Send + Sync>,
}
impl<F, B> HttpBatchService<F, B> {
pub fn new(
inner: HttpClient,
request_builder: impl Fn(B) -> F + Send + Sync + 'static,
) -> Self {
HttpBatchService {
inner,
request_builder: Arc::new(Box::new(request_builder)),
}
}
}
impl<F, B> Service<B> for HttpBatchService<F, B>
where
F: Future<Output = crate::Result<hyper::Request<Vec<u8>>>> + Send + 'static,
B: Send + 'static,
{
type Response = http::Response<Bytes>;
type Error = crate::Error;
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, body: B) -> Self::Future {
let request_builder = Arc::clone(&self.request_builder);
let mut http_client = self.inner.clone();
Box::pin(async move {
let request = request_builder(body).await?.map(Body::from);
let response = http_client.call(request).await?;
let (parts, body) = response.into_parts();
let mut body = body::aggregate(body).await?;
Ok(hyper::Response::from_parts(parts, body.to_bytes()))
})
}
}
impl<F, B> Clone for HttpBatchService<F, B> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
request_builder: Arc::clone(&self.request_builder),
}
}
}
impl<T: fmt::Debug> sink::Response for http::Response<T> {
fn is_successful(&self) -> bool {
self.status().is_success()
}
}
#[derive(Debug, Default, Clone)]
pub struct HttpRetryLogic;
impl RetryLogic for HttpRetryLogic {
type Error = HttpError;
type Response = hyper::Response<Bytes>;
fn is_retriable_error(&self, _error: &Self::Error) -> bool {
true
}
fn should_retry_response(&self, response: &Self::Response) -> RetryAction {
let status = response.status();
match status {
StatusCode::TOO_MANY_REQUESTS => RetryAction::Retry("too many requests".into()),
StatusCode::NOT_IMPLEMENTED => {
RetryAction::DontRetry("endpoint not implemented".into())
}
_ if status.is_server_error() => RetryAction::Retry(format!(
"{}: {}",
status,
String::from_utf8_lossy(response.body())
)),
_ if status.is_success() => RetryAction::Successful,
_ => RetryAction::DontRetry(format!("response status: {}", status)),
}
}
}
/// A helper config struct
#[derive(Deserialize, Serialize, Debug, Clone, Default)]
#[serde(deny_unknown_fields)]
pub struct RequestConfig {
#[serde(flatten)]
pub tower: TowerRequestConfig,
#[serde(default)]
pub headers: IndexMap<String, String>,
}
impl RequestConfig {
pub fn add_old_option(&mut self, headers: Option<IndexMap<String, String>>) {
if let Some(headers) = headers {
warn!("Option `headers` has been deprecated. Use `request.headers` instead.");
self.headers.extend(headers);
}
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::{sinks::util::service::Concurrency, test_util::next_addr};
use futures::{future::ready, StreamExt};
use hyper::{
service::{make_service_fn, service_fn},
Response, Server, Uri,
};
#[test]
fn util_http_retry_logic() {
let logic = HttpRetryLogic;
let response_429 = Response::builder().status(429).body(Bytes::new()).unwrap();
let response_500 = Response::builder().status(500).body(Bytes::new()).unwrap();
let response_400 = Response::builder().status(400).body(Bytes::new()).unwrap();
let response_501 = Response::builder().status(501).body(Bytes::new()).unwrap();
assert!(logic.should_retry_response(&response_429).is_retryable());
assert!(logic.should_retry_response(&response_500).is_retryable());
assert!(logic
.should_retry_response(&response_400)
.is_not_retryable());
assert!(logic
.should_retry_response(&response_501)
.is_not_retryable());
}
#[tokio::test]
async fn util_http_it_makes_http_requests() {
let addr = next_addr();
let uri = format!("http://{}:{}/", addr.ip(), addr.port())
.parse::<Uri>()
.unwrap();
let request = b"hello".to_vec();
let client = HttpClient::new(None).unwrap();
let mut service = HttpBatchService::new(client, move |body: Vec<u8>| {
Box::pin(ready(
http::Request::post(&uri).body(body).map_err(Into::into),
))
});
let (tx, rx) = futures::channel::mpsc::channel(10);
let new_service = make_service_fn(move |_| {
let tx = tx.clone();
let svc = service_fn(move |req| {
let mut tx = tx.clone();
async move {
let body = hyper::body::aggregate(req.into_body())
.await
.map_err(|error| format!("error: {}", error))?;
let string = String::from_utf8(body.bytes().into())
.map_err(|_| "Wasn't UTF-8".to_string())?;
tx.try_send(string).map_err(|_| "Send error".to_string())?;
Ok::<_, crate::Error>(Response::new(Body::from("")))
}
});
async move { Ok::<_, std::convert::Infallible>(svc) }
});
tokio::spawn(async move {
if let Err(error) = Server::bind(&addr).serve(new_service).await {
eprintln!("Server error: {}", error);
}
});
tokio::time::delay_for(std::time::Duration::from_millis(50)).await;
service.call(request).await.unwrap();
let (body, _rest) = rx.into_future().await;
assert_eq!(body.unwrap(), "hello");
}
#[test]
fn alias_in_flight_limit_works() {
let cfg = toml::from_str::<RequestConfig>("in_flight_limit = 10")
.expect("Fixed concurrency failed for in_flight_limit param");
assert_eq!(cfg.tower.concurrency(), &Concurrency::Fixed(10));
}
}