use std::time::{Duration, Instant};
#[derive(Debug)]
pub struct TokenBucket {
capacity: u32,
tokens: f64,
refill_rate: f64,
last_refill: Instant,
}
impl TokenBucket {
pub fn new(capacity: u32, refill_rate: f64) -> Self {
Self {
capacity,
tokens: capacity as f64,
refill_rate,
last_refill: Instant::now(),
}
}
pub fn try_acquire(&mut self, tokens: u32) -> Result<(), Duration> {
self.refill();
let tokens_f64 = tokens as f64;
if self.tokens >= tokens_f64 {
self.tokens -= tokens_f64;
Ok(())
} else {
let needed = tokens_f64 - self.tokens;
let wait_secs = needed / self.refill_rate;
Err(Duration::from_secs_f64(wait_secs))
}
}
pub fn acquire_blocking(&mut self, tokens: u32) -> Duration {
match self.try_acquire(tokens) {
Ok(()) => Duration::ZERO,
Err(wait) => {
std::thread::sleep(wait);
self.refill();
self.tokens -= tokens as f64;
wait
}
}
}
pub fn check_available(&mut self, tokens: u32) -> bool {
self.refill();
self.tokens >= tokens as f64
}
pub fn available(&mut self) -> u32 {
self.refill();
self.tokens.floor() as u32
}
pub fn capacity(&self) -> u32 {
self.capacity
}
pub fn refill_rate(&self) -> f64 {
self.refill_rate
}
pub fn reset(&mut self) {
self.tokens = self.capacity as f64;
self.last_refill = Instant::now();
}
fn refill(&mut self) {
let now = Instant::now();
let elapsed = now.duration_since(self.last_refill);
let added = elapsed.as_secs_f64() * self.refill_rate;
self.tokens = (self.tokens + added).min(self.capacity as f64);
self.last_refill = now;
}
}
#[derive(Debug, Clone)]
pub struct RateLimitConfig {
pub connection_limit: TokenBucketConfig,
pub rest_public: TokenBucketConfig,
pub rest_private: TokenBucketConfig,
pub ws_orders: TokenBucketConfig,
pub l3_depth_10: TokenBucketConfig,
pub l3_depth_100: TokenBucketConfig,
pub l3_depth_1000: TokenBucketConfig,
}
#[derive(Debug, Clone, Copy)]
pub struct TokenBucketConfig {
pub capacity: u32,
pub refill_rate: f64,
}
impl TokenBucketConfig {
pub const fn new(capacity: u32, refill_rate: f64) -> Self {
Self {
capacity,
refill_rate,
}
}
pub fn create_bucket(&self) -> TokenBucket {
TokenBucket::new(self.capacity, self.refill_rate)
}
}
impl Default for RateLimitConfig {
fn default() -> Self {
Self::kraken_defaults()
}
}
impl RateLimitConfig {
pub fn kraken_defaults() -> Self {
Self {
connection_limit: TokenBucketConfig::new(150, 0.25),
rest_public: TokenBucketConfig::new(15, 0.5),
rest_private: TokenBucketConfig::new(20, 0.33),
ws_orders: TokenBucketConfig::new(15, 15.0),
l3_depth_10: TokenBucketConfig::new(5, 1.0),
l3_depth_100: TokenBucketConfig::new(25, 5.0),
l3_depth_1000: TokenBucketConfig::new(100, 20.0),
}
}
pub fn high_tier() -> Self {
Self {
connection_limit: TokenBucketConfig::new(150, 0.25),
rest_public: TokenBucketConfig::new(45, 1.0),
rest_private: TokenBucketConfig::new(60, 1.0),
ws_orders: TokenBucketConfig::new(60, 60.0),
l3_depth_10: TokenBucketConfig::new(5, 1.0),
l3_depth_100: TokenBucketConfig::new(25, 5.0),
l3_depth_1000: TokenBucketConfig::new(100, 20.0),
}
}
pub fn permissive() -> Self {
Self {
connection_limit: TokenBucketConfig::new(1000, 100.0),
rest_public: TokenBucketConfig::new(1000, 100.0),
rest_private: TokenBucketConfig::new(1000, 100.0),
ws_orders: TokenBucketConfig::new(1000, 100.0),
l3_depth_10: TokenBucketConfig::new(1000, 100.0),
l3_depth_100: TokenBucketConfig::new(1000, 100.0),
l3_depth_1000: TokenBucketConfig::new(1000, 100.0),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RateLimitCategory {
Connection,
RestPublic,
RestPrivate,
WsOrders,
L3Depth10,
L3Depth100,
L3Depth1000,
}
impl RateLimitCategory {
pub fn get_config(self, config: &RateLimitConfig) -> TokenBucketConfig {
match self {
Self::Connection => config.connection_limit,
Self::RestPublic => config.rest_public,
Self::RestPrivate => config.rest_private,
Self::WsOrders => config.ws_orders,
Self::L3Depth10 => config.l3_depth_10,
Self::L3Depth100 => config.l3_depth_100,
Self::L3Depth1000 => config.l3_depth_1000,
}
}
pub fn from_l3_depth(depth: u32) -> Self {
match depth {
0..=10 => Self::L3Depth10,
11..=100 => Self::L3Depth100,
_ => Self::L3Depth1000,
}
}
}
#[derive(Debug, Clone)]
pub enum RateLimitResult {
Allowed,
Limited { wait: Duration, category: RateLimitCategory },
}
impl RateLimitResult {
pub fn is_allowed(&self) -> bool {
matches!(self, Self::Allowed)
}
pub fn wait_duration(&self) -> Option<Duration> {
match self {
Self::Allowed => None,
Self::Limited { wait, .. } => Some(*wait),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_token_bucket_creation() {
let bucket = TokenBucket::new(10, 1.0);
assert_eq!(bucket.capacity(), 10);
assert_eq!(bucket.refill_rate(), 1.0);
}
#[test]
fn test_token_bucket_acquire() {
let mut bucket = TokenBucket::new(10, 1.0);
assert!(bucket.try_acquire(5).is_ok());
assert_eq!(bucket.available(), 5);
assert!(bucket.try_acquire(5).is_ok());
assert_eq!(bucket.available(), 0);
let result = bucket.try_acquire(1);
assert!(result.is_err());
}
#[test]
fn test_token_bucket_refill() {
let mut bucket = TokenBucket::new(10, 100.0);
assert!(bucket.try_acquire(10).is_ok());
assert_eq!(bucket.available(), 0);
std::thread::sleep(Duration::from_millis(15));
assert!(bucket.available() >= 1);
}
#[test]
fn test_token_bucket_check_available() {
let mut bucket = TokenBucket::new(10, 1.0);
assert!(bucket.check_available(5));
assert!(bucket.check_available(10));
assert!(!bucket.check_available(11));
}
#[test]
fn test_token_bucket_reset() {
let mut bucket = TokenBucket::new(10, 1.0);
bucket.try_acquire(10).unwrap();
assert_eq!(bucket.available(), 0);
bucket.reset();
assert_eq!(bucket.available(), 10);
}
#[test]
fn test_rate_limit_config_defaults() {
let config = RateLimitConfig::kraken_defaults();
assert_eq!(config.connection_limit.capacity, 150);
assert_eq!(config.ws_orders.capacity, 15);
assert_eq!(config.rest_public.capacity, 15);
}
#[test]
fn test_rate_limit_category() {
let config = RateLimitConfig::kraken_defaults();
let connection = RateLimitCategory::Connection.get_config(&config);
assert_eq!(connection.capacity, 150);
let ws_orders = RateLimitCategory::WsOrders.get_config(&config);
assert_eq!(ws_orders.capacity, 15);
}
#[test]
fn test_l3_depth_category() {
assert_eq!(RateLimitCategory::from_l3_depth(10), RateLimitCategory::L3Depth10);
assert_eq!(RateLimitCategory::from_l3_depth(25), RateLimitCategory::L3Depth100);
assert_eq!(RateLimitCategory::from_l3_depth(500), RateLimitCategory::L3Depth1000);
}
#[test]
fn test_rate_limit_result() {
let allowed = RateLimitResult::Allowed;
assert!(allowed.is_allowed());
assert!(allowed.wait_duration().is_none());
let limited = RateLimitResult::Limited {
wait: Duration::from_secs(5),
category: RateLimitCategory::RestPublic,
};
assert!(!limited.is_allowed());
assert_eq!(limited.wait_duration(), Some(Duration::from_secs(5)));
}
}