1use std::cell::Cell;
11use std::fmt;
12use std::hash::Hash;
13use std::sync::atomic::{AtomicU64, Ordering};
14use std::sync::{Arc, Mutex, PoisonError};
15use std::time::Duration;
16
17use dashmap::DashMap;
18use navree_kernel::{BoxError, BoxFuture};
19use tokio::time::Instant;
20
21const SWEEP_EVERY: u64 = 1024;
23
24thread_local! {
25 static CHECKS: Cell<u64> = const { Cell::new(0) };
28}
29
30#[derive(Debug)]
53pub struct KeyedRateLimiter<K: Hash + Eq> {
54 interval: Duration,
55 period: Duration,
56 state: DashMap<K, Slot>,
57}
58
59#[derive(Clone, Copy, Debug)]
61struct Slot {
62 tat: Instant,
64 reported: Option<Instant>,
66}
67
68#[derive(Clone, Copy, Debug, PartialEq, Eq)]
70#[non_exhaustive]
71pub struct Limited {
72 pub retry_after: Duration,
74 pub report: bool,
77}
78
79impl Limited {
80 pub fn new(retry_after: Duration, report: bool) -> Self {
83 Self {
84 retry_after,
85 report,
86 }
87 }
88}
89
90impl Slot {
91 fn new(now: Instant) -> Self {
92 Self {
93 tat: now,
94 reported: None,
95 }
96 }
97
98 fn admit(&mut self, now: Instant, interval: Duration, period: Duration) -> Result<(), Limited> {
101 let next = self.tat.max(now) + interval;
102 let ahead = next - now;
103 if ahead > period {
104 let report = self
105 .reported
106 .is_none_or(|at| now.duration_since(at) >= period);
107 if report {
108 self.reported = Some(now);
109 }
110 return Err(Limited::new(ahead - period, report));
111 }
112 self.tat = next;
113 Ok(())
114 }
115}
116
117fn sweep_now() -> bool {
119 let checks = CHECKS.get().wrapping_add(1);
120 CHECKS.set(checks);
121 checks.is_multiple_of(SWEEP_EVERY)
122}
123
124fn interval(limit: u32, per: Duration) -> Duration {
126 per / limit.max(1)
127}
128
129pub type StoreVerdict = Result<Result<(), Limited>, BoxError>;
132
133pub trait RateLimitStore: Send + Sync + 'static {
155 fn hit<'a>(&'a self, key: &'a str, limit: u32, per: Duration) -> BoxFuture<'a, StoreVerdict>;
161}
162
163#[derive(Debug, Default)]
177pub struct MemoryRateLimitStore {
178 state: DashMap<String, Slot>,
179}
180
181impl MemoryRateLimitStore {
182 pub fn check(&self, key: &str, limit: u32, per: Duration) -> Result<(), Limited> {
184 let now = Instant::now();
185 if sweep_now() {
186 self.state.retain(|_, slot| slot.tat > now);
187 }
188 let mut slot = match self.state.get_mut(key) {
189 Some(slot) => slot,
190 None => self
191 .state
192 .entry(key.to_owned())
193 .or_insert_with(|| Slot::new(now)),
194 };
195 slot.admit(now, interval(limit, per), per)
196 }
197}
198
199impl RateLimitStore for MemoryRateLimitStore {
200 fn hit<'a>(&'a self, key: &'a str, limit: u32, per: Duration) -> BoxFuture<'a, StoreVerdict> {
201 let verdict = self.check(key, limit, per);
202 Box::pin(std::future::ready(Ok(verdict)))
203 }
204}
205
206const STORE_WAIT: Duration = Duration::from_millis(100);
209
210const STORE_REST: Duration = Duration::from_secs(3);
212
213const STORE_WARNING_EVERY: Duration = Duration::from_secs(60);
215
216pub(crate) struct Limiter<K: Hash + Eq> {
220 name: String,
221 limit: u32,
222 per: Duration,
223 store: Option<Arc<dyn RateLimitStore>>,
224 memory: KeyedRateLimiter<K>,
225 breaker: Breaker,
226 warned: Mutex<Option<Instant>>,
227}
228
229impl<K: Hash + Eq + Clone + fmt::Display> Limiter<K> {
230 pub(crate) fn new(
231 name: String,
232 limit: u32,
233 per: Duration,
234 store: Option<Arc<dyn RateLimitStore>>,
235 ) -> Self {
236 Self {
237 name,
238 limit,
239 per,
240 store,
241 memory: KeyedRateLimiter::new(limit, per),
242 breaker: Breaker::new(),
243 warned: Mutex::new(None),
244 }
245 }
246
247 pub(crate) async fn check(&self, key: &K) -> Result<(), Limited> {
249 self.memory.check(key)?;
251 let Some(store) = &self.store else {
252 return Ok(());
253 };
254 let Some(turn) = self.breaker.turn() else {
255 return Ok(());
256 };
257 let id = format!("{}:{key}", self.name);
258 let error =
259 match tokio::time::timeout(STORE_WAIT, store.hit(&id, self.limit, self.per)).await {
260 Ok(Ok(verdict)) => {
261 self.breaker.answered(turn);
262 return verdict;
263 }
264 Ok(Err(error)) => error.to_string(),
265 Err(_) => format!("no answer in {STORE_WAIT:?}"),
266 };
267 self.breaker.failed();
268 self.warn(&error);
269 Ok(())
270 }
271
272 fn warn(&self, error: &str) {
273 let now = Instant::now();
274 let mut warned = self.warned.lock().unwrap_or_else(PoisonError::into_inner);
275 if warned.is_none_or(|at| now.duration_since(at) >= STORE_WARNING_EVERY) {
276 *warned = Some(now);
277 tracing::warn!(target: "navree::http", limit = %self.name, %error, "the rate limit store could not count a request; this process counts on its own and asks the store again in a few seconds");
278 }
279 }
280}
281
282#[derive(Debug)]
286struct Breaker {
287 rest_until: AtomicU64,
290 start: Instant,
291}
292
293#[derive(Clone, Copy, Debug, PartialEq, Eq)]
295enum Turn {
296 Ask,
298 Probe(u64),
302}
303
304impl Breaker {
305 fn new() -> Self {
306 Self {
307 rest_until: AtomicU64::new(0),
308 start: Instant::now(),
309 }
310 }
311
312 fn now(&self) -> u64 {
314 let since = u64::try_from(self.start.elapsed().as_millis()).unwrap_or(u64::MAX / 2);
315 since.saturating_add(1)
316 }
317
318 fn turn(&self) -> Option<Turn> {
320 let rest_until = self.rest_until.load(Ordering::Acquire);
321 if rest_until == 0 {
322 return Some(Turn::Ask);
323 }
324 let now = self.now();
325 if now < rest_until {
326 return None;
327 }
328 let probing = now.saturating_add(millis(STORE_WAIT));
331 self.rest_until
332 .compare_exchange(rest_until, probing, Ordering::AcqRel, Ordering::Acquire)
333 .ok()
334 .map(|_| Turn::Probe(probing))
335 }
336
337 fn answered(&self, turn: Turn) {
339 if let Turn::Probe(probing) = turn {
340 let _ =
342 self.rest_until
343 .compare_exchange(probing, 0, Ordering::AcqRel, Ordering::Acquire);
344 }
345 }
346
347 fn failed(&self) {
349 let until = self.now().saturating_add(millis(STORE_REST));
350 self.rest_until.store(until, Ordering::Release);
351 }
352}
353
354fn millis(duration: Duration) -> u64 {
355 u64::try_from(duration.as_millis()).unwrap_or(u64::MAX / 2)
356}
357
358impl<K: Hash + Eq> fmt::Debug for Limiter<K> {
359 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
360 f.debug_struct("Limiter")
361 .field("name", &self.name)
362 .field("limit", &self.limit)
363 .field("per", &self.per)
364 .field("shared", &self.store.is_some())
365 .finish_non_exhaustive()
366 }
367}
368
369impl<K: Hash + Eq + Clone> KeyedRateLimiter<K> {
370 pub fn new(limit: u32, per: Duration) -> Self {
372 Self {
373 interval: interval(limit, per),
374 period: per,
375 state: DashMap::new(),
376 }
377 }
378
379 pub fn check(&self, key: &K) -> Result<(), Limited> {
381 let now = Instant::now();
382 if sweep_now() {
383 self.state.retain(|_, slot| slot.tat > now);
384 }
385 let mut slot = self.state.entry(key.clone()).or_insert(Slot::new(now));
387 slot.admit(now, self.interval, self.period)
388 }
389}
390
391#[cfg(test)]
392mod tests {
393 use super::*;
394
395 #[tokio::test(start_paused = true)]
396 async fn allows_a_burst_then_refills_one_per_interval() {
397 let limiter = KeyedRateLimiter::new(2, Duration::from_secs(60));
398 assert!(limiter.check(&"a").is_ok());
399 assert!(limiter.check(&"a").is_ok());
400 let retry = limiter.check(&"a").unwrap_err();
401 assert_eq!(retry.retry_after, Duration::from_secs(30));
402 assert!(limiter.check(&"b").is_ok(), "keys are independent");
403
404 tokio::time::advance(Duration::from_secs(30)).await;
405 assert!(limiter.check(&"a").is_ok(), "one request refilled");
406 assert!(limiter.check(&"a").is_err());
407 }
408
409 #[tokio::test(start_paused = true)]
410 async fn refusals_are_reported_once_per_window() {
411 let limiter = KeyedRateLimiter::new(1, Duration::from_secs(10));
412 assert!(limiter.check(&1).is_ok());
413 assert!(limiter.check(&1).unwrap_err().report);
414 assert!(!limiter.check(&1).unwrap_err().report);
415 assert!(limiter.check(&2).is_ok(), "keys are independent");
416 assert!(limiter.check(&2).unwrap_err().report);
417 tokio::time::advance(Duration::from_secs(10)).await;
418 assert!(limiter.check(&1).is_ok());
419 assert!(limiter.check(&1).unwrap_err().report, "a new window");
420 }
421
422 #[test]
424 fn concurrent_checks_never_allow_more_than_the_limit() {
425 let limiter = KeyedRateLimiter::new(100, Duration::from_secs(3600));
426 let allowed = std::sync::atomic::AtomicUsize::new(0);
427 std::thread::scope(|scope| {
428 for _ in 0..8 {
429 scope.spawn(|| {
430 for _ in 0..50 {
431 if limiter.check(&"shared").is_ok() {
432 allowed.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
433 }
434 }
435 });
436 }
437 });
438 assert_eq!(allowed.into_inner(), 100);
439 assert!(
440 limiter.check(&"another key").is_ok(),
441 "keys are independent"
442 );
443 }
444
445 #[tokio::test(start_paused = true)]
448 async fn the_memory_store_counts_like_the_limiter() {
449 let store = MemoryRateLimitStore::default();
450 let minute = Duration::from_secs(60);
451 assert!(store.check("a", 2, minute).is_ok());
452 assert!(store.check("a", 2, minute).is_ok());
453 let limited = store.check("a", 2, minute).unwrap_err();
454 assert_eq!(limited.retry_after, Duration::from_secs(30));
455 assert!(limited.report);
456 assert!(
457 !store.check("a", 2, minute).unwrap_err().report,
458 "once a window"
459 );
460 assert!(store.check("b", 2, minute).is_ok(), "keys are independent");
461 tokio::time::advance(Duration::from_secs(30)).await;
462 assert!(store.check("a", 2, minute).is_ok(), "one request refilled");
463 }
464
465 struct Down;
467
468 impl RateLimitStore for Down {
469 fn hit<'a>(&'a self, _: &'a str, _: u32, _: Duration) -> BoxFuture<'a, StoreVerdict> {
470 Box::pin(async { Err("connection refused".into()) })
471 }
472 }
473
474 struct Hung;
476
477 impl RateLimitStore for Hung {
478 fn hit<'a>(&'a self, _: &'a str, _: u32, _: Duration) -> BoxFuture<'a, StoreVerdict> {
479 Box::pin(std::future::pending())
480 }
481 }
482
483 #[tokio::test(start_paused = true)]
484 async fn a_store_that_fails_or_hangs_leaves_the_limit_to_the_process() {
485 for store in [Arc::new(Down) as Arc<dyn RateLimitStore>, Arc::new(Hung)] {
486 let limiter = Limiter::new(
487 "http:ip".to_owned(),
488 1,
489 Duration::from_secs(60),
490 Some(store),
491 );
492 let started = Instant::now();
493 assert!(limiter.check(&"192.0.2.1").await.is_ok());
494 assert!(limiter.check(&"192.0.2.1").await.is_err());
495 assert!(started.elapsed() <= STORE_WAIT, "{:?}", started.elapsed());
496 }
497 }
498
499 #[derive(Default)]
502 struct Scripted {
503 asked: std::sync::atomic::AtomicUsize,
504 mode: std::sync::atomic::AtomicU8,
506 counts: MemoryRateLimitStore,
507 }
508
509 const COUNTS: u8 = 0;
510 const FAILS: u8 = 1;
511 const HANGS: u8 = 2;
512
513 impl Scripted {
514 fn set(&self, mode: u8) {
515 self.mode.store(mode, Ordering::Relaxed);
516 }
517
518 fn asked(&self) -> usize {
519 self.asked.load(Ordering::Relaxed)
520 }
521 }
522
523 impl RateLimitStore for Scripted {
524 fn hit<'a>(
525 &'a self,
526 key: &'a str,
527 limit: u32,
528 per: Duration,
529 ) -> BoxFuture<'a, StoreVerdict> {
530 self.asked.fetch_add(1, Ordering::Relaxed);
531 match self.mode.load(Ordering::Relaxed) {
532 COUNTS => self.counts.hit(key, limit, per),
533 FAILS => Box::pin(async { Err("connection refused".into()) }),
534 _ => Box::pin(std::future::pending()),
535 }
536 }
537 }
538
539 fn limiter_on(store: &Arc<Scripted>, limit: u32) -> Limiter<&'static str> {
540 let store: Arc<dyn RateLimitStore> = store.clone();
541 Limiter::new(
542 "http:ip".to_owned(),
543 limit,
544 Duration::from_secs(3600),
545 Some(store),
546 )
547 }
548
549 #[tokio::test(start_paused = true)]
552 async fn a_store_that_failed_is_left_alone_for_a_while_then_asked_again() {
553 let store = Arc::new(Scripted::default());
554 let limiter = limiter_on(&store, 1000);
555 store.set(HANGS);
556 let started = Instant::now();
557 for _ in 0..50 {
558 assert!(limiter.check(&"192.0.2.1").await.is_ok());
559 }
560 assert_eq!(started.elapsed(), STORE_WAIT, "only the first one waited");
561 assert_eq!(store.asked(), 1);
562
563 tokio::time::advance(STORE_REST).await;
564 store.set(FAILS);
565 assert!(limiter.check(&"192.0.2.1").await.is_ok());
566 assert_eq!(store.asked(), 2, "one asks again, and finds it down");
567 assert!(limiter.check(&"192.0.2.1").await.is_ok());
568 assert_eq!(store.asked(), 2, "so it rests again");
569
570 tokio::time::advance(STORE_REST).await;
571 store.set(COUNTS);
572 assert!(limiter.check(&"192.0.2.1").await.is_ok());
573 assert!(limiter.check(&"192.0.2.1").await.is_ok());
574 assert_eq!(store.asked(), 4, "it answers, and every request asks it");
575 }
576
577 #[tokio::test(start_paused = true)]
580 async fn a_probe_that_never_finished_hands_the_turn_on() {
581 let store = Arc::new(Scripted::default());
582 let limiter = limiter_on(&store, 1000);
583 store.set(FAILS);
584 assert!(limiter.check(&"192.0.2.1").await.is_ok());
585 tokio::time::advance(STORE_REST).await;
586 store.set(HANGS);
587 let dropped = tokio::time::timeout(STORE_WAIT / 10, limiter.check(&"192.0.2.1")).await;
588 assert!(dropped.is_err(), "the probe was asking");
589 assert_eq!(store.asked(), 2);
590 assert!(limiter.check(&"192.0.2.1").await.is_ok());
591 assert_eq!(store.asked(), 2, "the probe has the turn");
592
593 tokio::time::advance(STORE_WAIT).await;
594 store.set(COUNTS);
595 assert!(limiter.check(&"192.0.2.1").await.is_ok());
596 assert_eq!(store.asked(), 3, "its time is up: another asks");
597 assert!(limiter.check(&"192.0.2.1").await.is_ok());
598 assert_eq!(store.asked(), 4);
599 }
600
601 #[tokio::test(start_paused = true)]
605 async fn the_process_counts_every_request_so_a_failing_store_gives_no_fresh_burst() {
606 let store = Arc::new(Scripted::default());
607 let limiter = limiter_on(&store, 3);
608 for _ in 0..3 {
609 assert!(limiter.check(&"192.0.2.1").await.is_ok());
610 }
611 assert_eq!(store.asked(), 3);
612 for _ in 0..20 {
613 assert!(limiter.check(&"192.0.2.1").await.is_err());
614 }
615 assert_eq!(store.asked(), 3, "refused here, the store not asked");
616
617 store.set(FAILS);
618 assert!(
619 limiter.check(&"192.0.2.1").await.is_err(),
620 "the client's burst is spent here too"
621 );
622 assert!(limiter.check(&"192.0.2.2").await.is_ok(), "another client");
623 }
624
625 #[tokio::test(start_paused = true)]
628 async fn the_shared_count_refuses_what_this_process_would_allow() {
629 let store = Arc::new(Scripted::default());
630 let here = limiter_on(&store, 2);
631 let there = limiter_on(&store, 2);
632 assert!(there.check(&"192.0.2.1").await.is_ok());
633 assert!(there.check(&"192.0.2.1").await.is_ok());
634 assert!(here.check(&"192.0.2.1").await.is_err(), "spent elsewhere");
635 }
636
637 #[tokio::test(start_paused = true)]
640 async fn limiters_on_one_store_share_their_counts() {
641 let store: Arc<dyn RateLimitStore> = Arc::new(MemoryRateLimitStore::default());
642 let minute = Duration::from_secs(60);
643 let here = Limiter::new("http:ip".to_owned(), 2, minute, Some(store.clone()));
644 let there = Limiter::new("http:ip".to_owned(), 2, minute, Some(store.clone()));
645 let other = Limiter::new("http:route:GET /x".to_owned(), 2, minute, Some(store));
646 assert!(here.check(&"192.0.2.1").await.is_ok());
647 assert!(there.check(&"192.0.2.1").await.is_ok());
648 assert!(here.check(&"192.0.2.1").await.is_err(), "counted together");
649 assert!(other.check(&"192.0.2.1").await.is_ok(), "another limit");
650 assert!(there.check(&"192.0.2.2").await.is_ok(), "another client");
651 }
652
653 #[tokio::test(start_paused = true)]
654 async fn rejected_requests_do_not_count() {
655 let limiter = KeyedRateLimiter::new(1, Duration::from_secs(10));
656 assert!(limiter.check(&1).is_ok());
657 for _ in 0..5 {
658 assert!(limiter.check(&1).is_err());
659 }
660 tokio::time::advance(Duration::from_secs(10)).await;
661 assert!(limiter.check(&1).is_ok());
662 }
663}