| 1 | use std::time::Duration; |
| 2 | |
| 3 | use common::time; |
| 4 | use tracing::{error, info}; |
| 5 | |
| 6 | use crate::{db, error::ServerError, network::Shared, publish::job, request::messages_deleted}; |
| 7 | |
| 8 | const SWEEP_INTERVAL: Duration = Duration::from_millis(time::HOUR_MILLIS); |
| 9 | const BATCH_SIZE: u32 = 500; |
| 10 | |
| 11 | pub(crate) async fn collect(shared: Shared) { |
| 12 | let mut interval = tokio::time::interval(SWEEP_INTERVAL); |
| 13 | loop { |
| 14 | interval.tick().await; |
| 15 | if let Err(error) = sweep(&shared).await { |
| 16 | error!("retention sweep: {error}"); |
| 17 | } |
| 18 | } |
| 19 | } |
| 20 | |
| 21 | fn cutoff(days: u32) -> u64 { |
| 22 | time::now_ms().saturating_sub(u64::from(days) * time::DAY_MILLIS) |
| 23 | } |
| 24 | |
| 25 | async fn purge_messages(cutoff: u64, shared: &Shared) -> Result<u64, ServerError> { |
| 26 | let mut purged = 0; |
| 27 | loop { |
| 28 | let mut deleted = 0; |
| 29 | job(shared, async |db| { |
| 30 | let rows = db::message::delete_before(cutoff, BATCH_SIZE, db).await?; |
| 31 | deleted = rows.len() as u64; |
| 32 | |
| 33 | Ok(messages_deleted(rows)) |
| 34 | }) |
| 35 | .await?; |
| 36 | if deleted == 0 { |
| 37 | return Ok(purged); |
| 38 | } |
| 39 | purged += deleted; |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | async fn purge_attachments(cutoff: u64, shared: &Shared) -> Result<u64, ServerError> { |
| 44 | let mut purged = 0; |
| 45 | loop { |
| 46 | let mut deleted = 0; |
| 47 | job(shared, async |db| { |
| 48 | deleted = db::attachment::delete_before(cutoff, BATCH_SIZE, db).await?; |
| 49 | |
| 50 | Ok(Vec::new()) |
| 51 | }) |
| 52 | .await?; |
| 53 | if deleted == 0 { |
| 54 | return Ok(purged); |
| 55 | } |
| 56 | purged += deleted; |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | async fn sweep(shared: &Shared) -> Result<(), ServerError> { |
| 61 | let settings = shared.db.run(db::settings::read).await?; |
| 62 | |
| 63 | let messages = match settings.message_retention_days { |
| 64 | 0 => 0, |
| 65 | days => purge_messages(cutoff(days), shared).await?, |
| 66 | }; |
| 67 | let attachments = match settings.attachment_retention_days { |
| 68 | 0 => 0, |
| 69 | days => purge_attachments(cutoff(days), shared).await?, |
| 70 | }; |
| 71 | |
| 72 | if messages + attachments > 0 { |
| 73 | info!("retention deleted {messages} messages, {attachments} attachments"); |
| 74 | } |
| 75 | |
| 76 | Ok(()) |
| 77 | } |