torrentdht 0.1.1

DHT discovery with mTLS handshake handoff; optional BitTorrent when the host opts in
Documentation
//! Token-bucket rate limiter for download/upload caps.

use std::sync::Arc;
use std::time::{Duration, Instant};

use tokio::sync::Mutex;

#[derive(Debug)]
struct RateState {
    max_bytes_per_sec: u64,
    allowance: f64,
    last: Instant,
}

impl RateState {
    fn new(max_bytes_per_sec: u64) -> Self {
        Self {
            max_bytes_per_sec,
            allowance: max_bytes_per_sec as f64,
            last: Instant::now(),
        }
    }

    fn refill(&mut self) {
        let now = Instant::now();
        let elapsed = now.duration_since(self.last).as_secs_f64();
        self.last = now;
        if self.max_bytes_per_sec == 0 {
            return;
        }
        self.allowance = (self.allowance + elapsed * self.max_bytes_per_sec as f64)
            .min(self.max_bytes_per_sec as f64 * 2.0);
    }

    async fn consume(&mut self, bytes: u64) {
        if self.max_bytes_per_sec == 0 {
            return;
        }
        loop {
            self.refill();
            let need = bytes as f64;
            if self.allowance >= need {
                self.allowance -= need;
                return;
            }
            let deficit = need - self.allowance;
            let wait_secs = deficit / self.max_bytes_per_sec as f64;
            let wait = Duration::from_secs_f64(wait_secs.max(0.001));
            tokio::time::sleep(wait).await;
        }
    }
}

#[derive(Debug, Clone)]
pub struct RateLimiter {
    state: Arc<Mutex<RateState>>,
}

impl RateLimiter {
    pub fn new(max_kbps: u64) -> Self {
        let max_bytes_per_sec = max_kbps.saturating_mul(1024);
        Self {
            state: Arc::new(Mutex::new(RateState::new(max_bytes_per_sec))),
        }
    }

    pub fn unlimited() -> Self {
        Self::new(0)
    }

    pub async fn consume(&self, bytes: u64) {
        if bytes == 0 {
            return;
        }
        self.state.lock().await.consume(bytes).await;
    }
}