forge
Explore
Log in

Don't you dare go Hollow

⏰ backup: run only when due by the last recorded attempt, so restarts add no sets

Browse files at this commit

56e88c8ede7a140123dae6977b20a9cfa65e341fAhmet Kaan GümüşParent: 551228f
README.mdmodified+4 -2
@@ -134,8 +134,10 @@ Restart iz after changing the config. `im client list` shows the registered clie
134 134
135 ## Backups135 ## Backups
136 136
137-With a `[backup]` section, iz writes a backup set into `dir` every `interval_hours` and keeps the newest137+With a `[backup]` section, iz checks every minute whether a backup is due and writes a set into `dir` when the
138-`keep` sets. A set is a directory with:138+last attempt (recorded in the database, so restarts do not reset it) is at least `interval_hours` old, or when none
139+was made yet. A failed attempt is retried at the interval, not every minute. It keeps the newest `keep` sets. A set
140+is a directory with:
139 141
140 - `iz.db`: a consistent copy of the database,142 - `iz.db`: a consistent copy of the database,
141 - `attachments/`: the local attachment files,143 - `attachments/`: the local attachment files,
crates/iz-web/src/backup.rsmodified+69 -15
@@ -1,6 +1,10 @@
1-//! The scheduled backup worker. Every `interval_hours` it writes one backup set under `[backup] dir`, then1+//! The scheduled backup worker. It wakes every minute and writes one backup set under `[backup] dir` when a run
2-//! keeps the newest `keep` finished sets and deletes the rest. It runs only when the config has a `[backup]`2+//! is due: no attempt is recorded yet, or the last attempt is at least `interval_hours` old. Then it keeps the
3-//! section, and stops with the stop flag.3+//! newest `keep` finished sets and deletes the rest. It runs only when the config has a `[backup]` section, and
4+//! stops with the stop flag.
5+//!
6+//! The attempt time is recorded before a set is written. So a failing run is retried at the interval and not
7+//! every minute, and a restart does not reset the timer: the next run is due from the recorded attempt.
4 //!8 //!
5 //! A set is a directory named by its UTC stamp (for example `20261028T093000Z`). It holds `iz.db` (a9 //! A set is a directory named by its UTC stamp (for example `20261028T093000Z`). It holds `iz.db` (a
6 //! `VACUUM INTO` snapshot), `attachments/<id>` for every attachment whose bytes are local, and10 //! `VACUUM INTO` snapshot), `attachments/<id>` for every attachment whose bytes are local, and
@@ -9,9 +13,9 @@
9 //! Only directories this worker created, or names that match the stamp pattern and hold a manifest, are ever13 //! Only directories this worker created, or names that match the stamp pattern and hold a manifest, are ever
10 //! deleted. Nothing is written in place.14 //! deleted. Nothing is written in place.
11 //!15 //!
12-//! The admin settings page can ask for a run now through [`BackupTrigger`]. At most one run is pending or16+//! The admin settings page can ask for a run now through [`BackupTrigger`], which runs at once. At most one run
13-//! running: a request made meanwhile starts nothing. Scheduled and requested runs both hold the busy flag, so17+//! is pending or running: a request made meanwhile starts nothing. Scheduled and requested runs both hold the
14-//! they never overlap.18+//! busy flag, so they never overlap.
15 //!19 //!
16 //! Every run records its outcome in the `settings` table (the attempt time, the last success, and the error of20 //! Every run records its outcome in the `settings` table (the attempt time, the last success, and the error of
17 //! the latest attempt), so a failing backup is visible on the Backups card. [`status`] reads it back and21 //! the latest attempt), so a failing backup is visible on the Backups card. [`status`] reads it back and
@@ -55,6 +59,11 @@ impl BackupTrigger {
55 true59 true
56 }60 }
57 61
62+ /// True when a run was requested and has not started yet.
63+ fn requested(&self) -> bool {
64+ self.busy.load(Ordering::Acquire)
65+ }
66+
58 /// Marks a run as running, so requests made meanwhile start nothing.67 /// Marks a run as running, so requests made meanwhile start nothing.
59 fn begin(&self) {68 fn begin(&self) {
60 self.busy.store(true, Ordering::Release);69 self.busy.store(true, Ordering::Release);
@@ -70,6 +79,9 @@ impl BackupTrigger {
70 const TMP_PREFIX: &str = ".tmp-";79 const TMP_PREFIX: &str = ".tmp-";
71 /// The database copy inside a set.80 /// The database copy inside a set.
72 const DB_FILE: &str = "iz.db";81 const DB_FILE: &str = "iz.db";
82+/// How often the worker checks whether a run is due. Reason: a due run starts at most a minute late, and a check
83+/// is one settings read.
84+const TICK: Duration = Duration::from_secs(60);
73 /// How long a healthcheck ping may take, in seconds. Reason: a slow ping must not hold the worker.85 /// How long a healthcheck ping may take, in seconds. Reason: a slow ping must not hold the worker.
74 const PING_TIMEOUT: Duration = Duration::from_secs(10);86 const PING_TIMEOUT: Duration = Duration::from_secs(10);
75 /// The stamp format of a set's directory name. Reason: no colons, so the name is portable.87 /// 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)
133 }145 }
134 146
135 /// Starts the backup worker when the config has a `[backup]` section. Without one this does nothing.147 /// Starts the backup worker when the config has a `[backup]` section. Without one this does nothing.
136-/// The first backup runs at once, then one every `interval_hours`, or sooner when an administrator asks for148+/// Every minute it checks whether a run is due (see [`is_due`]). An administrator's request runs at once (see
137-/// one (see [`BackupTrigger`]).149+/// [`BackupTrigger`]).
138 pub fn spawn(state: AppState, mut stop: watch::Receiver<bool>) {150 pub fn spawn(state: AppState, mut stop: watch::Receiver<bool>) {
139 let Some(policy) = state.config.backup.clone() else {151 let Some(policy) = state.config.backup.clone() else {
140 return;152 return;
@@ -151,31 +163,64 @@ pub fn spawn(state: AppState, mut stop: watch::Receiver<bool>) {
151 None163 None
152 }164 }
153 };165 };
154- let interval = Duration::from_secs(u64::from(policy.interval_hours) * 3600);
155 loop {166 loop {
156- state.backup.begin();
157- run_once(&state, &policy, client.as_ref(), &mut stop).await;
158- state.backup.finish();
159 tokio::select! {167 tokio::select! {
160- () = tokio::time::sleep(interval) => {}168+ () = tokio::time::sleep(TICK) => {}
161 () = state.backup.wake.notified() => {}169 () = state.backup.wake.notified() => {}
162 _ = stop.wait_for(|stopped| *stopped) => break,170 _ = stop.wait_for(|stopped| *stopped) => break,
163 }171 }
172+ if state.backup.requested() || due(&state.store, &policy).await {
173+ state.backup.begin();
174+ run_once(&state, &policy, client.as_ref(), &mut stop).await;
175+ state.backup.finish();
176+ }
164 }177 }
165 tracing::info!("backup worker stopped");178 tracing::info!("backup worker stopped");
166 });179 });
167 }180 }
168 181
182+/// Whether a run is due now: see [`is_due`]. A recorded attempt that cannot be read means no run this tick.
183+async fn due(store: &Store, policy: &BackupConfig) -> bool {
184+ match store.get_setting(LAST_ATTEMPT_SETTING).await {
185+ Ok(last) => is_due(last.as_deref(), policy.interval_hours, Timestamp::now()),
186+ Err(error) => {
187+ tracing::error!(error = %error, "backup attempt not read; no backup this tick");
188+ false
189+ }
190+ }
191+}
192+
193+/// Whether a run is due at `now`: none was attempted yet (no stamp, or one that does not parse), or the last
194+/// attempt is at least `interval_hours` old. A failed attempt counts too, so it is retried at the interval.
195+fn is_due(last_attempt: Option<&str>, interval_hours: u32, now: Timestamp) -> bool {
196+ let Some(last) = last_attempt.and_then(|stamp| timestamp_of(stamp).ok()) else {
197+ return true;
198+ };
199+ let interval = i64::from(interval_hours) * 3600;
200+ // An attempt stamped in the future means the clock went back: run rather than wait for it.
201+ let elapsed = now.as_second() - last.as_second();
202+ elapsed < 0 || elapsed >= interval
203+}
204+
169 /// One backup: record the attempt, write and publish a set, prune the old sets, ping the healthcheck, and205 /// One backup: record the attempt, write and publish a set, prune the old sets, ping the healthcheck, and
170 /// record the outcome. A failure is logged and recorded, and leaves no partial set. A stop request cancels a206 /// record the outcome. A failure is logged and recorded, and leaves no partial set. A stop request cancels a
171-/// set in progress and removes it.207+/// set in progress and removes it. When the attempt cannot be recorded nothing runs, so the worker does not
208+/// retry every tick against a failing store.
172 async fn run_once(209 async fn run_once(
173 state: &AppState,210 state: &AppState,
174 policy: &BackupConfig,211 policy: &BackupConfig,
175 client: Option<&reqwest::Client>,212 client: Option<&reqwest::Client>,
176 stop: &mut watch::Receiver<bool>,213 stop: &mut watch::Receiver<bool>,
177 ) {214 ) {
178- record_outcome(&state.store, LAST_ATTEMPT_SETTING, &now_stamp()).await;215+ // Recorded before the set is written, so the attempt stays on record even when the run is cut short.
216+ if let Err(error) = state
217+ .store
218+ .set_setting(LAST_ATTEMPT_SETTING, &now_stamp())
219+ .await
220+ {
221+ tracing::error!(error = %error, "backup attempt not recorded; no backup started");
222+ return;
223+ }
179 match write_and_publish(state, policy, stop).await {224 match write_and_publish(state, policy, stop).await {
180 Ok((name, files)) => {225 Ok((name, files)) => {
181 tracing::info!(set = %name, files, "backup set written");226 tracing::info!(set = %name, files, "backup set written");
@@ -419,6 +464,15 @@ mod tests {
419 assert!(dir.path().join(format!("{TMP_PREFIX}abc")).exists());464 assert!(dir.path().join(format!("{TMP_PREFIX}abc")).exists());
420 }465 }
421 466
467+ #[test]
468+ fn a_fresh_attempt_is_not_due_until_the_interval_has_passed() {
469+ let attempt = "2026-10-28T12:00:00.000000000Z";
470+ let at = |stamp: &str| stamp.parse::<Timestamp>().expect("time");
471+ assert!(is_due(None, 24, at("2026-10-28T12:00:00Z")));
472+ assert!(!is_due(Some(attempt), 24, at("2026-10-28T12:01:00Z")));
473+ assert!(is_due(Some(attempt), 24, at("2026-10-29T12:00:00Z")));
474+ }
475+
422 #[test]476 #[test]
423 fn a_backup_is_stale_without_a_success_or_after_two_days() {477 fn a_backup_is_stale_without_a_success_or_after_two_days() {
424 let now: Timestamp = "2026-10-28T12:00:00Z".parse().expect("time");478 let now: Timestamp = "2026-10-28T12:00:00Z".parse().expect("time");
docs/architecture.mdmodified+4 -0
@@ -205,6 +205,10 @@ activity and mail ledger, audit rows past `AUDIT_RETENTION_DAYS` = 365 in batche
205 `BackupTrigger` on `AppState` holds an atomic busy flag (set by a request or a scheduled run, cleared when the run ends)205 `BackupTrigger` on `AppState` holds an atomic busy flag (set by a request or a scheduled run, cleared when the run ends)
206 and a `Notify`. At most one run is pending or running; a request made meanwhile starts nothing. All stop with the stop flag.206 and a `Notify`. At most one run is pending or running; a request made meanwhile starts nothing. All stop with the stop flag.
207 207
208+The backup worker wakes every minute. A scheduled run is due when no `backup_last_attempt` is recorded or the last
209+attempt is at least `interval_hours` old (`backup::is_due`); the attempt is recorded before the set is written, so a
210+restart does not reset the timer and a failing run waits for the next interval. A "Back up now" request runs at once.
211+
208 Every backup run, scheduled or requested, records its outcome in `settings`: `backup_last_attempt` (when the run212 Every backup run, scheduled or requested, records its outcome in `settings`: `backup_last_attempt` (when the run
209 started), `backup_last_success` (when a set was published; never cleared) and `backup_last_error` (a short text,213 started), `backup_last_success` (when a set was published; never cleared) and `backup_last_error` (a short text,
210 empty after a success). The error text names the kind of failure and never a path or a database message. The214 empty after a success). The error text names the kind of failure and never a path or a database message. The