forge
Explore
Log in

Don't you dare go Hollow

iz

Clone
★ 0

0 watching0 forksRustAGPL-3.0567.3 KiB3950aceTahinli27 days ago34 commits

attachments.rs227 lines, 8.9 KiBHistoryRawDownload
1//! The deleter: the attachments' disk and Files-service work that runs outside a request. A deleted
2//! attachment's row is gone at once (the transaction in `iz-core` records the copies it owes in
3//! `blob_deletions`, one record per place); this worker removes them and retries with a backoff until they are
4//! gone, then clears the record. It runs until the stop flag is set, like every worker
5//! (`docs/architecture.md` section 8).
6//!
7//! The rules that keep a live copy safe are the same ones the mover follows (`mover.rs`). Every step that
8//! touches a copy, or the row that says where the bytes are, holds `AppState::blob_lock`. Under that lock, a
9//! record is judged against the row as it is then:
10//! - the row is `moving`: a move is under way, so the record waits;
11//! - the row is in the record's own place: the record is stale, and the copy is the live one, so nothing is removed;
12//! - the row is gone, or is in the other place: the owed copy is removed.
13//!
14//! Local copies are removed only through `iz_core::staging::remove_blob`, which builds the path from the validated
15//! attachment id. Files-service copies are removed with `DELETE`, which counts a missing object as done.
16
17use std::time::Duration;
18
19use iz_core::staging::remove_blob;
20use iz_core::store::attachments::{LOCATION_IN, LOCATION_LOCAL, LOCATION_MOVING};
21use tokio::sync::watch;
22
23use crate::state::AppState;
24
25/// The largest body of one upload request, in bytes. Reason: several files may come in one form, each up to the
26/// per-file limit (at most 500 MiB), and this bounds the whole request.
27pub const UPLOAD_REQUEST_MAX_BYTES: usize = 1024 * 1024 * 1024;
28/// How often the deleter looks for due deletions. Reason: a deleted file should be gone within seconds.
29const SWEEP_EVERY: Duration = Duration::from_secs(5);
30/// Most deletions one sweep handles. Reason: bounds one sweep when many files are deleted at once.
31const SWEEP_BATCH: i64 = 50;
32/// The first retry delay, in seconds. Doubles with each failed attempt.
33const RETRY_BASE_SECS: u64 = 5;
34/// The longest retry delay, in seconds. Reason: a copy that cannot be removed is looked at every ten minutes.
35const RETRY_CAP_SECS: u64 = 600;
36
37/// The delay before the next attempt after `attempts` failures.
38pub fn retry_delay(attempts: i64) -> Duration {
39 let shift = u32::try_from(attempts.clamp(0, 16)).unwrap_or(0);
40 Duration::from_secs((RETRY_BASE_SECS << shift).min(RETRY_CAP_SECS))
41}
42
43/// Starts the deleter. It sweeps at once, then every [`SWEEP_EVERY`], until `stop` is set.
44pub fn spawn(state: AppState, mut stop: watch::Receiver<bool>) {
45 tokio::spawn(async move {
46 loop {
47 sweep(&state).await;
48 tokio::select! {
49 () = tokio::time::sleep(SWEEP_EVERY) => {}
50 _ = stop.wait_for(|stopped| *stopped) => break,
51 }
52 }
53 tracing::info!("attachment deleter stopped");
54 });
55}
56
57/// What one owed copy came to on this pass.
58enum Step {
59 /// The copy is gone, or was never needed. The record is cleared.
60 Done,
61 /// A move is under way for this row. Looked at again soon, without a failed attempt counted.
62 Later,
63 /// The removal failed. The record is retried with the backoff.
64 Failed(String),
65}
66
67/// One pass over the due deletions. A failure is logged and retried later; it never stops the worker. Also
68/// run by the sweeper as a backstop.
69pub async fn sweep(state: &AppState) {
70 let due = match state.store.due_blob_deletions(SWEEP_BATCH).await {
71 Ok(due) => due,
72 Err(error) => {
73 tracing::warn!(error = %error, "reading the due attachment deletions failed");
74 return;
75 }
76 };
77 // Once a Files-service call fails, the rest of this pass leaves the Files copies for the next one: each call
78 // may wait for the connection, and the blob lock is held meanwhile.
79 let mut files_down = false;
80 for (id, location, attempts) in due {
81 if files_down && location == LOCATION_IN {
82 continue;
83 }
84 let step = remove_owed(state, &id, &location).await;
85 if matches!(step, Step::Failed(_)) && location == LOCATION_IN {
86 files_down = true;
87 }
88 match step {
89 Step::Done => {
90 if let Err(error) = state.store.finish_blob_deletion(&id, &location).await {
91 tracing::warn!(error = %error, "clearing a finished attachment deletion failed");
92 }
93 }
94 Step::Later => {
95 if let Err(error) = state
96 .store
97 .postpone_blob_deletion(&id, &location, Duration::from_secs(RETRY_BASE_SECS))
98 .await
99 {
100 tracing::warn!(error = %error, "postponing an attachment deletion failed");
101 }
102 }
103 Step::Failed(reason) => {
104 tracing::warn!(attempts, location = %location, reason, "removing an attachment copy failed; retrying");
105 if let Err(error) = state
106 .store
107 .defer_blob_deletion(&id, &location, attempts, retry_delay(attempts))
108 .await
109 {
110 tracing::warn!(error = %error, "scheduling an attachment deletion retry failed");
111 }
112 }
113 }
114 }
115}
116
117/// Removes one owed copy, judged against the row under the blob lock (see the module comment).
118async fn remove_owed(state: &AppState, id: &str, location: &str) -> Step {
119 let _guard = state.blob_lock.lock().await;
120 let here = match state.store.attachment_location(id).await {
121 Ok(here) => here,
122 Err(error) => return Step::Failed(error.to_string()),
123 };
124 match here.as_deref() {
125 Some(LOCATION_MOVING) => return Step::Later,
126 Some(current) if current == location => return Step::Done,
127 _ => {}
128 }
129 if location == LOCATION_LOCAL {
130 return match remove_blob(&state.config.data_dir, id).await {
131 Ok(()) => Step::Done,
132 Err(error) => Step::Failed(error.to_string()),
133 };
134 }
135 if location != LOCATION_IN {
136 return Step::Failed(format!("unknown location {location}"));
137 }
138 let Some(in_store) = state.in_store.as_ref() else {
139 return Step::Failed("the Files service is not configured".into());
140 };
141 match in_store.delete(id).await {
142 Ok(()) => Step::Done,
143 Err(error) => Step::Failed(error.to_string()),
144 }
145}
146
147#[cfg(test)]
148mod tests {
149 use super::*;
150
151 #[test]
152 fn the_retry_backoff_doubles_and_is_capped() {
153 assert_eq!(retry_delay(0), Duration::from_secs(5));
154 assert_eq!(retry_delay(1), Duration::from_secs(10));
155 assert_eq!(retry_delay(3), Duration::from_secs(40));
156 assert_eq!(retry_delay(40), Duration::from_secs(600));
157 assert_eq!(retry_delay(-3), Duration::from_secs(5));
158 }
159}
160
161#[cfg(test)]
162mod delete_tests {
163 use std::sync::Arc;
164
165 use iz_core::authz::{Actor, Role};
166 use iz_core::staging::blob_path;
167 use iz_core::store::attachments::{LOCATION_IN, LOCATION_LOCAL};
168
169 use super::*;
170 use crate::boot::test_state;
171 use crate::in_store::InStore;
172 use crate::in_store::test_support::{fake_in, reply, seed_attachment};
173
174 /// A DELETE that the Files service answers `404` for is already done: the record is cleared, not retried.
175 #[tokio::test]
176 async fn a_404_at_the_files_service_counts_as_deleted() {
177 let (_dir, mut state) = test_state().await;
178 let base = fake_in(|req| {
179 if req.method == "DELETE" {
180 reply(404, b"{}")
181 } else {
182 reply(405, b"")
183 }
184 })
185 .await;
186 state.in_store = Some(Arc::new(InStore::for_tests(&base)));
187 let row = seed_attachment(&state, "a.png", "image/png", b"pixels").await;
188 // The row has moved: its bytes are at the Files service and the local copy is gone.
189 assert!(
190 state
191 .store
192 .set_location_if(&row.id, LOCATION_LOCAL, LOCATION_IN)
193 .await
194 .expect("move")
195 );
196 std::fs::remove_file(blob_path(&state.config.data_dir, &row.id).expect("path"))
197 .expect("local copy removed");
198 let board = state.store.ensure_board("IZ").await.expect("board");
199 let uploader = Actor::Member {
200 sub: "bo".into(),
201 role: Role::Member,
202 im_admin: false,
203 disabled: false,
204 };
205 state
206 .store
207 .delete_attachment(&board.id, &row.id, &uploader)
208 .await
209 .expect("delete");
210 assert_eq!(
211 state.store.due_blob_deletions(10).await.expect("due").len(),
212 1
213 );
214
215 sweep(&state).await;
216
217 assert!(
218 state
219 .store
220 .due_blob_deletions(10)
221 .await
222 .expect("due")
223 .is_empty(),
224 "a 404 counts as deleted"
225 );
226 }
227}