use super::ops::OpsEvent;
use super::state::WebState;
const ADOPT_LIMIT: usize = 200;
const SWEEP_COOLDOWN: std::time::Duration = std::time::Duration::from_secs(20);
pub fn spawn(state: WebState) {
tokio::spawn(async move {
let adopted = state.ops.adopt_recent_logs(ADOPT_LIMIT).await;
if adopted > 0 {
tracing::info!(adopted, "read earlier operation logs back into history");
}
sweep_now(&state).await;
let mut events = state.ops.subscribe();
let mut last_sweep = std::time::Instant::now();
loop {
let event = match events.recv().await {
Ok(event) => event,
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
};
if !matches!(event, OpsEvent::Completed(_) | OpsEvent::Failed(_)) {
continue;
}
if last_sweep.elapsed() < SWEEP_COOLDOWN {
continue;
}
last_sweep = std::time::Instant::now();
sweep_now(&state).await;
}
});
}
pub async fn sweep_now(state: &WebState) {
sweep_logs(state).await;
}
async fn sweep_logs(state: &WebState) {
let Some(root) = state.ops.logs_root().map(std::path::Path::to_path_buf) else {
return;
};
let protected = state.ops.protected_logs().await;
let max_bytes = super::handlers::settings::configured_max_bytes();
let report = match tokio::task::spawn_blocking(move || {
wsb::logs::sweep(&root, max_bytes, &protected, false)
})
.await
{
Ok(report) => report,
Err(error) => {
tracing::warn!(%error, "the log sweep panicked");
return;
}
};
if !report.removed.is_empty() {
tracing::info!(
removed = report.removed.len(),
freed = %wsb::logs::human_bytes(report.freed_bytes),
remaining = %wsb::logs::human_bytes(report.remaining_bytes),
limit = %wsb::logs::human_bytes(max_bytes),
"swept old logs"
);
}
if report.still_over {
tracing::warn!(
remaining = %wsb::logs::human_bytes(report.remaining_bytes),
limit = %wsb::logs::human_bytes(max_bytes),
protected = report.protected,
unreachable = %wsb::logs::human_bytes(report.unreachable_bytes),
"the logs directory is over its limit; what is left is in use or \
is not something a sweep manages"
);
}
}