From fdb2a7bd54c5b54203ca2bf1736574e7657850a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 28 Oct 2026 15:15:17 +0300 Subject: [PATCH] =?UTF-8?q?=E2=8F=B0=20backup:=20run=20only=20when=20due?= =?UTF-8?q?=20by=20the=20last=20recorded=20attempt,=20so=20restarts=20add?= =?UTF-8?q?=20no=20sets?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 5 ++- crates/in-web/src/backup.rs | 79 +++++++++++++++++++++++++++++++------ docs/architecture.md | 11 ++++-- 3 files changed, 77 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index e951783..02a228c 100644 --- a/README.md +++ b/README.md @@ -97,7 +97,10 @@ directory, which you add to `ReadWritePaths`. ## Backups With `[backup]` set, `in serve` writes a backup set every `interval_hours`, keeps the newest `keep` sets, and -pings `healthcheck_url` after each good run (a failed ping is logged and nothing else). +pings `healthcheck_url` after each good run (a failed ping is logged and nothing else). The server checks once a +minute and runs when no attempt is recorded or the last attempt is at least `interval_hours` old. The attempt time +is stored in the database before each run, so restarting the server does not start a run or move the schedule. A +failing run is retried at the interval, not every minute. While the server runs, the *Backups* section of `/admin` has a *Back up now* button that starts a run at once. It is for administrators only and needs the form's CSRF token. At most one run is pending or running: a press made meanwhile diff --git a/crates/in-web/src/backup.rs b/crates/in-web/src/backup.rs index 2787d28..a01ed08 100644 --- a/crates/in-web/src/backup.rs +++ b/crates/in-web/src/backup.rs @@ -1,5 +1,10 @@ //! The scheduled backup worker: writes a backup set (snapshot, blob manifest and its MAC, see `in-core` `backup.rs`) -//! every `interval_hours`, keeps the newest `keep` sets, and pings the dead-man URL after each good run. +//! 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. @@ -27,7 +32,12 @@ use crate::state::AppState; /// How long the dead-man ping may take. pub const PING_TIMEOUT: Duration = Duration::from_secs(10); -/// Settings key: when a run was last attempted (a stamp). Written after every run. +/// 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"; @@ -60,6 +70,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); @@ -99,12 +114,18 @@ fn short_error(error: &Error) -> String { .collect() } -/// Stores the outcome of one run: the attempt time always; on success the success time and no error; on -/// failure the short error. A store failure is logged and never fails the run. +/// 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 { - store.set_setting(LAST_ATTEMPT_AT, &now).await?; match outcome { Ok(_) => { store.set_setting(LAST_SUCCESS_AT, &now).await?; @@ -119,6 +140,13 @@ async fn record_outcome(store: &Store, outcome: &in_core::error::Result, interval_hours: u32) -> bool { + let interval = Duration::from_secs(u64::from(interval_hours) * 60 * 60); + last_attempt.is_none_or(|stamp| stamp < stamp_before(interval).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. @@ -146,15 +174,23 @@ async fn ping(url: &str) { } } -/// Runs backups until the stop flag is set: one at start-up, then one per interval, and one at once whenever -/// the admin page asks for it. +/// 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; }; - let every = Duration::from_secs(u64::from(config.interval_hours) * 60 * 60); 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 { @@ -166,10 +202,17 @@ pub async fn run(state: AppState, mut stop: watch::Receiver) { Err(error) => tracing::error!(error = %error, "backup: the run failed"), } state.backup.finish(); - tokio::select! { - _ = stop.wait_for(|stopped| *stopped) => return, - () = tokio::time::sleep(every) => {} - () = state.backup.wake.notified() => {} + } +} + +/// 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 } } } @@ -180,7 +223,7 @@ mod tests { use in_core::time::{now_stamp, stamp_before}; - use super::{BackupTrigger, is_stale}; + use super::{BackupTrigger, is_due, is_stale}; #[test] fn a_second_request_while_one_is_pending_starts_nothing() { @@ -202,4 +245,14 @@ mod tests { 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 + )); + } } diff --git a/docs/architecture.md b/docs/architecture.md index 7301db9..3a15154 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -238,10 +238,13 @@ and has no sessions. which retries failed removals), seen JTIs, trash past `purge_after_days`, audit rows past 365 days, unreferenced blobs older than 24 h, quota drift check (nightly). - **backup** (optional): snapshot + blob tree manifest, HMAC-SHA256 over the manifest (`manifest.mac`, keyed from - `in.key`, checked before a restore parses anything), keep N, dead-man pings. The worker also runs when the admin - page asks (`BackupTrigger`: one busy flag and a `Notify` the worker waits on); at most one run is pending or running. - After every run, scheduled or manual, the outcome is written to `settings` (no migration): `backup.last_attempt_at` - always, `backup.last_success_at` on success (and the error is cleared), `backup.last_error` on failure (the first + `in.key`, checked before a restore parses anything), keep N, dead-man pings. The worker wakes every minute and + runs when no attempt is recorded or `backup.last_attempt_at` is at least `interval_hours` old (`backup::is_due`). + The attempt time is written before the run, so a restart neither starts a run nor resets the interval. The + worker also runs when the admin page asks (`BackupTrigger`: one busy flag and a `Notify` the worker waits on); at + most one run is pending or running. After every run, scheduled or manual, the outcome is written to `settings` + (no migration): `backup.last_attempt_at` before the run, `backup.last_success_at` on success (and the error is + cleared), `backup.last_error` on failure (the first line of the error, control characters removed, at most 200 characters; never the ping URL). The admin Backups section shows the last success and the last attempt, an alert while the latest run failed, and a warning when backups are on and the last success is older than the limit: `max(2 days, 2 × interval_hours)`