diff --git a/README.md b/README.md index ed81312..b06c629 100644 --- a/README.md +++ b/README.md @@ -134,8 +134,10 @@ Restart iz after changing the config. `im client list` shows the registered clie ## Backups -With a `[backup]` section, iz writes a backup set into `dir` every `interval_hours` and keeps the newest -`keep` sets. A set is a directory with: +With a `[backup]` section, iz checks every minute whether a backup is due and writes a set into `dir` when the +last attempt (recorded in the database, so restarts do not reset it) is at least `interval_hours` old, or when none +was made yet. A failed attempt is retried at the interval, not every minute. It keeps the newest `keep` sets. A set +is a directory with: - `iz.db`: a consistent copy of the database, - `attachments/`: the local attachment files, diff --git a/crates/iz-web/src/backup.rs b/crates/iz-web/src/backup.rs index 476c3b9..f2d874c 100644 --- a/crates/iz-web/src/backup.rs +++ b/crates/iz-web/src/backup.rs @@ -1,6 +1,10 @@ -//! The scheduled backup worker. Every `interval_hours` it writes one backup set under `[backup] dir`, then -//! 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 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 @@ -9,9 +13,9 @@ //! 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`]. 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. +//! 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 @@ -55,6 +59,11 @@ impl BackupTrigger { 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); @@ -70,6 +79,9 @@ impl BackupTrigger { 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. @@ -133,8 +145,8 @@ pub fn is_stale(last_success: Option<&str>, interval_hours: u32, now: Timestamp) } /// Starts the backup worker when the config has a `[backup]` section. Without one this does nothing. -/// The first backup runs at once, then one every `interval_hours`, or sooner when an administrator asks for -/// one (see [`BackupTrigger`]). +/// 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; @@ -151,31 +163,64 @@ pub fn spawn(state: AppState, mut stop: watch::Receiver) { None } }; - let interval = Duration::from_secs(u64::from(policy.interval_hours) * 3600); loop { - state.backup.begin(); - run_once(&state, &policy, client.as_ref(), &mut stop).await; - state.backup.finish(); tokio::select! { - () = tokio::time::sleep(interval) => {} + () = 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. +/// 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, ) { - record_outcome(&state.store, LAST_ATTEMPT_SETTING, &now_stamp()).await; + // 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"); @@ -419,6 +464,15 @@ mod tests { 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"); diff --git a/docs/architecture.md b/docs/architecture.md index b24bbd5..c41dd70 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -205,6 +205,10 @@ activity and mail ledger, audit rows past `AUDIT_RETENTION_DAYS` = 365 in batche `BackupTrigger` on `AppState` holds an atomic busy flag (set by a request or a scheduled run, cleared when the run ends) and a `Notify`. At most one run is pending or running; a request made meanwhile starts nothing. All stop with the stop flag. +The backup worker wakes every minute. A scheduled run is due when no `backup_last_attempt` is recorded or the last +attempt is at least `interval_hours` old (`backup::is_due`); the attempt is recorded before the set is written, so a +restart does not reset the timer and a failing run waits for the next interval. A "Back up now" request runs at once. + Every backup run, scheduled or requested, records its outcome in `settings`: `backup_last_attempt` (when the run started), `backup_last_success` (when a set was published; never cleared) and `backup_last_error` (a short text, empty after a success). The error text names the kind of failure and never a path or a database message. The