use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Mutex;
use crate::plexus::schema::PluginSchema;
#[derive(Debug)]
struct Entry {
schema: PluginSchema,
seen: String,
used: u64,
}
#[derive(Debug, Default)]
struct State {
epoch: u64,
tick: u64,
map: HashMap<String, Entry>,
}
impl State {
fn at(&mut self, epoch: u64) {
if self.epoch != epoch {
self.map.clear();
self.epoch = epoch;
}
}
}
#[derive(Debug)]
pub(super) struct Names {
max: usize,
state: Mutex<State>,
pub hops: AtomicU64,
pub hits: AtomicU64,
}
impl Names {
pub fn new(max: usize) -> Self {
Self { max, state: Mutex::new(State::default()), hops: AtomicU64::new(0), hits: AtomicU64::new(0) }
}
fn state(&self) -> std::sync::MutexGuard<'_, State> {
self.state.lock().unwrap_or_else(|p| p.into_inner())
}
pub fn get(&self, path: &str, epoch: u64) -> Option<PluginSchema> {
let mut s = self.state();
s.at(epoch);
s.tick += 1;
let tick = s.tick;
let e = s.map.get_mut(path)?;
e.used = tick;
self.hits.fetch_add(1, Ordering::Relaxed);
Some(e.schema.clone())
}
pub fn crossed(&self) {
self.hops.fetch_add(1, Ordering::Relaxed);
}
pub fn put(&self, path: &str, schema: PluginSchema, seen: String, epoch: u64) {
if self.max == 0 {
return;
}
let mut s = self.state();
s.at(epoch);
s.tick += 1;
let used = s.tick;
if !s.map.contains_key(path) && s.map.len() >= self.max {
if let Some(old) = s.map.iter().min_by_key(|(_, e)| e.used).map(|(k, _)| k.clone()) {
s.map.remove(&old);
}
}
s.map.insert(path.to_string(), Entry { schema, seen, used });
}
pub fn observe(&self, instance: &str, hash: &str) {
let mut s = self.state();
let below = format!("{instance}.");
s.map.retain(|k, e| !((k == instance || k.starts_with(&below)) && e.seen != hash));
}
pub fn len(&self, epoch: u64) -> usize {
let mut s = self.state();
s.at(epoch);
s.map.len()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn schema(ns: &str) -> PluginSchema {
PluginSchema::leaf(ns, "1.0", "d", vec![])
}
#[test]
fn a_name_is_kept_once_and_answered_after() {
let n = Names::new(4);
assert!(n.get("solar.earth", 0).is_none());
n.crossed();
n.put("solar.earth", schema("planet"), "h1".into(), 0);
for _ in 0..9 {
assert_eq!(n.get("solar.earth", 0).unwrap().namespace, "planet");
}
assert_eq!((n.hops.load(Ordering::Relaxed), n.hits.load(Ordering::Relaxed), n.len(0)), (1, 9, 1));
}
#[test]
fn the_least_recently_used_name_goes_first() {
let n = Names::new(2);
n.put("a.x", schema("x"), "h".into(), 0);
n.put("a.y", schema("y"), "h".into(), 0);
assert!(n.get("a.x", 0).is_some()); n.put("a.z", schema("z"), "h".into(), 0);
assert!(n.get("a.y", 0).is_none(), "y was the least recently used");
assert!(n.get("a.x", 0).is_some() && n.get("a.z", 0).is_some());
assert_eq!(n.len(0), 2);
}
#[test]
fn zero_keeps_nothing() {
let n = Names::new(0);
n.put("a.x", schema("x"), "h".into(), 0);
assert!(n.get("a.x", 0).is_none());
}
#[test]
fn another_hash_drops_the_name_and_those_below_it() {
let n = Names::new(8);
n.put("a.x", schema("x"), "h1".into(), 0);
n.put("a.x.moon.luna", schema("moon"), "h1".into(), 0);
n.put("a.y", schema("y"), "h1".into(), 0);
n.observe("a.x", "h1");
assert_eq!(n.len(0), 3, "the same hash keeps every name");
n.observe("a.x", "h2");
assert!(n.get("a.x", 0).is_none() && n.get("a.x.moon.luna", 0).is_none());
assert!(n.get("a.y", 0).is_some(), "another name stays");
}
#[test]
fn a_restart_drops_every_name() {
let n = Names::new(8);
n.put("a.x", schema("x"), "h".into(), 0);
n.put("a.y", schema("y"), "h".into(), 0);
assert!(n.get("a.x", 1).is_none());
assert_eq!(n.len(0), 0);
}
}