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
//! client ip address based rate limiting.

use core::{convert::Infallible, time::Duration};

use crate::{
    body::ResponseBody,
    error::Error,
    http::WebResponse,
    service::{ready::ReadyService, Service},
    WebContext,
};

use http_rate::Quota;

pub struct RateLimit(Quota);

macro_rules! constructor {
    ($method: tt) => {
        #[doc = concat!("Construct a RateLimit for a number of cells ",stringify!($method)," period. The given number of cells is")]
        /// also assumed to be the maximum burst size.
        ///
        /// # Panics
        /// - When max_burst is zero.
        pub fn $method(max_burst: u32) -> Self {
            Self(Quota::$method(max_burst))
        }
    };
}

impl RateLimit {
    constructor!(per_second);
    constructor!(per_minute);
    constructor!(per_hour);

    /// Construct a RateLimit that replenishes one cell in a given
    /// interval.
    ///
    /// # Panics
    /// - When the Duration is zero.
    pub fn with_period(replenish_1_per: Duration) -> Self {
        Self(Quota::with_period(replenish_1_per).unwrap())
    }
}

impl<S, E> Service<Result<S, E>> for RateLimit {
    type Response = RateLimitService<S>;
    type Error = E;

    async fn call(&self, res: Result<S, E>) -> Result<Self::Response, Self::Error> {
        res.map(|service| RateLimitService {
            service,
            rate_limit: http_rate::RateLimit::new(self.0),
        })
    }
}

pub struct RateLimitService<S> {
    service: S,
    rate_limit: http_rate::RateLimit,
}

impl<'r, C, B, S, ResB> Service<WebContext<'r, C, B>> for RateLimitService<S>
where
    S: for<'r2> Service<WebContext<'r2, C, B>, Response = WebResponse<ResB>, Error = Error<C>>,
{
    type Response = WebResponse<ResB>;
    type Error = Error<C>;

    async fn call(&self, ctx: WebContext<'r, C, B>) -> Result<Self::Response, Self::Error> {
        let headers = ctx.req().headers();
        let addr = ctx.req().body().socket_addr();
        let snap = self.rate_limit.rate_limit(headers, addr).map_err(Error::from_service)?;
        self.service.call(ctx).await.map(|mut res| {
            snap.extend_response(&mut res);
            res
        })
    }
}

impl<'r, C, B> Service<WebContext<'r, C, B>> for http_rate::TooManyRequests {
    type Response = WebResponse;
    type Error = Infallible;

    async fn call(&self, ctx: WebContext<'r, C, B>) -> Result<Self::Response, Self::Error> {
        let mut res = ctx.into_response(ResponseBody::empty());
        self.extend_response(&mut res);
        Ok(res)
    }
}

impl<S> ReadyService for RateLimitService<S>
where
    S: ReadyService,
{
    type Ready = S::Ready;

    #[inline]
    async fn ready(&self) -> Self::Ready {
        self.service.ready().await
    }
}