Skip to main content

hyper/body/
incoming.rs

1use std::fmt;
2use std::pin::Pin;
3use std::task::{Context, Poll};
4
5use bytes::Bytes;
6#[cfg(all(
7    any(feature = "http1", feature = "http2"),
8    any(feature = "client", feature = "server")
9))]
10use futures_core::ready;
11use http_body::{Body, Frame, SizeHint};
12
13#[cfg(all(feature = "http1", any(feature = "client", feature = "server")))]
14use super::chan;
15#[cfg(all(
16    any(feature = "http1", feature = "http2"),
17    any(feature = "client", feature = "server")
18))]
19use super::DecodedLength;
20#[cfg(all(feature = "http2", any(feature = "client", feature = "server")))]
21use crate::proto::h2::ping;
22
23/// A stream of `Bytes`, used when receiving bodies from the network.
24///
25/// Note that Users should not instantiate this struct directly. When working with the hyper client,
26/// `Incoming` is returned to you in responses. Similarly, when operating with the hyper server,
27/// it is provided within requests.
28///
29/// # Examples
30///
31/// ```rust,ignore
32/// async fn echo(
33///    req: Request<hyper::body::Incoming>,
34/// ) -> Result<Response<BoxBody<Bytes, hyper::Error>>, hyper::Error> {
35///    //Here, you can process `Incoming`
36/// }
37/// ```
38#[must_use = "streams do nothing unless polled"]
39pub struct Incoming {
40    kind: Kind,
41}
42
43enum Kind {
44    Empty,
45    #[cfg(all(feature = "http1", any(feature = "client", feature = "server")))]
46    Chan {
47        content_length: DecodedLength,
48        rx: chan::Receiver,
49    },
50    #[cfg(all(feature = "http2", any(feature = "client", feature = "server")))]
51    H2 {
52        content_length: DecodedLength,
53        data_done: bool,
54        ping: ping::Recorder,
55        recv: h2::RecvStream,
56    },
57    #[cfg(feature = "ffi")]
58    Ffi(crate::ffi::UserBody),
59}
60
61/// A sender half created through [`Body::channel()`].
62///
63/// Useful when wanting to stream chunks from another thread.
64///
65/// ## Body Closing
66///
67/// Note that the request body will always be closed normally when the sender is dropped (meaning
68/// that the empty terminating chunk will be sent to the remote). If you desire to close the
69/// connection with an incomplete response (e.g. in the case of an error during asynchronous
70/// processing), call the [`Sender::abort()`] method to abort the body in an abnormal fashion.
71///
72/// [`Body::channel()`]: struct.Body.html#method.channel
73/// [`Sender::abort()`]: struct.Sender.html#method.abort
74#[cfg(all(feature = "http1", any(feature = "client", feature = "server")))]
75pub(crate) use super::chan::Sender;
76
77impl Incoming {
78    /// Create a `Body` stream with an associated sender half.
79    ///
80    /// Useful when wanting to stream chunks from another thread.
81    #[cfg(all(feature = "http1", any(feature = "client", feature = "server")))]
82    #[inline]
83    #[cfg(test)]
84    pub(crate) fn channel() -> (Sender, Incoming) {
85        Self::new_channel(DecodedLength::CHUNKED, /*wanter =*/ false)
86    }
87
88    #[cfg(all(feature = "http1", any(feature = "client", feature = "server")))]
89    pub(crate) fn new_channel(content_length: DecodedLength, wanter: bool) -> (Sender, Incoming) {
90        let (tx, rx) = chan::channel(wanter);
91        let rx = Incoming::new(Kind::Chan { content_length, rx });
92
93        (tx, rx)
94    }
95
96    fn new(kind: Kind) -> Incoming {
97        Incoming { kind }
98    }
99
100    #[allow(dead_code)]
101    pub(crate) fn empty() -> Incoming {
102        Incoming::new(Kind::Empty)
103    }
104
105    #[cfg(feature = "ffi")]
106    pub(crate) fn ffi() -> Incoming {
107        Incoming::new(Kind::Ffi(crate::ffi::UserBody::new()))
108    }
109
110    #[cfg(all(feature = "http2", any(feature = "client", feature = "server")))]
111    pub(crate) fn h2(
112        recv: h2::RecvStream,
113        mut content_length: DecodedLength,
114        ping: ping::Recorder,
115    ) -> Self {
116        // If the stream is already EOS, then the "unknown length" is clearly
117        // actually ZERO.
118        if !content_length.is_exact() && recv.is_end_stream() {
119            content_length = DecodedLength::ZERO;
120        }
121
122        Incoming::new(Kind::H2 {
123            data_done: false,
124            ping,
125            content_length,
126            recv,
127        })
128    }
129
130    #[cfg(feature = "ffi")]
131    pub(crate) fn as_ffi_mut(&mut self) -> &mut crate::ffi::UserBody {
132        if !matches!(self.kind, Kind::Ffi(_)) {
133            self.kind = Kind::Ffi(crate::ffi::UserBody::new());
134        }
135
136        match &mut self.kind {
137            Kind::Ffi(body) => body,
138            _ => unreachable!(),
139        }
140    }
141}
142
143impl Body for Incoming {
144    type Data = Bytes;
145    type Error = crate::Error;
146
147    fn poll_frame(
148        #[cfg_attr(
149            not(all(
150                any(feature = "http1", feature = "http2"),
151                any(feature = "client", feature = "server")
152            )),
153            allow(unused_mut)
154        )]
155        mut self: Pin<&mut Self>,
156        #[cfg_attr(
157            not(all(
158                any(feature = "http1", feature = "http2"),
159                any(feature = "client", feature = "server")
160            )),
161            allow(unused_variables)
162        )]
163        cx: &mut Context<'_>,
164    ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
165        match &mut self.kind {
166            Kind::Empty => Poll::Ready(None),
167            #[cfg(all(feature = "http1", any(feature = "client", feature = "server")))]
168            Kind::Chan {
169                content_length: len,
170                rx,
171            } => {
172                if let Some(chunk) = ready!(rx.poll_next(cx)?) {
173                    len.sub_if(chunk.len() as u64);
174                    return Poll::Ready(Some(Ok(Frame::data(chunk))));
175                }
176                Poll::Ready(rx.take_trailers().map(Frame::trailers).map(Ok))
177            }
178            #[cfg(all(feature = "http2", any(feature = "client", feature = "server")))]
179            Kind::H2 {
180                data_done,
181                ping,
182                recv: h2,
183                content_length: len,
184            } => {
185                if !*data_done {
186                    match ready!(h2.poll_data(cx)) {
187                        Some(Ok(bytes)) => {
188                            let _ = h2.flow_control().release_capacity(bytes.len());
189                            len.sub_if(bytes.len() as u64);
190                            ping.record_data(bytes.len());
191                            return Poll::Ready(Some(Ok(Frame::data(bytes))));
192                        }
193                        Some(Err(e)) => {
194                            if let Some(h2::Reason::NO_ERROR) = e.reason() {
195                                // As mentioned in RFC 7540 Section 8.1, a RST_STREAM with NO_ERROR
196                                // indicates an early response, and should cause the body reading
197                                // to stop, but not fail it:
198                                return Poll::Ready(None);
199                            } else {
200                                return Poll::Ready(Some(Err(crate::Error::new_body(e))));
201                            }
202                        }
203                        None => {
204                            *data_done = true;
205                            // fall through to trailers
206                        }
207                    }
208                }
209
210                // after data, check trailers
211                match ready!(h2.poll_trailers(cx)) {
212                    Ok(t) => {
213                        ping.record_non_data();
214                        Poll::Ready(Ok(t.map(Frame::trailers)).transpose())
215                    }
216                    Err(e) => {
217                        if let Some(h2::Reason::NO_ERROR) = e.reason() {
218                            // Same as above, a RST_STREAM with NO_ERROR indicates an early
219                            // response, and should cause reading the trailers to stop, but
220                            // not fail it:
221                            Poll::Ready(None)
222                        } else {
223                            Poll::Ready(Some(Err(crate::Error::new_h2(e))))
224                        }
225                    }
226                }
227            }
228
229            #[cfg(feature = "ffi")]
230            Kind::Ffi(body) => body.poll_data(cx),
231        }
232    }
233
234    fn is_end_stream(&self) -> bool {
235        match &self.kind {
236            Kind::Empty => true,
237            #[cfg(all(feature = "http1", any(feature = "client", feature = "server")))]
238            Kind::Chan {
239                content_length,
240                rx: _,
241            } => *content_length == DecodedLength::ZERO,
242            #[cfg(all(feature = "http2", any(feature = "client", feature = "server")))]
243            Kind::H2 {
244                recv: h2,
245                content_length: _,
246                data_done: _,
247                ping: _,
248            } => h2.is_end_stream(),
249            #[cfg(feature = "ffi")]
250            Kind::Ffi(..) => false,
251        }
252    }
253
254    fn size_hint(&self) -> SizeHint {
255        #[cfg(all(
256            any(feature = "http1", feature = "http2"),
257            any(feature = "client", feature = "server")
258        ))]
259        fn opt_len(decoded_length: DecodedLength) -> SizeHint {
260            if let Some(content_length) = decoded_length.into_opt() {
261                SizeHint::with_exact(content_length)
262            } else {
263                SizeHint::default()
264            }
265        }
266
267        match self.kind {
268            Kind::Empty => SizeHint::with_exact(0),
269            #[cfg(all(feature = "http1", any(feature = "client", feature = "server")))]
270            Kind::Chan {
271                content_length,
272                rx: _,
273            } => opt_len(content_length),
274            #[cfg(all(feature = "http2", any(feature = "client", feature = "server")))]
275            Kind::H2 {
276                content_length,
277                data_done: _,
278                ping: _,
279                recv: _,
280            } => opt_len(content_length),
281            #[cfg(feature = "ffi")]
282            Kind::Ffi(..) => SizeHint::default(),
283        }
284    }
285}
286
287impl fmt::Debug for Incoming {
288    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
289        #[cfg(any(
290            all(
291                any(feature = "http1", feature = "http2"),
292                any(feature = "client", feature = "server")
293            ),
294            feature = "ffi"
295        ))]
296        #[derive(Debug)]
297        struct Streaming;
298        #[derive(Debug)]
299        struct Empty;
300
301        let mut builder = f.debug_tuple("Body");
302        match self.kind {
303            Kind::Empty => builder.field(&Empty),
304            #[cfg(any(
305                all(
306                    any(feature = "http1", feature = "http2"),
307                    any(feature = "client", feature = "server")
308                ),
309                feature = "ffi"
310            ))]
311            _ => builder.field(&Streaming),
312        };
313
314        builder.finish()
315    }
316}
317
318#[cfg(test)]
319mod tests {
320    #[cfg(all(feature = "http1", any(feature = "client", feature = "server")))]
321    use std::mem;
322    #[cfg(all(feature = "nightly", not(miri)))]
323    use std::pin::Pin;
324    #[cfg(all(feature = "http1", any(feature = "client", feature = "server")))]
325    use std::task::Poll;
326
327    #[cfg(all(feature = "http1", any(feature = "client", feature = "server")))]
328    use super::{Body, Incoming, SizeHint};
329    #[cfg(all(feature = "http1", any(feature = "client", feature = "server")))]
330    use super::{DecodedLength, Sender};
331    #[cfg(all(feature = "nightly", not(miri)))]
332    use bytes::Bytes;
333    #[cfg(all(feature = "http1", any(feature = "client", feature = "server")))]
334    use http_body_util::BodyExt;
335
336    #[cfg(all(feature = "http1", any(feature = "client", feature = "server")))]
337    #[test]
338    fn test_size_of() {
339        // These are mostly to help catch *accidentally* increasing
340        // the size by too much.
341
342        let body_size = mem::size_of::<Incoming>();
343        let body_expected_size = mem::size_of::<u64>() * 5;
344        assert!(
345            body_size <= body_expected_size,
346            "Body size = {} <= {}",
347            body_size,
348            body_expected_size,
349        );
350
351        assert_eq!(
352            mem::size_of::<Sender>(),
353            mem::size_of::<usize>() * 2,
354            "Sender"
355        );
356
357        assert_eq!(
358            mem::size_of::<Sender>(),
359            mem::size_of::<Option<Sender>>(),
360            "Option<Sender>"
361        );
362    }
363
364    #[cfg(all(feature = "nightly", not(miri)))]
365    #[bench]
366    fn bench_channel_create_and_drop(b: &mut test::Bencher) {
367        b.iter(|| {
368            let _ = test::black_box(Incoming::new_channel(
369                DecodedLength::CHUNKED,
370                /* wanter = */ false,
371            ));
372        });
373    }
374
375    #[cfg(all(feature = "nightly", not(miri)))]
376    #[bench]
377    fn bench_channel_data_handoff(b: &mut test::Bencher) {
378        let (mut tx, mut body) =
379            Incoming::new_channel(DecodedLength::CHUNKED, /* wanter = */ false);
380        let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
381
382        b.iter(|| {
383            assert!(tx.poll_ready(&mut cx).is_ready());
384            tx.try_send_data(Bytes::from_static(b"hello world"))
385                .unwrap();
386            let frame = match Pin::new(&mut body).poll_frame(&mut cx) {
387                Poll::Ready(Some(Ok(frame))) => frame,
388                unexpected => panic!("unexpected body poll: {unexpected:?}"),
389            };
390            test::black_box(frame);
391        });
392    }
393
394    #[cfg(all(feature = "nightly", not(miri)))]
395    #[bench]
396    fn bench_channel_want_transition(b: &mut test::Bencher) {
397        let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
398
399        b.iter(|| {
400            let (mut tx, mut body) =
401                Incoming::new_channel(DecodedLength::CHUNKED, /* wanter = */ true);
402            assert!(tx.poll_ready(&mut cx).is_pending());
403            assert!(Pin::new(&mut body).poll_frame(&mut cx).is_pending());
404            assert!(tx.poll_ready(&mut cx).is_ready());
405            let _ = test::black_box((tx, body));
406        });
407    }
408
409    #[cfg(all(feature = "http1", any(feature = "client", feature = "server")))]
410    #[test]
411    fn size_hint() {
412        fn eq(body: Incoming, b: SizeHint, note: &str) {
413            let a = body.size_hint();
414            assert_eq!(a.lower(), b.lower(), "lower for {:?}", note);
415            assert_eq!(a.upper(), b.upper(), "upper for {:?}", note);
416        }
417
418        eq(Incoming::empty(), SizeHint::with_exact(0), "empty");
419
420        eq(Incoming::channel().1, SizeHint::new(), "channel");
421
422        eq(
423            Incoming::new_channel(DecodedLength::new(4), /*wanter =*/ false).1,
424            SizeHint::with_exact(4),
425            "channel with length",
426        );
427    }
428
429    #[cfg(all(feature = "http1", any(feature = "client", feature = "server")))]
430    #[cfg(not(miri))]
431    #[tokio::test]
432    async fn channel_abort() {
433        let (tx, mut rx) = Incoming::channel();
434
435        tx.abort();
436
437        let err = rx.frame().await.unwrap().unwrap_err();
438        assert!(err.is_body_write_aborted(), "{:?}", err);
439    }
440
441    #[cfg(all(feature = "http1", any(feature = "client", feature = "server")))]
442    #[cfg(all(not(miri), feature = "http1"))]
443    #[tokio::test]
444    async fn channel_abort_when_buffer_is_full() {
445        let (mut tx, mut rx) = Incoming::channel();
446
447        tx.try_send_data("chunk 1".into()).expect("send 1");
448        // buffer is full, but can still send abort
449        tx.abort();
450
451        let chunk1 = rx
452            .frame()
453            .await
454            .expect("item 1")
455            .expect("chunk 1")
456            .into_data()
457            .unwrap();
458        assert_eq!(chunk1, "chunk 1");
459
460        let err = rx.frame().await.unwrap().unwrap_err();
461        assert!(err.is_body_write_aborted(), "{:?}", err);
462    }
463
464    #[cfg(feature = "http1")]
465    #[test]
466    fn channel_buffers_one() {
467        let (mut tx, _rx) = Incoming::channel();
468
469        tx.try_send_data("chunk 1".into()).expect("send 1");
470
471        // buffer is now full
472        let chunk2 = tx.try_send_data("chunk 2".into()).expect_err("send 2");
473        assert_eq!(chunk2, "chunk 2");
474    }
475
476    #[cfg(all(feature = "http1", any(feature = "client", feature = "server")))]
477    #[cfg(not(miri))]
478    #[tokio::test]
479    async fn channel_empty() {
480        let (_, mut rx) = Incoming::channel();
481
482        assert!(rx.frame().await.is_none());
483    }
484
485    #[cfg(all(feature = "http1", any(feature = "client", feature = "server")))]
486    #[test]
487    fn channel_ready() {
488        let (mut tx, _rx) = Incoming::new_channel(DecodedLength::CHUNKED, /*wanter = */ false);
489
490        let mut tx_ready = tokio_test::task::spawn(tx.ready());
491
492        assert!(tx_ready.poll().is_ready(), "tx is ready immediately");
493    }
494
495    #[cfg(all(feature = "http1", any(feature = "client", feature = "server")))]
496    #[test]
497    fn channel_wanter() {
498        let (mut tx, mut rx) =
499            Incoming::new_channel(DecodedLength::CHUNKED, /*wanter = */ true);
500
501        let mut tx_ready = tokio_test::task::spawn(tx.ready());
502        let mut rx_data = tokio_test::task::spawn(rx.frame());
503
504        assert!(
505            tx_ready.poll().is_pending(),
506            "tx isn't ready before rx has been polled"
507        );
508
509        assert!(rx_data.poll().is_pending(), "poll rx.data");
510        assert!(tx_ready.is_woken(), "rx poll wakes tx");
511
512        assert!(
513            tx_ready.poll().is_ready(),
514            "tx is ready after rx has been polled"
515        );
516    }
517
518    #[cfg(all(feature = "http1", any(feature = "client", feature = "server")))]
519    #[test]
520    fn channel_notices_closure() {
521        let (mut tx, rx) = Incoming::new_channel(DecodedLength::CHUNKED, /*wanter = */ true);
522
523        let mut tx_ready = tokio_test::task::spawn(tx.ready());
524
525        assert!(
526            tx_ready.poll().is_pending(),
527            "tx isn't ready before rx has been polled"
528        );
529
530        drop(rx);
531        assert!(tx_ready.is_woken(), "dropping rx wakes tx");
532
533        match &tx_ready.poll() {
534            Poll::Ready(Err(e)) if e.is_closed() => (),
535            unexpected => panic!("tx poll ready unexpected: {:?}", unexpected),
536        }
537    }
538}