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 struct GlobalRateLimiter {
21 : data: Vec<RateBucket>,
22 : info: Vec<RateBucketInfo>,
23 : }
24 :
25 : impl GlobalRateLimiter {
26 0 : pub 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 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 6001830 : fn should_allow_request(&mut self, info: &RateBucketInfo, now: Instant, n: u32) -> bool {
81 6001830 : if now - self.start < info.interval {
82 6001814 : self.count + n <= info.max_rpi
83 : } else {
84 : // bucket expired, reset
85 16 : self.count = 0;
86 16 : self.start = now;
87 16 :
88 16 : true
89 : }
90 6001830 : }
91 :
92 6001818 : fn inc(&mut self, n: u32) {
93 6001818 : self.count += n;
94 6001818 : }
95 : }
96 :
97 : #[derive(Clone, Copy, PartialEq)]
98 : pub struct RateBucketInfo {
99 : pub interval: Duration,
100 : // requests per interval
101 : pub max_rpi: u32,
102 : }
103 :
104 : impl std::fmt::Display for RateBucketInfo {
105 38 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
106 38 : let rps = self.rps().floor() as u64;
107 38 : write!(f, "{rps}@{}", humantime::format_duration(self.interval))
108 38 : }
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 64 : fn from_str(s: &str) -> Result<Self, Self::Err> {
121 64 : let Some((max_rps, interval)) = s.split_once('@') else {
122 0 : bail!("invalid rate info")
123 : };
124 64 : let max_rps = max_rps.parse()?;
125 64 : let interval = humantime::parse_duration(interval)?;
126 64 : Ok(Self::new(max_rps, interval))
127 64 : }
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 38 : pub fn rps(&self) -> f64 {
144 38 : (self.max_rpi as f64) / self.interval.as_secs_f64()
145 38 : }
146 :
147 6 : pub fn validate(info: &mut [Self]) -> anyhow::Result<()> {
148 16 : info.sort_unstable_by_key(|info| info.interval);
149 6 : let invalid = info
150 6 : .iter()
151 6 : .tuple_windows()
152 8 : .find(|(a, b)| a.max_rpi > b.max_rpi);
153 6 : if let Some((a, b)) = invalid {
154 2 : bail!(
155 2 : "invalid bucket RPS limits. {b} allows fewer requests per bucket than {a} ({} vs {})",
156 2 : b.max_rpi,
157 2 : a.max_rpi,
158 2 : );
159 4 : }
160 4 :
161 4 : Ok(())
162 6 : }
163 :
164 72 : pub const fn new(max_rps: u32, interval: Duration) -> Self {
165 72 : Self {
166 72 : interval,
167 72 : max_rpi: ((max_rps as u64) * (interval.as_millis() as u64) / 1000) as u32,
168 72 : }
169 72 : }
170 : }
171 :
172 : impl<K: Hash + Eq> BucketRateLimiter<K> {
173 8 : pub fn new(info: impl Into<Cow<'static, [RateBucketInfo]>>) -> Self {
174 8 : Self::new_with_rand_and_hasher(info, StdRng::from_entropy(), RandomState::new())
175 8 : }
176 : }
177 :
178 : impl<K: Hash + Eq, R: Rng, S: BuildHasher + Clone> BucketRateLimiter<K, R, S> {
179 10 : fn new_with_rand_and_hasher(
180 10 : info: impl Into<Cow<'static, [RateBucketInfo]>>,
181 10 : rand: R,
182 10 : hasher: S,
183 10 : ) -> Self {
184 10 : let info = info.into();
185 10 : info!(buckets = ?info, "endpoint rate limiter");
186 10 : Self {
187 10 : info,
188 10 : map: DashMap::with_hasher_and_shard_amount(hasher, 64),
189 10 : access_count: AtomicUsize::new(1), // start from 1 to avoid GC on the first request
190 10 : rand: Mutex::new(rand),
191 10 : }
192 10 : }
193 :
194 : /// Check that number of connections to the endpoint is below `max_rps` rps.
195 2000914 : pub fn check(&self, key: K, n: u32) -> bool {
196 2000914 : // do a partial GC every 2k requests. This cleans up ~ 1/64th of the map.
197 2000914 : // worst case memory usage is about:
198 2000914 : // = 2 * 2048 * 64 * (48B + 72B)
199 2000914 : // = 30MB
200 2000914 : if self.access_count.fetch_add(1, Ordering::AcqRel) % 2048 == 0 {
201 976 : self.do_gc();
202 1999938 : }
203 :
204 2000914 : let now = Instant::now();
205 2000914 : let mut entry = self.map.entry(key).or_insert_with(|| {
206 2000008 : vec![
207 2000008 : RateBucket {
208 2000008 : start: now,
209 2000008 : count: 0,
210 2000008 : };
211 2000008 : self.info.len()
212 2000008 : ]
213 2000914 : });
214 2000914 :
215 2000914 : let should_allow_request = entry
216 2000914 : .iter_mut()
217 2000914 : .zip(&*self.info)
218 6001830 : .all(|(bucket, info)| bucket.should_allow_request(info, now, n));
219 2000914 :
220 2000914 : if should_allow_request {
221 2000906 : // only increment the bucket counts if the request will actually be accepted
222 6001818 : entry.iter_mut().for_each(|b| b.inc(n));
223 2000906 : }
224 :
225 2000914 : should_allow_request
226 2000914 : }
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 976 : pub fn do_gc(&self) {
232 976 : info!(
233 0 : "cleaning up bucket rate limiter, current size = {}",
234 0 : self.map.len()
235 : );
236 976 : let n = self.map.shards().len();
237 976 : // this lock is ok as the periodic cycle of do_gc makes this very unlikely to collide
238 976 : // (impossible, infact, unless we have 2048 threads)
239 976 : let shard = self.rand.lock().unwrap().gen_range(0..n);
240 976 : self.map.shards()[shard].write().clear();
241 976 : }
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 2 : fn rate_bucket_rpi() {
257 2 : let rate_bucket = RateBucketInfo::new(50, Duration::from_secs(5));
258 2 : assert_eq!(rate_bucket.max_rpi, 50 * 5);
259 :
260 2 : let rate_bucket = RateBucketInfo::new(50, Duration::from_millis(500));
261 2 : assert_eq!(rate_bucket.max_rpi, 50 / 2);
262 2 : }
263 :
264 : #[test]
265 2 : fn rate_bucket_parse() {
266 2 : let rate_bucket: RateBucketInfo = "100@10s".parse().unwrap();
267 2 : assert_eq!(rate_bucket.interval, Duration::from_secs(10));
268 2 : assert_eq!(rate_bucket.max_rpi, 100 * 10);
269 2 : assert_eq!(rate_bucket.to_string(), "100@10s");
270 :
271 2 : let rate_bucket: RateBucketInfo = "100@1m".parse().unwrap();
272 2 : assert_eq!(rate_bucket.interval, Duration::from_secs(60));
273 2 : assert_eq!(rate_bucket.max_rpi, 100 * 60);
274 2 : assert_eq!(rate_bucket.to_string(), "100@1m");
275 2 : }
276 :
277 : #[test]
278 2 : fn default_rate_buckets() {
279 2 : let mut defaults = RateBucketInfo::DEFAULT_SET;
280 2 : RateBucketInfo::validate(&mut defaults[..]).unwrap();
281 2 : }
282 :
283 : #[test]
284 : #[should_panic = "invalid bucket RPS limits. 10@10s allows fewer requests per bucket than 300@1s (100 vs 300)"]
285 2 : fn rate_buckets_validate() {
286 2 : let mut rates: Vec<RateBucketInfo> = ["300@1s", "10@10s"]
287 2 : .into_iter()
288 4 : .map(|s| s.parse().unwrap())
289 2 : .collect();
290 2 : RateBucketInfo::validate(&mut rates).unwrap();
291 2 : }
292 :
293 : #[tokio::test]
294 2 : async fn test_rate_limits() {
295 2 : let mut rates: Vec<RateBucketInfo> = ["100@1s", "20@30s"]
296 2 : .into_iter()
297 4 : .map(|s| s.parse().unwrap())
298 2 : .collect();
299 2 : RateBucketInfo::validate(&mut rates).unwrap();
300 2 : let limiter = WakeComputeRateLimiter::new(rates);
301 2 :
302 2 : let endpoint = EndpointId::from("ep-my-endpoint-1234");
303 2 : let endpoint = EndpointIdInt::from(endpoint);
304 2 :
305 2 : time::pause();
306 2 :
307 202 : for _ in 0..100 {
308 200 : assert!(limiter.check(endpoint, 1));
309 2 : }
310 2 : // more connections fail
311 2 : assert!(!limiter.check(endpoint, 1));
312 2 :
313 2 : // fail even after 500ms as it's in the same bucket
314 2 : time::advance(time::Duration::from_millis(500)).await;
315 2 : assert!(!limiter.check(endpoint, 1));
316 2 :
317 2 : // after a full 1s, 100 requests are allowed again
318 2 : time::advance(time::Duration::from_millis(500)).await;
319 12 : for _ in 1..6 {
320 510 : for _ in 0..50 {
321 500 : assert!(limiter.check(endpoint, 2));
322 2 : }
323 10 : time::advance(time::Duration::from_millis(1000)).await;
324 2 : }
325 2 :
326 2 : // more connections after 600 will exceed the 20rps@30s limit
327 2 : assert!(!limiter.check(endpoint, 1));
328 2 :
329 2 : // will still fail before the 30 second limit
330 2 : time::advance(time::Duration::from_millis(30_000 - 6_000 - 1)).await;
331 2 : assert!(!limiter.check(endpoint, 1));
332 2 :
333 2 : // after the full 30 seconds, 100 requests are allowed again
334 2 : time::advance(time::Duration::from_millis(1)).await;
335 202 : for _ in 0..100 {
336 200 : assert!(limiter.check(endpoint, 1));
337 2 : }
338 2 : }
339 :
340 : #[tokio::test]
341 2 : async fn test_rate_limits_gc() {
342 2 : // fixed seeded random/hasher to ensure that the test is not flaky
343 2 : let rand = rand::rngs::StdRng::from_seed([1; 32]);
344 2 : let hasher = BuildHasherDefault::<FxHasher>::default();
345 2 :
346 2 : let limiter =
347 2 : BucketRateLimiter::new_with_rand_and_hasher(&RateBucketInfo::DEFAULT_SET, rand, hasher);
348 2000002 : for i in 0..1_000_000 {
349 2000000 : limiter.check(i, 1);
350 2000000 : }
351 2 : assert!(limiter.map.len() < 150_000);
352 2 : }
353 : }
|