//! How many expensive requests (page renders, raw downloads, clones) may run at once, and who //! may use the slots, so anonymous traffic can never crowd out the signed-in owner. //! //! A [`Pool`] has open slots, which anyone may use, and reserved slots, which only signed-in //! sessions may use (they take an open slot when the reserved ones are busy). An anonymous //! client may also hold only a few slots at once, so one address can't take them all; clients //! are identified as in sign-in throttling (an IPv4 address or IPv6 /64). use std::collections::HashMap; use std::sync::{Arc, Mutex}; use tokio::sync::{OwnedSemaphorePermit, Semaphore}; use super::throttle::Client; /// How many slots each anonymous client holds, shared between a pool and its slots. type Held = Arc>>; /// Who is asking for a slot. #[derive(Clone, Copy, Debug)] pub struct Visitor { pub client: Client, pub signed_in: bool, } pub struct Pool { open: Arc, reserved: Arc, per_client: usize, held: Held, } /// A slot in a [`Pool`], given back when dropped. pub struct Slot { _permit: OwnedSemaphorePermit, /// The anonymous client this slot counts against. counted: Option<(Held, Client)>, } impl Drop for Slot { fn drop(&mut self) { if let Some((held, client)) = &self.counted { let mut held = held.lock().unwrap_or_else(|e| e.into_inner()); if let Some(count) = held.get_mut(client) { *count -= 1; if *count == 0 { held.remove(client); } } } } } impl Pool { pub fn new(open: usize, reserved: usize, per_client: usize) -> Pool { Pool { open: Arc::new(Semaphore::new(open)), reserved: Arc::new(Semaphore::new(reserved)), per_client, held: Arc::default(), } } /// A slot for `visitor` now, or `None` if none is free to them: the caller answers busy. pub fn try_acquire(&self, visitor: Visitor) -> Option { if visitor.signed_in { let permit = Arc::clone(&self.reserved).try_acquire_owned().or_else(|_| Arc::clone(&self.open).try_acquire_owned()); return permit.ok().map(|permit| Slot { _permit: permit, counted: None }); } let mut held = self.held.lock().unwrap_or_else(|e| e.into_inner()); let count = held.entry(visitor.client).or_insert(0); let permit = (*count < self.per_client).then(|| Arc::clone(&self.open).try_acquire_owned().ok()).flatten(); match permit { Some(permit) => { *count += 1; Some(Slot { _permit: permit, counted: Some((Arc::clone(&self.held), visitor.client)) }) } None => { if *count == 0 { held.remove(&visitor.client); } None } } } } #[cfg(test)] mod tests { use super::*; fn anonymous(address: &str) -> Visitor { Visitor { client: Client::new(address.parse().unwrap()), signed_in: false } } fn owner() -> Visitor { Visitor { signed_in: true, ..anonymous("198.51.100.1") } } #[test] fn anonymous_traffic_cannot_take_the_reserved_slots() { let pool = Pool::new(4, 2, 1); let taken: Vec = (0..4).map(|i| pool.try_acquire(anonymous(&format!("203.0.113.{i}"))).unwrap()).collect(); assert!(pool.try_acquire(anonymous("203.0.113.99")).is_none(), "the open slots are full"); let first = pool.try_acquire(owner()).expect("the owner gets a reserved slot"); let second = pool.try_acquire(owner()).expect("and another"); assert!(pool.try_acquire(owner()).is_none(), "all slots are busy"); drop(taken); assert!(pool.try_acquire(owner()).is_some(), "the owner may also use open slots"); drop((first, second)); } #[test] fn one_anonymous_client_holds_only_its_share() { let pool = Pool::new(8, 0, 2); let a = anonymous("203.0.113.7"); let held = [pool.try_acquire(a).unwrap(), pool.try_acquire(a).unwrap()]; assert!(pool.try_acquire(a).is_none(), "a third slot for the same client"); assert!(pool.try_acquire(anonymous("2001:db8::1")).is_some(), "another client still gets one"); drop(held); assert!(pool.try_acquire(a).is_some(), "slots come back when dropped"); assert!(pool.held.lock().unwrap().is_empty(), "no client is remembered once it holds nothing"); } #[test] fn signed_in_sessions_have_no_per_client_cap() { let pool = Pool::new(4, 0, 1); let held: Vec = (0..4).map(|_| pool.try_acquire(owner()).unwrap()).collect(); assert_eq!(held.len(), 4); } }