#rate-limiting #bucket #token #algorithm #api #acquire

bin+lib tokenbucket

Provies a token-bucket algorithm with a simple API

7 releases

new 0.1.6 Nov 3, 2024
0.1.5 May 20, 2024
0.1.4 Apr 9, 2024
0.1.3 Aug 21, 2020

#2 in #acquire

Download history 3823/week @ 2024-07-18 4762/week @ 2024-07-25 5475/week @ 2024-08-01 5021/week @ 2024-08-08 4162/week @ 2024-08-15 3765/week @ 2024-08-22 2707/week @ 2024-08-29 4468/week @ 2024-09-05 4169/week @ 2024-09-12 4245/week @ 2024-09-19 4216/week @ 2024-09-26 4806/week @ 2024-10-03 4508/week @ 2024-10-10 4283/week @ 2024-10-17 3168/week @ 2024-10-24 3024/week @ 2024-10-31

16,169 downloads per month

MIT license

13KB
101 lines

tokenbucket

Documentation GitHub license Downloads

This library provides a TokenBucket Algorithm implementation for the Rust programming language.

Install

Add the following to your Cargo.toml

[dependencies]
tokenbucket = "0.1.6"

Usage

use tokenbucket::{TokenBucket, TokenAcquisitionResult};

fn main() {
    let mut bucket = TokenBucket::new(5.0, 100.0);
    match bucket.acquire(1.0) {
        Ok(rate)  => println!("rate/allow: {}, true", rate),
        Err(rate) => println!("rate/allow: {}, false", rate),
    }
}

See the documentation for more advanced usage examples.


lib.rs:

This crate provides a simple TokenBucket object for use in rate- limiting.

Short Example Program

use tokenbucket::TokenBucket;
use tokenbucket::TokenAcquisitionResult;
use std::{thread, time};

// Will acquire tokens at the specified rate for the specified duration.
// After each acquisition, the AcquisitionResult will be printed.
fn run(bucket: &mut TokenBucket, rate: u32, duration: u32) {
    for _ in 0..=(rate * duration) {
        // Acquire 1 token from the bucket.
        let acquisition: TokenAcquisitionResult = bucket.acquire(1.0);

        // Determine the acquisition result.
        match acquisition {
            Ok(rate)  => println!("rate/allow: {}, true", rate),
            Err(rate) => println!("rate/allow: {}, false", rate),
        }
        
        // Sleep for enough time to match the desired rate/second.
        thread::sleep(time::Duration::from_micros(
            (1000000.0 * (1.0 / rate as f64)) as u64,
        ));
    }
}

fn main() {
    // Create the TokenBucket object
    let mut token_bucket: TokenBucket = TokenBucket::new(5.0, 100.0);

    // Start of by acquiring 60 tokens per second for 10 seconds.
    run(&mut token_bucket, 60, 10);

    // Slow down to 2 tokens per second for 10 seconds.
    run(&mut token_bucket, 2, 10);
}

No runtime deps