forge
Explore
Log in

Don't you dare go Hollow

in

Clone
★ 0

0 watching0 forksRustAGPL-3.0528.7 KiB9215377Tahinli27 days ago37 commits

sweeper.rs343 lines, 13.3 KiBHistoryRawDownload
1//! The hourly sweeper. It removes what has expired or is no longer named by any row, and nothing else. Each
2//! pass does these steps, and a failed step is logged while the others still run:
3//!
4//! - sessions past their expiry, back-channel logout ids past their expiry, and open uploads not finished in
5//! 24 hours, with their staging directories;
6//! - staging directories under `data_dir/uploads` that no open upload names and that are at least 24 hours old.
7//! This is what retries a removal that failed earlier: the expiry step has already deleted the row;
8//! the directory is the only record left;
9//! - trash older than `purge_after_days` (a setting, 30 by default), with its bytes;
10//! - audit rows older than `AUDIT_RETENTION_DAYS` (365), in batches of `AUDIT_PURGE_BATCH`;
11//! - blobs under `files/`, `thumbs/` and `objects/` that no row names and that are at least 24 hours old;
12//! - leftover files in `data_dir/tmp` at least 24 hours old;
13//! - once a day, the quota check: every member's `used_bytes` is recomputed from their files, and any
14//! difference is logged and corrected.
15//!
16//! The rows go first, in their own transactions; the bytes are deleted after the row that named them is gone.
17//! No blob is removed while a row names it, and none younger than 24 hours is removed for lacking a row, which
18//! covers a write whose row has not yet committed.
19
20use std::collections::HashSet;
21use std::path::Path;
22use std::time::{Duration, SystemTime};
23
24use in_core::error::Result;
25use in_core::staging::{TMP_DIR, UPLOADS_DIR, remove_upload_dir, upload_dir};
26use in_core::store::audit::AUDIT_RETENTION_DAYS;
27use in_core::time::{now_stamp, stamp_before};
28use tokio::sync::watch;
29
30use crate::state::AppState;
31
32/// Time between two passes: one hour.
33pub const SWEEP_EVERY: Duration = Duration::from_secs(60 * 60);
34
35/// Age a blob or a staged file must reach before the sweeper may remove it for lacking a row: 24 hours.
36pub const ORPHAN_GRACE: Duration = Duration::from_secs(24 * 60 * 60);
37
38/// The settings key that records when the quota check last ran.
39const DRIFT_SETTING: &str = "quota_drift_checked_at";
40
41/// Time between two quota checks: a day.
42const DRIFT_EVERY: Duration = Duration::from_secs(24 * 60 * 60);
43
44/// The blob prefixes the sweeper owns. `objects/` is included because the `objects` table names its keys.
45const BLOB_PREFIXES: [&str; 3] = ["files/", "thumbs/", "objects/"];
46
47/// Runs passes until the stop flag is set.
48pub async fn run(state: AppState, mut stop: watch::Receiver<bool>) {
49 loop {
50 if let Err(error) = sweep(&state).await {
51 tracing::warn!(error = %error, "sweeper: pass failed");
52 }
53 tokio::select! {
54 _ = stop.wait_for(|stopped| *stopped) => return,
55 () = tokio::time::sleep(SWEEP_EVERY) => {}
56 }
57 }
58}
59
60/// One pass. The expiry steps come first; each later step is independent, so a failure in one is logged and
61/// the rest still run.
62pub async fn sweep(state: &AppState) -> Result<()> {
63 let now = now_stamp();
64 let sessions = state.store.sweep_expired_sessions(&now).await?;
65 let jtis = state.store.sweep_jti(&now).await?;
66 let uploads = state.store.expire_uploads(&now).await?;
67 for id in &uploads {
68 if let Err(error) = remove_upload_dir(&state.config.data_dir, id).await {
69 tracing::warn!(upload = %id, error = %error, "sweeper: staging directory not removed");
70 }
71 }
72 tracing::info!(
73 sessions,
74 seen_logout_ids = jtis,
75 expired_uploads = uploads.len(),
76 "sweeper: pass done"
77 );
78 log_step(
79 "upload dirs",
80 sweep_upload_dirs(state, SystemTime::now()).await,
81 );
82 log_step("trash", purge_trash(state).await);
83 log_step("audit", purge_audit(state).await);
84 log_step("blobs", sweep_blobs(state, SystemTime::now()).await);
85 log_step(
86 "tmp",
87 sweep_tmp(&state.config.data_dir, SystemTime::now()).await,
88 );
89 log_step("quota", check_quota_drift(state).await);
90 Ok(())
91}
92
93/// Logs a failed step and drops its error, so one failing step does not stop the pass.
94fn log_step<T>(step: &str, outcome: Result<T>) {
95 if let Err(error) = outcome {
96 tracing::warn!(step, error = %error, "sweeper: step failed");
97 }
98}
99
100/// The number of days trash is kept: the setting when it holds a number, else the default. Clamped to 1 to
101/// 3650 days.
102pub async fn purge_after_days(state: &AppState) -> Result<u64> {
103 let resolved = in_core::settings::resolve(
104 &state.store,
105 &state.config.limits,
106 in_core::settings::PURGE_KEY,
107 )
108 .await?;
109 Ok(u64::try_from(resolved.value).unwrap_or(1).clamp(1, 3650))
110}
111
112/// Purges trash older than the retention period, and deletes the bytes the store released. The rows go first;
113/// a blob that fails to delete is logged and left for a later pass to find as unreferenced.
114async fn purge_trash(state: &AppState) -> Result<usize> {
115 let days = purge_after_days(state).await?;
116 let cutoff = stamp_before(Duration::from_secs(days * 24 * 60 * 60));
117 let keys = state.store.purge_trashed_before(&cutoff).await?;
118 let count = keys.len();
119 for key in &keys {
120 if let Err(error) = state.blobs.delete(key).await {
121 tracing::warn!(key = %key, error = %error, "sweeper: released blob not deleted");
122 }
123 }
124 if count > 0 {
125 tracing::info!(released_blobs = count, "sweeper: trash purged");
126 }
127 Ok(count)
128}
129
130/// Removes audit rows older than [`AUDIT_RETENTION_DAYS`]. The store deletes them in batches, so a large backlog
131/// is cleared over several statements and the writer lock is free between them.
132async fn purge_audit(state: &AppState) -> Result<u64> {
133 let cutoff = stamp_before(Duration::from_secs(AUDIT_RETENTION_DAYS * 24 * 60 * 60));
134 let removed = state.store.purge_audit_before(&cutoff).await?;
135 if removed > 0 {
136 tracing::info!(audit_rows = removed, "sweeper: audit rows purged");
137 }
138 Ok(removed)
139}
140
141/// True when `modified` is at least [`ORPHAN_GRACE`] before `now`. A timestamp in the future counts as young.
142fn is_old(modified: SystemTime, now: SystemTime) -> bool {
143 now.duration_since(modified)
144 .is_ok_and(|age| age >= ORPHAN_GRACE)
145}
146
147/// Removes the blobs that no row names and that are at least [`ORPHAN_GRACE`] old, as of `now`. The set of
148/// referenced keys is read before the listing, so a blob written in between is young and kept.
149pub async fn sweep_blobs(state: &AppState, now: SystemTime) -> Result<usize> {
150 let referenced: HashSet<String> = state
151 .store
152 .referenced_blob_keys()
153 .await?
154 .into_iter()
155 .collect();
156 let mut removed = 0;
157 for prefix in BLOB_PREFIXES {
158 for (key, _size, modified) in state.blobs.list(prefix).await? {
159 if referenced.contains(&key) || !is_old(modified, now) {
160 continue;
161 }
162 match state.blobs.delete(&key).await {
163 Ok(()) => removed += 1,
164 Err(error) => {
165 tracing::warn!(key = %key, error = %error, "sweeper: orphan blob not deleted");
166 }
167 }
168 }
169 }
170 if removed > 0 {
171 tracing::info!(
172 orphan_blobs = removed,
173 "sweeper: unreferenced blobs removed"
174 );
175 }
176 Ok(removed)
177}
178
179/// Removes the staging directories under `data_dir/uploads` that no open upload names and that are at least
180/// [`ORPHAN_GRACE`] old, as of `now`. Only a direct child of that directory whose name is a well-formed upload
181/// id is removed; symbolic links and other entries are left alone.
182pub async fn sweep_upload_dirs(state: &AppState, now: SystemTime) -> Result<usize> {
183 let root = state.config.data_dir.join(UPLOADS_DIR);
184 let mut entries = match tokio::fs::read_dir(&root).await {
185 Ok(entries) => entries,
186 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(0),
187 Err(error) => return Err(error.into()),
188 };
189 let mut removed = 0;
190 while let Some(entry) = entries.next_entry().await? {
191 let Some(id) = entry.file_name().to_str().map(str::to_owned) else {
192 continue;
193 };
194 // `upload_dir` accepts only a well-formed upload id, and the path must be a direct child of the root.
195 let Ok(dir) = upload_dir(&state.config.data_dir, &id) else {
196 continue;
197 };
198 if dir.parent() != Some(root.as_path()) {
199 continue;
200 }
201 let Ok(meta) = tokio::fs::symlink_metadata(&dir).await else {
202 continue;
203 };
204 if !meta.is_dir() {
205 continue;
206 }
207 let Ok(modified) = meta.modified() else {
208 continue;
209 };
210 if !is_old(modified, now) || state.store.upload_is_open(&id).await? {
211 continue;
212 }
213 match remove_upload_dir(&state.config.data_dir, &id).await {
214 Ok(()) => removed += 1,
215 Err(error) => {
216 tracing::warn!(upload = %id, error = %error, "sweeper: staging directory not removed");
217 }
218 }
219 }
220 if removed > 0 {
221 tracing::info!(
222 staging_dirs = removed,
223 "sweeper: staging directories removed"
224 );
225 }
226 Ok(removed)
227}
228
229/// Removes the plain files in `data_dir/tmp` that are at least [`ORPHAN_GRACE`] old. Links are never followed,
230/// and only regular files are removed. The directory is the fixed staging directory of the data directory.
231pub async fn sweep_tmp(data_dir: &Path, now: SystemTime) -> Result<usize> {
232 let dir = data_dir.join(TMP_DIR);
233 let mut entries = match tokio::fs::read_dir(&dir).await {
234 Ok(entries) => entries,
235 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(0),
236 Err(error) => return Err(error.into()),
237 };
238 let mut removed = 0;
239 while let Some(entry) = entries.next_entry().await? {
240 let path = entry.path();
241 let Ok(meta) = tokio::fs::symlink_metadata(&path).await else {
242 continue;
243 };
244 if !meta.is_file() {
245 continue;
246 }
247 let Ok(modified) = meta.modified() else {
248 continue;
249 };
250 if !is_old(modified, now) {
251 continue;
252 }
253 match tokio::fs::remove_file(&path).await {
254 Ok(()) => removed += 1,
255 Err(error) => tracing::warn!(error = %error, "sweeper: staged leftover not removed"),
256 }
257 }
258 if removed > 0 {
259 tracing::info!(
260 staged_leftovers = removed,
261 "sweeper: staging leftovers removed"
262 );
263 }
264 Ok(removed)
265}
266
267/// Recomputes every member's used bytes from their files, at most once a day. Each difference is logged with
268/// the stored and the true value, and then corrected. Returns the number of members corrected.
269pub async fn check_quota_drift(state: &AppState) -> Result<usize> {
270 if let Some(last) = state.store.get_setting(DRIFT_SETTING).await?
271 && last > stamp_before(DRIFT_EVERY)
272 {
273 return Ok(0);
274 }
275 let drift = state.store.reconcile_quota().await?;
276 for item in &drift {
277 tracing::warn!(
278 member = %item.sub,
279 stored = item.stored,
280 actual = item.actual,
281 "sweeper: quota drift corrected"
282 );
283 }
284 state.store.set_setting(DRIFT_SETTING, &now_stamp()).await?;
285 Ok(drift.len())
286}
287
288#[cfg(test)]
289mod tests {
290 use super::*;
291 use crate::auth::test_support::signed_in;
292 use crate::boot::test_state;
293 use in_core::quota::DEFAULT_MEMBER_QUOTA;
294 use in_core::staging::StagedFile;
295 use in_core::store::files::{NewFile, files_blob_key};
296 use in_core::store::new_id;
297
298 /// Stores `bytes` under `key`, as an upload would: staged, then moved into the blob store.
299 async fn put_bytes(state: &AppState, key: &str, bytes: &[u8]) {
300 let mut staged = StagedFile::create(&state.config.data_dir, 1 << 20)
301 .await
302 .expect("staging");
303 staged.write(bytes).await.expect("write");
304 let staged = staged.finish().await.expect("finish");
305 state.blobs.put_file(key, &staged.path).await.expect("blob");
306 }
307
308 /// A referenced blob survives every pass. An unreferenced blob survives while it is young and goes once it
309 /// is older than the grace period.
310 #[tokio::test]
311 async fn referenced_blobs_stay_and_young_orphans_stay() {
312 let (_dir, state) = test_state().await;
313 let _ = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await;
314 let id = new_id();
315 let kept = files_blob_key(&id);
316 put_bytes(&state, &kept, b"kept").await;
317 state
318 .store
319 .insert_file(NewFile {
320 id,
321 owner: "ann".into(),
322 folder: None,
323 name: "kept.txt".into(),
324 mime: "text/plain".into(),
325 size: 4,
326 sha256: "0".repeat(64),
327 staged_claims: 0,
328 })
329 .await
330 .expect("row");
331 let orphan = "objects/svc-1/orphan";
332 put_bytes(&state, orphan, b"orphan").await;
333
334 assert_eq!(
335 sweep_blobs(&state, SystemTime::now()).await.expect("pass"),
336 0
337 );
338 let later = SystemTime::now() + ORPHAN_GRACE + Duration::from_secs(3600);
339 assert_eq!(sweep_blobs(&state, later).await.expect("pass"), 1);
340 assert_eq!(state.blobs.size(&kept).await.expect("size"), Some(4));
341 assert_eq!(state.blobs.size(orphan).await.expect("size"), None);
342 }
343}