use core::time::Duration;
use std::collections::BTreeMap;
use std::sync::{Arc, Mutex, PoisonError};
use tokio::time::Instant;
use super::DOG_SILENCE_BUDGET;
const PEER_CONTACT_CAPACITY: usize = 1024;
pub(super) const PEER_CONTACT_WARMUP: Duration = DOG_SILENCE_BUDGET;
#[derive(Debug, Clone, Default)]
pub struct PeerContacts {
seen: Arc<Mutex<Contacts>>,
}
#[derive(Debug)]
struct Contacts {
watching_since: Instant,
by_pid: BTreeMap<u32, Seen>,
clock: u64,
}
#[derive(Debug)]
struct Seen {
named_a_dog: bool,
touched: u64,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Contact {
None,
Anonymous,
Named,
Unknown,
}
impl PeerContacts {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn connected(&self, pid: u32) {
let mut seen = self.lock();
seen.clock = seen.clock.saturating_add(1);
let clock = seen.clock;
match seen.by_pid.get_mut(&pid) {
Some(entry) => entry.touched = clock,
None => {
seen.by_pid.insert(
pid,
Seen {
named_a_dog: false,
touched: clock,
},
);
seen.evict_oldest();
}
}
}
pub fn named_a_dog(&self, pid: u32) {
let mut seen = self.lock();
seen.clock = seen.clock.saturating_add(1);
let clock = seen.clock;
let entry = seen.by_pid.entry(pid).or_insert(Seen {
named_a_dog: false,
touched: clock,
});
entry.named_a_dog = true;
entry.touched = clock;
seen.evict_oldest();
}
#[must_use]
pub fn is_warming(&self) -> bool {
self.lock().watching_since.elapsed() < PEER_CONTACT_WARMUP
}
#[cfg(test)]
pub(crate) fn force_warm(&self) {
let mut seen = self.lock();
seen.watching_since = Instant::now() - PEER_CONTACT_WARMUP * 2;
}
#[must_use]
pub fn from_pid(&self, pid: Option<u32>) -> Contact {
let Some(pid) = pid else {
return Contact::Unknown;
};
let seen = self.lock();
match seen.by_pid.get(&pid) {
None if seen.watching_since.elapsed() < PEER_CONTACT_WARMUP => Contact::Unknown,
None => Contact::None,
Some(seen) if seen.named_a_dog => Contact::Named,
Some(_) => Contact::Anonymous,
}
}
fn lock(&self) -> std::sync::MutexGuard<'_, Contacts> {
self.seen.lock().unwrap_or_else(PoisonError::into_inner)
}
}
impl Default for Contacts {
fn default() -> Self {
Self {
watching_since: Instant::now(),
by_pid: BTreeMap::new(),
clock: 0,
}
}
}
impl Contacts {
fn evict_oldest(&mut self) {
if self.by_pid.len() <= PEER_CONTACT_CAPACITY {
return;
}
let oldest = self
.by_pid
.iter()
.min_by_key(|(_, seen)| seen.touched)
.map(|(pid, _)| *pid);
if let Some(pid) = oldest {
self.by_pid.remove(&pid);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::dogs::verdict::{Silence, stale_verdict};
#[tokio::test(start_paused = true)]
async fn a_pid_that_never_called_is_told_apart_from_one_that_called_anonymously() {
let contacts = PeerContacts::new();
tokio::time::advance(PEER_CONTACT_WARMUP * 2).await;
assert_eq!(
contacts.from_pid(Some(4242)),
Contact::None,
"nothing has connected from this pid, and that is a finding"
);
assert_eq!(
contacts.from_pid(None),
Contact::Unknown,
"no pid to ask about is not the same as a pid nothing came from"
);
contacts.connected(4242);
assert_eq!(
contacts.from_pid(Some(4242)),
Contact::Anonymous,
"a connection that named no dog is exactly the case the operator lost two days to"
);
contacts.named_a_dog(4242);
assert_eq!(contacts.from_pid(Some(4242)), Contact::Named);
}
#[tokio::test(start_paused = true)]
async fn a_cold_map_does_not_claim_a_pid_never_called() {
let contacts = PeerContacts::new();
assert_eq!(
contacts.from_pid(Some(4242)),
Contact::Unknown,
"a map this new was not listening long enough for an absence to mean anything"
);
assert_eq!(
stale_verdict("metrics", Silence::of(Some(4242), &contacts)),
stale_verdict("metrics", Silence::Unattributed),
"an unwarmed map must reach the arm that names both candidates"
);
tokio::time::advance(PEER_CONTACT_WARMUP - Duration::from_millis(1)).await;
assert_eq!(contacts.from_pid(Some(4242)), Contact::Unknown);
tokio::time::advance(Duration::from_millis(2)).await;
assert_eq!(
contacts.from_pid(Some(4242)),
Contact::None,
"shep was listening for a whole budget past the dog's silence"
);
assert!(
stale_verdict("metrics", Silence::of(Some(4242), &contacts))
.contains("cannot reach this shep"),
"the earned reinstall advice must survive"
);
}
#[test]
fn a_pid_that_has_named_a_dog_goes_on_having_named_one() {
let contacts = PeerContacts::new();
contacts.named_a_dog(7);
contacts.connected(7);
assert_eq!(contacts.from_pid(Some(7)), Contact::Named);
}
#[tokio::test(start_paused = true)]
async fn a_full_map_forgets_the_pid_that_stopped_calling() {
let contacts = PeerContacts::new();
tokio::time::advance(PEER_CONTACT_WARMUP * 2).await;
let dog = 1;
contacts.named_a_dog(dog);
for pid in 2..=u32::try_from(PEER_CONTACT_CAPACITY).unwrap() {
contacts.connected(pid);
if pid % 8 == 0 {
contacts.connected(dog);
}
}
let stranger = 2;
for pid in 1_000_000..1_000_100 {
contacts.connected(pid);
}
assert_eq!(
contacts.from_pid(Some(dog)),
Contact::Named,
"a peer that keeps calling must outlive a hundred that called once"
);
assert_eq!(
contacts.from_pid(Some(stranger)),
Contact::None,
"the oldest untouched entry is the one the bound spends"
);
assert!(
contacts.lock().by_pid.len() <= PEER_CONTACT_CAPACITY,
"the map must not grow past its bound"
);
}
}