[−][src]Crate leaky_bucket
tokio-based leaky-bucket rate limiter
This implements a leaky bucket from which you can acquire tokens.
If the tokens are already available, the acquisition will be instant (fast path) and the acquired number of tokens will be added to the bucket.
If the bucket overflows (i.e. goes over max), the task that tried to acquire the tokens will be suspended until the required number of tokens has been added.
Example
If the project is built with the static
feature (default), you can use
LeakyBucket
directly as long as you are inside a tokio runtime, like so:
use leaky_bucket::LeakyBucket; use std::{error::Error, time::Duration}; #[tokio::main] async fn main() -> Result<(), Box<dyn Error>> { let rate_limiter = LeakyBucket::builder() .max(100) .refill_interval(Duration::from_secs(10)) .refill_amount(100) .build()?; println!("Waiting for permit..."); // should take about ten seconds to get a permit. rate_limiter.acquire(100).await?; println!("I made it!"); Ok(()) }
Example using explicit coordinator
use leaky_bucket::LeakyBuckets; use std::{error::Error, time::Duration}; #[tokio::main] async fn main() -> Result<(), Box<dyn Error>> { let mut buckets = LeakyBuckets::new(); let coordinator = buckets.coordinate()?; // spawn the coordinate thread to refill the rate limiter. tokio::spawn(async move { coordinator.await.expect("coordinate thread errored") }); let rate_limiter = buckets .rate_limiter() .max(100) .refill_interval(Duration::from_secs(10)) .refill_amount(100) .build()?; println!("Waiting for permit..."); // should take about ten seconds to get a permit. rate_limiter.acquire(100).await?; println!("I made it!"); Ok(()) }
Structs
Acquire | Future associated with acquiring a single token. |
Builder | Builder for a leaky bucket. |
LeakyBucket | The leaky bucket. |
LeakyBuckets | Coordinator for rate limiters. Is used to create new rate limiters as needed. |
Enums
Error | Error type for the rate limiter. |