use crate::checker::Checker;
use crate::persist::Store;
use crate::proxy::Proxy;
use crate::server::Pool;
use rand::Rng;
use std::cmp::Reverse;
use std::collections::{BinaryHeap, HashMap, HashSet};
use std::net::IpAddr;
use std::sync::Arc;
use std::time::Duration;
use tokio::time::Instant;
use tokio_util::sync::CancellationToken;
type Key = (IpAddr, u16);
#[derive(Debug, Clone)]
pub struct RecheckConfig {
pub min_interval: Duration,
pub max_interval: Duration,
pub rate_per_sec: f64,
pub decay_halflife: Duration,
}
impl Default for RecheckConfig {
fn default() -> Self {
RecheckConfig {
min_interval: Duration::from_secs(60),
max_interval: Duration::from_secs(3600),
rate_per_sec: 5.0,
decay_halflife: Duration::from_secs(21_600), }
}
}
pub fn next_interval(ewma: f64, cfg: &RecheckConfig) -> Duration {
let e = ewma.clamp(0.0, 1.0);
let min = cfg.min_interval.as_secs_f64();
let max = cfg.max_interval.as_secs_f64();
Duration::from_secs_f64(min + e * (max - min))
}
pub fn decayed_score(ewma: f64, latency: f64, age: Duration, cfg: &RecheckConfig) -> f64 {
let base = ewma.clamp(0.0, 1.0) / (1.0 + latency.max(0.0));
let hl = cfg.decay_halflife.as_secs_f64();
let decay = if hl > 0.0 {
0.5f64.powf(age.as_secs_f64() / hl)
} else {
1.0
};
base * decay
}
fn should_retry(ewma: f64, latency: f64, age: Duration, cfg: &RecheckConfig) -> bool {
decayed_score(ewma, latency, age, cfg) >= EVICT_FLOOR
}
pub struct RecheckHandle {
cancel: CancellationToken,
}
impl RecheckHandle {
pub fn shutdown(&self) {
self.cancel.cancel();
}
}
impl Drop for RecheckHandle {
fn drop(&mut self) {
self.cancel.cancel();
}
}
struct Scheduled {
due: Instant,
host: std::net::IpAddr,
port: u16,
}
impl PartialEq for Scheduled {
fn eq(&self, o: &Self) -> bool {
self.due == o.due
}
}
impl Eq for Scheduled {}
impl PartialOrd for Scheduled {
fn partial_cmp(&self, o: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(o))
}
}
impl Ord for Scheduled {
fn cmp(&self, o: &Self) -> std::cmp::Ordering {
self.due.cmp(&o.due)
}
}
const EVICT_FLOOR: f64 = 0.02;
pub fn spawn_rechecker(
pool: Arc<Pool>,
checker: Arc<Checker>,
store: Arc<dyn Store>,
cfg: RecheckConfig,
) -> RecheckHandle {
let cancel = CancellationToken::new();
let handle_cancel = cancel.clone();
tokio::spawn(async move {
let mut heap: BinaryHeap<Reverse<Scheduled>> = BinaryHeap::new();
let mut ewma: HashMap<Key, f64> = HashMap::new();
let mut last_ok: HashMap<Key, Instant> = HashMap::new();
let mut retrying: HashSet<Key> = HashSet::new();
let gap = Duration::from_secs_f64(1.0 / cfg.rate_per_sec.max(0.001));
let mut next_start = Instant::now();
loop {
let now = Instant::now();
for (host, port) in pool.addrs() {
if let std::collections::hash_map::Entry::Vacant(slot) = ewma.entry((host, port)) {
slot.insert(1.0); last_ok.insert((host, port), now);
heap.push(Reverse(Scheduled {
due: now + jitter(cfg.min_interval),
host,
port,
}));
}
}
let Some(Reverse(top)) = heap.peek() else {
tokio::select! {
_ = cancel.cancelled() => break,
_ = tokio::time::sleep(cfg.min_interval) => {}
}
continue;
};
let due = top.due;
let wake = due.min(Instant::now() + cfg.min_interval);
tokio::select! {
_ = cancel.cancelled() => break,
_ = tokio::time::sleep_until(wake) => {}
}
if Instant::now() < due {
continue; }
let start_at = next_start.max(Instant::now());
tokio::select! {
_ = cancel.cancelled() => break,
_ = tokio::time::sleep_until(start_at) => {}
}
next_start = start_at + gap;
let Reverse(job) = heap.pop().expect("peeked");
let key = (job.host, job.port);
if !retrying.contains(&key) && !pool.addrs().contains(&key) {
ewma.remove(&key);
last_ok.remove(&key);
continue;
}
let mut proxy = Proxy::new(job.host, job.port, std::collections::BTreeSet::new());
let working = checker.check(&mut proxy).await;
let _ = store.upsert(&proxy);
let sample = if working { 1.0 } else { 0.0 };
let prev = ewma.get(&key).copied().unwrap_or(1.0);
let e = 0.3 * sample + 0.7 * prev;
ewma.insert(key, e);
let now = Instant::now();
let next_due = now + next_interval(e, &cfg) + jitter(cfg.min_interval);
if working {
last_ok.insert(key, now);
retrying.remove(&key);
pool.add(proxy); heap.push(Reverse(Scheduled {
due: next_due,
host: job.host,
port: job.port,
}));
} else {
pool.remove_addr(job.host, job.port);
let age = now.saturating_duration_since(*last_ok.get(&key).unwrap_or(&now));
if should_retry(e, proxy.avg_resp_time(), age, &cfg) {
retrying.insert(key);
heap.push(Reverse(Scheduled {
due: next_due,
host: job.host,
port: job.port,
}));
} else {
ewma.remove(&key);
last_ok.remove(&key);
retrying.remove(&key);
}
}
}
});
RecheckHandle {
cancel: handle_cancel,
}
}
fn jitter(base: Duration) -> Duration {
let f = 1.0 + rand::rng().random_range(-0.5..=0.5);
Duration::from_secs_f64(base.as_secs_f64() * f)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cadence_grows_with_stability() {
let cfg = RecheckConfig {
min_interval: Duration::from_secs(60),
max_interval: Duration::from_secs(3600),
..Default::default()
};
assert_eq!(next_interval(0.0, &cfg), Duration::from_secs(60)); assert_eq!(next_interval(1.0, &cfg), Duration::from_secs(3600)); assert!(next_interval(1.0, &cfg) > next_interval(0.0, &cfg));
assert!(next_interval(0.9, &cfg) >= next_interval(0.4, &cfg));
assert_eq!(next_interval(2.0, &cfg), Duration::from_secs(3600));
}
#[test]
fn decay_halves_score_at_one_half_life() {
let cfg = RecheckConfig {
decay_halflife: Duration::from_secs(3600),
..Default::default()
};
let fresh = decayed_score(1.0, 0.5, Duration::ZERO, &cfg);
let one_hl = decayed_score(1.0, 0.5, Duration::from_secs(3600), &cfg);
assert!(
(one_hl - fresh * 0.5).abs() < 1e-9,
"half-life must halve the score"
);
let two_hl = decayed_score(1.0, 0.5, Duration::from_secs(7200), &cfg);
assert!((two_hl - fresh * 0.25).abs() < 1e-9);
}
#[test]
fn staleness_drives_eviction() {
let cfg = RecheckConfig {
decay_halflife: Duration::from_secs(60),
..Default::default()
};
assert!(
should_retry(0.5, 0.0, Duration::ZERO, &cfg),
"a decent, just-seen score keeps being retried"
);
assert!(
!should_retry(0.5, 0.0, Duration::from_secs(600), &cfg),
"ten half-lives of staleness must decay below the evict floor"
);
}
#[test]
fn zero_halflife_does_not_nan() {
let cfg = RecheckConfig {
decay_halflife: Duration::ZERO,
..Default::default()
};
let s0 = decayed_score(1.0, 0.0, Duration::ZERO, &cfg);
let s1 = decayed_score(1.0, 0.0, Duration::from_secs(3600), &cfg);
assert!(
s0.is_finite() && s1.is_finite(),
"no NaN/Inf from a zero half-life"
);
assert!(should_retry(0.5, 0.0, Duration::from_secs(3600), &cfg));
}
}