//! The scheduled backup worker: writes a backup set (snapshot, blob manifest and its MAC, see `in-core` `backup.rs`) //! when one is due, keeps the newest `keep` sets, and pings the dead-man URL after each good run. //! //! A run is due when no attempt is recorded yet, or the last attempt is at least `interval_hours` old (see //! [`is_due`]). The worker checks every [`TICK`]. The attempt time is written before the run starts, and it lives //! in the database, so a restart does not reset the interval, and a crash-looping server cannot write a set on //! every start. A failing run is retried at the interval, not every tick. //! //! The admin page can ask for a run now through [`BackupTrigger`]. At most one run is pending or running: a request //! made meanwhile starts nothing, and a scheduled run that is already going counts as running too. //! //! A failed run is logged and the next one is tried at the next interval; a failed ping is logged and nothing //! else. The ping URL carries a secret, so it is never logged. The worker is not started without a `[backup]` //! table. //! //! After every run, scheduled or manual, the outcome is recorded in the `settings` table (see [`record_outcome`]) //! so the admin page can show the last success, the last attempt and the error of a failed run. The recorded //! error is short text, never the ping URL. use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; use in_core::backup; use in_core::config::Backup; use in_core::error::Error; use in_core::store::Store; use in_core::time::{now_stamp, stamp_before}; use tokio::sync::{Notify, watch}; use crate::state::AppState; /// How long the dead-man ping may take. pub const PING_TIMEOUT: Duration = Duration::from_secs(10); /// How often the worker checks whether a run is due. A minute is short enough that a run starts close to its time, /// and a check reads one setting, so it costs nothing. const TICK: Duration = Duration::from_secs(60); /// Settings key: when a run was last attempted (a stamp). Written before every run, so a run that is cut short /// still counts as an attempt. pub const LAST_ATTEMPT_AT: &str = "backup.last_attempt_at"; /// Settings key: when a run last succeeded (a stamp). pub const LAST_SUCCESS_AT: &str = "backup.last_success_at"; /// Settings key: the short error of the latest run. Present only while the latest run failed. pub const LAST_ERROR: &str = "backup.last_error"; /// The longest error text that is stored, in characters. Long errors are cut so the admin page stays short. const ERROR_CHARS: usize = 200; /// The shortest time without a successful backup before the admin page warns: two days, in seconds. The /// limit is never shorter than two backup intervals (see [`is_stale`]). pub const STALE_AFTER: Duration = Duration::from_secs(2 * 24 * 60 * 60); /// Asks the backup worker for a run now. At most one run is pending or running: a request made while one is /// pending or running starts nothing. #[derive(Default)] pub struct BackupTrigger { /// True from a request, or from the start of a run, until that run ends. busy: AtomicBool, /// Wakes the worker out of its wait when a request arrives. wake: Notify, } impl BackupTrigger { /// Asks for a run now. Returns true when this request starts one, false when one is already pending or /// running. pub fn request(&self) -> bool { if self.busy.swap(true, Ordering::AcqRel) { return false; } self.wake.notify_one(); true } /// True when a run was requested and has not started yet. fn requested(&self) -> bool { self.busy.load(Ordering::Acquire) } /// Marks a run as running, so requests made meanwhile start nothing. fn begin(&self) { self.busy.store(true, Ordering::Release); } /// Marks the run as ended. A request made after this starts a new run. fn finish(&self) { self.busy.store(false, Ordering::Release); } } /// Runs one backup now and returns the new set's directory. async fn run_once(state: &AppState, config: &Backup) -> in_core::error::Result { // The stamp names the set; `:` and `.` are not wanted in file names. let stamp = now_stamp().replace([':', '.'], "-"); let set = backup::write_set( &state.store, state.blobs.as_ref(), &config.dir, &stamp, &state.key, ) .await?; let removed = backup::prune(&config.dir, config.keep as usize)?; tracing::info!(set = %set.display(), pruned = removed, "backup: set written"); Ok(set) } /// The short text of a failed run: the first line of its error, without control characters, cut to /// [`ERROR_CHARS`] characters. fn short_error(error: &Error) -> String { let text = error.to_string(); let line = text.lines().next().unwrap_or_default(); line.chars() .filter(|c| !c.is_control()) .take(ERROR_CHARS) .collect() } /// Stores the attempt time before a run starts. A store failure is logged and never stops the run. async fn record_attempt(store: &Store) { if let Err(error) = store.set_setting(LAST_ATTEMPT_AT, &now_stamp()).await { tracing::error!(error = %error, "backup: the attempt was not recorded"); } } /// Stores the outcome of one run: on success the success time and no error; on failure the short error. A store /// failure is logged and never fails the run. async fn record_outcome(store: &Store, outcome: &in_core::error::Result) { let now = now_stamp(); let recorded: in_core::error::Result<()> = async { match outcome { Ok(_) => { store.set_setting(LAST_SUCCESS_AT, &now).await?; store.clear_setting(LAST_ERROR).await } Err(error) => store.set_setting(LAST_ERROR, &short_error(error)).await, } } .await; if let Err(error) = recorded { tracing::error!(error = %error, "backup: the outcome was not recorded"); } } /// True when a run is due: none was attempted, or the last attempt is at least `interval_hours` old. The stamps /// have a fixed width, so comparing them as text compares their times. pub fn is_due(last_attempt: Option<&str>, interval_hours: u32) -> bool { let interval = Duration::from_secs(u64::from(interval_hours) * 60 * 60); // An attempt stamped in the future means the clock went back: run rather than wait for it. let now = now_stamp(); last_attempt.is_none_or(|stamp| stamp < stamp_before(interval).as_str() || stamp > now.as_str()) } /// True when there is no successful backup within the limit: [`STALE_AFTER`] or two backup intervals, /// whichever is longer, so a weekly schedule is not always overdue. The stamps have a fixed width, so /// comparing them as text compares their times. pub fn is_stale(last_success: Option<&str>, interval_hours: u32) -> bool { let interval = Duration::from_secs(u64::from(interval_hours) * 2 * 60 * 60); let limit = STALE_AFTER.max(interval); last_success.is_none_or(|stamp| stamp < stamp_before(limit).as_str()) } /// Pings the dead-man URL once. Only failures are logged, and the URL itself never is. async fn ping(url: &str) { let client = match reqwest::Client::builder().timeout(PING_TIMEOUT).build() { Ok(client) => client, Err(error) => { tracing::warn!(error = %error, "backup: could not prepare the dead-man ping"); return; } }; match client.get(url).send().await { Ok(response) if response.status().is_success() => {} Ok(response) => { tracing::warn!(status = %response.status(), "backup: dead-man ping was not accepted") } Err(error) => tracing::warn!(error = %error.without_url(), "backup: dead-man ping failed"), } } /// Runs backups until the stop flag is set. Every [`TICK`] it checks whether a run is due (see [`is_due`]); a /// request from the admin page starts a run at once. pub async fn run(state: AppState, mut stop: watch::Receiver) { let Some(config) = state.config.backup.clone() else { return; }; loop { tokio::select! { _ = stop.wait_for(|stopped| *stopped) => return, () = tokio::time::sleep(TICK) => {} () = state.backup.wake.notified() => {} } if !state.backup.requested() && !due(&state.store, &config).await { continue; } state.backup.begin(); record_attempt(&state.store).await; let outcome = run_once(&state, &config).await; record_outcome(&state.store, &outcome).await; match outcome { Ok(_) => { if let Some(url) = &config.healthcheck_url { ping(url).await; } } Err(error) => tracing::error!(error = %error, "backup: the run failed"), } state.backup.finish(); } } /// True when a scheduled run is due, by the attempt recorded in the database. A store failure is logged and /// counts as not due, so the next tick tries again. async fn due(store: &Store, config: &Backup) -> bool { match store.get_setting(LAST_ATTEMPT_AT).await { Ok(last) => is_due(last.as_deref(), config.interval_hours), Err(error) => { tracing::error!(error = %error, "backup: the last attempt could not be read"); false } } } #[cfg(test)] mod tests { use std::time::Duration; use in_core::time::{now_stamp, stamp_before}; use super::{BackupTrigger, is_due, is_stale}; #[test] fn a_second_request_while_one_is_pending_starts_nothing() { let trigger = BackupTrigger::default(); assert!(trigger.request()); assert!(!trigger.request()); trigger.begin(); assert!(!trigger.request()); trigger.finish(); assert!(trigger.request()); } #[test] fn no_success_within_the_limit_is_stale() { assert!(is_stale(None, 24)); assert!(!is_stale(Some(&now_stamp()), 24)); // Three days ago: stale on a daily schedule, not on a weekly one (limit two weeks). let three_days = stamp_before(Duration::from_secs(3 * 86_400)); assert!(is_stale(Some(&three_days), 24)); assert!(!is_stale(Some(&three_days), 168)); } #[test] fn a_fresh_attempt_makes_the_next_tick_not_due() { assert!(is_due(None, 24)); assert!(!is_due(Some(&now_stamp()), 24)); assert!(is_due( Some(&stamp_before(Duration::from_secs(25 * 3600))), 24 )); } }