8 releases

0.2.4 Oct 29, 2024
0.2.3 Dec 11, 2023
0.2.2 Nov 17, 2022
0.2.0 Jun 9, 2022
0.1.1 Jan 28, 2022

#376 in Network programming

Download history 606/week @ 2024-07-29 366/week @ 2024-08-05 341/week @ 2024-08-12 300/week @ 2024-08-19 458/week @ 2024-08-26 378/week @ 2024-09-02 246/week @ 2024-09-09 319/week @ 2024-09-16 413/week @ 2024-09-23 269/week @ 2024-09-30 189/week @ 2024-10-07 174/week @ 2024-10-14 404/week @ 2024-10-21 563/week @ 2024-10-28 392/week @ 2024-11-04 310/week @ 2024-11-11

1,679 downloads per month
Used in bevy_mod_pies_spacetrader…

MIT/Apache

19KB
325 lines

Hierarchical token Bucket

This crate implements Hierarchical Token Bucket algorithm with fixed structure https://en.wikipedia.org/wiki/Token_bucket#Hierarchical_token_bucket

Crate does not rely on periodic updates to maintain the token buckets which means it can be updated right before requesting tokens

use htb::*;
use std::time::Duration;

#[derive(Clone, Copy, Eq, PartialEq)]
enum Rate {
    Long,
    Short,
}

impl From<Rate> for usize {
    fn from(rate: Rate) -> Self {
        match rate {
            Rate::Long => 0,
            Rate::Short => 1,
        }
    }
}

// let's implement a rate limiter with two required properties:
// - packet rate should not exceed 250 msg per second
// - packet rate should not exceed 1500 msg per 15 seconds

let mut htb = HTB::new(&[
    BucketCfg {
        this: Rate::Long,
        parent: None,
        rate: (1500, Duration::from_secs(15)),
        capacity: 0,
    },
    BucketCfg {
        this: Rate::Short,
        parent: Some(Rate::Long),
        rate: (250, Duration::from_secs(1)),
        capacity: 250,
    },
])?;

// we are allowed a single 250 token burst
assert!(htb.take_n(Rate::Short, 250));
assert!(!htb.peek(Rate::Short));
htb.advance(Duration::from_secs(1));

// after this point established packet rate obeys "long" indefinitely
for _ in 0..10 {
    assert!(htb.take_n(Rate::Short, 100));
    assert!(!htb.peek(Rate::Short));
    htb.advance(Duration::from_secs(1));
}

// if we stop consuming tokens for some time
htb.advance(Duration::from_secs(10));
assert!(htb.take_n(Rate::Short, 250));
// we get more bursts
assert!(!htb.peek(Rate::Short));
# Ok::<(), Error>(())

Dependencies

~11–415KB