diff --git a/crates/tessera-hub/src/state.rs b/crates/tessera-hub/src/state.rs index a595246..965f1c1 100644 --- a/crates/tessera-hub/src/state.rs +++ b/crates/tessera-hub/src/state.rs @@ -145,12 +145,13 @@ impl HubState { for id in jobs { let offsite = offsite.clone(); let prepared = state.vault.read().await.prepare_offsite_copy(id); - let success = match prepared { - Ok(copy) => offsite.copy_capture(copy).await.is_ok(), - Err(_) => false, + let result = match prepared { + Ok(copy) => offsite.copy_capture(copy).await, + Err(error) => Err(error), }; - if !success { - tracing::warn!(%id, "off-site capture copy failed"); + let success = result.is_ok(); + if let Err(error) = &result { + tracing::warn!(%id, error = %format!("{error:#}"), "off-site capture copy failed"); } if state.db.set_offsite_result(id, success).is_err() { tracing::warn!(%id, "could not save off-site copy status"); diff --git a/crates/tessera-store/src/offsite.rs b/crates/tessera-store/src/offsite.rs index 1ebad72..c8afb54 100644 --- a/crates/tessera-store/src/offsite.rs +++ b/crates/tessera-store/src/offsite.rs @@ -10,8 +10,28 @@ use std::{ use tokio::process::Command; use uuid::Uuid; +/// Wall-clock limits per restic call. A WAN object store answers in under a second most of the time and +/// in well over ten seconds some of the time, so these are sized for the slow case. +#[derive(Clone, Copy)] +struct Limits { + probe: u64, + list: u64, + init: u64, + copy: u64, +} + +const LIMITS: Limits = Limits { + probe: 120, + list: 120, + init: 90, + copy: 3600, +}; +/// A listing that times out is retried this many times before the copy is called failed. +const VERIFY_ATTEMPTS: usize = 3; + pub struct Offsite { repo: restic::Repository, + limits: Limits, } pub struct OffsiteCopy { @@ -46,15 +66,16 @@ impl Offsite { path: PathBuf::from(repository), password: password.into(), }, + limits: LIMITS, }) } fn command(&self) -> Command { let mut command = Command::from(self.repo.command()); command - .args(["-o", "s3.retries=1", "--stuck-request-timeout=15s"]) + .args(["-o", "s3.retries=3", "--stuck-request-timeout=60s"]) .stdout(Stdio::piped()) - .stderr(Stdio::null()) + .stderr(Stdio::piped()) .kill_on_drop(true); command } @@ -63,9 +84,16 @@ impl Offsite { restic::validate_id(id)?; let mut password = tempfile::NamedTempFile::new()?; writeln!(password, "{}", source.password)?; - let probe = run(self.command().args(["snapshots", "--json"]), 10).await?; + let probe = run( + self.command().args(["snapshots", "--json"]), + self.limits.probe, + ) + .await?; if probe.status.code() == Some(10) { - safe(run(self.command().arg("init"), 30).await?, "init")?; + safe( + run(self.command().arg("init"), self.limits.init).await?, + "init", + )?; } else { safe(probe, "probe")?; } @@ -82,7 +110,7 @@ impl Offsite { .arg("--from-password-file") .arg(password.path()) .arg(id), - 3600, + self.limits.copy, ) .await?, "copy", @@ -90,28 +118,36 @@ impl Offsite { Ok(()) } + /// The restic id of the copy tagged for this snapshot, `None` when there is none (or no repository yet). async fn tagged_snapshot(&self, snapshot: Uuid) -> Result> { #[derive(serde::Deserialize)] struct Copy { id: String, } - let output = safe( - run( - self.command().args([ - "snapshots", - "--json", - "--tag", - &restic::tessera_tag(snapshot), - ]), - 15, - ) - .await?, - "list", - )?; + let output = run( + self.command().args([ + "snapshots", + "--json", + "--tag", + &restic::tessera_tag(snapshot), + ]), + self.limits.list, + ) + .await?; + // Exit code 10: the repository does not exist yet, so nothing has been copied. + if output.status.code() == Some(10) { + return Ok(None); + } + let output = safe(output, "list")?; let mut snapshots: Vec = serde_json::from_slice(&output.stdout)?; Ok(snapshots.pop().map(|copy| copy.id)) } + /// `tagged_snapshot` with retries: a slow listing must not turn a finished copy into a failed one. + async fn tagged_snapshot_retrying(&self, snapshot: Uuid) -> Result> { + retry(VERIFY_ATTEMPTS, &[2, 5], || self.tagged_snapshot(snapshot)).await + } + pub async fn restore(&self, snapshot: Uuid, dest: &Path) -> Result { let id = self .tagged_snapshot(snapshot) @@ -141,9 +177,20 @@ impl Offsite { } pub async fn copy_capture(&self, copy: OffsiteCopy) -> Result<()> { + // A copy is complete once its tagged snapshot exists (restic writes the snapshot last), so an earlier + // attempt that finished but could not be confirmed is simply accepted instead of copied again. + if self + .tagged_snapshot_retrying(copy.snapshot) + .await? + .is_some() + { + return Ok(()); + } self.copy_from(©.source, ©.restic_id).await?; ensure!( - self.tagged_snapshot(copy.snapshot).await?.is_some(), + self.tagged_snapshot_retrying(copy.snapshot) + .await? + .is_some(), "off-site snapshot tag not found after copy" ); Ok(()) @@ -156,15 +203,173 @@ async fn run(command: &mut Command, seconds: u64) -> Result { command.spawn()?.wait_with_output(), ) .await - .context("off-site Restic operation timed out")??; + .with_context(|| format!("off-site Restic operation timed out after {seconds}s"))??; Ok(result) } fn safe(output: Output, step: &str) -> Result { ensure!( output.status.success(), - "off-site Restic {step} failed ({})", - output.status + "off-site Restic {step} failed ({}){}", + output.status, + stderr_tail(&output.stderr) ); Ok(output) } + +/// The end of restic's error output, on one line, so a failure says why. Restic never prints the +/// repository password or S3 keys (they travel in the environment). +fn stderr_tail(stderr: &[u8]) -> String { + let text = String::from_utf8_lossy(stderr); + let text = text.split_whitespace().collect::>().join(" "); + if text.is_empty() { + return String::new(); + } + let start = text + .char_indices() + .rev() + .nth(299) + .map_or(0, |(index, _)| index); + format!(": {}", &text[start..]) +} + +async fn retry(attempts: usize, delays: &[u64], mut attempt: F) -> Result +where + F: FnMut() -> Fut, + Fut: std::future::Future>, +{ + let mut tries = 0; + loop { + match attempt().await { + Ok(value) => return Ok(value), + Err(error) => { + tries += 1; + if tries >= attempts { + return Err(error); + } + let wait = delays + .get(tries - 1) + .or(delays.last()) + .copied() + .unwrap_or(0); + tokio::time::sleep(Duration::from_secs(wait)).await; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + #[tokio::test] + async fn a_slow_listing_is_retried_until_it_answers() { + let calls = AtomicUsize::new(0); + let value = retry(3, &[0], || async { + if calls.fetch_add(1, Ordering::SeqCst) < 2 { + anyhow::bail!("timed out") + } + Ok(7) + }) + .await + .unwrap(); + assert_eq!((value, calls.load(Ordering::SeqCst)), (7, 3)); + } + + #[tokio::test] + async fn retries_stop_and_report_the_last_error() { + let calls = AtomicUsize::new(0); + let error = retry::<(), _, _>(3, &[0], || async { + calls.fetch_add(1, Ordering::SeqCst); + anyhow::bail!("still down") + }) + .await + .unwrap_err(); + assert_eq!( + (error.to_string(), calls.load(Ordering::SeqCst)), + ("still down".into(), 3) + ); + } + + #[test] + fn a_failure_names_its_reason_without_dumping_the_output() { + let long = "x".repeat(2000); + let tail = stderr_tail(format!("line one\n {long} end").as_bytes()); + assert!(tail.starts_with(": ") && tail.ends_with(" end") && tail.len() <= 304); + assert_eq!(stderr_tail(b""), ""); + } + + fn restic_available() -> bool { + std::process::Command::new("restic") + .arg("version") + .output() + .is_ok_and(|out| out.status.success()) + } + + /// Real restic, local directories standing in for the object store: an absent destination repository is + /// created and filled, and an already-copied snapshot is accepted without touching the source again. + #[tokio::test] + async fn a_finished_copy_is_confirmed_and_not_copied_twice() { + if !restic_available() { + return; + } + let dir = tempfile::tempdir().unwrap(); + let source = restic::Repository { + path: dir.path().join("source"), + password: "source-pass".into(), + }; + fs::create_dir(&source.path).unwrap(); + let init = source.command().arg("init").output().unwrap(); + assert!(init.status.success()); + let data = dir.path().join("payload"); + fs::write(&data, b"synthetic dump").unwrap(); + let snapshot = Uuid::new_v4(); + let backup = source + .command() + .args(["backup", "--tag", &restic::tessera_tag(snapshot)]) + .arg(&data) + .output() + .unwrap(); + assert!(backup.status.success()); + let listing = source + .command() + .args(["snapshots", "--json"]) + .output() + .unwrap(); + let id = serde_json::from_slice::>(&listing.stdout).unwrap()[0] + ["id"] + .as_str() + .unwrap() + .to_string(); + + let offsite = Offsite { + repo: restic::Repository { + path: dir.path().join("offsite"), + password: "offsite-pass".into(), + }, + limits: LIMITS, + }; + let copy = |source: &restic::Repository| OffsiteCopy { + snapshot, + source: restic::Repository { + path: source.path.clone(), + password: source.password.clone(), + }, + restic_id: id.clone(), + }; + offsite.copy_capture(copy(&source)).await.unwrap(); + assert!(offsite.tagged_snapshot(snapshot).await.unwrap().is_some()); + + fs::remove_dir_all(&source.path).unwrap(); + offsite + .copy_capture(copy(&source)) + .await + .expect("an existing tagged copy needs no source"); + let other = Uuid::new_v4(); + let mut missing = copy(&source); + missing.snapshot = other; + let error = offsite.copy_capture(missing).await.unwrap_err(); + assert!(format!("{error:#}").contains("copy failed"), "{error:#}"); + } +}