Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/pacak/htb-rs
https://github.com/pacak/htb-rs
Last synced: 3 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/pacak/htb-rs
- Owner: pacak
- License: apache-2.0
- Created: 2021-09-01T05:46:32.000Z (over 3 years ago)
- Default Branch: master
- Last Pushed: 2023-12-11T15:30:55.000Z (about 1 year ago)
- Last Synced: 2024-09-17T18:05:35.287Z (4 months ago)
- Language: Rust
- Size: 23.4 KB
- Stars: 5
- Watchers: 2
- Forks: 2
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: Changelog.md
- License: LICENSE-APACHE
Awesome Lists containing this project
README
# Hierarchical token Bucket
This crate implements Hierarchical Token Bucket algorithm with fixed structure
Crate does not rely on periodic updates to maintain the token buckets which
means it can be updated right before requesting tokens```rust
use htb::*;
use std::time::Duration;#[derive(Clone, Copy, Eq, PartialEq)]
enum Rate {
Long,
Short,
}impl From 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 secondslet 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>(())
```