-
-
Notifications
You must be signed in to change notification settings - Fork 117
Expand file tree
/
Copy pathfuture.rs
More file actions
91 lines (78 loc) · 2.49 KB
/
Copy pathfuture.rs
File metadata and controls
91 lines (78 loc) · 2.49 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
use std::{
future::Future,
pin::Pin,
task::{Context, Poll, ready},
time::Duration,
};
use http::Response;
use pin_project_lite::pin_project;
use tokio::time::Sleep;
use super::body::TimeoutBody;
use crate::error::{BoxError, Error, TimedOut};
pin_project! {
/// [`Timeout`] response future
#[derive(Debug)]
pub struct ResponseFuture<F> {
#[pin]
pub(crate) response: F,
#[pin]
pub(crate) total_timeout: Option<Sleep>,
#[pin]
pub(crate) read_timeout: Option<Sleep>,
}
}
impl<F, T, E> Future for ResponseFuture<F>
where
F: Future<Output = Result<T, E>>,
E: Into<BoxError>,
{
type Output = Result<T, BoxError>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut this = self.project();
// First, try polling the future
match this.response.poll(cx) {
Poll::Ready(v) => return Poll::Ready(v.map_err(Into::into)),
Poll::Pending => {}
}
// Helper closure for polling a timeout and returning a TimedOut error
let mut check_timeout = |sleep: Option<Pin<&mut Sleep>>| {
if let Some(sleep) = sleep {
if sleep.poll(cx).is_ready() {
return Some(Poll::Ready(Err(Error::request(TimedOut).into())));
}
}
None
};
// Check total timeout first
if let Some(poll) = check_timeout(this.total_timeout.as_mut().as_pin_mut()) {
return poll;
}
// Check read timeout
if let Some(poll) = check_timeout(this.read_timeout.as_mut().as_pin_mut()) {
return poll;
}
Poll::Pending
}
}
pin_project! {
/// Response future for [`ResponseBodyTimeout`].
pub struct ResponseBodyTimeoutFuture<Fut> {
#[pin]
pub(crate) inner: Fut,
pub(crate) total_timeout: Option<Duration>,
pub(crate) read_timeout: Option<Duration>,
}
}
impl<Fut, ResBody, E> Future for ResponseBodyTimeoutFuture<Fut>
where
Fut: Future<Output = Result<Response<ResBody>, E>>,
{
type Output = Result<Response<TimeoutBody<ResBody>>, E>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let total_timeout = self.total_timeout;
let read_timeout = self.read_timeout;
let res = ready!(self.project().inner.poll(cx))?
.map(|body| TimeoutBody::new(total_timeout, read_timeout, body));
Poll::Ready(Ok(res))
}
}