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
//! Limits Middleware.

#[cfg(feature = "multipart")]
use std::sync::Arc;

use crate::{types, Handler, IntoResponse, Request, Response, Result, Transform};

/// A configuration for [`LimitsMiddleware`].
#[derive(Debug, Clone)]
pub struct Config {
    limits: types::Limits,
    #[cfg(feature = "multipart")]
    multipart: Arc<types::MultipartLimits>,
}

impl Config {
    /// Creates a new Config.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets a limits for the Text/Bytes/Form.
    #[must_use]
    pub fn limits(mut self, limits: types::Limits) -> Self {
        self.limits = limits.sort();
        self
    }

    /// Sets a limits for the Multipart Form.
    #[cfg(feature = "multipart")]
    #[must_use]
    pub fn multipart(mut self, limits: types::MultipartLimits) -> Self {
        *Arc::make_mut(&mut self.multipart) = limits;
        self
    }
}

impl Default for Config {
    fn default() -> Self {
        Self {
            limits: types::Limits::default(),
            #[cfg(feature = "multipart")]
            multipart: Arc::new(types::MultipartLimits::default()),
        }
    }
}

impl<H> Transform<H> for Config
where
    H: Clone,
{
    type Output = LimitsMiddleware<H>;

    fn transform(&self, h: H) -> Self::Output {
        LimitsMiddleware {
            h,
            config: self.clone(),
        }
    }
}

/// Limits middleware.
#[derive(Debug, Clone)]
pub struct LimitsMiddleware<H> {
    h: H,
    config: Config,
}

#[crate::async_trait]
impl<H, O> Handler<Request> for LimitsMiddleware<H>
where
    H: Handler<Request, Output = Result<O>>,
    O: IntoResponse,
{
    type Output = Result<Response>;

    async fn call(&self, mut req: Request) -> Self::Output {
        req.extensions_mut().insert(self.config.limits.clone());
        #[cfg(feature = "multipart")]
        req.extensions_mut().insert(self.config.multipart.clone());

        self.h.call(req).await.map(IntoResponse::into_response)
    }
}