Crate ratelimit [] [src]

A token bucket ratelimiter for rust which can be used by either a single thread or shared across threads using a mpsc synchronous channel

Goals

  • a simple token bucket ratelimiter
  • usable in single or multi thread code

Future work

  • consider additional types of ratelimiters

Usage

Construct a new Ratelimit and call block between actions. For multi-thread clone the channel sender to pass to the threads, in a separate thread, call run on the Ratelimit in a tight loop.

Example

Construct Ratelimit and use in single and then multi-thread modes


extern crate ratelimit;

use std::thread;
use std::sync::mpsc;
use std::time::Duration;

let mut ratelimit = ratelimit::Ratelimit::configure()
    .capacity(1) //number of tokens the bucket will hold
    .quantum(1) //add one token per interval
    .interval(Duration::new(1, 0)) //add quantum tokens every 1 second
    .build();

// count down to ignition
println!("Count-down....");
for i in -10..0 {
    println!("T {}", i);
    ratelimit.block(1);
}
println!("Ignition!");

// clone the sender from Ratelimit
let sender = ratelimit.clone_sender();

// create ratelimited threads
for i in 0..2 {
    let s = sender.clone();
    thread::spawn(move || {
        for x in 0..5 {
            s.send(());
            println!(".");
        }
    });
}

// run the ratelimiter
thread::spawn(move || {
    loop {
        ratelimit.run();
    }
});

Structs

Config
Ratelimit