Skip to main content

navree_http/
limiter.rs

1//! Rate limits: one algorithm (GCRA), counted where the app says.
2//!
3//! The per-IP limit and route throttles count in this process
4//! ([`KeyedRateLimiter`]), and when `http.rate_limit_store` names a
5//! [`RateLimitStore`] every process of the app shares, there too: `redis`
6//! with navree-redis's `RedisModule`, or one the app registers under a name
7//! of its own. [`KeyedRateLimiter`] is public too, for limits a route can't declare
8//! (per OAuth client, per API key).
9
10use 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
21/// How often (in checks on one thread) expired keys are swept.
22const SWEEP_EVERY: u64 = 1024;
23
24thread_local! {
25    /// Checks made on this thread, counting to the next sweep: a shared
26    /// counter would be one more cache line every request writes.
27    static CHECKS: Cell<u64> = const { Cell::new(0) };
28}
29
30/// Allows `limit` requests per `per` and key, as a burst, refilling one
31/// request every `per / limit` (generic cell rate algorithm: one timestamp
32/// per key). The keys are sharded, so concurrent requests from different
33/// keys rarely wait for each other.
34///
35/// It counts in this process: each instance of the app keeps its own counts.
36/// The per-IP limit and route throttles
37/// ([`RouteDef::throttle`](crate::RouteDef::throttle)) count like this,
38/// and in a shared [`RateLimitStore`] too when `http.rate_limit_store` names
39/// one.
40///
41/// ```
42/// use std::time::Duration;
43/// use navree_http::KeyedRateLimiter;
44///
45/// let limiter = KeyedRateLimiter::new(2, Duration::from_secs(60));
46/// assert!(limiter.check(&"client-a").is_ok());
47/// assert!(limiter.check(&"client-a").is_ok());
48/// let limited = limiter.check(&"client-a").unwrap_err();
49/// assert!(limited.retry_after > Duration::ZERO);
50/// assert!(limiter.check(&"client-b").is_ok());
51/// ```
52#[derive(Debug)]
53pub struct KeyedRateLimiter<K: Hash + Eq> {
54    interval: Duration,
55    period: Duration,
56    state: DashMap<K, Slot>,
57}
58
59/// A key's state.
60#[derive(Clone, Copy, Debug)]
61struct Slot {
62    /// Theoretical arrival time of the next request.
63    tat: Instant,
64    /// When a refusal was last reported.
65    reported: Option<Instant>,
66}
67
68/// A refused request.
69#[derive(Clone, Copy, Debug, PartialEq, Eq)]
70#[non_exhaustive]
71pub struct Limited {
72    /// When the key may send again.
73    pub retry_after: Duration,
74    /// Whether this refusal should be reported (audited): the first one for
75    /// the key in a window of `per`, so a flood is reported once a window.
76    pub report: bool,
77}
78
79impl Limited {
80    /// A refusal: the key may send again after `retry_after`, and `report`
81    /// says whether it is the first one of its window.
82    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    /// Counts a request at `now`, one `interval` apart and a burst of
99    /// `period / interval`. A refused request does not count.
100    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
117/// Whether this thread's turn to sweep expired keys has come.
118fn sweep_now() -> bool {
119    let checks = CHECKS.get().wrapping_add(1);
120    CHECKS.set(checks);
121    checks.is_multiple_of(SWEEP_EVERY)
122}
123
124/// The interval between requests of a limit of `limit` per `per`.
125fn interval(limit: u32, per: Duration) -> Duration {
126    per / limit.max(1)
127}
128
129/// What a [`RateLimitStore`] says of a request: allowed (`Ok`), or
130/// [`Limited`]. The outer error is the store's own: it could not count.
131pub type StoreVerdict = Result<Result<(), Limited>, BoxError>;
132
133/// Where the per-IP limit and route throttles count their requests, when
134/// every process of the app must count them together: behind a load balancer
135/// N servers that each count on their own allow N times the limit.
136///
137/// `http.rate_limit_store` names the store, as a provider of
138/// `dyn RateLimitStore` registered under that name: navree-redis's
139/// `RedisModule` registers `redis`. Unset (or `memory`), each process counts
140/// on its own, with no store at all.
141///
142/// Each process also counts every request itself, first: it sees only some of
143/// a client's requests, so its own count never refuses one the shared count
144/// would allow, and a flood is refused there without a round trip to the
145/// store. A store that fails or takes longer than 100 ms is not waited for,
146/// and is left alone for 3 seconds: the process's own count decides, so a
147/// limit holds per process while its store is down, a slow store does not
148/// slow every request, and the log says so once a minute. Then one request
149/// asks the store again, and the others go on without it until it answers.
150///
151/// Keys are the limit's name and the client's: `http:ip:203.0.113.9` for the
152/// per-IP limit, `http:route:POST /api/exports:user:<uuid>` for a route
153/// throttle.
154pub trait RateLimitStore: Send + Sync + 'static {
155    /// Counts a request against `key`: at most `limit` (at least 1) per
156    /// `per`, as a burst, then one every `per / limit`, by the generic cell
157    /// rate algorithm as [`KeyedRateLimiter`] counts. A refused request does
158    /// not count, and [`Limited::report`] is set on the first refusal of `key`
159    /// in a window of `per`.
160    fn hit<'a>(&'a self, key: &'a str, limit: u32, per: Duration) -> BoxFuture<'a, StoreVerdict>;
161}
162
163/// A [`RateLimitStore`] in this process's memory: the limits of every app it
164/// is registered in are counted together. For tests, and for several apps
165/// in one process.
166///
167/// ```
168/// use std::time::Duration;
169/// use navree_http::MemoryRateLimitStore;
170///
171/// let store = MemoryRateLimitStore::default();
172/// let minute = Duration::from_secs(60);
173/// assert!(store.check("exports:ada", 1, minute).is_ok());
174/// assert!(store.check("exports:ada", 1, minute).is_err());
175/// ```
176#[derive(Debug, Default)]
177pub struct MemoryRateLimitStore {
178    state: DashMap<String, Slot>,
179}
180
181impl MemoryRateLimitStore {
182    /// Counts a request against `key`, as [`RateLimitStore::hit`] does.
183    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
206/// How long a store may take to count a request before the process's own
207/// count decides.
208const STORE_WAIT: Duration = Duration::from_millis(100);
209
210/// How long a store that failed or did not answer is left alone.
211const STORE_REST: Duration = Duration::from_secs(3);
212
213/// How often a failing store is logged.
214const STORE_WARNING_EVERY: Duration = Duration::from_secs(60);
215
216/// One of the app's limits, `limit` per `per` and key: counted in this
217/// process, and then in the app's [`RateLimitStore`] under `name` when it has
218/// one and the store is answering.
219pub(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    /// Counts a request for `key`: [`Limited`] when over the limit.
248    pub(crate) async fn check(&self, key: &K) -> Result<(), Limited> {
249        // Here first, always: see [`RateLimitStore`].
250        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/// Whether a request asks the store: not for [`STORE_REST`] after it failed
283/// or did not answer, then one request at a time until one gets an answer.
284/// One atomic, as every request of the per-IP limit looks at it.
285#[derive(Debug)]
286struct Breaker {
287    /// Until when the store is left alone, in milliseconds since `start`
288    /// (never 0); 0 while it answers.
289    rest_until: AtomicU64,
290    start: Instant,
291}
292
293/// A request's turn to ask the store.
294#[derive(Clone, Copy, Debug, PartialEq, Eq)]
295enum Turn {
296    /// The store answers: every request asks it.
297    Ask,
298    /// The store failed and has rested: this request asks for all of them,
299    /// which leave it alone until this one has an answer, or until the
300    /// time an answer may take, as given.
301    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    /// Now, in milliseconds since `start`, from 1.
313    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    /// Whether this request asks the store, and how.
319    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        // A probe that is dropped before its answer gives the next request
329        // the turn once its time is up.
330        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    /// The store answered the request that had `turn`.
338    fn answered(&self, turn: Turn) {
339        if let Turn::Probe(probing) = turn {
340            // Unless another request saw it fail meanwhile.
341            let _ =
342                self.rest_until
343                    .compare_exchange(probing, 0, Ordering::AcqRel, Ordering::Acquire);
344        }
345    }
346
347    /// The store failed or did not answer: it rests from now.
348    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    /// `limit` requests per `per` (a `limit` of 0 is treated as 1).
371    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    /// Counts a request for `key`: [`Limited`] when over the limit.
380    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        // Holds the lock of the key's shard until the slot is updated.
386        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    /// Checks of one key from many threads at once allow exactly the burst.
423    #[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    /// The store counts every limit by its key, with the limit the request
446    /// names, by the same rules.
447    #[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    /// A store that is down: the limit still holds, in this process.
466    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    /// A store that never answers.
475    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    /// A store that answers, fails or hangs as it is told, and counts the
500    /// requests it was asked to count.
501    #[derive(Default)]
502    struct Scripted {
503        asked: std::sync::atomic::AtomicUsize,
504        /// 0 counts, 1 fails, 2 never answers.
505        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    /// While a store is down or slow, requests do not wait for it: one finds
550    /// out, the rest leave it alone for a while, then one asks again.
551    #[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    /// A probe that is dropped before its answer (its client went away)
578    /// does not keep the store from being asked again.
579    #[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    /// The process counts every request too: when the store goes down there
602    /// is no fresh burst to hand out, and a flood is refused here without
603    /// asking the store at all.
604    #[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    /// The store's count decides when it is lower: other processes spent the
626    /// client's requests.
627    #[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    /// Two limiters on one store are one limit: the store sees the limit's
638    /// name and the client's key.
639    #[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}