Crates.io | gcra |
lib.rs | gcra |
version | 0.6.0 |
source | src |
created_at | 2022-06-12 08:14:33.816766 |
updated_at | 2024-08-01 06:32:00.870203 |
description | A basic implementation of GCRA algorithm for rate limiting |
homepage | https://github.com/lytefast/gcra-rs |
repository | https://github.com/lytefast/gcra-rs |
max_upload_size | |
id | 604485 |
size | 62,820 |
Library which implements the core GCRA functionality in rust.
rate-limiter
a LRU + expiring rate limiter. Implements Send + Sync
so can be used asynchronously.use gcra::{RateLimit, RatelimitGuard};
fn check_rate_limit() {
const LIMIT: u32 = 1;
// Create a rate limit that allows `1/1s`
let rate_limit = RateLimit::per_sec(LIMIT);
let mut rate_limit_guard = RateLimitGuard::new_state(rate_limit);
assert!(rate_limit_guard.check_and_modify(1).is_ok());
assert!(
rate_limit_guard.check_and_modify(1).is_err(),
"We should be over the limit now"
);
}
rate-limiter
use std::sync::Arc;
use gcra::{GcraError, RateLimit, RateLimiter};
#[tokio::main]
async fn main() -> Result<(), GcraError> {
let rate_limit = RateLimit::per_sec(2);
let rate_limiter = Arc::new(RateLimiter::new(4));
rate_limiter.check("key", &rate_limit, 1).await?;
rate_limiter.check("key", &rate_limit, 1).await?;
match rate_limiter.check("key", rate_limit.clone(), 1).await {
Err(GcraError::DeniedUntil { next_allowed_at }) => {
print!("Denied: Request next at {:?}", next_allowed_at);
Ok(())
}
unexpected => panic!("Opps something went wrong! {:?}", unexpected),
}
}