1use std::fmt;
4use std::io;
5use std::pin::Pin;
6use std::task::{Context, Poll};
7
8use futures_io::AsyncRead;
9use hyper::body::{Body, Bytes, Frame, SizeHint};
10
11use crate::receive::ReplyBody;
12use crate::stall::Tracker;
13
14const MAX_FRAME: usize = 64 * 1024;
16
17const YIELD_AFTER: usize = 256 * 1024;
22
23pub(crate) enum ServeBody {
26 Empty,
27 Full(Option<Bytes>),
29 Stream(StreamBody),
30 Reply(ReplyBody),
31}
32
33impl ServeBody {
34 pub(crate) fn stream(
39 reader: Box<dyn AsyncRead + Unpin + Send>,
40 len: Option<u64>,
41 tracker: Tracker,
42 ) -> ServeBody {
43 ServeBody::Stream(StreamBody {
44 reader,
45 remaining: len,
46 buf: Vec::new(),
47 run: 0,
48 tracker,
49 })
50 }
51}
52
53pub(crate) struct StreamBody {
55 reader: Box<dyn AsyncRead + Unpin + Send>,
56 remaining: Option<u64>,
58 buf: Vec<u8>,
63 run: usize,
65 tracker: Tracker,
66}
67
68impl StreamBody {
69 fn poll_frame(&mut self, cx: &mut Context<'_>) -> Poll<Option<io::Result<Frame<Bytes>>>> {
70 let want = match self.remaining {
71 Some(0) => return Poll::Ready(None),
72 Some(n) => n.min(MAX_FRAME as u64) as usize,
73 None => MAX_FRAME,
74 };
75 if self.run >= YIELD_AFTER {
76 self.run = 0;
77 cx.waker().wake_by_ref();
78 return Poll::Pending;
79 }
80 if self.buf.len() < want {
81 self.buf.resize(want, 0);
82 }
83 let read = Pin::new(&mut self.reader).poll_read(cx, &mut self.buf[..want]);
84 let n = match read {
85 Poll::Pending => {
86 self.run = 0;
87 self.tracker.reading();
88 return Poll::Pending;
89 }
90 Poll::Ready(Ok(n)) => n,
91 Poll::Ready(Err(e)) => return Poll::Ready(Some(Err(e))),
92 };
93 if n == 0 {
94 return Poll::Ready(self.remaining.map(|_| {
95 Err(io::Error::new(
96 io::ErrorKind::UnexpectedEof,
97 "the file ended before its length",
98 ))
99 }));
100 }
101 if let Some(remaining) = &mut self.remaining {
102 *remaining -= n as u64;
103 }
104 self.run += n;
105 self.tracker.progress();
106 if n == self.buf.len() {
107 let data = std::mem::take(&mut self.buf);
108 return Poll::Ready(Some(Ok(Frame::data(Bytes::from(data)))));
109 }
110 Poll::Ready(Some(Ok(Frame::data(Bytes::copy_from_slice(
111 &self.buf[..n],
112 )))))
113 }
114}
115
116pub struct ReceiveBody(pub(crate) ServeBody);
124
125impl ReceiveBody {
126 pub(crate) fn into_serve(self) -> ServeBody {
128 self.0
129 }
130}
131
132impl fmt::Debug for ReceiveBody {
134 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135 f.debug_struct("ReceiveBody").finish_non_exhaustive()
136 }
137}
138
139impl Body for ReceiveBody {
140 type Data = Bytes;
141 type Error = io::Error;
142
143 fn poll_frame(
144 self: Pin<&mut Self>,
145 cx: &mut Context<'_>,
146 ) -> Poll<Option<io::Result<Frame<Bytes>>>> {
147 Pin::new(&mut self.get_mut().0).poll_frame(cx)
148 }
149
150 fn is_end_stream(&self) -> bool {
151 self.0.is_end_stream()
152 }
153
154 fn size_hint(&self) -> SizeHint {
155 self.0.size_hint()
156 }
157}
158
159impl Body for ServeBody {
160 type Data = Bytes;
161 type Error = io::Error;
162
163 fn poll_frame(
164 self: Pin<&mut Self>,
165 cx: &mut Context<'_>,
166 ) -> Poll<Option<io::Result<Frame<Bytes>>>> {
167 match self.get_mut() {
168 ServeBody::Empty => Poll::Ready(None),
169 ServeBody::Full(bytes) => Poll::Ready(bytes.take().map(|b| Ok(Frame::data(b)))),
170 ServeBody::Stream(stream) => stream.poll_frame(cx),
171 ServeBody::Reply(reply) => Poll::Ready(reply.poll_frame().map(Ok)),
172 }
173 }
174
175 fn is_end_stream(&self) -> bool {
176 match self {
177 ServeBody::Empty => true,
178 ServeBody::Full(bytes) => bytes.is_none(),
179 ServeBody::Stream(stream) => stream.remaining == Some(0),
180 ServeBody::Reply(reply) => reply.remaining() == 0,
181 }
182 }
183
184 fn size_hint(&self) -> SizeHint {
185 match self {
186 ServeBody::Empty => SizeHint::with_exact(0),
187 ServeBody::Full(bytes) => {
188 SizeHint::with_exact(bytes.as_ref().map_or(0, |b| b.len() as u64))
189 }
190 ServeBody::Stream(stream) => stream
191 .remaining
192 .map_or_else(SizeHint::default, SizeHint::with_exact),
193 ServeBody::Reply(reply) => SizeHint::with_exact(reply.remaining()),
194 }
195 }
196}
197
198#[cfg(test)]
199pub(crate) mod tests {
200 use std::sync::Arc;
201 use std::sync::atomic::{AtomicUsize, Ordering};
202 use std::task::{Wake, Waker};
203 use std::time::Duration;
204
205 use super::*;
206 use crate::stall::Stall;
207 use futures_lite::io::Cursor;
208 use ostrya_rt::block_on;
209
210 pub(crate) async fn frames(mut body: ServeBody) -> io::Result<Vec<Bytes>> {
212 let mut out = Vec::new();
213 while let Some(frame) = std::future::poll_fn(|cx| Pin::new(&mut body).poll_frame(cx)).await
214 {
215 out.push(frame?.into_data().unwrap());
216 }
217 Ok(out)
218 }
219
220 fn reader(bytes: Vec<u8>) -> Box<dyn AsyncRead + Unpin + Send> {
221 Box::new(Cursor::new(bytes))
222 }
223
224 pub(crate) fn tracker() -> Tracker {
226 Stall::new(Duration::from_secs(3600)).track()
227 }
228
229 fn stream(bytes: Vec<u8>, len: Option<u64>) -> ServeBody {
230 ServeBody::stream(reader(bytes), len, tracker())
231 }
232
233 #[test]
234 fn a_stream_yields_frames_of_at_most_64_kib() {
235 let data: Vec<u8> = (0..200_000u32).map(|i| i as u8).collect();
236 for len in [None, Some(200_000)] {
237 let frames = block_on(frames(stream(data.clone(), len))).unwrap();
238 assert!(frames.iter().all(|f| f.len() <= MAX_FRAME && !f.is_empty()));
239 assert_eq!(frames.concat(), data);
240 }
241 }
242
243 struct Short {
245 data: Cursor<Vec<u8>>,
246 max: usize,
247 }
248
249 impl AsyncRead for Short {
250 fn poll_read(
251 self: Pin<&mut Self>,
252 cx: &mut Context<'_>,
253 buf: &mut [u8],
254 ) -> Poll<io::Result<usize>> {
255 let this = self.get_mut();
256 let max = this.max.min(buf.len());
257 Pin::new(&mut this.data).poll_read(cx, &mut buf[..max])
258 }
259 }
260
261 #[test]
264 fn short_reads_give_frames_of_their_length() {
265 let data: Vec<u8> = (0..100_000u32).map(|i| (i % 251) as u8).collect();
266 for len in [None, Some(100_000)] {
267 let reader = Box::new(Short {
268 data: Cursor::new(data.clone()),
269 max: 3000,
270 });
271 let body = ServeBody::stream(reader, len, tracker());
272 let frames = block_on(frames(body)).unwrap();
273 assert!(frames[..frames.len() - 1].iter().all(|f| f.len() == 3000));
274 assert_eq!(frames.concat(), data);
275 }
276 }
277
278 #[test]
281 fn a_known_length_bounds_the_body() {
282 let body = stream(b"0123456789".to_vec(), Some(4));
283 assert_eq!(body.size_hint().exact(), Some(4));
284 assert_eq!(block_on(frames(body)).unwrap().concat(), b"0123");
285 let err = block_on(frames(stream(b"012".to_vec(), Some(4)))).unwrap_err();
286 assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof);
287 assert!(stream(Vec::new(), Some(0)).is_end_stream());
288 assert_eq!(stream(b"x".to_vec(), None).size_hint().exact(), None);
289 }
290
291 struct CountWakes(AtomicUsize);
293
294 impl Wake for CountWakes {
295 fn wake(self: Arc<Self>) {
296 self.0.fetch_add(1, Ordering::Relaxed);
297 }
298 }
299
300 #[test]
303 fn a_ready_stream_yields_after_256_kib() {
304 let wakes = Arc::new(CountWakes(AtomicUsize::new(0)));
305 let waker = Waker::from(wakes.clone());
306 let mut cx = Context::from_waker(&waker);
307 let mut body = stream(vec![7u8; 1024 * 1024], None);
308 let mut given = 0;
309 loop {
310 match Pin::new(&mut body).poll_frame(&mut cx) {
311 Poll::Ready(Some(frame)) => given += frame.unwrap().into_data().unwrap().len(),
312 Poll::Pending => break,
313 Poll::Ready(None) => panic!("the body ended before it yielded"),
314 }
315 }
316 assert_eq!(given, YIELD_AFTER);
317 assert_eq!(wakes.0.load(Ordering::Relaxed), 1);
318 assert!(matches!(
319 Pin::new(&mut body).poll_frame(&mut cx),
320 Poll::Ready(Some(Ok(_)))
321 ));
322 }
323}