//! The sweeper worker: housekeeping that is not urgent. It runs once at start and then every hour until the //! stop flag is set. Each run deletes expired sessions and expired logout-token records, retries the //! attachment copies still owed (the deleter in `attachments.rs` does this too, every few seconds; this pass //! is the backstop), deletes activity and mail-ledger rows older than `RETENTION_DAYS`, deletes audit rows //! older than `AUDIT_RETENTION_DAYS`, and removes staged uploads left in `data_dir/tmp` by a crash. //! //! It never deletes live data: pending mail, pending deletions that are not yet due, and sessions that have //! not expired are left alone. A failed step is logged and the next step still runs. use std::future::Future; use std::path::Path; use std::time::{Duration, SystemTime}; use iz_core::staging::TMP_DIR; use iz_core::store::audit::AUDIT_RETENTION_DAYS; use iz_core::store::sweep::RETENTION_DAYS; use jiff::{SignedDuration, Timestamp}; use tokio::sync::watch; use crate::attachments; use crate::state::AppState; /// How often the sweeper runs after its first pass. Reason: none of this is urgent. const SWEEP_EVERY: Duration = Duration::from_secs(60 * 60); /// Rows deleted per statement. Reason: keeps each write short so the writer is not held for long. const BATCH: i64 = 500; /// A staged upload older than this is an orphan. Reason: no upload stays in staging for a day. const TEMP_MAX_AGE: Duration = Duration::from_secs(24 * 60 * 60); /// Starts the sweeper. It runs at once, then every [`SWEEP_EVERY`], until `stop` is set. pub fn spawn(state: AppState, mut stop: watch::Receiver) { tokio::spawn(async move { loop { sweep(&state).await; tokio::select! { () = tokio::time::sleep(SWEEP_EVERY) => {} _ = stop.wait_for(|stopped| *stopped) => break, } } tracing::info!("sweeper stopped"); }); } /// One full run. Each step is independent: a failure is logged and the run goes on. async fn sweep(state: &AppState) { note("expired sessions", state.store.sweep_sessions().await); note("expired logout tokens", state.store.sweep_jti().await); attachments::sweep(state).await; match Timestamp::now().checked_sub(SignedDuration::from_hours(24 * RETENTION_DAYS)) { Ok(cutoff) => { drain("activity", |batch| { state.store.prune_activity(cutoff, batch) }) .await; drain("mail decisions", |batch| { state.store.prune_mail_decisions(cutoff, batch) }) .await; drain("finished mail", |batch| { state.store.prune_mail_outbox(cutoff, batch) }) .await; } Err(error) => { tracing::warn!(error = %error, "retention cutoff is out of range; not pruned") } } match Timestamp::now().checked_sub(SignedDuration::from_hours(24 * AUDIT_RETENTION_DAYS)) { Ok(cutoff) => { drain("audit rows", |batch| state.store.prune_audit(cutoff, batch)).await; } Err(error) => { tracing::warn!(error = %error, "retention cutoff is out of range; not pruned") } } note( "stale staged uploads", remove_stale_temp_files(&state.config.data_dir).await, ); } /// Logs a step's count when it is not zero, and logs a failed step. Returns nothing: a sweep step has no /// result the caller needs. fn note(what: &str, result: iz_core::Result) { match result { Ok(0) => {} Ok(count) => tracing::info!(count, what, "sweeper removed rows"), Err(error) => tracing::warn!(error = %error, what, "sweeper step failed"), } } /// Runs a batched delete until a batch comes back short, a batch fails, or the step runs out of rows. Logs /// the total when it is not zero. async fn drain(what: &str, mut step: F) where F: FnMut(i64) -> Fut, Fut: Future>, { let mut total: u64 = 0; loop { match step(BATCH).await { Ok(deleted) => { total += deleted; if deleted < u64::try_from(BATCH).unwrap_or(0) { break; } } Err(error) => { tracing::warn!(error = %error, what, "sweeper batch failed"); break; } } } note(what, Ok(total)); } /// Removes regular files in `data_dir/tmp` that were last changed more than [`TEMP_MAX_AGE`] ago. A missing /// staging directory means there is nothing to remove. Links and directories are left alone. async fn remove_stale_temp_files(data_dir: &Path) -> iz_core::Result { let dir = data_dir.join(TMP_DIR); let mut entries = match tokio::fs::read_dir(&dir).await { Ok(entries) => entries, Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(0), Err(error) => return Err(error.into()), }; let cutoff = SystemTime::now() .checked_sub(TEMP_MAX_AGE) .unwrap_or(SystemTime::UNIX_EPOCH); let mut removed: u64 = 0; while let Some(entry) = entries.next_entry().await? { let meta = entry.metadata().await?; if !meta.is_file() { continue; } if meta.modified()? < cutoff { tokio::fs::remove_file(entry.path()).await?; removed += 1; } } Ok(removed) }