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

use governor::{
    clock::{Clock, DefaultClock},
    state::keyed::DefaultKeyedStateStore,
    Quota, RateLimiter,
};
use lazy_static::lazy_static;
use std::{
    convert::TryInto,
    error::Error,
    net::{IpAddr, SocketAddr},
    num::NonZeroU32,
    sync::Arc,
    time::Duration,
};
use std::fmt::Display;
use std::hash::Hash;
use tide::{
    http::StatusCode,
    log::{debug},
    utils::async_trait,
    Middleware, Next, Request, Response, Result,
};

lazy_static! {
    static ref CLOCK: DefaultClock = DefaultClock::default();
}

pub trait LimitKey: 'static + Default + Send + Sync {
    type KeyType: Display + Hash + Eq + Send + Sync + Clone;
    fn get_key<State: Clone + Send + Sync + 'static>(&self, req: &Request<State>) -> Result<Self::KeyType>;
}

#[derive(Default)]
pub struct IPAddrKey {

}

impl LimitKey for IPAddrKey {
    type KeyType = IpAddr;

    fn get_key<State: Clone + Send + Sync + 'static>(&self, req: &Request<State>) -> Result<Self::KeyType> {
        let remote = req.remote().ok_or_else(|| {
            tide::Error::from_str(
                StatusCode::InternalServerError,
                "failed to get request remote address",
            )
        })?;
        let remote: IpAddr = match remote.parse::<SocketAddr>() {
            Ok(r) => r.ip(),
            Err(_) => remote.parse()?,
        };
        log::debug!("remote: {}", remote);
        Ok(remote)
    }
}

#[derive(Debug, Clone)]
pub struct TideGovernorMiddleware<Key: LimitKey> {
    limit_key: Key,
    limiter: Arc<RateLimiter<Key::KeyType, DefaultKeyedStateStore<Key::KeyType>, DefaultClock>>,
}

impl<Key: LimitKey> TideGovernorMiddleware<Key> {
    pub fn new<T>(limit_key: Key, duration: Duration, times: T) -> Option<Self>
        where
            T: TryInto<NonZeroU32> {
        let times= times.try_into().map_or_else(|_| None, |v: NonZeroU32| Some(v))?;
        let replenish_interval_ns =
            duration.as_nanos() / times.get() as u128;
        Some(Self {
            limit_key,
            limiter: Arc::new(RateLimiter::<Key::KeyType, _, _>::keyed(Quota::with_period(
                Duration::from_nanos(replenish_interval_ns as u64),
            )?.allow_burst(times))),
        })
    }

    #[must_use]
    pub fn with_period<T>(duration: Duration, times: T) -> Option<Self>
        where
            T: TryInto<NonZeroU32> {
        let times= times.try_into().map_or_else(|_| None, |v: NonZeroU32| Some(v))?;
        let replenish_interval_ns =
            duration.as_nanos() / times.get() as u128;
        Some(Self {
            limit_key: Key::default(),
            limiter: Arc::new(RateLimiter::<Key::KeyType, _, _>::keyed(Quota::with_period(
                Duration::from_nanos(replenish_interval_ns as u64),
            )?.allow_burst(times))),
        })
    }

    pub fn per_second<T>(times: T) -> Result<Self>
        where
            T: TryInto<NonZeroU32>,
            T::Error: Error + Send + Sync + 'static,
    {
        Ok(Self {
            limit_key: Key::default(),
            limiter: Arc::new(RateLimiter::<Key::KeyType, _, _>::keyed(Quota::per_second(
                times.try_into()?,
            ))),
        })
    }

    pub fn per_minute<T>(times: T) -> Result<Self>
        where
            T: TryInto<NonZeroU32>,
            T::Error: Error + Send + Sync + 'static,
    {
        Ok(Self {
            limit_key: Key::default(),
            limiter: Arc::new(RateLimiter::<Key::KeyType, _, _>::keyed(Quota::per_minute(
                times.try_into()?,
            ))),
        })
    }

    pub fn per_hour<T>(times: T) -> Result<Self>
        where
            T: TryInto<NonZeroU32>,
            T::Error: Error + Send + Sync + 'static,
    {
        Ok(Self {
            limit_key: Key::default(),
            limiter: Arc::new(RateLimiter::<Key::KeyType, _, _>::keyed(Quota::per_hour(
                times.try_into()?,
            ))),
        })
    }
}

#[async_trait]
impl<State: Clone + Send + Sync + 'static, Key: LimitKey> Middleware<State> for TideGovernorMiddleware<Key> {
    async fn handle(&self, req: Request<State>, next: Next<'_, State>) -> tide::Result {
        let remote = self.limit_key.get_key(&req)?;

        match self.limiter.check_key(&remote) {
            Ok(_) => {
                debug!("allowing remote {}", remote);
                Ok(next.run(req).await)
            }
            Err(negative) => {
                let wait_time = negative.wait_time_from(CLOCK.now());
                let res = Response::builder(StatusCode::TooManyRequests)
                    .header(
                        tide::http::headers::RETRY_AFTER,
                        wait_time.as_secs().to_string(),
                    )
                    .build();
                debug!(
                    "blocking address {} for {} seconds",
                    remote,
                    wait_time.as_secs()
                );
                Ok(res)
            }
        }
    }
}