use dashmap::DashMap;
use std::sync::atomic::{AtomicUsize, Ordering};
pub struct ConnectionLimiter {
per_host: DashMap<Box<str>, AtomicUsize>,
global_count: AtomicUsize,
global_limit: usize,
per_host_limit: usize,
}
impl ConnectionLimiter {
pub fn new(global: usize, per_host: usize) -> Self {
Self {
per_host: DashMap::new(),
global_count: AtomicUsize::new(0),
global_limit: global,
per_host_limit: per_host,
}
}
pub fn try_acquire(&self, host: &str) -> bool {
loop {
let current = self.global_count.load(Ordering::Relaxed);
if current >= self.global_limit {
return false;
}
match self.global_count.compare_exchange_weak(
current,
current + 1,
Ordering::AcqRel,
Ordering::Relaxed,
) {
Ok(_) => break,
Err(_) => continue,
}
}
let entry = self
.per_host
.entry(host.to_owned().into_boxed_str())
.or_insert_with(|| AtomicUsize::new(0));
loop {
let current = entry.load(Ordering::Relaxed);
if current >= self.per_host_limit {
self.global_count.fetch_sub(1, Ordering::Relaxed);
return false;
}
match entry.compare_exchange_weak(
current,
current + 1,
Ordering::AcqRel,
Ordering::Relaxed,
) {
Ok(_) => return true,
Err(_) => continue,
}
}
}
pub fn release(&self, host: &str) {
if let Some(entry) = self.per_host.get(host) {
let prev = entry.fetch_sub(1, Ordering::AcqRel);
debug_assert!(prev > 0, "release called more times than acquire for host");
}
let prev = self.global_count.fetch_sub(1, Ordering::AcqRel);
debug_assert!(prev > 0, "global release underflow");
}
pub fn host_count(&self, host: &str) -> usize {
self.per_host
.get(host)
.map(|e| e.load(Ordering::Relaxed))
.unwrap_or(0)
}
pub fn global_count(&self) -> usize {
self.global_count.load(Ordering::Relaxed)
}
pub fn global_limit(&self) -> usize {
self.global_limit
}
pub fn per_host_limit(&self) -> usize {
self.per_host_limit
}
pub fn available_for(&self, host: &str) -> usize {
let current = self.host_count(host);
if current >= self.per_host_limit {
return 0;
}
self.per_host_limit - current
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_connection_limiter_per_host() {
let limiter = ConnectionLimiter::new(10, 2);
assert!(
limiter.try_acquire("example.com"),
"First acquisition should succeed"
);
assert!(
limiter.try_acquire("example.com"),
"Second acquisition should succeed"
);
assert!(
!limiter.try_acquire("example.com"),
"Third acquisition should fail (per-host limit)"
);
assert!(
limiter.try_acquire("other.com"),
"Different host should work"
);
assert!(
limiter.try_acquire("other.com"),
"Second slot for other host"
);
assert!(
!limiter.try_acquire("other.com"),
"Third slot for other host should fail"
);
limiter.release("example.com");
assert!(
limiter.try_acquire("example.com"),
"After release, should acquire again"
);
assert_eq!(
limiter.available_for("example.com"),
0,
"No slots available after acquiring limit"
);
limiter.release("example.com");
assert_eq!(
limiter.available_for("example.com"),
1,
"One slot available after release"
);
}
#[tokio::test]
async fn test_connection_limiter_concurrent_no_deadlock() {
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
let limiter = Arc::new(ConnectionLimiter::new(100, 10));
let success_count = Arc::new(AtomicUsize::new(0));
let mut handles = Vec::new();
for _ in 0..20 {
let l = limiter.clone();
let s = success_count.clone();
handles.push(tokio::spawn(async move {
if l.try_acquire("example.com") {
s.fetch_add(1, Ordering::Relaxed);
}
}));
}
for h in handles {
h.await.expect("task should not panic");
}
assert_eq!(
success_count.load(Ordering::Relaxed),
10,
"per-host limit must cap successful acquires"
);
assert_eq!(
limiter.host_count("example.com"),
10,
"host_count must reflect the 10 successful acquires"
);
assert_eq!(
limiter.global_count(),
10,
"global_count must equal the 10 successful acquires"
);
for _ in 0..5 {
limiter.release("example.com");
}
assert_eq!(
limiter.host_count("example.com"),
5,
"host_count must drop to 5 after 5 releases"
);
assert_eq!(
limiter.global_count(),
5,
"global_count must drop to 5 after 5 releases"
);
}
}