use dashmap::DashMap;
use std::time::{Duration, Instant};
const DEFAULT_WORKER_IDLE_TTL_S: f64 = 3600.0;
const TTL_MARGIN: Duration = Duration::from_secs(300);
const DEFAULT_MAX_ENTRIES: usize = 4096;
struct Entry {
worker_id: String,
last_used: Instant,
}
pub struct InstanceRegistry {
map: DashMap<String, Entry>,
ttl: Option<Duration>,
max: usize,
}
impl InstanceRegistry {
pub fn from_env() -> Self {
let worker_ttl = std::env::var("ZAKURO_CLS_IDLE_TTL_S")
.ok()
.and_then(|v| v.parse::<f64>().ok())
.unwrap_or(DEFAULT_WORKER_IDLE_TTL_S);
let ttl = if worker_ttl > 0.0 && worker_ttl.is_finite() {
Some(Duration::from_secs_f64(worker_ttl) + TTL_MARGIN)
} else {
None
};
let max = std::env::var("ZC_AFFINITY_MAX")
.ok()
.and_then(|v| v.parse::<usize>().ok())
.filter(|n| *n > 0)
.unwrap_or(DEFAULT_MAX_ENTRIES);
Self::with_limits(ttl, max)
}
pub fn with_limits(ttl: Option<Duration>, max: usize) -> Self {
Self {
map: DashMap::new(),
ttl,
max: max.max(1),
}
}
fn expired(&self, e: &Entry, now: Instant) -> bool {
self.ttl
.is_some_and(|t| now.duration_since(e.last_used) > t)
}
pub fn insert(&self, instance_id: String, worker_id: String) {
let now = Instant::now();
if !self.map.contains_key(&instance_id) && self.map.len() >= self.max {
self.purge_expired();
while self.map.len() >= self.max {
let oldest = self
.map
.iter()
.min_by_key(|e| e.value().last_used)
.map(|e| e.key().clone());
match oldest {
Some(k) => {
self.map.remove(&k);
}
None => break,
}
}
}
self.map.insert(
instance_id,
Entry {
worker_id,
last_used: now,
},
);
}
pub fn get(&self, instance_id: &str) -> Option<String> {
let now = Instant::now();
let mut entry = self.map.get_mut(instance_id)?;
if self.expired(&entry, now) {
drop(entry);
self.map.remove(instance_id);
return None;
}
entry.last_used = now;
Some(entry.worker_id.clone())
}
pub fn remove(&self, instance_id: &str) -> Option<String> {
self.map.remove(instance_id).map(|(_, e)| e.worker_id)
}
pub fn retain_workers(&self, keep: impl Fn(&str) -> bool) {
self.map.retain(|_, e| keep(&e.worker_id));
}
pub fn purge_expired(&self) -> usize {
let now = Instant::now();
let before = self.map.len();
self.map.retain(|_, e| !self.expired(e, now));
before.saturating_sub(self.map.len())
}
pub fn list(&self) -> Vec<(String, String)> {
self.map
.iter()
.map(|e| (e.key().clone(), e.value().worker_id.clone()))
.collect()
}
pub fn len(&self) -> usize {
self.map.len()
}
pub fn is_empty(&self) -> bool {
self.map.is_empty()
}
}
impl Default for InstanceRegistry {
fn default() -> Self {
Self::from_env()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::thread::sleep;
#[test]
fn idle_entry_expires_and_get_refreshes() {
let r = InstanceRegistry::with_limits(Some(Duration::from_millis(80)), 10);
r.insert("a".into(), "w1".into());
r.insert("b".into(), "w1".into());
sleep(Duration::from_millis(50));
assert_eq!(r.get("a").as_deref(), Some("w1")); sleep(Duration::from_millis(50));
assert_eq!(r.get("a").as_deref(), Some("w1"));
assert_eq!(r.get("b"), None); assert_eq!(r.len(), 1);
}
#[test]
fn purge_expired_drops_idle_entries() {
let r = InstanceRegistry::with_limits(Some(Duration::from_millis(10)), 10);
r.insert("a".into(), "w1".into());
sleep(Duration::from_millis(30));
assert_eq!(r.purge_expired(), 1);
assert!(r.is_empty());
}
#[test]
fn size_is_bounded_and_lru_is_evicted() {
let r = InstanceRegistry::with_limits(None, 3);
for i in 0..3 {
r.insert(format!("i{i}"), "w".into());
sleep(Duration::from_millis(2));
}
assert!(r.get("i0").is_some()); sleep(Duration::from_millis(2));
r.insert("i3".into(), "w".into());
assert_eq!(r.len(), 3);
assert_eq!(r.get("i1"), None);
assert!(r.get("i0").is_some() && r.get("i2").is_some() && r.get("i3").is_some());
for i in 10..100 {
r.insert(format!("n{i}"), "w".into());
}
assert_eq!(r.len(), 3);
}
#[test]
fn remove_and_retain() {
let r = InstanceRegistry::with_limits(None, 10);
r.insert("a".into(), "w1".into());
r.insert("b".into(), "w2".into());
assert_eq!(r.remove("a").as_deref(), Some("w1"));
r.retain_workers(|w| w != "w2");
assert!(r.is_empty());
}
}