forge
Explore
Log in

Don't you dare go Hollow

iz

Clone
★ 0

0 watching0 forksRustAGPL-3.0567.3 KiB3950aceTahinli27 days ago34 commits

sweeper.rs141 lines, 5.4 KiBHistoryRawDownload
1//! The sweeper worker: housekeeping that is not urgent. It runs once at start and then every hour until the
2//! stop flag is set. Each run deletes expired sessions and expired logout-token records, retries the
3//! attachment copies still owed (the deleter in `attachments.rs` does this too, every few seconds; this pass
4//! is the backstop), deletes activity and mail-ledger rows older than `RETENTION_DAYS`, deletes audit rows
5//! older than `AUDIT_RETENTION_DAYS`, and removes staged uploads left in `data_dir/tmp` by a crash.
6//!
7//! It never deletes live data: pending mail, pending deletions that are not yet due, and sessions that have
8//! not expired are left alone. A failed step is logged and the next step still runs.
9
10use std::future::Future;
11use std::path::Path;
12use std::time::{Duration, SystemTime};
13
14use iz_core::staging::TMP_DIR;
15use iz_core::store::audit::AUDIT_RETENTION_DAYS;
16use iz_core::store::sweep::RETENTION_DAYS;
17use jiff::{SignedDuration, Timestamp};
18use tokio::sync::watch;
19
20use crate::attachments;
21use crate::state::AppState;
22
23/// How often the sweeper runs after its first pass. Reason: none of this is urgent.
24const SWEEP_EVERY: Duration = Duration::from_secs(60 * 60);
25/// Rows deleted per statement. Reason: keeps each write short so the writer is not held for long.
26const BATCH: i64 = 500;
27/// A staged upload older than this is an orphan. Reason: no upload stays in staging for a day.
28const TEMP_MAX_AGE: Duration = Duration::from_secs(24 * 60 * 60);
29
30/// Starts the sweeper. It runs at once, then every [`SWEEP_EVERY`], until `stop` is set.
31pub fn spawn(state: AppState, mut stop: watch::Receiver<bool>) {
32 tokio::spawn(async move {
33 loop {
34 sweep(&state).await;
35 tokio::select! {
36 () = tokio::time::sleep(SWEEP_EVERY) => {}
37 _ = stop.wait_for(|stopped| *stopped) => break,
38 }
39 }
40 tracing::info!("sweeper stopped");
41 });
42}
43
44/// One full run. Each step is independent: a failure is logged and the run goes on.
45async fn sweep(state: &AppState) {
46 note("expired sessions", state.store.sweep_sessions().await);
47 note("expired logout tokens", state.store.sweep_jti().await);
48 attachments::sweep(state).await;
49 match Timestamp::now().checked_sub(SignedDuration::from_hours(24 * RETENTION_DAYS)) {
50 Ok(cutoff) => {
51 drain("activity", |batch| {
52 state.store.prune_activity(cutoff, batch)
53 })
54 .await;
55 drain("mail decisions", |batch| {
56 state.store.prune_mail_decisions(cutoff, batch)
57 })
58 .await;
59 drain("finished mail", |batch| {
60 state.store.prune_mail_outbox(cutoff, batch)
61 })
62 .await;
63 }
64 Err(error) => {
65 tracing::warn!(error = %error, "retention cutoff is out of range; not pruned")
66 }
67 }
68 match Timestamp::now().checked_sub(SignedDuration::from_hours(24 * AUDIT_RETENTION_DAYS)) {
69 Ok(cutoff) => {
70 drain("audit rows", |batch| state.store.prune_audit(cutoff, batch)).await;
71 }
72 Err(error) => {
73 tracing::warn!(error = %error, "retention cutoff is out of range; not pruned")
74 }
75 }
76 note(
77 "stale staged uploads",
78 remove_stale_temp_files(&state.config.data_dir).await,
79 );
80}
81
82/// Logs a step's count when it is not zero, and logs a failed step. Returns nothing: a sweep step has no
83/// result the caller needs.
84fn note(what: &str, result: iz_core::Result<u64>) {
85 match result {
86 Ok(0) => {}
87 Ok(count) => tracing::info!(count, what, "sweeper removed rows"),
88 Err(error) => tracing::warn!(error = %error, what, "sweeper step failed"),
89 }
90}
91
92/// Runs a batched delete until a batch comes back short, a batch fails, or the step runs out of rows. Logs
93/// the total when it is not zero.
94async fn drain<F, Fut>(what: &str, mut step: F)
95where
96 F: FnMut(i64) -> Fut,
97 Fut: Future<Output = iz_core::Result<u64>>,
98{
99 let mut total: u64 = 0;
100 loop {
101 match step(BATCH).await {
102 Ok(deleted) => {
103 total += deleted;
104 if deleted < u64::try_from(BATCH).unwrap_or(0) {
105 break;
106 }
107 }
108 Err(error) => {
109 tracing::warn!(error = %error, what, "sweeper batch failed");
110 break;
111 }
112 }
113 }
114 note(what, Ok(total));
115}
116
117/// Removes regular files in `data_dir/tmp` that were last changed more than [`TEMP_MAX_AGE`] ago. A missing
118/// staging directory means there is nothing to remove. Links and directories are left alone.
119async fn remove_stale_temp_files(data_dir: &Path) -> iz_core::Result<u64> {
120 let dir = data_dir.join(TMP_DIR);
121 let mut entries = match tokio::fs::read_dir(&dir).await {
122 Ok(entries) => entries,
123 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(0),
124 Err(error) => return Err(error.into()),
125 };
126 let cutoff = SystemTime::now()
127 .checked_sub(TEMP_MAX_AGE)
128 .unwrap_or(SystemTime::UNIX_EPOCH);
129 let mut removed: u64 = 0;
130 while let Some(entry) = entries.next_entry().await? {
131 let meta = entry.metadata().await?;
132 if !meta.is_file() {
133 continue;
134 }
135 if meta.modified()? < cutoff {
136 tokio::fs::remove_file(entry.path()).await?;
137 removed += 1;
138 }
139 }
140 Ok(removed)
141}