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

fdb2a7bd54c5b54203ca2bf1736574e7657850a4Ahmet Kaan GümüşParent: 18fc018
README.mdmodified+4 -1
@@ -97,7 +97,10 @@ directory, which you add to `ReadWritePaths`.
97 ## Backups97 ## Backups
98 98
99 With `[backup]` set, `in serve` writes a backup set every `interval_hours`, keeps the newest `keep` sets, and99 With `[backup]` set, `in serve` writes a backup set every `interval_hours`, keeps the newest `keep` sets, and
100-pings `healthcheck_url` after each good run (a failed ping is logged and nothing else).100+pings `healthcheck_url` after each good run (a failed ping is logged and nothing else). The server checks once a
101+minute and runs when no attempt is recorded or the last attempt is at least `interval_hours` old. The attempt time
102+is stored in the database before each run, so restarting the server does not start a run or move the schedule. A
103+failing run is retried at the interval, not every minute.
101 104
102 While the server runs, the *Backups* section of `/admin` has a *Back up now* button that starts a run at once. It is105 While the server runs, the *Backups* section of `/admin` has a *Back up now* button that starts a run at once. It is
103 for administrators only and needs the form's CSRF token. At most one run is pending or running: a press made meanwhile106 for administrators only and needs the form's CSRF token. At most one run is pending or running: a press made meanwhile
crates/in-web/src/backup.rsmodified+66 -13
@@ -1,5 +1,10 @@
1 //! The scheduled backup worker: writes a backup set (snapshot, blob manifest and its MAC, see `in-core` `backup.rs`)1 //! The scheduled backup worker: writes a backup set (snapshot, blob manifest and its MAC, see `in-core` `backup.rs`)
2-//! every `interval_hours`, keeps the newest `keep` sets, and pings the dead-man URL after each good run.2+//! when one is due, keeps the newest `keep` sets, and pings the dead-man URL after each good run.
3+//!
4+//! A run is due when no attempt is recorded yet, or the last attempt is at least `interval_hours` old (see
5+//! [`is_due`]). The worker checks every [`TICK`]. The attempt time is written before the run starts, and it lives
6+//! in the database, so a restart does not reset the interval, and a crash-looping server cannot write a set on
7+//! every start. A failing run is retried at the interval, not every tick.
3 //!8 //!
4 //! The admin page can ask for a run now through [`BackupTrigger`]. At most one run is pending or running: a request9 //! The admin page can ask for a run now through [`BackupTrigger`]. At most one run is pending or running: a request
5 //! made meanwhile starts nothing, and a scheduled run that is already going counts as running too.10 //! made meanwhile starts nothing, and a scheduled run that is already going counts as running too.
@@ -27,7 +32,12 @@ use crate::state::AppState;
27 /// How long the dead-man ping may take.32 /// How long the dead-man ping may take.
28 pub const PING_TIMEOUT: Duration = Duration::from_secs(10);33 pub const PING_TIMEOUT: Duration = Duration::from_secs(10);
29 34
30-/// Settings key: when a run was last attempted (a stamp). Written after every run.35+/// How often the worker checks whether a run is due. A minute is short enough that a run starts close to its time,
36+/// and a check reads one setting, so it costs nothing.
37+const TICK: Duration = Duration::from_secs(60);
38+
39+/// Settings key: when a run was last attempted (a stamp). Written before every run, so a run that is cut short
40+/// still counts as an attempt.
31 pub const LAST_ATTEMPT_AT: &str = "backup.last_attempt_at";41 pub const LAST_ATTEMPT_AT: &str = "backup.last_attempt_at";
32 /// Settings key: when a run last succeeded (a stamp).42 /// Settings key: when a run last succeeded (a stamp).
33 pub const LAST_SUCCESS_AT: &str = "backup.last_success_at";43 pub const LAST_SUCCESS_AT: &str = "backup.last_success_at";
@@ -60,6 +70,11 @@ impl BackupTrigger {
60 true70 true
61 }71 }
62 72
73+ /// True when a run was requested and has not started yet.
74+ fn requested(&self) -> bool {
75+ self.busy.load(Ordering::Acquire)
76+ }
77+
63 /// Marks a run as running, so requests made meanwhile start nothing.78 /// Marks a run as running, so requests made meanwhile start nothing.
64 fn begin(&self) {79 fn begin(&self) {
65 self.busy.store(true, Ordering::Release);80 self.busy.store(true, Ordering::Release);
@@ -99,12 +114,18 @@ fn short_error(error: &Error) -> String {
99 .collect()114 .collect()
100 }115 }
101 116
102-/// Stores the outcome of one run: the attempt time always; on success the success time and no error; on117+/// Stores the attempt time before a run starts. A store failure is logged and never stops the run.
103-/// failure the short error. A store failure is logged and never fails the run.118+async fn record_attempt(store: &Store) {
119+ if let Err(error) = store.set_setting(LAST_ATTEMPT_AT, &now_stamp()).await {
120+ tracing::error!(error = %error, "backup: the attempt was not recorded");
121+ }
122+}
123+
124+/// Stores the outcome of one run: on success the success time and no error; on failure the short error. A store
125+/// failure is logged and never fails the run.
104 async fn record_outcome(store: &Store, outcome: &in_core::error::Result<std::path::PathBuf>) {126 async fn record_outcome(store: &Store, outcome: &in_core::error::Result<std::path::PathBuf>) {
105 let now = now_stamp();127 let now = now_stamp();
106 let recorded: in_core::error::Result<()> = async {128 let recorded: in_core::error::Result<()> = async {
107- store.set_setting(LAST_ATTEMPT_AT, &now).await?;
108 match outcome {129 match outcome {
109 Ok(_) => {130 Ok(_) => {
110 store.set_setting(LAST_SUCCESS_AT, &now).await?;131 store.set_setting(LAST_SUCCESS_AT, &now).await?;
@@ -119,6 +140,13 @@ async fn record_outcome(store: &Store, outcome: &in_core::error::Result<std::pat
119 }140 }
120 }141 }
121 142
143+/// True when a run is due: none was attempted, or the last attempt is at least `interval_hours` old. The stamps
144+/// have a fixed width, so comparing them as text compares their times.
145+pub fn is_due(last_attempt: Option<&str>, interval_hours: u32) -> bool {
146+ let interval = Duration::from_secs(u64::from(interval_hours) * 60 * 60);
147+ last_attempt.is_none_or(|stamp| stamp < stamp_before(interval).as_str())
148+}
149+
122 /// True when there is no successful backup within the limit: [`STALE_AFTER`] or two backup intervals,150 /// True when there is no successful backup within the limit: [`STALE_AFTER`] or two backup intervals,
123 /// whichever is longer, so a weekly schedule is not always overdue. The stamps have a fixed width, so151 /// whichever is longer, so a weekly schedule is not always overdue. The stamps have a fixed width, so
124 /// comparing them as text compares their times.152 /// comparing them as text compares their times.
@@ -146,15 +174,23 @@ async fn ping(url: &str) {
146 }174 }
147 }175 }
148 176
149-/// Runs backups until the stop flag is set: one at start-up, then one per interval, and one at once whenever177+/// Runs backups until the stop flag is set. Every [`TICK`] it checks whether a run is due (see [`is_due`]); a
150-/// the admin page asks for it.178+/// request from the admin page starts a run at once.
151 pub async fn run(state: AppState, mut stop: watch::Receiver<bool>) {179 pub async fn run(state: AppState, mut stop: watch::Receiver<bool>) {
152 let Some(config) = state.config.backup.clone() else {180 let Some(config) = state.config.backup.clone() else {
153 return;181 return;
154 };182 };
155- let every = Duration::from_secs(u64::from(config.interval_hours) * 60 * 60);
156 loop {183 loop {
184+ tokio::select! {
185+ _ = stop.wait_for(|stopped| *stopped) => return,
186+ () = tokio::time::sleep(TICK) => {}
187+ () = state.backup.wake.notified() => {}
188+ }
189+ if !state.backup.requested() && !due(&state.store, &config).await {
190+ continue;
191+ }
157 state.backup.begin();192 state.backup.begin();
193+ record_attempt(&state.store).await;
158 let outcome = run_once(&state, &config).await;194 let outcome = run_once(&state, &config).await;
159 record_outcome(&state.store, &outcome).await;195 record_outcome(&state.store, &outcome).await;
160 match outcome {196 match outcome {
@@ -166,10 +202,17 @@ pub async fn run(state: AppState, mut stop: watch::Receiver<bool>) {
166 Err(error) => tracing::error!(error = %error, "backup: the run failed"),202 Err(error) => tracing::error!(error = %error, "backup: the run failed"),
167 }203 }
168 state.backup.finish();204 state.backup.finish();
169- tokio::select! {205+ }
170- _ = stop.wait_for(|stopped| *stopped) => return,206+}
171- () = tokio::time::sleep(every) => {}207+
172- () = state.backup.wake.notified() => {}208+/// True when a scheduled run is due, by the attempt recorded in the database. A store failure is logged and
209+/// counts as not due, so the next tick tries again.
210+async fn due(store: &Store, config: &Backup) -> bool {
211+ match store.get_setting(LAST_ATTEMPT_AT).await {
212+ Ok(last) => is_due(last.as_deref(), config.interval_hours),
213+ Err(error) => {
214+ tracing::error!(error = %error, "backup: the last attempt could not be read");
215+ false
173 }216 }
174 }217 }
175 }218 }
@@ -180,7 +223,7 @@ mod tests {
180 223
181 use in_core::time::{now_stamp, stamp_before};224 use in_core::time::{now_stamp, stamp_before};
182 225
183- use super::{BackupTrigger, is_stale};226+ use super::{BackupTrigger, is_due, is_stale};
184 227
185 #[test]228 #[test]
186 fn a_second_request_while_one_is_pending_starts_nothing() {229 fn a_second_request_while_one_is_pending_starts_nothing() {
@@ -202,4 +245,14 @@ mod tests {
202 assert!(is_stale(Some(&three_days), 24));245 assert!(is_stale(Some(&three_days), 24));
203 assert!(!is_stale(Some(&three_days), 168));246 assert!(!is_stale(Some(&three_days), 168));
204 }247 }
248+
249+ #[test]
250+ fn a_fresh_attempt_makes_the_next_tick_not_due() {
251+ assert!(is_due(None, 24));
252+ assert!(!is_due(Some(&now_stamp()), 24));
253+ assert!(is_due(
254+ Some(&stamp_before(Duration::from_secs(25 * 3600))),
255+ 24
256+ ));
257+ }
205 }258 }
docs/architecture.mdmodified+7 -4
@@ -238,10 +238,13 @@ and has no sessions.
238 which retries failed removals), seen JTIs, trash past238 which retries failed removals), seen JTIs, trash past
239 `purge_after_days`, audit rows past 365 days, unreferenced blobs older than 24 h, quota drift check (nightly).239 `purge_after_days`, audit rows past 365 days, unreferenced blobs older than 24 h, quota drift check (nightly).
240 - **backup** (optional): snapshot + blob tree manifest, HMAC-SHA256 over the manifest (`manifest.mac`, keyed from240 - **backup** (optional): snapshot + blob tree manifest, HMAC-SHA256 over the manifest (`manifest.mac`, keyed from
241- `in.key`, checked before a restore parses anything), keep N, dead-man pings. The worker also runs when the admin241+ `in.key`, checked before a restore parses anything), keep N, dead-man pings. The worker wakes every minute and
242- page asks (`BackupTrigger`: one busy flag and a `Notify` the worker waits on); at most one run is pending or running.242+ runs when no attempt is recorded or `backup.last_attempt_at` is at least `interval_hours` old (`backup::is_due`).
243- After every run, scheduled or manual, the outcome is written to `settings` (no migration): `backup.last_attempt_at`243+ The attempt time is written before the run, so a restart neither starts a run nor resets the interval. The
244- always, `backup.last_success_at` on success (and the error is cleared), `backup.last_error` on failure (the first244+ worker also runs when the admin page asks (`BackupTrigger`: one busy flag and a `Notify` the worker waits on); at
245+ most one run is pending or running. After every run, scheduled or manual, the outcome is written to `settings`
246+ (no migration): `backup.last_attempt_at` before the run, `backup.last_success_at` on success (and the error is
247+ cleared), `backup.last_error` on failure (the first
245 line of the error, control characters removed, at most 200 characters; never the ping URL). The admin Backups248 line of the error, control characters removed, at most 200 characters; never the ping URL). The admin Backups
246 section shows the last success and the last attempt, an alert while the latest run failed, and a warning when249 section shows the last success and the last attempt, an alert while the latest run failed, and a warning when
247 backups are on and the last success is older than the limit: `max(2 days, 2 × interval_hours)`250 backups are on and the last success is older than the limit: `max(2 days, 2 × interval_hours)`