use std::time::Duration; use common::time; use tracing::{error, info}; use crate::{ call::shared::messages_deleted, db::{self, Connection}, error::ServerError, network::Shared, publish::{Broadcast, job}, }; const SWEEP_INTERVAL: Duration = Duration::from_millis(time::HOUR_MILLIS); const BATCH_SIZE: u32 = 500; pub(crate) async fn collect(shared: Shared) { let mut interval = tokio::time::interval(SWEEP_INTERVAL); loop { interval.tick().await; if let Err(error) = sweep(&shared).await { error!("retention sweep: {error}"); } } } fn cutoff(days: u32) -> u64 { time::now_ms().saturating_sub(u64::from(days) * time::DAY_MILLIS) } async fn purge( shared: &Shared, batch: impl AsyncFn(&Connection) -> Result<(u64, Vec), ServerError>, ) -> Result { let mut purged = 0; loop { let mut deleted = 0; job(shared, async |db| { let (count, broadcasts) = batch(db).await?; deleted = count; Ok(broadcasts) }) .await?; if deleted == 0 { return Ok(purged); } purged += deleted; } } async fn sweep(shared: &Shared) -> Result<(), ServerError> { let settings = shared.db.run(db::settings::read).await?; let messages = match settings.message_retention_days { 0 => 0, days => { let cutoff = cutoff(days); purge(shared, async |db| { let rows = db::message::delete_before(cutoff, BATCH_SIZE, db).await?; Ok((rows.len() as u64, messages_deleted(rows))) }) .await? } }; let attachments = match settings.attachment_retention_days { 0 => 0, days => { let cutoff = cutoff(days); purge(shared, async |db| { let deleted = db::attachment::delete_before(cutoff, BATCH_SIZE, db).await?; Ok((deleted, Vec::new())) }) .await? } }; if messages + attachments > 0 { info!("retention deleted {messages} messages, {attachments} attachments"); } Ok(()) }