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
//! A rate limiter shared by every process that shares the cache, as
//! Laravel's `RateLimiter`: `limit` attempts per `period` for each key,
//! counted in fixed windows in the cache (`cache::increment`).
//!
//! ```ignore
//! if !RateLimit::attempt(&format!("login:{email}"), 5, 1.minutes()).await? {
//! let wait = RateLimit::available_in(&format!("login:{email}"), 1.minutes());
//! return Err(Error::too_many_requests(wait));
//! }
//! ```
//!
//! With `[cache] store = "database"` the counts are shared across servers;
//! with the default memory store they're per process. `Throttle` counts
//! with it.
use chrono::TimeDelta;
use crate::error::Result;
use crate::jobs::Delay;
/// See the [module docs](self).
pub struct RateLimit;
/// The cache key of `key`'s current window, and when that window ends.
fn window(key: &str, period: TimeDelta) -> (String, TimeDelta) {
let seconds = period.num_seconds().max(1);
let now = crate::time::now().timestamp();
let window = now.div_euclid(seconds);
let ends_in = TimeDelta::seconds((window + 1) * seconds - now);
(format!("glacier:rate:{key}:{seconds}:{window}"), ends_in)
}
impl RateLimit {
/// Counts an attempt for `key`; whether it's within `limit` per
/// `period`. Attempts over the limit are counted too.
///
/// # Errors
///
/// When the cache can't be written.
pub async fn attempt(key: &str, limit: u32, period: impl Delay) -> Result<bool> {
let (cache_key, ends_in) = window(key, period.delay());
let count = crate::cache::increment(&cache_key, 1, ends_in).await?;
Ok(count <= i64::from(limit))
}
/// Whether `key` has used up its `limit` for this `period`, without
/// counting an attempt.
///
/// # Errors
///
/// When the cache can't be read.
pub async fn too_many(key: &str, limit: u32, period: impl Delay) -> Result<bool> {
Ok(Self::remaining(key, limit, period).await? == 0)
}
/// How many attempts `key` has left in this window.
///
/// # Errors
///
/// When the cache can't be read.
pub async fn remaining(key: &str, limit: u32, period: impl Delay) -> Result<u32> {
let (cache_key, _) = window(key, period.delay());
let used: i64 = crate::cache::read(&cache_key).await?.unwrap_or(0);
Ok(u32::try_from((i64::from(limit) - used).max(0)).unwrap_or(0))
}
/// Forgets `key`'s attempts in this window: after a successful sign-in,
/// say.
///
/// # Errors
///
/// When the cache can't be written.
pub async fn clear(key: &str, period: impl Delay) -> Result<()> {
let (cache_key, _) = window(key, period.delay());
crate::cache::delete(&cache_key).await
}
/// How long until `key`'s window ends and its count starts again, for
/// a `Retry-After` header.
pub fn available_in(key: &str, period: impl Delay) -> TimeDelta {
window(key, period.delay()).1
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn counts_attempts_in_fixed_windows() {
crate::cache::with_test_store(async {
let minute = TimeDelta::minutes(1);
assert!(RateLimit::attempt("login:ada", 2, minute).await.unwrap());
assert_eq!(
RateLimit::remaining("login:ada", 2, minute).await.unwrap(),
1
);
assert!(RateLimit::attempt("login:ada", 2, minute).await.unwrap());
assert!(!RateLimit::attempt("login:ada", 2, minute).await.unwrap());
assert!(RateLimit::too_many("login:ada", 2, minute).await.unwrap());
// Another key has its own count.
assert!(RateLimit::attempt("login:bo", 2, minute).await.unwrap());
RateLimit::clear("login:ada", minute).await.unwrap();
assert_eq!(
RateLimit::remaining("login:ada", 2, minute).await.unwrap(),
2
);
let wait = RateLimit::available_in("login:ada", minute);
assert!(wait > TimeDelta::zero() && wait <= minute);
})
.await;
}
}