forge
Explore
Log in

Don't you dare go Hollow

iz

Clone
★ 0

0 watching0 forksRustAGPL-3.0567.3 KiB3950aceTahinli27 days ago34 commits

backup.rs484 lines, 20.5 KiBHistoryRawDownload
1//! The scheduled backup worker. It wakes every minute and writes one backup set under `[backup] dir` when a run
2//! is due: no attempt is recorded yet, or the last attempt is at least `interval_hours` old. Then it keeps the
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.
8//!
9//! A set is a directory named by its UTC stamp (for example `20261028T093000Z`). It holds `iz.db` (a
10//! `VACUUM INTO` snapshot), `attachments/<id>` for every attachment whose bytes are local, and
11//! `manifest.json` and `manifest.mac` written last (`iz_core::manifest`), the MAC keyed by the instance key. A set is built in `.tmp-<ulid>` and renamed to its
12//! stamp only when complete, so a directory with a manifest is always a whole set. A failed set is removed.
13//! Only directories this worker created, or names that match the stamp pattern and hold a manifest, are ever
14//! deleted. Nothing is written in place.
15//!
16//! The admin settings page can ask for a run now through [`BackupTrigger`], which runs at once. At most one run
17//! is pending or running: a request made meanwhile starts nothing. Scheduled and requested runs both hold the
18//! busy flag, so they never overlap.
19//!
20//! Every run records its outcome in the `settings` table (the attempt time, the last success, and the error of
21//! the latest attempt), so a failing backup is visible on the Backups card. [`status`] reads it back and
22//! [`is_stale`] says when no success is recent enough to warn about.
23
24use std::os::unix::fs::DirBuilderExt;
25use std::path::{Path, PathBuf};
26use std::sync::atomic::{AtomicBool, Ordering};
27use std::time::Duration;
28
29use iz_core::clock::{stamp_of, timestamp_of};
30use iz_core::config::BackupConfig;
31use iz_core::manifest::{self, MANIFEST_NAME};
32use iz_core::staging::{ATTACHMENTS_DIR, blob_path};
33use iz_core::store::{Store, new_id};
34use iz_core::time::now_stamp;
35use iz_core::{Error, Result};
36use jiff::Timestamp;
37use tokio::sync::{Notify, watch};
38
39use crate::state::AppState;
40
41/// Asks the backup worker for a run now. A run is pending or running at most once: a request made while one is
42/// pending or running starts nothing.
43#[derive(Default)]
44pub struct BackupTrigger {
45 /// True from a request, or from the start of a scheduled run, until that run ends.
46 busy: AtomicBool,
47 /// Wakes the worker out of its wait when a request arrives.
48 wake: Notify,
49}
50
51impl BackupTrigger {
52 /// Asks for a run now. Returns true when this request starts one, false when one is already pending or
53 /// running.
54 pub fn request(&self) -> bool {
55 if self.busy.swap(true, Ordering::AcqRel) {
56 return false;
57 }
58 self.wake.notify_one();
59 true
60 }
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
67 /// Marks a run as running, so requests made meanwhile start nothing.
68 fn begin(&self) {
69 self.busy.store(true, Ordering::Release);
70 }
71
72 /// Marks the run as ended. A request made after this starts a new run.
73 fn finish(&self) {
74 self.busy.store(false, Ordering::Release);
75 }
76}
77
78/// Prefix of a set that is still being written. Reason: a crash leaves a visibly unfinished directory.
79const TMP_PREFIX: &str = ".tmp-";
80/// The database copy inside a set.
81const 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.
84const TICK: Duration = Duration::from_secs(60);
85/// How long a healthcheck ping may take, in seconds. Reason: a slow ping must not hold the worker.
86const PING_TIMEOUT: Duration = Duration::from_secs(10);
87/// The stamp format of a set's directory name. Reason: no colons, so the name is portable.
88const SET_STAMP_FORMAT: &str = "%Y%m%dT%H%M%SZ";
89/// Length of a set's directory name, which is the stamp format above.
90const SET_NAME_LEN: usize = 16;
91
92/// Settings key: when a run was last attempted (a UTC stamp).
93pub const LAST_ATTEMPT_SETTING: &str = "backup_last_attempt";
94/// Settings key: when a run last succeeded (a UTC stamp). Never cleared, so the card shows the last good set.
95pub const LAST_SUCCESS_SETTING: &str = "backup_last_success";
96/// Settings key: the text of the error of the latest attempt. Empty after a success.
97pub const LAST_ERROR_SETTING: &str = "backup_last_error";
98/// Time without a success after which the settings page warns. Reason: two days lets one scheduled run be
99/// missed without a warning, and a longer gap means the backups are not happening.
100const STALE_AFTER: Duration = Duration::from_secs(2 * 24 * 3600);
101/// Longest error text kept, in characters. Reason: the settings page shows it on one line.
102const ERROR_TEXT_MAX: usize = 200;
103
104/// The recorded outcome of the backup runs, as the settings page reads it. Stamps are UTC; `None` when no
105/// value was recorded.
106#[derive(Debug, Clone, Default)]
107pub struct BackupStatus {
108 /// When the latest attempt started.
109 pub last_attempt: Option<String>,
110 /// When the last successful run finished.
111 pub last_success: Option<String>,
112 /// The text of the error of the latest attempt. `None` when that attempt succeeded.
113 pub last_error: Option<String>,
114}
115
116/// Reads the recorded outcome. Empty values count as not recorded.
117pub async fn status(store: &Store) -> Result<BackupStatus> {
118 Ok(BackupStatus {
119 last_attempt: store
120 .get_setting(LAST_ATTEMPT_SETTING)
121 .await?
122 .filter(|value| !value.is_empty()),
123 last_success: store
124 .get_setting(LAST_SUCCESS_SETTING)
125 .await?
126 .filter(|value| !value.is_empty()),
127 last_error: store
128 .get_setting(LAST_ERROR_SETTING)
129 .await?
130 .filter(|value| !value.is_empty()),
131 })
132}
133
134/// Whether the backups are overdue at `now`: no success was ever recorded, or the last one is older than
135/// [`STALE_AFTER`] or two backup intervals, whichever is longer, so a weekly schedule is not always overdue.
136/// A stamp that does not parse counts as no success.
137pub fn is_stale(last_success: Option<&str>, interval_hours: u32, now: Timestamp) -> bool {
138 let Some(last) = last_success.and_then(|stamp| timestamp_of(stamp).ok()) else {
139 return true;
140 };
141 let limit = i64::try_from(STALE_AFTER.as_secs())
142 .unwrap_or(i64::MAX)
143 .max(i64::from(interval_hours) * 2 * 3600);
144 now.as_second().saturating_sub(last.as_second()) > limit
145}
146
147/// Starts the backup worker when the config has a `[backup]` section. Without one this does nothing.
148/// Every minute it checks whether a run is due (see [`is_due`]). An administrator's request runs at once (see
149/// [`BackupTrigger`]).
150pub fn spawn(state: AppState, mut stop: watch::Receiver<bool>) {
151 let Some(policy) = state.config.backup.clone() else {
152 return;
153 };
154 tokio::spawn(async move {
155 let client = match reqwest::Client::builder()
156 .timeout(PING_TIMEOUT)
157 .user_agent(concat!("iz/", env!("CARGO_PKG_VERSION")))
158 .build()
159 {
160 Ok(client) => Some(client),
161 Err(error) => {
162 tracing::warn!(error = %error, "healthcheck client not built; pings are off");
163 None
164 }
165 };
166 loop {
167 tokio::select! {
168 () = tokio::time::sleep(TICK) => {}
169 () = state.backup.wake.notified() => {}
170 _ = stop.wait_for(|stopped| *stopped) => break,
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 }
177 }
178 tracing::info!("backup worker stopped");
179 });
180}
181
182/// Whether a run is due now: see [`is_due`]. A recorded attempt that cannot be read means no run this tick.
183async 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.
195fn 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
205/// One backup: record the attempt, write and publish a set, prune the old sets, ping the healthcheck, and
206/// record the outcome. A failure is logged and recorded, and leaves no partial set. A stop request cancels a
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.
209async fn run_once(
210 state: &AppState,
211 policy: &BackupConfig,
212 client: Option<&reqwest::Client>,
213 stop: &mut watch::Receiver<bool>,
214) {
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 }
224 match write_and_publish(state, policy, stop).await {
225 Ok((name, files)) => {
226 tracing::info!(set = %name, files, "backup set written");
227 record_outcome(&state.store, LAST_SUCCESS_SETTING, &now_stamp()).await;
228 record_outcome(&state.store, LAST_ERROR_SETTING, "").await;
229 let keep = usize::try_from(policy.keep).unwrap_or(usize::MAX);
230 match prune(&policy.dir, keep) {
231 Ok(0) => {}
232 Ok(removed) => tracing::info!(removed, "old backup sets deleted"),
233 Err(error) => tracing::warn!(error = %error, "pruning old backup sets failed"),
234 }
235 if let (Some(url), Some(client)) = (policy.healthcheck_url.as_deref(), client) {
236 ping(client, url).await;
237 }
238 }
239 Err(error) => {
240 record_outcome(&state.store, LAST_ERROR_SETTING, &error_text(&error)).await;
241 tracing::warn!(error = %error, "backup failed; the partial set was removed");
242 }
243 }
244}
245
246/// Writes one set in a temporary directory and publishes it under its stamp. Returns the set's name and its
247/// file count. On failure this removes the temporary directory, by its exact path.
248async fn write_and_publish(
249 state: &AppState,
250 policy: &BackupConfig,
251 stop: &mut watch::Receiver<bool>,
252) -> Result<(String, usize)> {
253 ensure_dir(&policy.dir)?;
254 let now = Timestamp::now();
255 let name = now.strftime(SET_STAMP_FORMAT).to_string();
256 let created_at = stamp_of(now)?;
257 let tmp = policy.dir.join(format!("{TMP_PREFIX}{}", new_id()));
258 let outcome = tokio::select! {
259 result = write_set(&state.store, &state.config.data_dir, &state.key, &tmp, &created_at) => result,
260 _ = stop.wait_for(|stopped| *stopped) => {
261 Err(Error::Io(std::io::Error::other("stopped before the set was finished")))
262 }
263 };
264 let outcome = outcome.and_then(|files| publish(&tmp, &policy.dir, &name).map(|()| files));
265 if outcome.is_err() {
266 // Only the directory this run created is removed, by its exact path.
267 let _ = std::fs::remove_dir_all(&tmp);
268 }
269 outcome.map(|files| (name, files))
270}
271
272/// Stores one outcome value. A failure is logged and never fails or stops the run.
273async fn record_outcome(store: &Store, key: &str, value: &str) {
274 if let Err(error) = store.set_setting(key, value).await {
275 tracing::error!(error = %error, key, "backup outcome not recorded");
276 }
277}
278
279/// The short text kept for a failed run and shown on the settings page. It never holds a database message,
280/// since those can echo statement text, and it names no path: a filesystem error keeps only its OS reason.
281fn error_text(error: &Error) -> String {
282 let text = match error {
283 Error::Io(_) => error.to_string(),
284 Error::Conflict(text) => text.clone(),
285 Error::Database(_) => "database error".to_owned(),
286 Error::Migration(_) => "migration error".to_owned(),
287 _ => "backup failed".to_owned(),
288 };
289 text.chars().take(ERROR_TEXT_MAX).collect()
290}
291
292/// Writes the files of one set into `tmp` and the manifest and its MAC last. Returns the number of files
293/// listed, not counting the manifest. The caller removes `tmp` on error.
294async fn write_set(
295 store: &Store,
296 data_dir: &Path,
297 instance_key: &[u8; 32],
298 tmp: &Path,
299 created_at: &str,
300) -> Result<usize> {
301 create_dir(tmp, false)?;
302 store.snapshot_to(&tmp.join(DB_FILE)).await?;
303 let mut paths = vec![DB_FILE.to_owned()];
304 let attachments = tmp.join(ATTACHMENTS_DIR);
305 create_dir(&attachments, false)?;
306 for id in store.local_attachment_ids().await? {
307 let source = blob_path(data_dir, &id)?;
308 let relative = format!("{ATTACHMENTS_DIR}/{id}");
309 let target = tmp.join(&relative);
310 tokio::fs::copy(&source, &target).await?;
311 tokio::fs::File::open(&target).await?.sync_all().await?;
312 paths.push(relative);
313 }
314 let files = paths.len();
315 // Hashing reads every file, which can take a while; it runs off the async threads.
316 let dir = tmp.to_owned();
317 let created = created_at.to_owned();
318 let build = env!("IZ_BUILD_SHA").to_owned();
319 let key = *instance_key;
320 tokio::task::spawn_blocking(move || {
321 manifest::write_manifest(&dir, &key, &created, &build, &paths)
322 })
323 .await
324 .map_err(|error| Error::Io(std::io::Error::other(error)))??;
325 Ok(files)
326}
327
328/// Creates the backup directory and any missing parents, unless it already exists.
329fn ensure_dir(dir: &Path) -> std::io::Result<()> {
330 if dir.is_dir() {
331 return Ok(());
332 }
333 create_dir(dir, true)
334}
335
336/// Renames a complete set to its stamp and makes the rename durable. Refuses to replace an existing name.
337fn publish(tmp: &Path, dir: &Path, name: &str) -> Result<()> {
338 let target = dir.join(name);
339 if std::fs::symlink_metadata(&target).is_ok() {
340 return Err(Error::Conflict(format!("backup set {name} already exists")));
341 }
342 std::fs::rename(tmp, &target)?;
343 std::fs::File::open(dir)?.sync_all()?;
344 Ok(())
345}
346
347/// Deletes all finished sets except the newest `keep`. Only directories named like a set and holding a
348/// manifest are candidates, so an unrelated directory in the backup dir is never touched. Returns the count.
349fn prune(dir: &Path, keep: usize) -> Result<usize> {
350 let mut sets: Vec<PathBuf> = std::fs::read_dir(dir)?
351 .filter_map(std::result::Result::ok)
352 .filter(|entry| is_set_name(&entry.file_name().to_string_lossy()))
353 .map(|entry| entry.path())
354 .filter(|path| is_finished_set(path))
355 .collect();
356 // The stamp is fixed width and sorts in time order, so the name order is the age order.
357 sets.sort();
358 let excess = sets.len().saturating_sub(keep);
359 for old in &sets[..excess] {
360 std::fs::remove_dir_all(old)?;
361 }
362 Ok(excess)
363}
364
365/// Whether `name` has the shape of a set's directory name: `YYYYMMDDTHHMMSSZ`.
366fn is_set_name(name: &str) -> bool {
367 let bytes = name.as_bytes();
368 bytes.len() == SET_NAME_LEN
369 && bytes.iter().enumerate().all(|(i, byte)| match i {
370 8 => *byte == b'T',
371 15 => *byte == b'Z',
372 _ => byte.is_ascii_digit(),
373 })
374}
375
376/// Whether `path` is a real directory (not a link) that holds a manifest.
377fn is_finished_set(path: &Path) -> bool {
378 let is_dir = std::fs::symlink_metadata(path).is_ok_and(|meta| meta.file_type().is_dir());
379 let has_manifest = std::fs::symlink_metadata(path.join(MANIFEST_NAME))
380 .is_ok_and(|meta| meta.file_type().is_file());
381 is_dir && has_manifest
382}
383
384/// Creates a directory with mode 0700. `recursive` also creates missing parents.
385fn create_dir(path: &Path, recursive: bool) -> std::io::Result<()> {
386 std::fs::DirBuilder::new()
387 .recursive(recursive)
388 .mode(0o700)
389 .create(path)
390}
391
392/// Pings the healthcheck once. A failure is logged without the URL, because the URL can carry a secret key.
393async fn ping(client: &reqwest::Client, url: &str) {
394 match client.get(url).send().await {
395 Ok(response) if response.status().is_success() => {}
396 Ok(response) => {
397 tracing::warn!(status = %response.status(), "healthcheck ping was refused");
398 }
399 Err(error) => {
400 tracing::warn!(error = %error.without_url(), "healthcheck ping failed");
401 }
402 }
403}
404
405#[cfg(test)]
406mod tests {
407 use super::*;
408
409 #[test]
410 fn a_second_request_while_one_is_pending_or_running_starts_nothing() {
411 let trigger = BackupTrigger::default();
412 assert!(trigger.request());
413 assert!(!trigger.request());
414 trigger.begin();
415 assert!(!trigger.request());
416 trigger.finish();
417 assert!(trigger.request());
418 }
419
420 /// A finished set on disk: a directory with a manifest, named by its stamp.
421 fn fake_set(dir: &Path, name: &str) {
422 let set = dir.join(name);
423 std::fs::create_dir(&set).expect("set dir");
424 std::fs::write(set.join(MANIFEST_NAME), b"{}").expect("manifest");
425 }
426
427 #[tokio::test]
428 async fn a_written_set_verifies_and_is_published_by_its_stamp() {
429 let dir = tempfile::tempdir().expect("temp dir");
430 let store = Store::open(&dir.path().join("iz.db")).await.expect("store");
431 let tmp = dir.path().join(format!("{TMP_PREFIX}{}", new_id()));
432 let created = "2026-10-28T09:30:00.000000000Z";
433 let key = [6u8; 32];
434 write_set(&store, dir.path(), &key, &tmp, created)
435 .await
436 .expect("set written");
437 publish(&tmp, dir.path(), "20261028T093000Z").expect("published");
438 let published = dir.path().join("20261028T093000Z");
439 let verified = manifest::verify_set(&published, &key).expect("the set verifies");
440 assert_eq!(verified.created_at, created);
441 assert!(verified.files.iter().any(|file| file.path == DB_FILE));
442 assert!(!tmp.exists(), "the temporary name is gone after the rename");
443 }
444
445 #[test]
446 fn prune_keeps_the_newest_sets_and_leaves_other_directories() {
447 let dir = tempfile::tempdir().expect("temp dir");
448 for name in [
449 "20260101T000000Z",
450 "20260102T000000Z",
451 "20260103T000000Z",
452 "20260104T000000Z",
453 ] {
454 fake_set(dir.path(), name);
455 }
456 std::fs::create_dir(dir.path().join("notes")).expect("unrelated dir");
457 std::fs::create_dir(dir.path().join(format!("{TMP_PREFIX}abc"))).expect("tmp dir");
458 assert_eq!(prune(dir.path(), 2).expect("prune"), 2);
459 assert!(!dir.path().join("20260101T000000Z").exists());
460 assert!(!dir.path().join("20260102T000000Z").exists());
461 assert!(dir.path().join("20260103T000000Z").exists());
462 assert!(dir.path().join("20260104T000000Z").exists());
463 assert!(dir.path().join("notes").exists());
464 assert!(dir.path().join(format!("{TMP_PREFIX}abc")).exists());
465 }
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
476 #[test]
477 fn a_backup_is_stale_without_a_success_or_after_two_days() {
478 let now: Timestamp = "2026-10-28T12:00:00Z".parse().expect("time");
479 assert!(is_stale(None, 24, now));
480 assert!(!is_stale(Some("2026-10-26T12:00:00.000000000Z"), 24, now));
481 assert!(is_stale(Some("2026-10-26T11:59:59.000000000Z"), 24, now));
482 assert!(!is_stale(Some("2026-10-26T11:59:59.000000000Z"), 168, now));
483 }
484}