Line data Source code
1 : use std::borrow::Cow;
2 : use std::collections::hash_map::RandomState;
3 : use std::hash::{BuildHasher, Hash};
4 : use std::sync::atomic::{AtomicUsize, Ordering};
5 : use std::sync::Mutex;
6 :
7 : use anyhow::bail;
8 : use dashmap::DashMap;
9 : use itertools::Itertools;
10 : use rand::rngs::StdRng;
11 : use rand::{Rng, SeedableRng};
12 : use tokio::time::{Duration, Instant};
13 : use tracing::info;
14 :
15 : use crate::intern::EndpointIdInt;
16 :
17 : pub(crate) struct GlobalRateLimiter {
18 : data: Vec<RateBucket>,
19 : info: Vec<RateBucketInfo>,
20 : }
21 :
22 : impl GlobalRateLimiter {
23 0 : pub(crate) fn new(info: Vec<RateBucketInfo>) -> Self {
24 0 : Self {
25 0 : data: vec![
26 0 : RateBucket {
27 0 : start: Instant::now(),
28 0 : count: 0,
29 0 : };
30 0 : info.len()
31 0 : ],
32 0 : info,
33 0 : }
34 0 : }
35 :
36 : /// Check that number of connections is below `max_rps` rps.
37 0 : pub(crate) fn check(&mut self) -> bool {
38 0 : let now = Instant::now();
39 0 :
40 0 : let should_allow_request = self
41 0 : .data
42 0 : .iter_mut()
43 0 : .zip(&self.info)
44 0 : .all(|(bucket, info)| bucket.should_allow_request(info, now, 1));
45 0 :
46 0 : if should_allow_request {
47 0 : // only increment the bucket counts if the request will actually be accepted
48 0 : self.data.iter_mut().for_each(|b| b.inc(1));
49 0 : }
50 :
51 0 : should_allow_request
52 0 : }
53 : }
54 :
55 : // Simple per-endpoint rate limiter.
56 : //
57 : // Check that number of connections to the endpoint is below `max_rps` rps.
58 : // Purposefully ignore user name and database name as clients can reconnect
59 : // with different names, so we'll end up sending some http requests to
60 : // the control plane.
61 : pub type WakeComputeRateLimiter = BucketRateLimiter<EndpointIdInt, StdRng, RandomState>;
62 :
63 : pub struct BucketRateLimiter<Key, Rand = StdRng, Hasher = RandomState> {
64 : map: DashMap<Key, Vec<RateBucket>, Hasher>,
65 : info: Cow<'static, [RateBucketInfo]>,
66 : access_count: AtomicUsize,
67 : rand: Mutex<Rand>,
68 : }
69 :
70 : #[derive(Clone, Copy)]
71 : struct RateBucket {
72 : start: Instant,
73 : count: u32,
74 : }
75 :
76 : impl RateBucket {
77 3000915 : fn should_allow_request(&mut self, info: &RateBucketInfo, now: Instant, n: u32) -> bool {
78 3000915 : if now - self.start < info.interval {
79 3000907 : self.count + n <= info.max_rpi
80 : } else {
81 : // bucket expired, reset
82 8 : self.count = 0;
83 8 : self.start = now;
84 8 :
85 8 : true
86 : }
87 3000915 : }
88 :
89 3000909 : fn inc(&mut self, n: u32) {
90 3000909 : self.count += n;
91 3000909 : }
92 : }
93 :
94 : #[derive(Clone, Copy, PartialEq)]
95 : pub struct RateBucketInfo {
96 : pub(crate) interval: Duration,
97 : // requests per interval
98 : pub(crate) max_rpi: u32,
99 : }
100 :
101 : impl std::fmt::Display for RateBucketInfo {
102 19 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103 19 : let rps = self.rps().floor() as u64;
104 19 : write!(f, "{rps}@{}", humantime::format_duration(self.interval))
105 19 : }
106 : }
107 :
108 : impl std::fmt::Debug for RateBucketInfo {
109 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
110 0 : write!(f, "{self}")
111 0 : }
112 : }
113 :
114 : impl std::str::FromStr for RateBucketInfo {
115 : type Err = anyhow::Error;
116 :
117 32 : fn from_str(s: &str) -> Result<Self, Self::Err> {
118 32 : let Some((max_rps, interval)) = s.split_once('@') else {
119 0 : bail!("invalid rate info")
120 : };
121 32 : let max_rps = max_rps.parse()?;
122 32 : let interval = humantime::parse_duration(interval)?;
123 32 : Ok(Self::new(max_rps, interval))
124 32 : }
125 : }
126 :
127 : impl RateBucketInfo {
128 : pub const DEFAULT_SET: [Self; 3] = [
129 : Self::new(300, Duration::from_secs(1)),
130 : Self::new(200, Duration::from_secs(60)),
131 : Self::new(100, Duration::from_secs(600)),
132 : ];
133 :
134 : pub const DEFAULT_ENDPOINT_SET: [Self; 3] = [
135 : Self::new(500, Duration::from_secs(1)),
136 : Self::new(300, Duration::from_secs(60)),
137 : Self::new(200, Duration::from_secs(600)),
138 : ];
139 :
140 19 : pub fn rps(&self) -> f64 {
141 19 : (self.max_rpi as f64) / self.interval.as_secs_f64()
142 19 : }
143 :
144 3 : pub fn validate(info: &mut [Self]) -> anyhow::Result<()> {
145 8 : info.sort_unstable_by_key(|info| info.interval);
146 3 : let invalid = info
147 3 : .iter()
148 3 : .tuple_windows()
149 4 : .find(|(a, b)| a.max_rpi > b.max_rpi);
150 3 : if let Some((a, b)) = invalid {
151 1 : bail!(
152 1 : "invalid bucket RPS limits. {b} allows fewer requests per bucket than {a} ({} vs {})",
153 1 : b.max_rpi,
154 1 : a.max_rpi,
155 1 : );
156 2 : }
157 2 :
158 2 : Ok(())
159 3 : }
160 :
161 36 : pub const fn new(max_rps: u32, interval: Duration) -> Self {
162 36 : Self {
163 36 : interval,
164 36 : max_rpi: ((max_rps as u64) * (interval.as_millis() as u64) / 1000) as u32,
165 36 : }
166 36 : }
167 : }
168 :
169 : impl<K: Hash + Eq> BucketRateLimiter<K> {
170 4 : pub fn new(info: impl Into<Cow<'static, [RateBucketInfo]>>) -> Self {
171 4 : Self::new_with_rand_and_hasher(info, StdRng::from_entropy(), RandomState::new())
172 4 : }
173 : }
174 :
175 : impl<K: Hash + Eq, R: Rng, S: BuildHasher + Clone> BucketRateLimiter<K, R, S> {
176 5 : fn new_with_rand_and_hasher(
177 5 : info: impl Into<Cow<'static, [RateBucketInfo]>>,
178 5 : rand: R,
179 5 : hasher: S,
180 5 : ) -> Self {
181 5 : let info = info.into();
182 5 : info!(buckets = ?info, "endpoint rate limiter");
183 5 : Self {
184 5 : info,
185 5 : map: DashMap::with_hasher_and_shard_amount(hasher, 64),
186 5 : access_count: AtomicUsize::new(1), // start from 1 to avoid GC on the first request
187 5 : rand: Mutex::new(rand),
188 5 : }
189 5 : }
190 :
191 : /// Check that number of connections to the endpoint is below `max_rps` rps.
192 1000457 : pub(crate) fn check(&self, key: K, n: u32) -> bool {
193 1000457 : // do a partial GC every 2k requests. This cleans up ~ 1/64th of the map.
194 1000457 : // worst case memory usage is about:
195 1000457 : // = 2 * 2048 * 64 * (48B + 72B)
196 1000457 : // = 30MB
197 1000457 : if self.access_count.fetch_add(1, Ordering::AcqRel) % 2048 == 0 {
198 488 : self.do_gc();
199 999969 : }
200 :
201 1000457 : let now = Instant::now();
202 1000457 : let mut entry = self.map.entry(key).or_insert_with(|| {
203 1000004 : vec![
204 1000004 : RateBucket {
205 1000004 : start: now,
206 1000004 : count: 0,
207 1000004 : };
208 1000004 : self.info.len()
209 1000004 : ]
210 1000457 : });
211 1000457 :
212 1000457 : let should_allow_request = entry
213 1000457 : .iter_mut()
214 1000457 : .zip(&*self.info)
215 3000915 : .all(|(bucket, info)| bucket.should_allow_request(info, now, n));
216 1000457 :
217 1000457 : if should_allow_request {
218 1000453 : // only increment the bucket counts if the request will actually be accepted
219 3000909 : entry.iter_mut().for_each(|b| b.inc(n));
220 1000453 : }
221 :
222 1000457 : should_allow_request
223 1000457 : }
224 :
225 : /// Clean the map. Simple strategy: remove all entries in a random shard.
226 : /// At worst, we'll double the effective max_rps during the cleanup.
227 : /// But that way deletion does not aquire mutex on each entry access.
228 488 : pub(crate) fn do_gc(&self) {
229 488 : info!(
230 0 : "cleaning up bucket rate limiter, current size = {}",
231 0 : self.map.len()
232 : );
233 488 : let n = self.map.shards().len();
234 488 : // this lock is ok as the periodic cycle of do_gc makes this very unlikely to collide
235 488 : // (impossible, infact, unless we have 2048 threads)
236 488 : let shard = self.rand.lock().unwrap().gen_range(0..n);
237 488 : self.map.shards()[shard].write().clear();
238 488 : }
239 : }
240 :
241 : #[cfg(test)]
242 : mod tests {
243 : use std::hash::BuildHasherDefault;
244 : use std::time::Duration;
245 :
246 : use rand::SeedableRng;
247 : use rustc_hash::FxHasher;
248 : use tokio::time;
249 :
250 : use super::{BucketRateLimiter, WakeComputeRateLimiter};
251 : use crate::intern::EndpointIdInt;
252 : use crate::rate_limiter::RateBucketInfo;
253 : use crate::types::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 : }
|