[][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

use futures::prelude::*;
use leaky_bucket::LeakyBuckets;
use std::{error::Error, time::Duration};

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let buckets = LeakyBuckets::new();

    let rate_limiter = buckets
        .rate_limiter()
        .max(100)
        .refill_interval(Duration::from_secs(10))
        .refill_amount(100)
        .build()?;

    let coordinator = buckets.coordinate().boxed();

    // spawn the coordinate thread to refill the rate limiter.
    tokio::spawn(async move { coordinator.await.expect("coordinate thread errored") });
    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.