1use crate::{Error, ThrottleResult, REDIS};
2use anyhow::Context;
3use mod_redis::{Cmd, FromRedisValue, RedisConnection, Script};
4use redis_cell_impl::{time, MemoryStore, Rate, RateLimiter, RateQuota};
5use std::sync::{LazyLock, Mutex};
6use std::time::Duration;
7
8static MEMORY: LazyLock<Mutex<MemoryStore>> = LazyLock::new(|| Mutex::new(MemoryStore::new()));
9
10static GCRA_SCRIPT: LazyLock<Script> = LazyLock::new(|| {
12 Script::new(
13 r#"
14local key = KEYS[1]
15local limit = ARGV[1]
16local period = ARGV[2]
17local max_burst = ARGV[3]
18local quantity = ARGV[4]
19
20local interval = period / limit
21local increment = interval * quantity
22local burst_offset = interval * max_burst
23
24local now = tonumber(redis.call("TIME")[1])
25local tat = redis.call("GET", key)
26
27if not tat then
28 tat = now
29else
30 tat = tonumber(tat)
31end
32tat = math.max(tat, now)
33
34local new_tat = tat + increment
35local allow_at = new_tat - burst_offset
36local diff = now - allow_at
37
38local throttled
39local reset_after
40local retry_after
41
42local remaining = math.floor(diff / interval) -- poor man's round
43
44if remaining < 0 then
45 throttled = 1
46 -- calculate how many tokens there actually are, since
47 -- remaining is how many there would have been if we had been able to limit
48 -- and we did not limit
49 remaining = math.floor((now - (tat - burst_offset)) / interval)
50 reset_after = math.ceil(tat - now)
51 retry_after = math.ceil(diff * -1)
52elseif remaining == 0 and increment <= 0 then
53 -- request with cost of 0
54 -- cost of 0 with remaining 0 is still limited
55 throttled = 1
56 remaining = 0
57 reset_after = math.ceil(tat - now)
58 retry_after = 0 -- retry_after is meaningless when quantity is 0
59else
60 throttled = 0
61 reset_after = math.ceil(new_tat - now)
62 retry_after = 0
63 redis.call("SET", key, new_tat, "EX", reset_after)
64end
65
66return {throttled, remaining, reset_after, retry_after, tostring(diff), tostring(interval)}
67"#,
68 )
69});
70
71fn local_throttle(
72 key: &str,
73 limit: u64,
74 period: Duration,
75 max_burst: u64,
76 quantity: Option<u64>,
77) -> Result<ThrottleResult, Error> {
78 let mut store = MEMORY.lock().unwrap();
79 let max_rate = Rate::per_period(
80 limit as i64,
81 time::Duration::try_from(period).map_err(|err| Error::Generic(format!("{err:#}")))?,
82 );
83 let mut limiter = RateLimiter::new(
84 &mut *store,
85 &RateQuota {
86 max_burst: max_burst.min(limit - 1) as i64,
87 max_rate,
88 },
89 );
90 let quantity = quantity.unwrap_or(1) as i64;
91 let (throttled, rate_limit_result) = limiter
92 .rate_limit(key, quantity)
93 .map_err(|err| Error::Generic(format!("{err:#}")))?;
94
95 let mut retry_after = rate_limit_result.retry_after.whole_seconds();
99 if rate_limit_result.retry_after.subsec_milliseconds() > 0 {
100 retry_after += 1
101 }
102 let mut reset_after = rate_limit_result.reset_after.whole_seconds();
103 if rate_limit_result.reset_after.subsec_milliseconds() > 0 {
104 reset_after += 1
105 }
106
107 Ok(ThrottleResult {
108 throttled,
109 limit: rate_limit_result.limit as u64,
110 remaining: rate_limit_result.remaining as u64,
111 reset_after: Duration::from_secs(reset_after.max(0) as u64),
112 retry_after: if retry_after <= 0 {
113 None
114 } else {
115 Some(Duration::from_secs(retry_after.max(0) as u64))
116 },
117 })
118}
119
120async fn redis_cell_throttle(
121 conn: &RedisConnection,
122 key: &str,
123 limit: u64,
124 period: Duration,
125 max_burst: u64,
126 quantity: Option<u64>,
127) -> Result<ThrottleResult, Error> {
128 let mut cmd = Cmd::new();
129 cmd.arg("CL.THROTTLE")
130 .arg(key)
131 .arg(max_burst)
132 .arg(limit)
133 .arg(period.as_secs())
134 .arg(quantity.unwrap_or(1));
135 let result = conn.query(cmd).await?;
136 let result = <Vec<i64> as FromRedisValue>::from_redis_value(&result)?;
137
138 Ok(ThrottleResult {
139 throttled: result[0] != 0,
140 limit: result[1] as u64,
141 remaining: result[2] as u64,
142 retry_after: match result[3] {
143 n if n <= 0 => None,
144 n => Some(Duration::from_secs(n as u64)),
145 },
146 reset_after: Duration::from_secs(result[4].max(0) as u64),
147 })
148}
149
150async fn redis_script_throttle(
151 conn: &RedisConnection,
152 key: &str,
153 limit: u64,
154 period: Duration,
155 max_burst: u64,
156 quantity: Option<u64>,
157) -> Result<ThrottleResult, Error> {
158 let mut script = GCRA_SCRIPT.prepare_invoke();
159 script
160 .key(key)
161 .arg(limit)
162 .arg(period.as_secs())
163 .arg(max_burst)
164 .arg(quantity.unwrap_or(1));
165
166 let result = conn
167 .invoke_script(script)
168 .await
169 .context("error invoking redis GCRA script")?;
170 let result =
171 <(u64, u64, u64, u64, String, String) as FromRedisValue>::from_redis_value(&result)?;
172
173 Ok(ThrottleResult {
174 throttled: result.0 == 1,
175 limit: max_burst + 1,
176 remaining: result.1,
177 retry_after: match result.3 {
178 0 => None,
179 n => Some(Duration::from_secs(n)),
180 },
181 reset_after: Duration::from_secs(result.2),
182 })
183}
184
185pub async fn throttle(
203 key: &str,
204 limit: u64,
205 period: Duration,
206 max_burst: u64,
207 quantity: Option<u64>,
208 force_local: bool,
209) -> Result<ThrottleResult, Error> {
210 match (force_local, REDIS.get()) {
211 (false, Some(cx)) => {
212 if cx.has_redis_cell {
213 redis_cell_throttle(&cx, key, limit, period, max_burst, quantity).await
214 } else {
215 redis_script_throttle(&cx, key, limit, period, max_burst, quantity).await
216 }
217 }
218 _ => local_throttle(key, limit, period, max_burst, quantity),
219 }
220}
221
222#[cfg(test)]
223mod test {
224 use super::*;
225 use crate::redis::RedisContext;
226 use mod_redis::test::RedisServer;
227
228 trait Throttler {
229 async fn throttle(
230 &self,
231 key: &str,
232 limit: u64,
233 period: Duration,
234 max_burst: u64,
235 quantity: Option<u64>,
236 ) -> Result<ThrottleResult, Error>;
237 }
238
239 impl Throttler for Mutex<MemoryStore> {
240 async fn throttle(
241 &self,
242 key: &str,
243 limit: u64,
244 period: Duration,
245 max_burst: u64,
246 quantity: Option<u64>,
247 ) -> Result<ThrottleResult, Error> {
248 local_throttle(key, limit, period, max_burst, quantity)
249 }
250 }
251
252 struct RedisWithCell(RedisConnection);
253
254 impl Throttler for RedisWithCell {
255 async fn throttle(
256 &self,
257 key: &str,
258 limit: u64,
259 period: Duration,
260 max_burst: u64,
261 quantity: Option<u64>,
262 ) -> Result<ThrottleResult, Error> {
263 redis_cell_throttle(&self.0, key, limit, period, max_burst, quantity).await
264 }
265 }
266
267 struct VanillaRedis(RedisConnection);
268
269 impl Throttler for VanillaRedis {
270 async fn throttle(
271 &self,
272 key: &str,
273 limit: u64,
274 period: Duration,
275 max_burst: u64,
276 quantity: Option<u64>,
277 ) -> Result<ThrottleResult, Error> {
278 redis_script_throttle(&self.0, key, limit, period, max_burst, quantity).await
279 }
280 }
281
282 async fn test_big_limits(
283 limit: u64,
284 max_burst: Option<u64>,
285 permitted_tolerance: f64,
286 throttler: &impl Throttler,
287 ) {
288 let period = Duration::from_secs(60);
289 let max_burst = max_burst.unwrap_or(limit);
290 let key = format!("test_big_limits-{limit}-{max_burst}");
291
292 let mut throttled_iter = None;
293
294 for i in 0..limit * 2 {
295 let result = throttler
296 .throttle(&key, limit, period, max_burst, None)
297 .await
298 .unwrap();
299 if result.throttled {
300 println!("iter: {i} -> {result:?}");
301 throttled_iter.replace(i);
302 break;
303 }
304 }
305
306 let throttled_iter = throttled_iter.expect("to hit the throttle limit");
307 let diff = ((max_burst as f64) - (throttled_iter as f64)).abs();
308 let tolerance = (max_burst as f64) * permitted_tolerance;
309 println!(
310 "throttled after {throttled_iter} iterations for \
311 limit {limit}. diff={diff}. tolerance {tolerance}"
312 );
313 let max_rate = Rate::per_period(limit as i64, time::Duration::try_from(period).unwrap());
314 println!("max_rate: {max_rate:?}");
315
316 assert!(
317 diff <= tolerance,
318 "throttled after {throttled_iter} iterations for \
319 limit {limit}. diff={diff} is not within tolerance {tolerance}"
320 );
321 }
322
323 #[tokio::test]
324 async fn basic_throttle_100() {
325 test_big_limits(100, None, 0.01, &*MEMORY).await;
326 }
327
328 #[tokio::test]
329 async fn basic_throttle_1_000() {
330 test_big_limits(1_000, Some(100), 0.02, &*MEMORY).await;
331 }
332
333 #[tokio::test]
334 async fn basic_throttle_6_000() {
335 test_big_limits(6_000, Some(100), 0.02, &*MEMORY).await;
336 }
337
338 #[tokio::test]
339 async fn basic_throttle_60_000() {
340 test_big_limits(60_000, Some(100), 0.1, &*MEMORY).await;
341 }
342
343 #[tokio::test]
344 async fn basic_throttle_60_000_burst_30k() {
345 test_big_limits(60_000, Some(100), 0.1, &*MEMORY).await;
349 }
350
351 #[tokio::test]
352 async fn redis_cell_throttle_1_000() {
353 if !RedisServer::is_available() {
354 return;
355 }
356
357 let redis = RedisServer::spawn("").await.unwrap();
358 let conn = redis.connection().await.unwrap();
359 let cx = RedisContext::try_from(conn).await.unwrap();
360 if !cx.has_redis_cell {
361 return;
362 }
363
364 test_big_limits(1_000, None, 0.02, &RedisWithCell(cx.connection)).await;
365 }
366
367 #[tokio::test]
368 async fn redis_script_throttle_1_000() {
369 if !RedisServer::is_available() {
370 return;
371 }
372
373 let redis = RedisServer::spawn("").await.unwrap();
374 let conn = redis.connection().await.unwrap();
375 let cx = RedisContext::try_from(conn).await.unwrap();
376 test_big_limits(1_000, None, 0.2, &VanillaRedis(cx.connection)).await;
377 }
378}