//! The hourly sweeper. It removes what has expired or is no longer named by any row, and nothing else. Each //! pass does these steps, and a failed step is logged while the others still run: //! //! - sessions past their expiry, back-channel logout ids past their expiry, and open uploads not finished in //! 24 hours, with their staging directories; //! - staging directories under `data_dir/uploads` that no open upload names and that are at least 24 hours old. //! This is what retries a removal that failed earlier: the expiry step has already deleted the row; //! the directory is the only record left; //! - trash older than `purge_after_days` (a setting, 30 by default), with its bytes; //! - audit rows older than `AUDIT_RETENTION_DAYS` (365), in batches of `AUDIT_PURGE_BATCH`; //! - blobs under `files/`, `thumbs/` and `objects/` that no row names and that are at least 24 hours old; //! - leftover files in `data_dir/tmp` at least 24 hours old; //! - once a day, the quota check: every member's `used_bytes` is recomputed from their files, and any //! difference is logged and corrected. //! //! The rows go first, in their own transactions; the bytes are deleted after the row that named them is gone. //! No blob is removed while a row names it, and none younger than 24 hours is removed for lacking a row, which //! covers a write whose row has not yet committed. use std::collections::HashSet; use std::path::Path; use std::time::{Duration, SystemTime}; use in_core::error::Result; use in_core::staging::{TMP_DIR, UPLOADS_DIR, remove_upload_dir, upload_dir}; use in_core::store::audit::AUDIT_RETENTION_DAYS; use in_core::time::{now_stamp, stamp_before}; use tokio::sync::watch; use crate::state::AppState; /// Time between two passes: one hour. pub const SWEEP_EVERY: Duration = Duration::from_secs(60 * 60); /// Age a blob or a staged file must reach before the sweeper may remove it for lacking a row: 24 hours. pub const ORPHAN_GRACE: Duration = Duration::from_secs(24 * 60 * 60); /// The settings key that records when the quota check last ran. const DRIFT_SETTING: &str = "quota_drift_checked_at"; /// Time between two quota checks: a day. const DRIFT_EVERY: Duration = Duration::from_secs(24 * 60 * 60); /// The blob prefixes the sweeper owns. `objects/` is included because the `objects` table names its keys. const BLOB_PREFIXES: [&str; 3] = ["files/", "thumbs/", "objects/"]; /// Runs passes until the stop flag is set. pub async fn run(state: AppState, mut stop: watch::Receiver) { loop { if let Err(error) = sweep(&state).await { tracing::warn!(error = %error, "sweeper: pass failed"); } tokio::select! { _ = stop.wait_for(|stopped| *stopped) => return, () = tokio::time::sleep(SWEEP_EVERY) => {} } } } /// One pass. The expiry steps come first; each later step is independent, so a failure in one is logged and /// the rest still run. pub async fn sweep(state: &AppState) -> Result<()> { let now = now_stamp(); let sessions = state.store.sweep_expired_sessions(&now).await?; let jtis = state.store.sweep_jti(&now).await?; let uploads = state.store.expire_uploads(&now).await?; for id in &uploads { if let Err(error) = remove_upload_dir(&state.config.data_dir, id).await { tracing::warn!(upload = %id, error = %error, "sweeper: staging directory not removed"); } } tracing::info!( sessions, seen_logout_ids = jtis, expired_uploads = uploads.len(), "sweeper: pass done" ); log_step( "upload dirs", sweep_upload_dirs(state, SystemTime::now()).await, ); log_step("trash", purge_trash(state).await); log_step("audit", purge_audit(state).await); log_step("blobs", sweep_blobs(state, SystemTime::now()).await); log_step( "tmp", sweep_tmp(&state.config.data_dir, SystemTime::now()).await, ); log_step("quota", check_quota_drift(state).await); Ok(()) } /// Logs a failed step and drops its error, so one failing step does not stop the pass. fn log_step(step: &str, outcome: Result) { if let Err(error) = outcome { tracing::warn!(step, error = %error, "sweeper: step failed"); } } /// The number of days trash is kept: the setting when it holds a number, else the default. Clamped to 1 to /// 3650 days. pub async fn purge_after_days(state: &AppState) -> Result { let resolved = in_core::settings::resolve( &state.store, &state.config.limits, in_core::settings::PURGE_KEY, ) .await?; Ok(u64::try_from(resolved.value).unwrap_or(1).clamp(1, 3650)) } /// Purges trash older than the retention period, and deletes the bytes the store released. The rows go first; /// a blob that fails to delete is logged and left for a later pass to find as unreferenced. async fn purge_trash(state: &AppState) -> Result { let days = purge_after_days(state).await?; let cutoff = stamp_before(Duration::from_secs(days * 24 * 60 * 60)); let keys = state.store.purge_trashed_before(&cutoff).await?; let count = keys.len(); for key in &keys { if let Err(error) = state.blobs.delete(key).await { tracing::warn!(key = %key, error = %error, "sweeper: released blob not deleted"); } } if count > 0 { tracing::info!(released_blobs = count, "sweeper: trash purged"); } Ok(count) } /// Removes audit rows older than [`AUDIT_RETENTION_DAYS`]. The store deletes them in batches, so a large backlog /// is cleared over several statements and the writer lock is free between them. async fn purge_audit(state: &AppState) -> Result { let cutoff = stamp_before(Duration::from_secs(AUDIT_RETENTION_DAYS * 24 * 60 * 60)); let removed = state.store.purge_audit_before(&cutoff).await?; if removed > 0 { tracing::info!(audit_rows = removed, "sweeper: audit rows purged"); } Ok(removed) } /// True when `modified` is at least [`ORPHAN_GRACE`] before `now`. A timestamp in the future counts as young. fn is_old(modified: SystemTime, now: SystemTime) -> bool { now.duration_since(modified) .is_ok_and(|age| age >= ORPHAN_GRACE) } /// Removes the blobs that no row names and that are at least [`ORPHAN_GRACE`] old, as of `now`. The set of /// referenced keys is read before the listing, so a blob written in between is young and kept. pub async fn sweep_blobs(state: &AppState, now: SystemTime) -> Result { let referenced: HashSet = state .store .referenced_blob_keys() .await? .into_iter() .collect(); let mut removed = 0; for prefix in BLOB_PREFIXES { for (key, _size, modified) in state.blobs.list(prefix).await? { if referenced.contains(&key) || !is_old(modified, now) { continue; } match state.blobs.delete(&key).await { Ok(()) => removed += 1, Err(error) => { tracing::warn!(key = %key, error = %error, "sweeper: orphan blob not deleted"); } } } } if removed > 0 { tracing::info!( orphan_blobs = removed, "sweeper: unreferenced blobs removed" ); } Ok(removed) } /// Removes the staging directories under `data_dir/uploads` that no open upload names and that are at least /// [`ORPHAN_GRACE`] old, as of `now`. Only a direct child of that directory whose name is a well-formed upload /// id is removed; symbolic links and other entries are left alone. pub async fn sweep_upload_dirs(state: &AppState, now: SystemTime) -> Result { let root = state.config.data_dir.join(UPLOADS_DIR); let mut entries = match tokio::fs::read_dir(&root).await { Ok(entries) => entries, Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(0), Err(error) => return Err(error.into()), }; let mut removed = 0; while let Some(entry) = entries.next_entry().await? { let Some(id) = entry.file_name().to_str().map(str::to_owned) else { continue; }; // `upload_dir` accepts only a well-formed upload id, and the path must be a direct child of the root. let Ok(dir) = upload_dir(&state.config.data_dir, &id) else { continue; }; if dir.parent() != Some(root.as_path()) { continue; } let Ok(meta) = tokio::fs::symlink_metadata(&dir).await else { continue; }; if !meta.is_dir() { continue; } let Ok(modified) = meta.modified() else { continue; }; if !is_old(modified, now) || state.store.upload_is_open(&id).await? { continue; } match remove_upload_dir(&state.config.data_dir, &id).await { Ok(()) => removed += 1, Err(error) => { tracing::warn!(upload = %id, error = %error, "sweeper: staging directory not removed"); } } } if removed > 0 { tracing::info!( staging_dirs = removed, "sweeper: staging directories removed" ); } Ok(removed) } /// Removes the plain files in `data_dir/tmp` that are at least [`ORPHAN_GRACE`] old. Links are never followed, /// and only regular files are removed. The directory is the fixed staging directory of the data directory. pub async fn sweep_tmp(data_dir: &Path, now: SystemTime) -> 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 mut removed = 0; while let Some(entry) = entries.next_entry().await? { let path = entry.path(); let Ok(meta) = tokio::fs::symlink_metadata(&path).await else { continue; }; if !meta.is_file() { continue; } let Ok(modified) = meta.modified() else { continue; }; if !is_old(modified, now) { continue; } match tokio::fs::remove_file(&path).await { Ok(()) => removed += 1, Err(error) => tracing::warn!(error = %error, "sweeper: staged leftover not removed"), } } if removed > 0 { tracing::info!( staged_leftovers = removed, "sweeper: staging leftovers removed" ); } Ok(removed) } /// Recomputes every member's used bytes from their files, at most once a day. Each difference is logged with /// the stored and the true value, and then corrected. Returns the number of members corrected. pub async fn check_quota_drift(state: &AppState) -> Result { if let Some(last) = state.store.get_setting(DRIFT_SETTING).await? && last > stamp_before(DRIFT_EVERY) { return Ok(0); } let drift = state.store.reconcile_quota().await?; for item in &drift { tracing::warn!( member = %item.sub, stored = item.stored, actual = item.actual, "sweeper: quota drift corrected" ); } state.store.set_setting(DRIFT_SETTING, &now_stamp()).await?; Ok(drift.len()) } #[cfg(test)] mod tests { use super::*; use crate::auth::test_support::signed_in; use crate::boot::test_state; use in_core::quota::DEFAULT_MEMBER_QUOTA; use in_core::staging::StagedFile; use in_core::store::files::{NewFile, files_blob_key}; use in_core::store::new_id; /// Stores `bytes` under `key`, as an upload would: staged, then moved into the blob store. async fn put_bytes(state: &AppState, key: &str, bytes: &[u8]) { let mut staged = StagedFile::create(&state.config.data_dir, 1 << 20) .await .expect("staging"); staged.write(bytes).await.expect("write"); let staged = staged.finish().await.expect("finish"); state.blobs.put_file(key, &staged.path).await.expect("blob"); } /// A referenced blob survives every pass. An unreferenced blob survives while it is young and goes once it /// is older than the grace period. #[tokio::test] async fn referenced_blobs_stay_and_young_orphans_stay() { let (_dir, state) = test_state().await; let _ = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; let id = new_id(); let kept = files_blob_key(&id); put_bytes(&state, &kept, b"kept").await; state .store .insert_file(NewFile { id, owner: "ann".into(), folder: None, name: "kept.txt".into(), mime: "text/plain".into(), size: 4, sha256: "0".repeat(64), staged_claims: 0, }) .await .expect("row"); let orphan = "objects/svc-1/orphan"; put_bytes(&state, orphan, b"orphan").await; assert_eq!( sweep_blobs(&state, SystemTime::now()).await.expect("pass"), 0 ); let later = SystemTime::now() + ORPHAN_GRACE + Duration::from_secs(3600); assert_eq!(sweep_blobs(&state, later).await.expect("pass"), 1); assert_eq!(state.blobs.size(&kept).await.expect("size"), Some(4)); assert_eq!(state.blobs.size(orphan).await.expect("size"), None); } }