Skip to content

Commit

Permalink
ratelimit: add method to retrieve the next refill time (#124)
Browse files Browse the repository at this point in the history
Useful to check whether the rate limiter has been is use in the recent
past, e.g. to drop obsolete per client rate limiters.
  • Loading branch information
cgzones authored Oct 31, 2024
1 parent c2fe95f commit f0e3edc
Showing 1 changed file with 11 additions and 0 deletions.
11 changes: 11 additions & 0 deletions ratelimit/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,11 @@ impl Ratelimiter {
self.available.load(Ordering::Relaxed)
}

/// Returns the time of the next refill.
pub fn next_refill(&self) -> Instant {
self.refill_at.load(Ordering::Relaxed)
}

/// Sets the number of tokens available to some amount. Returns an error if
/// the amount exceeds the bucket capacity.
pub fn set_available(&self, amount: u64) -> Result<(), Error> {
Expand Down Expand Up @@ -472,9 +477,15 @@ mod tests {
.unwrap();

std::thread::sleep(Duration::from_millis(10));
assert!(rl.next_refill() < clocksource::precise::Instant::now());

assert!(rl.try_wait().is_ok());
assert!(rl.try_wait().is_err());
assert!(rl.dropped() >= 8);
assert!(rl.next_refill() >= clocksource::precise::Instant::now());

std::thread::sleep(Duration::from_millis(5));
assert!(rl.next_refill() < clocksource::precise::Instant::now());
}

// quick test that capacity acts as expected
Expand Down

0 comments on commit f0e3edc

Please sign in to comment.