//! The deleter: the attachments' disk and Files-service work that runs outside a request. A deleted //! attachment's row is gone at once (the transaction in `iz-core` records the copies it owes in //! `blob_deletions`, one record per place); this worker removes them and retries with a backoff until they are //! gone, then clears the record. It runs until the stop flag is set, like every worker //! (`docs/architecture.md` section 8). //! //! The rules that keep a live copy safe are the same ones the mover follows (`mover.rs`). Every step that //! touches a copy, or the row that says where the bytes are, holds `AppState::blob_lock`. Under that lock, a //! record is judged against the row as it is then: //! - the row is `moving`: a move is under way, so the record waits; //! - the row is in the record's own place: the record is stale, and the copy is the live one, so nothing is removed; //! - the row is gone, or is in the other place: the owed copy is removed. //! //! Local copies are removed only through `iz_core::staging::remove_blob`, which builds the path from the validated //! attachment id. Files-service copies are removed with `DELETE`, which counts a missing object as done. use std::time::Duration; use iz_core::staging::remove_blob; use iz_core::store::attachments::{LOCATION_IN, LOCATION_LOCAL, LOCATION_MOVING}; use tokio::sync::watch; use crate::state::AppState; /// The largest body of one upload request, in bytes. Reason: several files may come in one form, each up to the /// per-file limit (at most 500 MiB), and this bounds the whole request. pub const UPLOAD_REQUEST_MAX_BYTES: usize = 1024 * 1024 * 1024; /// How often the deleter looks for due deletions. Reason: a deleted file should be gone within seconds. const SWEEP_EVERY: Duration = Duration::from_secs(5); /// Most deletions one sweep handles. Reason: bounds one sweep when many files are deleted at once. const SWEEP_BATCH: i64 = 50; /// The first retry delay, in seconds. Doubles with each failed attempt. const RETRY_BASE_SECS: u64 = 5; /// The longest retry delay, in seconds. Reason: a copy that cannot be removed is looked at every ten minutes. const RETRY_CAP_SECS: u64 = 600; /// The delay before the next attempt after `attempts` failures. pub fn retry_delay(attempts: i64) -> Duration { let shift = u32::try_from(attempts.clamp(0, 16)).unwrap_or(0); Duration::from_secs((RETRY_BASE_SECS << shift).min(RETRY_CAP_SECS)) } /// Starts the deleter. It sweeps at once, then every [`SWEEP_EVERY`], until `stop` is set. pub fn spawn(state: AppState, mut stop: watch::Receiver) { tokio::spawn(async move { loop { sweep(&state).await; tokio::select! { () = tokio::time::sleep(SWEEP_EVERY) => {} _ = stop.wait_for(|stopped| *stopped) => break, } } tracing::info!("attachment deleter stopped"); }); } /// What one owed copy came to on this pass. enum Step { /// The copy is gone, or was never needed. The record is cleared. Done, /// A move is under way for this row. Looked at again soon, without a failed attempt counted. Later, /// The removal failed. The record is retried with the backoff. Failed(String), } /// One pass over the due deletions. A failure is logged and retried later; it never stops the worker. Also /// run by the sweeper as a backstop. pub async fn sweep(state: &AppState) { let due = match state.store.due_blob_deletions(SWEEP_BATCH).await { Ok(due) => due, Err(error) => { tracing::warn!(error = %error, "reading the due attachment deletions failed"); return; } }; // Once a Files-service call fails, the rest of this pass leaves the Files copies for the next one: each call // may wait for the connection, and the blob lock is held meanwhile. let mut files_down = false; for (id, location, attempts) in due { if files_down && location == LOCATION_IN { continue; } let step = remove_owed(state, &id, &location).await; if matches!(step, Step::Failed(_)) && location == LOCATION_IN { files_down = true; } match step { Step::Done => { if let Err(error) = state.store.finish_blob_deletion(&id, &location).await { tracing::warn!(error = %error, "clearing a finished attachment deletion failed"); } } Step::Later => { if let Err(error) = state .store .postpone_blob_deletion(&id, &location, Duration::from_secs(RETRY_BASE_SECS)) .await { tracing::warn!(error = %error, "postponing an attachment deletion failed"); } } Step::Failed(reason) => { tracing::warn!(attempts, location = %location, reason, "removing an attachment copy failed; retrying"); if let Err(error) = state .store .defer_blob_deletion(&id, &location, attempts, retry_delay(attempts)) .await { tracing::warn!(error = %error, "scheduling an attachment deletion retry failed"); } } } } } /// Removes one owed copy, judged against the row under the blob lock (see the module comment). async fn remove_owed(state: &AppState, id: &str, location: &str) -> Step { let _guard = state.blob_lock.lock().await; let here = match state.store.attachment_location(id).await { Ok(here) => here, Err(error) => return Step::Failed(error.to_string()), }; match here.as_deref() { Some(LOCATION_MOVING) => return Step::Later, Some(current) if current == location => return Step::Done, _ => {} } if location == LOCATION_LOCAL { return match remove_blob(&state.config.data_dir, id).await { Ok(()) => Step::Done, Err(error) => Step::Failed(error.to_string()), }; } if location != LOCATION_IN { return Step::Failed(format!("unknown location {location}")); } let Some(in_store) = state.in_store.as_ref() else { return Step::Failed("the Files service is not configured".into()); }; match in_store.delete(id).await { Ok(()) => Step::Done, Err(error) => Step::Failed(error.to_string()), } } #[cfg(test)] mod tests { use super::*; #[test] fn the_retry_backoff_doubles_and_is_capped() { assert_eq!(retry_delay(0), Duration::from_secs(5)); assert_eq!(retry_delay(1), Duration::from_secs(10)); assert_eq!(retry_delay(3), Duration::from_secs(40)); assert_eq!(retry_delay(40), Duration::from_secs(600)); assert_eq!(retry_delay(-3), Duration::from_secs(5)); } } #[cfg(test)] mod delete_tests { use std::sync::Arc; use iz_core::authz::{Actor, Role}; use iz_core::staging::blob_path; use iz_core::store::attachments::{LOCATION_IN, LOCATION_LOCAL}; use super::*; use crate::boot::test_state; use crate::in_store::InStore; use crate::in_store::test_support::{fake_in, reply, seed_attachment}; /// A DELETE that the Files service answers `404` for is already done: the record is cleared, not retried. #[tokio::test] async fn a_404_at_the_files_service_counts_as_deleted() { let (_dir, mut state) = test_state().await; let base = fake_in(|req| { if req.method == "DELETE" { reply(404, b"{}") } else { reply(405, b"") } }) .await; state.in_store = Some(Arc::new(InStore::for_tests(&base))); let row = seed_attachment(&state, "a.png", "image/png", b"pixels").await; // The row has moved: its bytes are at the Files service and the local copy is gone. assert!( state .store .set_location_if(&row.id, LOCATION_LOCAL, LOCATION_IN) .await .expect("move") ); std::fs::remove_file(blob_path(&state.config.data_dir, &row.id).expect("path")) .expect("local copy removed"); let board = state.store.ensure_board("IZ").await.expect("board"); let uploader = Actor::Member { sub: "bo".into(), role: Role::Member, im_admin: false, disabled: false, }; state .store .delete_attachment(&board.id, &row.id, &uploader) .await .expect("delete"); assert_eq!( state.store.due_blob_deletions(10).await.expect("due").len(), 1 ); sweep(&state).await; assert!( state .store .due_blob_deletions(10) .await .expect("due") .is_empty(), "a 404 counts as deleted" ); } }