use std::sync::{
Arc,
atomic::{AtomicUsize, Ordering},
};
#[derive(Debug, Clone)]
pub struct ConnectionLimiter {
active: Arc<AtomicUsize>,
max: usize,
}
impl ConnectionLimiter {
#[must_use]
pub(crate) fn new(max: usize) -> Self {
Self {
active: Arc::new(AtomicUsize::new(0)),
max,
}
}
pub fn try_acquire(&self) -> Result<ConnectionSlot, usize> {
let active = self.active.fetch_add(1, Ordering::SeqCst) + 1;
if active > self.max {
self.active.fetch_sub(1, Ordering::SeqCst);
Err(active - 1)
} else {
Ok(ConnectionSlot {
active: Arc::clone(&self.active),
})
}
}
}
pub const PRE_AUTH_HANDSHAKE_MULTIPLIER: usize = 4;
#[derive(Debug)]
pub struct ConnectionSlot {
active: Arc<AtomicUsize>,
}
impl Drop for ConnectionSlot {
fn drop(&mut self) {
self.active.fetch_sub(1, Ordering::SeqCst);
}
}
#[cfg(test)]
mod limiter_tests {
use super::ConnectionLimiter;
use crate::serve::connection;
use std::sync::atomic::Ordering;
#[test]
fn acquires_up_to_max_and_refuses_the_next() {
let limiter = ConnectionLimiter::new(2);
let a = limiter
.try_acquire()
.expect("1st connection is under the cap");
let b = limiter
.try_acquire()
.expect("2nd connection is exactly at the cap");
let refused = limiter
.try_acquire()
.expect_err("3rd connection is over the cap");
assert_eq!(
refused, 2,
"the refusal should report the active count that caused it"
);
drop(a);
let c = limiter
.try_acquire()
.expect("a slot freed by drop can be reacquired");
drop(b);
drop(c);
assert_eq!(limiter.active.load(Ordering::SeqCst), 0);
}
#[test]
fn a_refused_attempt_never_permanently_eats_into_the_cap() {
let limiter = ConnectionLimiter::new(1);
let _held = limiter.try_acquire().unwrap();
for _ in 0..5 {
limiter.try_acquire().unwrap_err();
}
assert_eq!(limiter.active.load(Ordering::SeqCst), 1);
}
#[test]
fn the_slot_releases_its_count_even_when_the_holder_panics() {
let limiter = ConnectionLimiter::new(1);
let slot = limiter.try_acquire().unwrap();
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let _slot = slot; panic!("simulated connection-thread panic while holding a ConnectionSlot");
}));
assert!(result.is_err());
assert_eq!(limiter.active.load(Ordering::SeqCst), 0);
}
#[test]
fn refuse_for_capacity_writes_a_decodable_error_naming_the_capacity_code() {
let mut buf: Vec<u8> = Vec::new();
connection::refuse_for_capacity(&mut buf, None, 64, 64);
let mut cursor = std::io::Cursor::new(buf);
let err: indicatrix_net::messages::ErrorMsg =
indicatrix_net::messages::read_message(&mut cursor).unwrap();
assert_eq!(err.code, connection::CONNECTION_LIMIT_REACHED_CODE);
assert!(err.message.contains("64"), "{}", err.message);
}
}