Skip to main content

fetchlet_http/dev/
body.rs

1use std::pin::Pin;
2use std::task::{Context, Poll};
3
4use bytes::Bytes;
5use http_body::{Body, Frame, SizeHint};
6
7/// The response body of a [`DevService`](super::DevService): the
8/// generation's body, that body followed by the reload script, or the reload
9/// poll's answer.
10pub struct DevBody<B> {
11    kind: Kind<B>,
12}
13
14enum Kind<B> {
15    Plain(Pin<Box<B>>),
16    Appended {
17        body: Pin<Box<B>>,
18        tail: Option<Bytes>,
19        /// Trailers held back until the tail is sent.
20        trailers: Option<Frame<Bytes>>,
21        finished: bool,
22    },
23    Full(Option<Bytes>),
24}
25
26impl<B> DevBody<B> {
27    pub(super) fn plain(body: B) -> Self {
28        Self {
29            kind: Kind::Plain(Box::pin(body)),
30        }
31    }
32
33    pub(super) fn appended(body: B, tail: Bytes) -> Self {
34        Self {
35            kind: Kind::Appended {
36                body: Box::pin(body),
37                tail: Some(tail),
38                trailers: None,
39                finished: false,
40            },
41        }
42    }
43
44    pub(super) fn full(bytes: Bytes) -> Self {
45        Self {
46            kind: Kind::Full(Some(bytes)),
47        }
48    }
49}
50
51impl<B> Body for DevBody<B>
52where
53    B: Body<Data = Bytes>,
54{
55    type Data = Bytes;
56
57    type Error = B::Error;
58
59    fn poll_frame(
60        self: Pin<&mut Self>,
61        context: &mut Context<'_>,
62    ) -> Poll<Option<Result<Frame<Bytes>, B::Error>>> {
63        match &mut self.get_mut().kind {
64            Kind::Plain(body) => body.as_mut().poll_frame(context),
65            Kind::Full(bytes) => Poll::Ready(bytes.take().map(|bytes| Ok(Frame::data(bytes)))),
66            Kind::Appended {
67                body,
68                tail,
69                trailers,
70                finished,
71            } => {
72                if !*finished {
73                    match body.as_mut().poll_frame(context) {
74                        Poll::Pending => return Poll::Pending,
75                        Poll::Ready(Some(Err(error))) => return Poll::Ready(Some(Err(error))),
76                        Poll::Ready(Some(Ok(frame))) if frame.is_data() => {
77                            return Poll::Ready(Some(Ok(frame)));
78                        }
79                        Poll::Ready(Some(Ok(frame))) => {
80                            *trailers = Some(frame);
81                            *finished = true;
82                        }
83                        Poll::Ready(None) => *finished = true,
84                    }
85                }
86                if let Some(tail) = tail.take() {
87                    return Poll::Ready(Some(Ok(Frame::data(tail))));
88                }
89                Poll::Ready(trailers.take().map(Ok))
90            }
91        }
92    }
93
94    fn is_end_stream(&self) -> bool {
95        match &self.kind {
96            Kind::Plain(body) => body.is_end_stream(),
97            Kind::Full(bytes) => bytes.is_none(),
98            Kind::Appended {
99                tail,
100                trailers,
101                finished,
102                ..
103            } => *finished && tail.is_none() && trailers.is_none(),
104        }
105    }
106
107    fn size_hint(&self) -> SizeHint {
108        match &self.kind {
109            Kind::Plain(body) => body.size_hint(),
110            Kind::Full(bytes) => {
111                SizeHint::with_exact(bytes.as_ref().map_or(0, |bytes| bytes.len() as u64))
112            }
113            Kind::Appended { .. } => SizeHint::default(),
114        }
115    }
116}
117
118#[cfg(test)]
119mod tests {
120    use http_body_util::{BodyExt, Full};
121
122    use super::*;
123
124    #[tokio::test]
125    async fn the_tail_follows_the_body() {
126        let body = DevBody::appended(
127            Full::new(Bytes::from_static(b"<p>page</p>")),
128            Bytes::from_static(b"<script></script>"),
129        );
130        let bytes = body.collect().await.unwrap().to_bytes();
131        assert_eq!(&bytes[..], b"<p>page</p><script></script>");
132    }
133
134    #[tokio::test]
135    async fn the_tail_precedes_trailers() {
136        let mut trailers = http::HeaderMap::new();
137        trailers.insert("x-done", http::HeaderValue::from_static("1"));
138        let body = DevBody::appended(
139            Frames(
140                vec![
141                    Frame::data(Bytes::from_static(b"a")),
142                    Frame::trailers(trailers),
143                ]
144                .into_iter(),
145            ),
146            Bytes::from_static(b"b"),
147        );
148        let collected = body.collect().await.unwrap();
149        assert_eq!(collected.trailers().unwrap().get("x-done").unwrap(), "1");
150        assert_eq!(&collected.to_bytes()[..], b"ab");
151    }
152
153    /// A body of ready frames.
154    struct Frames(std::vec::IntoIter<Frame<Bytes>>);
155
156    impl Body for Frames {
157        type Data = Bytes;
158        type Error = std::convert::Infallible;
159
160        fn poll_frame(
161            mut self: Pin<&mut Self>,
162            _context: &mut Context<'_>,
163        ) -> Poll<Option<Result<Frame<Bytes>, Self::Error>>> {
164            Poll::Ready(self.0.next().map(Ok))
165        }
166    }
167}