use alloc::collections::VecDeque;
use core::net::{IpAddr, SocketAddr};
use std::collections::HashMap;
use std::time::Instant;
use crate::id::PeerId;
use crate::store::{DEFAULT_IPV6_PREFIX, WaitingLimits, source_key};
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Admission {
pub record: bool,
pub evict: Vec<PeerId>,
}
#[derive(Debug, Clone)]
pub struct WaitingQueue {
limits: WaitingLimits,
ipv6_prefix: u8,
sources: HashMap<Option<IpAddr>, VecDeque<(PeerId, Instant)>>,
}
impl WaitingQueue {
pub fn new(limits: WaitingLimits) -> Self {
Self {
limits,
ipv6_prefix: DEFAULT_IPV6_PREFIX,
sources: HashMap::new(),
}
}
#[must_use]
pub fn with_ipv6_prefix(mut self, bits: u8) -> Self {
self.ipv6_prefix = bits.min(128);
self
}
pub fn limits(&self) -> WaitingLimits {
self.limits
}
pub fn ipv6_prefix(&self) -> u8 {
self.ipv6_prefix
}
pub fn admit(
&mut self,
id: PeerId,
source: Option<SocketAddr>,
stored: usize,
now: Instant,
) -> Admission {
let refused = Admission {
record: false,
evict: Vec::new(),
};
if stored >= self.limits.total {
return refused;
}
let bucket = source.map(|source| source_key(source.ip(), self.ipv6_prefix));
let held = self.sources.entry(bucket).or_default();
if held.iter().any(|(had, at)| {
*had == id && now.saturating_duration_since(*at) < self.limits.rerecord
}) {
return refused;
}
held.retain(|(had, _)| *had != id);
held.push_back((id, now));
let mut evict = Vec::new();
while held.len() > self.limits.per_source {
if let Some((old, _)) = held.pop_front() {
evict.push(old);
}
}
Admission {
record: true,
evict,
}
}
pub fn remember(&mut self, id: PeerId, source: Option<SocketAddr>, at: Instant) -> Vec<PeerId> {
let bucket = source.map(|source| source_key(source.ip(), self.ipv6_prefix));
let held = self.sources.entry(bucket).or_default();
held.retain(|(had, _)| *had != id);
let position = held
.iter()
.position(|(_, when)| *when > at)
.unwrap_or(held.len());
held.insert(position, (id, at));
let mut forgotten = Vec::new();
while held.len() > self.limits.per_source {
if let Some((old, _)) = held.pop_front() {
forgotten.push(old);
}
}
forgotten
}
pub fn prune(&mut self, now: Instant, stored: impl Fn(&PeerId) -> bool) {
let rerecord = self.limits.rerecord;
for held in self.sources.values_mut() {
held.retain(|(id, at)| stored(id) || now.saturating_duration_since(*at) < rerecord);
}
self.sources.retain(|_, held| !held.is_empty());
}
pub fn len(&self) -> usize {
self.sources.values().map(VecDeque::len).sum()
}
pub fn is_empty(&self) -> bool {
self.sources.is_empty()
}
pub fn forget(&mut self, id: &PeerId) {
for held in self.sources.values_mut() {
held.retain(|(had, _)| had != id);
}
self.sources.retain(|_, held| !held.is_empty());
}
}