Skip to content

Commit

Permalink
Fix rate limiter (#4560)
Browse files Browse the repository at this point in the history
  • Loading branch information
sunaurus committed Mar 25, 2024
1 parent ef4bb3c commit 99d01e1
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion crates/utils/src/rate_limit/rate_limiter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ impl<K: Eq + Hash, C: MapLevel> MapLevel for Map<K, C> {

// Evaluated if `some_children_remaining` is false
let total_has_refill_in_future = || {
group.total.into_iter().all(|(action_type, bucket)| {
group.total.into_iter().any(|(action_type, bucket)| {
#[allow(clippy::indexing_slicing)]
let config = configs[action_type];
bucket.update(now, config).tokens != config.capacity
Expand Down Expand Up @@ -416,5 +416,23 @@ mod tests {
rate_limiter.remove_full_buckets(now);
assert!(rate_limiter.ipv4_buckets.is_empty());
assert!(rate_limiter.ipv6_buckets.is_empty());

// `remove full buckets` should not remove empty buckets
let ip = "1.1.1.1".parse().unwrap();
// empty the bucket with 2 requests
assert!(rate_limiter.check(ActionType::Post, ip, now));
assert!(rate_limiter.check(ActionType::Post, ip, now));

rate_limiter.remove_full_buckets(now);
assert!(!rate_limiter.ipv4_buckets.is_empty());

// `remove full buckets` should not remove partial buckets
now.secs += 2;
let ip = "1.1.1.1".parse().unwrap();
// Only make one request, so bucket still has 1 token
assert!(rate_limiter.check(ActionType::Post, ip, now));

rate_limiter.remove_full_buckets(now);
assert!(!rate_limiter.ipv4_buckets.is_empty());
}
}

0 comments on commit 99d01e1

Please sign in to comment.