micro_web/
body.rs

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
use bytes::Bytes;
use http_body::Body as HttpBody;
use http_body::{Frame, SizeHint};
use http_body_util::combinators::UnsyncBoxBody;
use micro_http::protocol::body::ReqBody;
use micro_http::protocol::{HttpError, ParseError};
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use tokio::sync::Mutex;

#[derive(Clone)]
pub struct OptionReqBody {
    inner: Arc<Mutex<Option<ReqBody>>>,
}

impl From<ReqBody> for OptionReqBody {
    fn from(body: ReqBody) -> Self {
        OptionReqBody { inner: Arc::new(Mutex::new(Some(body))) }
    }
}

impl OptionReqBody {
    pub async fn can_consume(&self) -> bool {
        let guard = self.inner.lock().await;
        guard.is_some()
    }

    pub async fn apply<T, F, Fut>(&self, f: F) -> Fut::Output
    where
        F: FnOnce(ReqBody) -> Fut,
        Fut: Future<Output = Result<T, ParseError>>,
    {
        let mut guard = self.inner.lock().await;
        if guard.is_none() {
            return Err(ParseError::invalid_body("body has been consumed"));
        }

        let req_body = (*guard).take().unwrap();

        f(req_body).await
    }
}

pub struct ResponseBody {
    inner: Kind,
}

enum Kind {
    Once(Option<Bytes>),
    Stream(UnsyncBoxBody<Bytes, HttpError>),
}

impl ResponseBody {
    pub fn empty() -> Self {
        Self { inner: Kind::Once(None) }
    }

    pub fn once(bytes: Bytes) -> Self {
        Self { inner: Kind::Once(Some(bytes)) }
    }

    pub fn stream<B>(body: B) -> Self
    where
        B: HttpBody<Data = Bytes, Error = HttpError> + Send + 'static,
    {
        Self { inner: Kind::Stream(UnsyncBoxBody::new(body)) }
    }

    pub fn is_empty(&self) -> bool {
        match &self.inner {
            Kind::Once(None) => false,
            Kind::Once(Some(bytes)) => bytes.is_empty(),
            Kind::Stream(body) => body.is_end_stream(),
        }
    }

    pub fn take(&mut self) -> Self {
        self.replace(ResponseBody::empty())
    }

    pub fn replace(&mut self, body: Self) -> Self {
        std::mem::replace(self, body)
    }
}

impl From<String> for ResponseBody {
    fn from(value: String) -> Self {
        ResponseBody { inner: Kind::Once(Some(Bytes::from(value))) }
    }
}

impl From<()> for ResponseBody {
    fn from(_: ()) -> Self {
        Self::empty()
    }
}

impl From<Option<Bytes>> for ResponseBody {
    fn from(option: Option<Bytes>) -> Self {
        match option {
            Some(bytes) => Self::once(bytes),
            None => Self::empty(),
        }
    }
}

impl From<&'static str> for ResponseBody {
    fn from(value: &'static str) -> Self {
        if value.is_empty() {
            Self::empty()
        } else {
            Self::once(value.as_bytes().into())
        }
    }
}

impl HttpBody for ResponseBody {
    type Data = Bytes;
    type Error = HttpError;

    fn poll_frame(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
        let kind = &mut self.get_mut().inner;
        match kind {
            Kind::Once(option_bytes) if option_bytes.is_none() => Poll::Ready(None),
            Kind::Once(option_bytes) => Poll::Ready(Some(Ok(Frame::data(option_bytes.take().unwrap())))),
            Kind::Stream(box_body) => {
                let pin = Pin::new(box_body);
                pin.poll_frame(cx)
            }
        }
    }

    fn is_end_stream(&self) -> bool {
        let kind = &self.inner;
        match kind {
            Kind::Once(option_bytes) => option_bytes.is_none(),
            Kind::Stream(box_body) => box_body.is_end_stream(),
        }
    }

    fn size_hint(&self) -> SizeHint {
        let kind = &self.inner;
        match kind {
            Kind::Once(None) => SizeHint::with_exact(0),
            Kind::Once(Some(bytes)) => SizeHint::with_exact(bytes.len() as u64),
            Kind::Stream(box_body) => box_body.size_hint(),
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::body::ResponseBody;
    use bytes::Bytes;
    use futures::TryStreamExt;
    use http_body::{Body as HttpBody, Frame};
    use http_body_util::{BodyExt, StreamBody};
    use micro_http::protocol::ParseError;
    use std::io;

    fn check_send<T: Send>() {}

    #[test]
    fn is_send() {
        check_send::<ResponseBody>();
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
    async fn test_string_body() {
        let s = "Hello world".to_string();
        let len = s.len() as u64;

        let mut body = ResponseBody::from(s);

        assert_eq!(body.size_hint().exact(), Some(len));
        assert!(!body.is_end_stream());

        let bytes = body.frame().await.unwrap().unwrap().into_data().unwrap();
        assert_eq!(bytes, Bytes::from("Hello world"));

        assert!(body.is_end_stream());
        assert!(body.frame().await.is_none());
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
    async fn test_empty_body() {
        let mut body = ResponseBody::from("");

        assert!(body.is_end_stream());
        assert_eq!(body.size_hint().exact(), Some(0));

        assert!(body.frame().await.is_none());
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
    async fn test_stream_body() {
        let chunks: Vec<Result<_, io::Error>> = vec![
            Ok(Frame::data(Bytes::from(vec![1]))),
            Ok(Frame::data(Bytes::from(vec![2]))),
            Ok(Frame::data(Bytes::from(vec![3]))),
        ];
        let stream = futures::stream::iter(chunks).map_err(|err| ParseError::io(err).into());
        let stream_body = StreamBody::new(stream);

        let mut body = ResponseBody::stream(stream_body);

        assert!(body.size_hint().exact().is_none());
        assert!(!body.is_end_stream());
        assert_eq!(body.frame().await.unwrap().unwrap().into_data().unwrap().as_ref(), [1]);
        assert_eq!(body.frame().await.unwrap().unwrap().into_data().unwrap().as_ref(), [2]);
        assert_eq!(body.frame().await.unwrap().unwrap().into_data().unwrap().as_ref(), [3]);

        assert!(!body.is_end_stream());

        assert!(body.frame().await.is_none());

        assert!(!body.is_end_stream());
    }
}