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
use crate::BoxError;
use http_body::Body;
use pin_project_lite::pin_project;
use std::{
future::Future,
pin::Pin,
task::{ready, Context, Poll},
time::Duration,
};
use tokio::time::{sleep, Sleep};
pin_project! {
/// Wrapper around a [`Body`] that enforces a hard deadline on the entire body transfer.
///
/// Unlike [`TimeoutBody`][super::TimeoutBody], which resets its deadline each time a frame is
/// received, `DeadlineBody` starts a single timer at construction and returns a
/// [`TimeoutError`][super::TimeoutError] if the body is not fully consumed before the deadline.
///
/// The deadline is **wall-clock time from construction**, not cumulative poll time. The
/// timer continues to count even if the consumer is not actively polling the body. If you
/// poll some frames, pause to do other work, and then resume, the elapsed pause time counts
/// toward the deadline.
///
/// # When to use this
///
/// This is primarily useful as middleware on public-facing endpoints where you want to bound
/// the total wall-clock time a single request can hold resources (task slots, memory for
/// buffering, etc.), regardless of how frequently data trickles in. A slow client sending
/// one byte per second will never trip [`TimeoutBody`][super::TimeoutBody]'s idle timeout,
/// but will correctly trip `DeadlineBody`.
///
/// If you only need to detect stalled connections where no data flows for a period, use
/// [`TimeoutBody`][super::TimeoutBody] instead. The two can be stacked if you want both
/// an idle timeout and a hard deadline.
///
/// # Example
///
/// ```
/// use http::{Request, Response};
/// use bytes::Bytes;
/// use http_body_util::Full;
/// use std::time::Duration;
/// use tower::ServiceBuilder;
/// use tower_http::timeout::RequestBodyDeadlineLayer;
///
/// async fn handle(_: Request<Full<Bytes>>) -> Result<Response<Full<Bytes>>, std::convert::Infallible> {
/// // ...
/// # todo!()
/// }
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let svc = ServiceBuilder::new()
/// // Timeout bodies after 30 seconds total
/// .layer(RequestBodyDeadlineLayer::new(Duration::from_secs(30)))
/// .service_fn(handle);
/// # Ok(())
/// # }
/// ```
pub struct DeadlineBody<B> {
#[pin]
sleep: Sleep,
#[pin]
body: B,
}
}
impl<B> DeadlineBody<B> {
/// Creates a new [`DeadlineBody`].
///
/// The timeout starts immediately. If the body is not fully consumed within `timeout`,
/// subsequent `poll_frame` calls will return a [`TimeoutError`][super::TimeoutError].
pub fn new(timeout: Duration, body: B) -> Self {
DeadlineBody {
sleep: sleep(timeout),
body,
}
}
}
impl<B> Body for DeadlineBody<B>
where
B: Body,
B::Error: Into<BoxError>,
{
type Data = B::Data;
type Error = Box<dyn std::error::Error + Send + Sync>;
fn poll_frame(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<http_body::Frame<Self::Data>, Self::Error>>> {
let this = self.project();
// Error if the absolute timeout has expired.
if let Poll::Ready(()) = this.sleep.poll(cx) {
return Poll::Ready(Some(Err(Box::new(super::TimeoutError(())))));
}
// Check for body data.
let frame = ready!(this.body.poll_frame(cx));
Poll::Ready(frame.transpose().map_err(Into::into).transpose())
}
fn is_end_stream(&self) -> bool {
self.body.is_end_stream()
}
fn size_hint(&self) -> http_body::SizeHint {
self.body.size_hint()
}
}
#[cfg(test)]
mod tests {
use super::*;
use bytes::Bytes;
use http_body::Frame;
use http_body_util::BodyExt;
use pin_project_lite::pin_project;
use std::{error::Error, fmt::Display};
use tokio::time::sleep;
#[derive(Debug)]
struct MockError;
impl Error for MockError {}
impl Display for MockError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "mock error")
}
}
pin_project! {
/// A body that yields a frame after a delay.
struct MockBody {
#[pin]
sleep: Sleep,
}
}
impl Body for MockBody {
type Data = Bytes;
type Error = MockError;
fn poll_frame(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
let this = self.project();
this.sleep
.poll(cx)
.map(|_| Some(Ok(Frame::data(vec![].into()))))
}
}
pin_project! {
/// A body that yields multiple frames with a delay between each.
struct MultiFrameBody {
frames_remaining: usize,
frame_interval: Duration,
#[pin]
sleep: Option<Sleep>,
}
}
impl Body for MultiFrameBody {
type Data = Bytes;
type Error = MockError;
fn poll_frame(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
let mut this = self.project();
if *this.frames_remaining == 0 {
return Poll::Ready(None);
}
// Start the sleep if not active.
let sleep_pinned = if let Some(s) = this.sleep.as_mut().as_pin_mut() {
s
} else {
this.sleep.set(Some(sleep(*this.frame_interval)));
this.sleep.as_mut().as_pin_mut().unwrap()
};
ready!(sleep_pinned.poll(cx));
this.sleep.set(None);
*this.frames_remaining -= 1;
Poll::Ready(Some(Ok(Frame::data(Bytes::from("chunk")))))
}
}
#[tokio::test]
async fn body_completes_within_timeout() {
let mock_body = MockBody {
sleep: sleep(Duration::from_millis(50)),
};
let timeout_body = DeadlineBody::new(Duration::from_millis(200), mock_body);
assert!(timeout_body
.boxed()
.frame()
.await
.expect("no frame")
.is_ok());
}
#[tokio::test]
async fn body_exceeds_timeout() {
let mock_body = MockBody {
sleep: sleep(Duration::from_millis(200)),
};
let timeout_body = DeadlineBody::new(Duration::from_millis(50), mock_body);
let result = timeout_body.boxed().frame().await.unwrap();
assert!(result.is_err());
assert!(result
.unwrap_err()
.downcast_ref::<super::super::TimeoutError>()
.is_some());
}
#[tokio::test]
async fn deadline_fires_despite_steady_frames() {
// Each frame arrives every 30ms (well within an idle timeout of 100ms),
// but total transfer takes 5 * 30ms = 150ms, exceeding the 100ms deadline.
let body = MultiFrameBody {
frames_remaining: 5,
frame_interval: Duration::from_millis(30),
sleep: None,
};
let timeout_body = DeadlineBody::new(Duration::from_millis(100), body);
let mut boxed = timeout_body.boxed();
let mut got_error = false;
loop {
match boxed.frame().await {
Some(Ok(_)) => {}
Some(Err(_)) => {
got_error = true;
break;
}
None => break,
}
}
assert!(
got_error,
"expected timeout error before all frames arrived"
);
}
#[tokio::test]
async fn all_frames_arrive_within_deadline() {
// Each frame arrives every 20ms, total = 3 * 20ms = 60ms, within 200ms deadline.
let body = MultiFrameBody {
frames_remaining: 3,
frame_interval: Duration::from_millis(20),
sleep: None,
};
let timeout_body = DeadlineBody::new(Duration::from_millis(200), body);
let mut boxed = timeout_body.boxed();
let mut frame_count = 0;
loop {
match boxed.frame().await {
Some(Ok(_)) => frame_count += 1,
Some(Err(e)) => panic!("unexpected error: {}", e),
None => break,
}
}
assert_eq!(frame_count, 3);
}
}