1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
use super::throttle::Client;
type Held = Arc<Mutex<HashMap<Client, usize>>>;
#[derive(Clone, Copy, Debug)]
pub struct Visitor {
pub client: Client,
pub signed_in: bool,
}
pub struct Pool {
open: Arc<Semaphore>,
reserved: Arc<Semaphore>,
per_client: usize,
held: Held,
}
pub struct Slot {
_permit: OwnedSemaphorePermit,
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(),
}
}
pub fn try_acquire(&self, visitor: Visitor) -> Option<Slot> {
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<Slot> =
(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<Slot> = (0..4).map(|_| pool.try_acquire(owner()).unwrap()).collect();
assert_eq!(held.len(), 4);
}
}