salvo_core 0.94.0

Salvo is a powerful web framework that can make your work easier.
Documentation
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
use std::fmt::{self, Debug, Formatter};
use std::io::{Error as IoError, ErrorKind, Result as IoResult};
use std::pin::Pin;
use std::task::{Context, Poll};

use bytes::Bytes;
use futures_util::stream::Stream;
use hyper::body::{Body, Frame, Incoming, SizeHint};

use crate::BoxedError;
use crate::fuse::FuseConfig;

#[doc(hidden)]
#[derive(Debug)]
pub struct BodyTimeout {
    duration: std::time::Duration,
    sleep: Pin<Box<tokio::time::Sleep>>,
    armed: bool,
}

impl BodyTimeout {
    fn new(duration: std::time::Duration) -> Self {
        Self {
            duration,
            sleep: Box::pin(tokio::time::sleep(std::time::Duration::from_secs(
                86400 * 365,
            ))),
            armed: false,
        }
    }

    fn apply(&mut self, poll: PollFrame, cx: &mut Context<'_>) -> PollFrame {
        match poll {
            Poll::Pending => {
                if !self.armed {
                    self.armed = true;
                    self.sleep
                        .as_mut()
                        .reset(tokio::time::Instant::now() + self.duration);
                }
                if self.sleep.as_mut().poll(cx).is_ready() {
                    // Fail only this request body. On HTTP/2 and HTTP/3 the error ends the
                    // offending stream (RST_STREAM) while sibling streams multiplexed over
                    // the same connection keep running; on HTTP/1 the connection carries a
                    // single request, so it is torn down as before. Deliberately does not
                    // abort the whole transport connection, which would take down unrelated
                    // in-flight streams.
                    Poll::Ready(Some(Err(IoError::new(
                        ErrorKind::TimedOut,
                        "request body timeout",
                    ))))
                } else {
                    Poll::Pending
                }
            }
            ready => {
                // A frame that arrives after the deadline already elapsed must still time out,
                // or a client dribbling each chunk just past the deadline evades the limit.
                if self.armed && self.sleep.as_mut().poll(cx).is_ready() {
                    self.armed = false;
                    return Poll::Ready(Some(Err(IoError::new(
                        ErrorKind::TimedOut,
                        "request body timeout",
                    ))));
                }
                self.armed = false;
                ready
            }
        }
    }
}

pub(crate) type BoxedBody =
    Pin<Box<dyn Body<Data = Bytes, Error = BoxedError> + Send + Sync + 'static>>;
pub(crate) type PollFrame = Poll<Option<Result<Frame<Bytes>, IoError>>>;

/// Body for HTTP request.
#[non_exhaustive]
#[derive(Default)]
pub enum ReqBody {
    /// None body.
    #[default]
    None,
    /// Once bytes body.
    Once(Bytes),
    /// Hyper default body.
    Hyper {
        /// Inner body.
        inner: Incoming,
        /// Request-body timeout state.
        fuse_config: Option<BodyTimeout>,
    },
    /// Boxed body.
    Boxed {
        /// Inner body.
        inner: BoxedBody,
        /// Request-body timeout state.
        fuse_config: Option<BodyTimeout>,
    },
}
impl ReqBody {
    #[doc(hidden)]
    pub fn set_fuse_config(&mut self, value: Option<FuseConfig>) {
        match self {
            Self::None | Self::Once(_) => {}
            Self::Hyper { fuse_config, .. } | Self::Boxed { fuse_config, .. } => {
                *fuse_config = value
                    .and_then(|config| config.request_body_timeout)
                    .map(BodyTimeout::new);
            }
        }
    }
    /// Returns true if the body is not set.
    #[inline]
    pub fn is_none(&self) -> bool {
        matches!(*self, Self::None)
    }
    /// Returns true if the body contains one byte buffer.
    #[inline]
    pub fn is_once(&self) -> bool {
        matches!(*self, Self::Once(_))
    }
    /// Returns true if the body is Hyper's default incoming body type.
    #[inline]
    pub fn is_hyper(&self) -> bool {
        matches!(*self, Self::Hyper { .. })
    }
    /// Returns true if the body is boxed.
    #[inline]
    pub fn is_boxed(&self) -> bool {
        matches!(*self, Self::Boxed { .. })
    }

    /// Set body to none and returns current body.
    #[inline]
    #[must_use]
    pub fn take(&mut self) -> Self {
        std::mem::replace(self, Self::None)
    }
}

impl Body for ReqBody {
    type Data = Bytes;
    type Error = IoError;

    fn poll_frame(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> PollFrame {
        #[inline]
        fn through_fuse_config(
            poll: PollFrame,
            fuse_config: Option<&mut BodyTimeout>,
            cx: &mut Context<'_>,
        ) -> PollFrame {
            match fuse_config {
                Some(timeout) => timeout.apply(poll, cx),
                None => poll,
            }
        }
        match &mut *self {
            Self::None => Poll::Ready(None),
            Self::Once(bytes) => {
                if bytes.is_empty() {
                    Poll::Ready(None)
                } else {
                    let bytes = std::mem::take(bytes);
                    Poll::Ready(Some(Ok(Frame::data(bytes))))
                }
            }
            Self::Hyper { inner, fuse_config } => {
                let poll = Pin::new(inner).poll_frame(cx).map_err(IoError::other);
                through_fuse_config(poll, fuse_config.as_mut(), cx)
            }
            Self::Boxed { inner, fuse_config } => {
                let poll = Pin::new(inner).poll_frame(cx).map_err(IoError::other);
                through_fuse_config(poll, fuse_config.as_mut(), cx)
            }
        }
    }

    fn is_end_stream(&self) -> bool {
        match self {
            Self::None => true,
            Self::Once(bytes) => bytes.is_empty(),
            Self::Hyper { inner, .. } => inner.is_end_stream(),
            Self::Boxed { inner, .. } => inner.is_end_stream(),
        }
    }

    fn size_hint(&self) -> SizeHint {
        match self {
            Self::None => SizeHint::with_exact(0),
            Self::Once(bytes) => SizeHint::with_exact(bytes.len() as u64),
            Self::Hyper { inner, .. } => inner.size_hint(),
            Self::Boxed { inner, .. } => inner.size_hint(),
        }
    }
}
impl Stream for ReqBody {
    type Item = IoResult<Frame<Bytes>>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        match Body::poll_frame(self, cx) {
            Poll::Ready(Some(Ok(frame))) => Poll::Ready(Some(Ok(frame))),
            Poll::Ready(Some(Err(e))) => Poll::Ready(Some(Err(IoError::other(e)))),
            Poll::Ready(None) => Poll::Ready(None),
            Poll::Pending => Poll::Pending,
        }
    }
}

impl From<Bytes> for ReqBody {
    fn from(value: Bytes) -> Self {
        Self::Once(value)
    }
}
impl From<Incoming> for ReqBody {
    fn from(inner: Incoming) -> Self {
        Self::Hyper {
            inner,
            fuse_config: None,
        }
    }
}
impl From<String> for ReqBody {
    #[inline]
    fn from(value: String) -> Self {
        Self::Once(value.into())
    }
}
impl TryFrom<ReqBody> for Incoming {
    type Error = crate::Error;
    fn try_from(body: ReqBody) -> Result<Self, Self::Error> {
        match body {
            ReqBody::None => Err(crate::Error::other(
                "ReqBody::None cannot convert to Incoming",
            )),
            ReqBody::Once(_) => Err(crate::Error::other(
                "ReqBody::Once cannot convert to Incoming",
            )),
            ReqBody::Hyper { inner, .. } => Ok(inner),
            ReqBody::Boxed { .. } => Err(crate::Error::other(
                "ReqBody::Boxed cannot convert to Incoming",
            )),
        }
    }
}

impl From<&'static [u8]> for ReqBody {
    fn from(value: &'static [u8]) -> Self {
        Self::Once(Bytes::from_static(value))
    }
}

impl From<&'static str> for ReqBody {
    fn from(value: &'static str) -> Self {
        Self::Once(Bytes::from_static(value.as_bytes()))
    }
}

impl From<Vec<u8>> for ReqBody {
    fn from(value: Vec<u8>) -> Self {
        Self::Once(value.into())
    }
}

impl<T> From<Box<T>> for ReqBody
where
    T: Into<Self>,
{
    fn from(value: Box<T>) -> Self {
        (*value).into()
    }
}

cfg_feature! {
    #![feature = "quinn"]
    pub(crate) mod h3 {
        use std::boxed::Box;
        use std::pin::Pin;
        use std::task::{ready, Context, Poll};
        use std::fmt::{self, Debug, Formatter};

        use hyper::body::{Body, Frame, SizeHint};
        use salvo_http3::quic::RecvStream;
        use salvo_http3::error::Code;

        use bytes::{Buf, Bytes};

        use crate::BoxedError;
        use crate::http::ReqBody;

        /// HTTP/3 request body.
        pub struct H3ReqBody<S, B>
        where
            S: RecvStream + Send + Unpin,
            B: Buf + Send + Unpin,
        {
            inner: salvo_http3::server::RequestStream<S, B>,
        }
        impl<S, B> Debug for H3ReqBody<S, B>
        where
            S: RecvStream + Send + Unpin,
            B: Buf + Send + Unpin,
        {
            fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
                f.debug_struct("H3ReqBody").finish()
            }
        }
        impl<S, B> H3ReqBody<S, B>
        where
            S: RecvStream + Send + Unpin + 'static,
            B: Buf + Send + Unpin + 'static,
        {
            /// Creates a new `H3ReqBody` instance.
            pub fn new(inner: salvo_http3::server::RequestStream<S, B>) -> Self {
                Self { inner }
            }
        }

        impl<S, B> Body for H3ReqBody<S, B>
        where
            S: RecvStream + Send + Unpin,
            B: Buf + Send + Unpin,
        {
            type Data = Bytes;
            type Error = BoxedError;

            fn poll_frame(
                mut self: Pin<&mut Self>,
                cx: &mut Context<'_>,
            ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
                let this = &mut *self;
                match ready!(this.inner.poll_recv_data(cx)) {
                    Ok(Some(buf)) => {
                        Poll::Ready(Some(Ok(Frame::data(Bytes::copy_from_slice(buf.chunk())))))
                    }
                    Ok(None) => Poll::Ready(None),
                    Err(e) => Poll::Ready(Some(Err(e.into()))),
                }
            }

            fn is_end_stream(&self) -> bool {
                false // TODO: check this
            }

            fn size_hint(&self) -> SizeHint {
                SizeHint::default()
            }
        }

        impl<S, B> Drop for H3ReqBody<S, B>
        where
            S: RecvStream + Send + Unpin,
            B: Buf + Send + Unpin,
        {
            fn drop(&mut self) {
                self.inner.stop_sending(Code::H3_NO_ERROR);
            }
        }

        impl<S, B> From<H3ReqBody<S, B>> for ReqBody
        where
            S: RecvStream + Send + Sync + Unpin + 'static,
            B: Buf + Send + Sync + Unpin + 'static,
        {
            fn from(value: H3ReqBody<S, B>) -> Self {
                Self::Boxed {
                    inner: Box::pin(value),
                    fuse_config: None,
                }
            }
        }
    }
}

impl Debug for ReqBody {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::None => write!(f, "ReqBody::None"),
            Self::Once(value) => f.debug_tuple("ReqBody::Once").field(value).finish(),
            Self::Hyper { inner, .. } => f
                .debug_struct("ReqBody::Hyper")
                .field("inner", inner)
                .finish(),
            Self::Boxed { .. } => write!(f, "ReqBody::Boxed{{..}}"),
        }
    }
}

#[cfg(test)]
mod tests {
    use bytes::Bytes;

    use super::*;

    #[test]
    fn test_take() {
        let mut b = ReqBody::Once(Bytes::from("abc"));
        let old = b.take();
        assert!(matches!(old, ReqBody::Once(_)));
        assert!(b.is_none());
    }

    #[test]
    fn test_debug() {
        let b = ReqBody::None;
        let s = format!("{b:?}");
        assert!(s.contains("ReqBody::None"));
    }

    #[test]
    fn test_is_end_stream() {
        let b = ReqBody::None;
        assert!(b.is_end_stream());
        let b = ReqBody::Once(Bytes::new());
        assert!(b.is_end_stream());
    }

    #[tokio::test]
    async fn request_body_timeout_fails_only_the_body() {
        use std::future::poll_fn;
        use std::time::Duration;

        struct PendingBody;
        impl Body for PendingBody {
            type Data = Bytes;
            type Error = BoxedError;
            fn poll_frame(
                self: Pin<&mut Self>,
                _cx: &mut Context<'_>,
            ) -> Poll<Option<Result<Frame<Bytes>, Self::Error>>> {
                Poll::Pending
            }
        }

        let mut body = ReqBody::Boxed {
            inner: Box::pin(PendingBody),
            fuse_config: None,
        };
        body.set_fuse_config(Some(FuseConfig {
            request_body_timeout: Some(Duration::from_millis(10)),
            ..FuseConfig::disabled()
        }));

        // The stalled body must surface a `TimedOut` error to its reader. That error
        // ends only this request stream; no connection-wide abort is involved.
        let frame = poll_fn(|cx| Pin::new(&mut body).poll_frame(cx)).await;
        let error = frame.expect("body must yield a frame").unwrap_err();
        assert_eq!(error.kind(), ErrorKind::TimedOut);
    }

    #[tokio::test]
    async fn request_body_timeout_rejects_a_late_frame() {
        use std::future::poll_fn;
        use std::time::Duration;

        let mut timeout = BodyTimeout::new(Duration::from_millis(10));

        // Arm the timer as a pending frame poll would, then let the deadline lapse.
        poll_fn(|cx| {
            let _ = timeout.apply(Poll::Pending, cx);
            Poll::Ready(())
        })
        .await;
        tokio::time::sleep(Duration::from_millis(40)).await;

        // A frame that only arrives now — past the deadline — must be converted to a timeout,
        // not accepted as if the gap had been within bounds.
        let out = poll_fn(|cx| {
            let frame = Frame::data(Bytes::from_static(b"x"));
            Poll::Ready(timeout.apply(Poll::Ready(Some(Ok(frame))), cx))
        })
        .await;
        match out {
            Poll::Ready(Some(Err(error))) => assert_eq!(error.kind(), ErrorKind::TimedOut),
            _ => panic!("a late body frame must time out"),
        }
    }
}