use std::time::Duration;
use tokio_util::sync::CancellationToken;
const DEFAULT_SWEEP_INTERVAL: Duration = Duration::from_secs(10);
const DEFAULT_EVICTION_THRESHOLD: u32 = 30;
#[derive(Clone)]
pub struct SweepConfig {
pub interval: Duration,
pub eviction_threshold: u32,
}
impl Default for SweepConfig {
fn default() -> Self {
Self {
interval: DEFAULT_SWEEP_INTERVAL,
eviction_threshold: DEFAULT_EVICTION_THRESHOLD,
}
}
}
impl SweepConfig {
pub fn new() -> Self {
Self::default()
}
pub fn with_interval(mut self, interval: Duration) -> Self {
self.interval = interval;
self
}
pub fn with_eviction_threshold(mut self, threshold: u32) -> Self {
self.eviction_threshold = threshold;
self
}
}
pub async fn run<F>(config: SweepConfig, cancel: CancellationToken, mut sweep_fn: F)
where
F: FnMut(u32) -> usize,
{
use tokio::time::MissedTickBehavior;
log::info!(
"Starting stale-series sweeper, interval={}s, eviction_threshold={}",
config.interval.as_secs(),
config.eviction_threshold
);
let mut interval = tokio::time::interval(config.interval);
interval.set_missed_tick_behavior(MissedTickBehavior::Skip);
interval.tick().await;
loop {
tokio::select! {
_ = interval.tick() => {}
_ = cancel.cancelled() => {
log::info!("Stale-series sweeper shutting down");
return;
}
}
let evicted = sweep_fn(config.eviction_threshold);
if evicted > 0 {
log::debug!("Evicted {evicted} stale metric series");
}
}
}