use std::sync::Arc;
use std::time::Duration;
use tokio::sync::watch;
use tokio::task::JoinHandle;
use crate::store::Store;
const DEFAULT_SWEEP_INTERVAL_SEC: u64 = 10;
pub struct DigestSweeperHandle {
shutdown_tx: watch::Sender<bool>,
task: Option<JoinHandle<()>>,
}
impl DigestSweeperHandle {
pub async fn shutdown(mut self) {
let _ = self.shutdown_tx.send(true);
if let Some(task) = self.task.take() {
let _ = task.await;
}
}
pub fn is_running(&self) -> bool {
self.task.is_some()
}
}
impl Drop for DigestSweeperHandle {
fn drop(&mut self) {
let _ = self.shutdown_tx.send(true);
if let Some(task) = self.task.take() {
task.abort();
}
}
}
pub fn spawn_digest_sweeper<S>(store: Arc<S>, interval: Duration) -> DigestSweeperHandle
where
S: Store + Send + Sync + 'static,
{
let (shutdown_tx, mut shutdown_rx) = watch::channel(false);
if interval.is_zero() {
tracing::info!("digest sweeper disabled (interval = 0)");
let _ = shutdown_tx.send(true);
return DigestSweeperHandle {
shutdown_tx,
task: None,
};
}
tracing::info!(
interval_ms = interval.as_millis() as u64,
"spawning background digest sweeper"
);
let task = tokio::spawn(async move {
let mut ticker = tokio::time::interval(interval);
ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
ticker.tick().await;
loop {
tokio::select! {
_ = ticker.tick() => {
let rebuilt =
crate::mcp::handlers::sweep_dirty_digests(&*store).await;
if rebuilt > 0 {
tracing::debug!(
rebuilt,
"background digest sweeper refreshed dirty digests"
);
}
}
changed = shutdown_rx.changed() => {
if changed.is_err() || *shutdown_rx.borrow() {
tracing::info!("background digest sweeper stopping");
return;
}
}
}
}
});
DigestSweeperHandle {
shutdown_tx,
task: Some(task),
}
}
pub fn resolve_sweep_interval_from_env() -> Duration {
let secs = std::env::var("MEMD_DIGEST_SWEEP_INTERVAL_SEC")
.ok()
.and_then(|v| v.parse::<u64>().ok())
.unwrap_or(DEFAULT_SWEEP_INTERVAL_SEC);
Duration::from_secs(secs)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::store::MemoryStore;
use crate::task_memory::digest_dirty::{global, DigestDirtyKey};
use std::time::Duration;
#[tokio::test]
async fn sweeper_drains_dirty_keys_on_tick() {
let _ = global().drain_dirty();
let store = Arc::new(MemoryStore::new());
let handle = spawn_digest_sweeper(store, Duration::from_millis(80));
global().mark_dirty(DigestDirtyKey {
tenant_id: "sweeper_tick".to_string(),
project_id: Some("proj".to_string()),
role: crate::task_memory::DIGEST_ROLE_EVIDENCE_LIBRARY.to_string(),
});
let drained_within = tokio::time::timeout(Duration::from_millis(500), async {
loop {
let peeked = global().contains(&DigestDirtyKey {
tenant_id: "sweeper_tick".to_string(),
project_id: Some("proj".to_string()),
role: crate::task_memory::DIGEST_ROLE_EVIDENCE_LIBRARY.to_string(),
});
if !peeked {
return ();
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
})
.await;
handle.shutdown().await;
drained_within.expect("sweeper must drain the dirty key within 500ms");
}
#[tokio::test]
async fn interval_zero_disables_sweeper() {
let store = Arc::new(MemoryStore::new());
let handle = spawn_digest_sweeper(store, Duration::ZERO);
assert!(
!handle.is_running(),
"interval=0 must not spawn a background task"
);
handle.shutdown().await;
}
}