rqbit/crates/librqbit/src/limits.rs

70 lines
1.7 KiB
Rust
Raw Normal View History

use arc_swap::ArcSwapOption;
use governor::DefaultDirectRateLimiter as RateLimiter;
use governor::Quota;
2024-11-07 21:40:17 +00:00
use serde::Deserialize;
use serde::Serialize;
use std::num::NonZeroU32;
use std::sync::Arc;
2024-11-07 21:40:17 +00:00
2024-11-20 15:30:56 +00:00
#[derive(Default, Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
2024-11-07 21:40:17 +00:00
pub struct LimitsConfig {
2024-11-20 16:13:37 +00:00
pub upload_bps: Option<NonZeroU32>,
pub download_bps: Option<NonZeroU32>,
2024-11-07 21:40:17 +00:00
}
struct Limit(ArcSwapOption<RateLimiter>);
2024-11-07 21:40:17 +00:00
2024-11-07 21:55:31 +00:00
impl Limit {
2024-11-20 16:13:37 +00:00
fn new_inner(bps: Option<NonZeroU32>) -> Option<Arc<RateLimiter>> {
2024-11-16 10:58:26 +00:00
let bps = bps?;
Some(Arc::new(RateLimiter::direct(Quota::per_second(bps))))
2024-11-07 21:55:31 +00:00
}
2024-11-20 16:13:37 +00:00
fn new(bps: Option<NonZeroU32>) -> Self {
Self(ArcSwapOption::new(Self::new_inner(bps)))
2024-11-07 21:55:31 +00:00
}
2024-11-20 16:13:37 +00:00
async fn acquire(&self, size: NonZeroU32) -> anyhow::Result<()> {
let lim = self.0.load().clone();
2024-11-07 21:55:31 +00:00
if let Some(rl) = lim.as_ref() {
rl.until_n_ready(size).await?;
2024-11-07 21:55:31 +00:00
}
Ok(())
2024-11-07 21:55:31 +00:00
}
2024-11-20 16:13:37 +00:00
fn set(&self, limit: Option<NonZeroU32>) {
2024-11-07 21:55:31 +00:00
let new = Self::new_inner(limit);
self.0.swap(new);
2024-11-07 21:55:31 +00:00
}
}
pub struct Limits {
down: Limit,
up: Limit,
}
impl Limits {
pub fn new(config: LimitsConfig) -> Self {
2024-11-07 21:40:17 +00:00
Self {
2024-11-07 21:55:31 +00:00
down: Limit::new(config.download_bps),
up: Limit::new(config.upload_bps),
2024-11-07 21:40:17 +00:00
}
}
2024-11-20 16:13:37 +00:00
pub async fn prepare_for_upload(&self, len: NonZeroU32) -> anyhow::Result<()> {
2024-11-07 21:55:31 +00:00
self.up.acquire(len).await
2024-11-07 21:40:17 +00:00
}
2024-11-20 16:13:37 +00:00
pub async fn prepare_for_download(&self, len: NonZeroU32) -> anyhow::Result<()> {
2024-11-07 21:55:31 +00:00
self.down.acquire(len).await
}
2024-11-20 16:13:37 +00:00
pub fn set_upload_bps(&self, bps: Option<NonZeroU32>) {
2024-11-07 21:55:31 +00:00
self.up.set(bps);
}
pub fn set_download_bps(&self, bps: Option<NonZeroU32>) {
2024-11-07 21:55:31 +00:00
self.down.set(bps);
2024-11-07 21:40:17 +00:00
}
}