//! The scheduled backup worker. It wakes every minute and writes one backup set under `[backup] dir` when a run //! is due: no attempt is recorded yet, or the last attempt is at least `interval_hours` old. Then it keeps the //! newest `keep` finished sets and deletes the rest. It runs only when the config has a `[backup]` section, and //! stops with the stop flag. //! //! The attempt time is recorded before a set is written. So a failing run is retried at the interval and not //! every minute, and a restart does not reset the timer: the next run is due from the recorded attempt. //! //! A set is a directory named by its UTC stamp (for example `20261028T093000Z`). It holds `iz.db` (a //! `VACUUM INTO` snapshot), `attachments/` for every attachment whose bytes are local, and //! `manifest.json` and `manifest.mac` written last (`iz_core::manifest`), the MAC keyed by the instance key. A set is built in `.tmp-` and renamed to its //! stamp only when complete, so a directory with a manifest is always a whole set. A failed set is removed. //! Only directories this worker created, or names that match the stamp pattern and hold a manifest, are ever //! deleted. Nothing is written in place. //! //! The admin settings page can ask for a run now through [`BackupTrigger`], which runs at once. At most one run //! is pending or running: a request made meanwhile starts nothing. Scheduled and requested runs both hold the //! busy flag, so they never overlap. //! //! Every run records its outcome in the `settings` table (the attempt time, the last success, and the error of //! the latest attempt), so a failing backup is visible on the Backups card. [`status`] reads it back and //! [`is_stale`] says when no success is recent enough to warn about. use std::os::unix::fs::DirBuilderExt; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; use iz_core::clock::{stamp_of, timestamp_of}; use iz_core::config::BackupConfig; use iz_core::manifest::{self, MANIFEST_NAME}; use iz_core::staging::{ATTACHMENTS_DIR, blob_path}; use iz_core::store::{Store, new_id}; use iz_core::time::now_stamp; use iz_core::{Error, Result}; use jiff::Timestamp; use tokio::sync::{Notify, watch}; use crate::state::AppState; /// Asks the backup worker for a run now. A run is pending or running at most once: 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 scheduled 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); } } /// Prefix of a set that is still being written. Reason: a crash leaves a visibly unfinished directory. const TMP_PREFIX: &str = ".tmp-"; /// The database copy inside a set. const DB_FILE: &str = "iz.db"; /// How often the worker checks whether a run is due. Reason: a due run starts at most a minute late, and a check /// is one settings read. const TICK: Duration = Duration::from_secs(60); /// How long a healthcheck ping may take, in seconds. Reason: a slow ping must not hold the worker. const PING_TIMEOUT: Duration = Duration::from_secs(10); /// The stamp format of a set's directory name. Reason: no colons, so the name is portable. const SET_STAMP_FORMAT: &str = "%Y%m%dT%H%M%SZ"; /// Length of a set's directory name, which is the stamp format above. const SET_NAME_LEN: usize = 16; /// Settings key: when a run was last attempted (a UTC stamp). pub const LAST_ATTEMPT_SETTING: &str = "backup_last_attempt"; /// Settings key: when a run last succeeded (a UTC stamp). Never cleared, so the card shows the last good set. pub const LAST_SUCCESS_SETTING: &str = "backup_last_success"; /// Settings key: the text of the error of the latest attempt. Empty after a success. pub const LAST_ERROR_SETTING: &str = "backup_last_error"; /// Time without a success after which the settings page warns. Reason: two days lets one scheduled run be /// missed without a warning, and a longer gap means the backups are not happening. const STALE_AFTER: Duration = Duration::from_secs(2 * 24 * 3600); /// Longest error text kept, in characters. Reason: the settings page shows it on one line. const ERROR_TEXT_MAX: usize = 200; /// The recorded outcome of the backup runs, as the settings page reads it. Stamps are UTC; `None` when no /// value was recorded. #[derive(Debug, Clone, Default)] pub struct BackupStatus { /// When the latest attempt started. pub last_attempt: Option, /// When the last successful run finished. pub last_success: Option, /// The text of the error of the latest attempt. `None` when that attempt succeeded. pub last_error: Option, } /// Reads the recorded outcome. Empty values count as not recorded. pub async fn status(store: &Store) -> Result { Ok(BackupStatus { last_attempt: store .get_setting(LAST_ATTEMPT_SETTING) .await? .filter(|value| !value.is_empty()), last_success: store .get_setting(LAST_SUCCESS_SETTING) .await? .filter(|value| !value.is_empty()), last_error: store .get_setting(LAST_ERROR_SETTING) .await? .filter(|value| !value.is_empty()), }) } /// Whether the backups are overdue at `now`: no success was ever recorded, or the last one is older than /// [`STALE_AFTER`] or two backup intervals, whichever is longer, so a weekly schedule is not always overdue. /// A stamp that does not parse counts as no success. pub fn is_stale(last_success: Option<&str>, interval_hours: u32, now: Timestamp) -> bool { let Some(last) = last_success.and_then(|stamp| timestamp_of(stamp).ok()) else { return true; }; let limit = i64::try_from(STALE_AFTER.as_secs()) .unwrap_or(i64::MAX) .max(i64::from(interval_hours) * 2 * 3600); now.as_second().saturating_sub(last.as_second()) > limit } /// Starts the backup worker when the config has a `[backup]` section. Without one this does nothing. /// Every minute it checks whether a run is due (see [`is_due`]). An administrator's request runs at once (see /// [`BackupTrigger`]). pub fn spawn(state: AppState, mut stop: watch::Receiver) { let Some(policy) = state.config.backup.clone() else { return; }; tokio::spawn(async move { let client = match reqwest::Client::builder() .timeout(PING_TIMEOUT) .user_agent(concat!("iz/", env!("CARGO_PKG_VERSION"))) .build() { Ok(client) => Some(client), Err(error) => { tracing::warn!(error = %error, "healthcheck client not built; pings are off"); None } }; loop { tokio::select! { () = tokio::time::sleep(TICK) => {} () = state.backup.wake.notified() => {} _ = stop.wait_for(|stopped| *stopped) => break, } if state.backup.requested() || due(&state.store, &policy).await { state.backup.begin(); run_once(&state, &policy, client.as_ref(), &mut stop).await; state.backup.finish(); } } tracing::info!("backup worker stopped"); }); } /// Whether a run is due now: see [`is_due`]. A recorded attempt that cannot be read means no run this tick. async fn due(store: &Store, policy: &BackupConfig) -> bool { match store.get_setting(LAST_ATTEMPT_SETTING).await { Ok(last) => is_due(last.as_deref(), policy.interval_hours, Timestamp::now()), Err(error) => { tracing::error!(error = %error, "backup attempt not read; no backup this tick"); false } } } /// Whether a run is due at `now`: none was attempted yet (no stamp, or one that does not parse), or the last /// attempt is at least `interval_hours` old. A failed attempt counts too, so it is retried at the interval. fn is_due(last_attempt: Option<&str>, interval_hours: u32, now: Timestamp) -> bool { let Some(last) = last_attempt.and_then(|stamp| timestamp_of(stamp).ok()) else { return true; }; let interval = i64::from(interval_hours) * 3600; // An attempt stamped in the future means the clock went back: run rather than wait for it. let elapsed = now.as_second() - last.as_second(); elapsed < 0 || elapsed >= interval } /// One backup: record the attempt, write and publish a set, prune the old sets, ping the healthcheck, and /// record the outcome. A failure is logged and recorded, and leaves no partial set. A stop request cancels a /// set in progress and removes it. When the attempt cannot be recorded nothing runs, so the worker does not /// retry every tick against a failing store. async fn run_once( state: &AppState, policy: &BackupConfig, client: Option<&reqwest::Client>, stop: &mut watch::Receiver, ) { // Recorded before the set is written, so the attempt stays on record even when the run is cut short. if let Err(error) = state .store .set_setting(LAST_ATTEMPT_SETTING, &now_stamp()) .await { tracing::error!(error = %error, "backup attempt not recorded; no backup started"); return; } match write_and_publish(state, policy, stop).await { Ok((name, files)) => { tracing::info!(set = %name, files, "backup set written"); record_outcome(&state.store, LAST_SUCCESS_SETTING, &now_stamp()).await; record_outcome(&state.store, LAST_ERROR_SETTING, "").await; let keep = usize::try_from(policy.keep).unwrap_or(usize::MAX); match prune(&policy.dir, keep) { Ok(0) => {} Ok(removed) => tracing::info!(removed, "old backup sets deleted"), Err(error) => tracing::warn!(error = %error, "pruning old backup sets failed"), } if let (Some(url), Some(client)) = (policy.healthcheck_url.as_deref(), client) { ping(client, url).await; } } Err(error) => { record_outcome(&state.store, LAST_ERROR_SETTING, &error_text(&error)).await; tracing::warn!(error = %error, "backup failed; the partial set was removed"); } } } /// Writes one set in a temporary directory and publishes it under its stamp. Returns the set's name and its /// file count. On failure this removes the temporary directory, by its exact path. async fn write_and_publish( state: &AppState, policy: &BackupConfig, stop: &mut watch::Receiver, ) -> Result<(String, usize)> { ensure_dir(&policy.dir)?; let now = Timestamp::now(); let name = now.strftime(SET_STAMP_FORMAT).to_string(); let created_at = stamp_of(now)?; let tmp = policy.dir.join(format!("{TMP_PREFIX}{}", new_id())); let outcome = tokio::select! { result = write_set(&state.store, &state.config.data_dir, &state.key, &tmp, &created_at) => result, _ = stop.wait_for(|stopped| *stopped) => { Err(Error::Io(std::io::Error::other("stopped before the set was finished"))) } }; let outcome = outcome.and_then(|files| publish(&tmp, &policy.dir, &name).map(|()| files)); if outcome.is_err() { // Only the directory this run created is removed, by its exact path. let _ = std::fs::remove_dir_all(&tmp); } outcome.map(|files| (name, files)) } /// Stores one outcome value. A failure is logged and never fails or stops the run. async fn record_outcome(store: &Store, key: &str, value: &str) { if let Err(error) = store.set_setting(key, value).await { tracing::error!(error = %error, key, "backup outcome not recorded"); } } /// The short text kept for a failed run and shown on the settings page. It never holds a database message, /// since those can echo statement text, and it names no path: a filesystem error keeps only its OS reason. fn error_text(error: &Error) -> String { let text = match error { Error::Io(_) => error.to_string(), Error::Conflict(text) => text.clone(), Error::Database(_) => "database error".to_owned(), Error::Migration(_) => "migration error".to_owned(), _ => "backup failed".to_owned(), }; text.chars().take(ERROR_TEXT_MAX).collect() } /// Writes the files of one set into `tmp` and the manifest and its MAC last. Returns the number of files /// listed, not counting the manifest. The caller removes `tmp` on error. async fn write_set( store: &Store, data_dir: &Path, instance_key: &[u8; 32], tmp: &Path, created_at: &str, ) -> Result { create_dir(tmp, false)?; store.snapshot_to(&tmp.join(DB_FILE)).await?; let mut paths = vec![DB_FILE.to_owned()]; let attachments = tmp.join(ATTACHMENTS_DIR); create_dir(&attachments, false)?; for id in store.local_attachment_ids().await? { let source = blob_path(data_dir, &id)?; let relative = format!("{ATTACHMENTS_DIR}/{id}"); let target = tmp.join(&relative); tokio::fs::copy(&source, &target).await?; tokio::fs::File::open(&target).await?.sync_all().await?; paths.push(relative); } let files = paths.len(); // Hashing reads every file, which can take a while; it runs off the async threads. let dir = tmp.to_owned(); let created = created_at.to_owned(); let build = env!("IZ_BUILD_SHA").to_owned(); let key = *instance_key; tokio::task::spawn_blocking(move || { manifest::write_manifest(&dir, &key, &created, &build, &paths) }) .await .map_err(|error| Error::Io(std::io::Error::other(error)))??; Ok(files) } /// Creates the backup directory and any missing parents, unless it already exists. fn ensure_dir(dir: &Path) -> std::io::Result<()> { if dir.is_dir() { return Ok(()); } create_dir(dir, true) } /// Renames a complete set to its stamp and makes the rename durable. Refuses to replace an existing name. fn publish(tmp: &Path, dir: &Path, name: &str) -> Result<()> { let target = dir.join(name); if std::fs::symlink_metadata(&target).is_ok() { return Err(Error::Conflict(format!("backup set {name} already exists"))); } std::fs::rename(tmp, &target)?; std::fs::File::open(dir)?.sync_all()?; Ok(()) } /// Deletes all finished sets except the newest `keep`. Only directories named like a set and holding a /// manifest are candidates, so an unrelated directory in the backup dir is never touched. Returns the count. fn prune(dir: &Path, keep: usize) -> Result { let mut sets: Vec = std::fs::read_dir(dir)? .filter_map(std::result::Result::ok) .filter(|entry| is_set_name(&entry.file_name().to_string_lossy())) .map(|entry| entry.path()) .filter(|path| is_finished_set(path)) .collect(); // The stamp is fixed width and sorts in time order, so the name order is the age order. sets.sort(); let excess = sets.len().saturating_sub(keep); for old in &sets[..excess] { std::fs::remove_dir_all(old)?; } Ok(excess) } /// Whether `name` has the shape of a set's directory name: `YYYYMMDDTHHMMSSZ`. fn is_set_name(name: &str) -> bool { let bytes = name.as_bytes(); bytes.len() == SET_NAME_LEN && bytes.iter().enumerate().all(|(i, byte)| match i { 8 => *byte == b'T', 15 => *byte == b'Z', _ => byte.is_ascii_digit(), }) } /// Whether `path` is a real directory (not a link) that holds a manifest. fn is_finished_set(path: &Path) -> bool { let is_dir = std::fs::symlink_metadata(path).is_ok_and(|meta| meta.file_type().is_dir()); let has_manifest = std::fs::symlink_metadata(path.join(MANIFEST_NAME)) .is_ok_and(|meta| meta.file_type().is_file()); is_dir && has_manifest } /// Creates a directory with mode 0700. `recursive` also creates missing parents. fn create_dir(path: &Path, recursive: bool) -> std::io::Result<()> { std::fs::DirBuilder::new() .recursive(recursive) .mode(0o700) .create(path) } /// Pings the healthcheck once. A failure is logged without the URL, because the URL can carry a secret key. async fn ping(client: &reqwest::Client, url: &str) { match client.get(url).send().await { Ok(response) if response.status().is_success() => {} Ok(response) => { tracing::warn!(status = %response.status(), "healthcheck ping was refused"); } Err(error) => { tracing::warn!(error = %error.without_url(), "healthcheck ping failed"); } } } #[cfg(test)] mod tests { use super::*; #[test] fn a_second_request_while_one_is_pending_or_running_starts_nothing() { let trigger = BackupTrigger::default(); assert!(trigger.request()); assert!(!trigger.request()); trigger.begin(); assert!(!trigger.request()); trigger.finish(); assert!(trigger.request()); } /// A finished set on disk: a directory with a manifest, named by its stamp. fn fake_set(dir: &Path, name: &str) { let set = dir.join(name); std::fs::create_dir(&set).expect("set dir"); std::fs::write(set.join(MANIFEST_NAME), b"{}").expect("manifest"); } #[tokio::test] async fn a_written_set_verifies_and_is_published_by_its_stamp() { let dir = tempfile::tempdir().expect("temp dir"); let store = Store::open(&dir.path().join("iz.db")).await.expect("store"); let tmp = dir.path().join(format!("{TMP_PREFIX}{}", new_id())); let created = "2026-10-28T09:30:00.000000000Z"; let key = [6u8; 32]; write_set(&store, dir.path(), &key, &tmp, created) .await .expect("set written"); publish(&tmp, dir.path(), "20261028T093000Z").expect("published"); let published = dir.path().join("20261028T093000Z"); let verified = manifest::verify_set(&published, &key).expect("the set verifies"); assert_eq!(verified.created_at, created); assert!(verified.files.iter().any(|file| file.path == DB_FILE)); assert!(!tmp.exists(), "the temporary name is gone after the rename"); } #[test] fn prune_keeps_the_newest_sets_and_leaves_other_directories() { let dir = tempfile::tempdir().expect("temp dir"); for name in [ "20260101T000000Z", "20260102T000000Z", "20260103T000000Z", "20260104T000000Z", ] { fake_set(dir.path(), name); } std::fs::create_dir(dir.path().join("notes")).expect("unrelated dir"); std::fs::create_dir(dir.path().join(format!("{TMP_PREFIX}abc"))).expect("tmp dir"); assert_eq!(prune(dir.path(), 2).expect("prune"), 2); assert!(!dir.path().join("20260101T000000Z").exists()); assert!(!dir.path().join("20260102T000000Z").exists()); assert!(dir.path().join("20260103T000000Z").exists()); assert!(dir.path().join("20260104T000000Z").exists()); assert!(dir.path().join("notes").exists()); assert!(dir.path().join(format!("{TMP_PREFIX}abc")).exists()); } #[test] fn a_fresh_attempt_is_not_due_until_the_interval_has_passed() { let attempt = "2026-10-28T12:00:00.000000000Z"; let at = |stamp: &str| stamp.parse::().expect("time"); assert!(is_due(None, 24, at("2026-10-28T12:00:00Z"))); assert!(!is_due(Some(attempt), 24, at("2026-10-28T12:01:00Z"))); assert!(is_due(Some(attempt), 24, at("2026-10-29T12:00:00Z"))); } #[test] fn a_backup_is_stale_without_a_success_or_after_two_days() { let now: Timestamp = "2026-10-28T12:00:00Z".parse().expect("time"); assert!(is_stale(None, 24, now)); assert!(!is_stale(Some("2026-10-26T12:00:00.000000000Z"), 24, now)); assert!(is_stale(Some("2026-10-26T11:59:59.000000000Z"), 24, now)); assert!(!is_stale(Some("2026-10-26T11:59:59.000000000Z"), 168, now)); } }