LCOV - code coverage report
Current view: top level - proxy/src/rate_limiter - limiter.rs (source / functions) Coverage Total Hit
Test: fc67f8dc6087a0b4f4f0bcd74f6e1dc25fab8cf3.info Lines: 84.9 % 218 185
Test Date: 2024-09-24 13:57:57 Functions: 77.1 % 48 37

            Line data    Source code
       1              : use std::{
       2              :     borrow::Cow,
       3              :     collections::hash_map::RandomState,
       4              :     hash::{BuildHasher, Hash},
       5              :     sync::{
       6              :         atomic::{AtomicUsize, Ordering},
       7              :         Mutex,
       8              :     },
       9              : };
      10              : 
      11              : use anyhow::bail;
      12              : use dashmap::DashMap;
      13              : use itertools::Itertools;
      14              : use rand::{rngs::StdRng, Rng, SeedableRng};
      15              : use tokio::time::{Duration, Instant};
      16              : use tracing::info;
      17              : 
      18              : use crate::intern::EndpointIdInt;
      19              : 
      20              : pub(crate) struct GlobalRateLimiter {
      21              :     data: Vec<RateBucket>,
      22              :     info: Vec<RateBucketInfo>,
      23              : }
      24              : 
      25              : impl GlobalRateLimiter {
      26            0 :     pub(crate) fn new(info: Vec<RateBucketInfo>) -> Self {
      27            0 :         Self {
      28            0 :             data: vec![
      29            0 :                 RateBucket {
      30            0 :                     start: Instant::now(),
      31            0 :                     count: 0,
      32            0 :                 };
      33            0 :                 info.len()
      34            0 :             ],
      35            0 :             info,
      36            0 :         }
      37            0 :     }
      38              : 
      39              :     /// Check that number of connections is below `max_rps` rps.
      40            0 :     pub(crate) fn check(&mut self) -> bool {
      41            0 :         let now = Instant::now();
      42            0 : 
      43            0 :         let should_allow_request = self
      44            0 :             .data
      45            0 :             .iter_mut()
      46            0 :             .zip(&self.info)
      47            0 :             .all(|(bucket, info)| bucket.should_allow_request(info, now, 1));
      48            0 : 
      49            0 :         if should_allow_request {
      50            0 :             // only increment the bucket counts if the request will actually be accepted
      51            0 :             self.data.iter_mut().for_each(|b| b.inc(1));
      52            0 :         }
      53              : 
      54            0 :         should_allow_request
      55            0 :     }
      56              : }
      57              : 
      58              : // Simple per-endpoint rate limiter.
      59              : //
      60              : // Check that number of connections to the endpoint is below `max_rps` rps.
      61              : // Purposefully ignore user name and database name as clients can reconnect
      62              : // with different names, so we'll end up sending some http requests to
      63              : // the control plane.
      64              : pub type WakeComputeRateLimiter = BucketRateLimiter<EndpointIdInt, StdRng, RandomState>;
      65              : 
      66              : pub struct BucketRateLimiter<Key, Rand = StdRng, Hasher = RandomState> {
      67              :     map: DashMap<Key, Vec<RateBucket>, Hasher>,
      68              :     info: Cow<'static, [RateBucketInfo]>,
      69              :     access_count: AtomicUsize,
      70              :     rand: Mutex<Rand>,
      71              : }
      72              : 
      73              : #[derive(Clone, Copy)]
      74              : struct RateBucket {
      75              :     start: Instant,
      76              :     count: u32,
      77              : }
      78              : 
      79              : impl RateBucket {
      80      3000915 :     fn should_allow_request(&mut self, info: &RateBucketInfo, now: Instant, n: u32) -> bool {
      81      3000915 :         if now - self.start < info.interval {
      82      3000907 :             self.count + n <= info.max_rpi
      83              :         } else {
      84              :             // bucket expired, reset
      85            8 :             self.count = 0;
      86            8 :             self.start = now;
      87            8 : 
      88            8 :             true
      89              :         }
      90      3000915 :     }
      91              : 
      92      3000909 :     fn inc(&mut self, n: u32) {
      93      3000909 :         self.count += n;
      94      3000909 :     }
      95              : }
      96              : 
      97              : #[derive(Clone, Copy, PartialEq)]
      98              : pub struct RateBucketInfo {
      99              :     pub(crate) interval: Duration,
     100              :     // requests per interval
     101              :     pub(crate) max_rpi: u32,
     102              : }
     103              : 
     104              : impl std::fmt::Display for RateBucketInfo {
     105           19 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     106           19 :         let rps = self.rps().floor() as u64;
     107           19 :         write!(f, "{rps}@{}", humantime::format_duration(self.interval))
     108           19 :     }
     109              : }
     110              : 
     111              : impl std::fmt::Debug for RateBucketInfo {
     112            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     113            0 :         write!(f, "{self}")
     114            0 :     }
     115              : }
     116              : 
     117              : impl std::str::FromStr for RateBucketInfo {
     118              :     type Err = anyhow::Error;
     119              : 
     120           32 :     fn from_str(s: &str) -> Result<Self, Self::Err> {
     121           32 :         let Some((max_rps, interval)) = s.split_once('@') else {
     122            0 :             bail!("invalid rate info")
     123              :         };
     124           32 :         let max_rps = max_rps.parse()?;
     125           32 :         let interval = humantime::parse_duration(interval)?;
     126           32 :         Ok(Self::new(max_rps, interval))
     127           32 :     }
     128              : }
     129              : 
     130              : impl RateBucketInfo {
     131              :     pub const DEFAULT_SET: [Self; 3] = [
     132              :         Self::new(300, Duration::from_secs(1)),
     133              :         Self::new(200, Duration::from_secs(60)),
     134              :         Self::new(100, Duration::from_secs(600)),
     135              :     ];
     136              : 
     137              :     pub const DEFAULT_ENDPOINT_SET: [Self; 3] = [
     138              :         Self::new(500, Duration::from_secs(1)),
     139              :         Self::new(300, Duration::from_secs(60)),
     140              :         Self::new(200, Duration::from_secs(600)),
     141              :     ];
     142              : 
     143           19 :     pub fn rps(&self) -> f64 {
     144           19 :         (self.max_rpi as f64) / self.interval.as_secs_f64()
     145           19 :     }
     146              : 
     147            3 :     pub fn validate(info: &mut [Self]) -> anyhow::Result<()> {
     148            8 :         info.sort_unstable_by_key(|info| info.interval);
     149            3 :         let invalid = info
     150            3 :             .iter()
     151            3 :             .tuple_windows()
     152            4 :             .find(|(a, b)| a.max_rpi > b.max_rpi);
     153            3 :         if let Some((a, b)) = invalid {
     154            1 :             bail!(
     155            1 :                 "invalid bucket RPS limits. {b} allows fewer requests per bucket than {a} ({} vs {})",
     156            1 :                 b.max_rpi,
     157            1 :                 a.max_rpi,
     158            1 :             );
     159            2 :         }
     160            2 : 
     161            2 :         Ok(())
     162            3 :     }
     163              : 
     164           36 :     pub const fn new(max_rps: u32, interval: Duration) -> Self {
     165           36 :         Self {
     166           36 :             interval,
     167           36 :             max_rpi: ((max_rps as u64) * (interval.as_millis() as u64) / 1000) as u32,
     168           36 :         }
     169           36 :     }
     170              : }
     171              : 
     172              : impl<K: Hash + Eq> BucketRateLimiter<K> {
     173            4 :     pub fn new(info: impl Into<Cow<'static, [RateBucketInfo]>>) -> Self {
     174            4 :         Self::new_with_rand_and_hasher(info, StdRng::from_entropy(), RandomState::new())
     175            4 :     }
     176              : }
     177              : 
     178              : impl<K: Hash + Eq, R: Rng, S: BuildHasher + Clone> BucketRateLimiter<K, R, S> {
     179            5 :     fn new_with_rand_and_hasher(
     180            5 :         info: impl Into<Cow<'static, [RateBucketInfo]>>,
     181            5 :         rand: R,
     182            5 :         hasher: S,
     183            5 :     ) -> Self {
     184            5 :         let info = info.into();
     185            5 :         info!(buckets = ?info, "endpoint rate limiter");
     186            5 :         Self {
     187            5 :             info,
     188            5 :             map: DashMap::with_hasher_and_shard_amount(hasher, 64),
     189            5 :             access_count: AtomicUsize::new(1), // start from 1 to avoid GC on the first request
     190            5 :             rand: Mutex::new(rand),
     191            5 :         }
     192            5 :     }
     193              : 
     194              :     /// Check that number of connections to the endpoint is below `max_rps` rps.
     195      1000457 :     pub(crate) fn check(&self, key: K, n: u32) -> bool {
     196      1000457 :         // do a partial GC every 2k requests. This cleans up ~ 1/64th of the map.
     197      1000457 :         // worst case memory usage is about:
     198      1000457 :         //    = 2 * 2048 * 64 * (48B + 72B)
     199      1000457 :         //    = 30MB
     200      1000457 :         if self.access_count.fetch_add(1, Ordering::AcqRel) % 2048 == 0 {
     201          488 :             self.do_gc();
     202       999969 :         }
     203              : 
     204      1000457 :         let now = Instant::now();
     205      1000457 :         let mut entry = self.map.entry(key).or_insert_with(|| {
     206      1000004 :             vec![
     207      1000004 :                 RateBucket {
     208      1000004 :                     start: now,
     209      1000004 :                     count: 0,
     210      1000004 :                 };
     211      1000004 :                 self.info.len()
     212      1000004 :             ]
     213      1000457 :         });
     214      1000457 : 
     215      1000457 :         let should_allow_request = entry
     216      1000457 :             .iter_mut()
     217      1000457 :             .zip(&*self.info)
     218      3000915 :             .all(|(bucket, info)| bucket.should_allow_request(info, now, n));
     219      1000457 : 
     220      1000457 :         if should_allow_request {
     221      1000453 :             // only increment the bucket counts if the request will actually be accepted
     222      3000909 :             entry.iter_mut().for_each(|b| b.inc(n));
     223      1000453 :         }
     224              : 
     225      1000457 :         should_allow_request
     226      1000457 :     }
     227              : 
     228              :     /// Clean the map. Simple strategy: remove all entries in a random shard.
     229              :     /// At worst, we'll double the effective max_rps during the cleanup.
     230              :     /// But that way deletion does not aquire mutex on each entry access.
     231          488 :     pub(crate) fn do_gc(&self) {
     232          488 :         info!(
     233            0 :             "cleaning up bucket rate limiter, current size = {}",
     234            0 :             self.map.len()
     235              :         );
     236          488 :         let n = self.map.shards().len();
     237          488 :         // this lock is ok as the periodic cycle of do_gc makes this very unlikely to collide
     238          488 :         // (impossible, infact, unless we have 2048 threads)
     239          488 :         let shard = self.rand.lock().unwrap().gen_range(0..n);
     240          488 :         self.map.shards()[shard].write().clear();
     241          488 :     }
     242              : }
     243              : 
     244              : #[cfg(test)]
     245              : mod tests {
     246              :     use std::{hash::BuildHasherDefault, time::Duration};
     247              : 
     248              :     use rand::SeedableRng;
     249              :     use rustc_hash::FxHasher;
     250              :     use tokio::time;
     251              : 
     252              :     use super::{BucketRateLimiter, WakeComputeRateLimiter};
     253              :     use crate::{intern::EndpointIdInt, rate_limiter::RateBucketInfo, EndpointId};
     254              : 
     255              :     #[test]
     256            1 :     fn rate_bucket_rpi() {
     257            1 :         let rate_bucket = RateBucketInfo::new(50, Duration::from_secs(5));
     258            1 :         assert_eq!(rate_bucket.max_rpi, 50 * 5);
     259              : 
     260            1 :         let rate_bucket = RateBucketInfo::new(50, Duration::from_millis(500));
     261            1 :         assert_eq!(rate_bucket.max_rpi, 50 / 2);
     262            1 :     }
     263              : 
     264              :     #[test]
     265            1 :     fn rate_bucket_parse() {
     266            1 :         let rate_bucket: RateBucketInfo = "100@10s".parse().unwrap();
     267            1 :         assert_eq!(rate_bucket.interval, Duration::from_secs(10));
     268            1 :         assert_eq!(rate_bucket.max_rpi, 100 * 10);
     269            1 :         assert_eq!(rate_bucket.to_string(), "100@10s");
     270              : 
     271            1 :         let rate_bucket: RateBucketInfo = "100@1m".parse().unwrap();
     272            1 :         assert_eq!(rate_bucket.interval, Duration::from_secs(60));
     273            1 :         assert_eq!(rate_bucket.max_rpi, 100 * 60);
     274            1 :         assert_eq!(rate_bucket.to_string(), "100@1m");
     275            1 :     }
     276              : 
     277              :     #[test]
     278            1 :     fn default_rate_buckets() {
     279            1 :         let mut defaults = RateBucketInfo::DEFAULT_SET;
     280            1 :         RateBucketInfo::validate(&mut defaults[..]).unwrap();
     281            1 :     }
     282              : 
     283              :     #[test]
     284              :     #[should_panic = "invalid bucket RPS limits. 10@10s allows fewer requests per bucket than 300@1s (100 vs 300)"]
     285            1 :     fn rate_buckets_validate() {
     286            1 :         let mut rates: Vec<RateBucketInfo> = ["300@1s", "10@10s"]
     287            1 :             .into_iter()
     288            2 :             .map(|s| s.parse().unwrap())
     289            1 :             .collect();
     290            1 :         RateBucketInfo::validate(&mut rates).unwrap();
     291            1 :     }
     292              : 
     293              :     #[tokio::test]
     294            1 :     async fn test_rate_limits() {
     295            1 :         let mut rates: Vec<RateBucketInfo> = ["100@1s", "20@30s"]
     296            1 :             .into_iter()
     297            2 :             .map(|s| s.parse().unwrap())
     298            1 :             .collect();
     299            1 :         RateBucketInfo::validate(&mut rates).unwrap();
     300            1 :         let limiter = WakeComputeRateLimiter::new(rates);
     301            1 : 
     302            1 :         let endpoint = EndpointId::from("ep-my-endpoint-1234");
     303            1 :         let endpoint = EndpointIdInt::from(endpoint);
     304            1 : 
     305            1 :         time::pause();
     306            1 : 
     307          101 :         for _ in 0..100 {
     308          100 :             assert!(limiter.check(endpoint, 1));
     309            1 :         }
     310            1 :         // more connections fail
     311            1 :         assert!(!limiter.check(endpoint, 1));
     312            1 : 
     313            1 :         // fail even after 500ms as it's in the same bucket
     314            1 :         time::advance(time::Duration::from_millis(500)).await;
     315            1 :         assert!(!limiter.check(endpoint, 1));
     316            1 : 
     317            1 :         // after a full 1s, 100 requests are allowed again
     318            1 :         time::advance(time::Duration::from_millis(500)).await;
     319            6 :         for _ in 1..6 {
     320          255 :             for _ in 0..50 {
     321          250 :                 assert!(limiter.check(endpoint, 2));
     322            1 :             }
     323            5 :             time::advance(time::Duration::from_millis(1000)).await;
     324            1 :         }
     325            1 : 
     326            1 :         // more connections after 600 will exceed the 20rps@30s limit
     327            1 :         assert!(!limiter.check(endpoint, 1));
     328            1 : 
     329            1 :         // will still fail before the 30 second limit
     330            1 :         time::advance(time::Duration::from_millis(30_000 - 6_000 - 1)).await;
     331            1 :         assert!(!limiter.check(endpoint, 1));
     332            1 : 
     333            1 :         // after the full 30 seconds, 100 requests are allowed again
     334            1 :         time::advance(time::Duration::from_millis(1)).await;
     335          101 :         for _ in 0..100 {
     336          100 :             assert!(limiter.check(endpoint, 1));
     337            1 :         }
     338            1 :     }
     339              : 
     340              :     #[tokio::test]
     341            1 :     async fn test_rate_limits_gc() {
     342            1 :         // fixed seeded random/hasher to ensure that the test is not flaky
     343            1 :         let rand = rand::rngs::StdRng::from_seed([1; 32]);
     344            1 :         let hasher = BuildHasherDefault::<FxHasher>::default();
     345            1 : 
     346            1 :         let limiter =
     347            1 :             BucketRateLimiter::new_with_rand_and_hasher(&RateBucketInfo::DEFAULT_SET, rand, hasher);
     348      1000001 :         for i in 0..1_000_000 {
     349      1000000 :             limiter.check(i, 1);
     350      1000000 :         }
     351            1 :         assert!(limiter.map.len() < 150_000);
     352            1 :     }
     353              : }
        

Generated by: LCOV version 2.1-beta