feat: roll back a failed restore and say when a safety copy is gone
- a restore whose apply failed can be undone from its safety copy, which is its recovery: the failed apply stops fencing the target in the transaction that starts the undo (job phase rolled_back, audited restore.rolled_back); an apply whose agent went silent still waits for an administrator to reconcile it; reconciled restores can be undone - run views carry undo_state (available, superseded, expired), undo_kept_until, undo_of and restore_job_id - undo state for a list is worked out in one database pass and a file lookup per copy; the vault is read only for the newest restore of each target - eligibility is checked again inside the transaction that creates the run Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -71,25 +71,73 @@ struct RunView {
|
||||
snapshot_id: Option<String>,
|
||||
/// This run put a target back from the safety copy of an earlier restore.
|
||||
undo: bool,
|
||||
/// A completed restore that can still be undone: the newest restore of its target, with its safety copy in
|
||||
/// the vault. Never says where the copy is.
|
||||
/// For an undo, the run whose restore it puts back; the Activity log shows the undo under it.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
undo_of: Option<String>,
|
||||
/// The restore job this run queued, which is how the Activity log ties a restore to its run.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
restore_job_id: Option<String>,
|
||||
/// This restore can be put back right now: it is the newest of its target and its safety copy is in the vault.
|
||||
/// Never says where the copy is.
|
||||
undo_available: bool,
|
||||
/// Why it can or cannot be put back, for a restore that took a safety copy: `available`, `superseded` (something
|
||||
/// was restored onto the target after it) or `expired` (retention has forgotten the copy).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
undo_state: Option<&'static str>,
|
||||
/// While it can be undone: when the safety copy is first at risk of being forgotten. Retention keeps a copy a
|
||||
/// week, and longer while it is one of the target's newest few.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
undo_kept_until: Option<i64>,
|
||||
}
|
||||
|
||||
/// Can this run still be undone: see `Db::undo_candidate`, and the safety copy must still exist.
|
||||
async fn can_undo(state: &HubState, run: &RefreshRun) -> bool {
|
||||
if run.status != "completed" {
|
||||
return false;
|
||||
}
|
||||
match state.db.undo_candidate(&run.id, &run.relation_id) {
|
||||
Ok(Ok(safety)) => snapshot_fits(state, &run.relation_id, safety)
|
||||
.await
|
||||
.unwrap_or(false),
|
||||
_ => false,
|
||||
}
|
||||
/// What `undo_views` found out about one run.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Undo {
|
||||
state: &'static str,
|
||||
kept_until: Option<i64>,
|
||||
}
|
||||
|
||||
async fn view(state: &HubState, run: &RefreshRun, admin: bool) -> Result<RunView, StatusCode> {
|
||||
/// For every run in the list that took a safety copy, whether it can be put back. The database answers for all of
|
||||
/// them in one go; the vault is only asked whether a copy still exists (a file lookup), and read only for the one
|
||||
/// restore per target that could still be undone.
|
||||
async fn undo_views(
|
||||
state: &HubState,
|
||||
runs: &[RefreshRun],
|
||||
) -> Result<std::collections::HashMap<String, Undo>, StatusCode> {
|
||||
let infos = state.db.undo_infos(runs).map_err(internal)?;
|
||||
let mut views = std::collections::HashMap::new();
|
||||
if infos.is_empty() {
|
||||
return Ok(views);
|
||||
}
|
||||
let vault = state.vault.read().await;
|
||||
for run in runs {
|
||||
let Some(info) = infos.get(&run.id) else {
|
||||
continue;
|
||||
};
|
||||
// Safety copies are forgotten by retention: the restore stays in the log, but there is nothing to go back to.
|
||||
if !vault.has_published_snapshot(info.safety).map_err(internal)? {
|
||||
views.insert(run.id.clone(), Undo { state: "expired", kept_until: None });
|
||||
} else if !info.latest {
|
||||
views.insert(run.id.clone(), Undo { state: "superseded", kept_until: None });
|
||||
} else if let Some(taken) = fitting_snapshot(state, &vault, &run.relation_id, info.safety)? {
|
||||
let kept = taken + tessera_core::decay::SAFETY_KEEP_DAYS * 86_400;
|
||||
views.insert(run.id.clone(), Undo { state: "available", kept_until: Some(kept) });
|
||||
}
|
||||
}
|
||||
Ok(views)
|
||||
}
|
||||
|
||||
async fn view_one(state: &HubState, run: &RefreshRun, admin: bool) -> Result<RunView, StatusCode> {
|
||||
let undo = undo_views(state, std::slice::from_ref(run)).await?;
|
||||
view(state, run, admin, undo.get(&run.id))
|
||||
}
|
||||
|
||||
fn view(
|
||||
state: &HubState,
|
||||
run: &RefreshRun,
|
||||
admin: bool,
|
||||
undo: Option<&Undo>,
|
||||
) -> Result<RunView, StatusCode> {
|
||||
let Progress {
|
||||
capture_status,
|
||||
capture_phase,
|
||||
@@ -117,7 +165,11 @@ async fn view(state: &HubState, run: &RefreshRun, admin: bool) -> Result<RunView
|
||||
requested_by: admin.then(|| run.requester.clone()),
|
||||
snapshot_id: admin.then(|| run.snapshot_id.clone()).flatten(),
|
||||
undo: run.is_undo(),
|
||||
undo_available: can_undo(state, run).await,
|
||||
undo_of: state.db.undo_parent(run).map_err(internal)?,
|
||||
restore_job_id: run.restore_job_id.clone(),
|
||||
undo_available: undo.is_some_and(|undo| undo.state == "available"),
|
||||
undo_state: undo.map(|undo| undo.state),
|
||||
undo_kept_until: undo.and_then(|undo| undo.kept_until),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -168,39 +220,46 @@ fn valid_key(key: &str) -> bool {
|
||||
}
|
||||
|
||||
/// Is this snapshot one that a relation may restore: a database capture of the relation's own source orbit,
|
||||
/// never a safety copy of some target, with what a restore needs (format, checksum, source identity)?
|
||||
async fn snapshot_fits(
|
||||
/// never a safety copy of some target, with what a restore needs (format, checksum, source identity)? When it is,
|
||||
/// when it was taken (seconds since the epoch).
|
||||
fn fitting_snapshot(
|
||||
state: &HubState,
|
||||
vault: &tessera_store::Vault,
|
||||
relation: &str,
|
||||
snapshot: Uuid,
|
||||
) -> Result<bool, StatusCode> {
|
||||
) -> Result<Option<i64>, StatusCode> {
|
||||
let Some(source) = state.db.relation_source_orbit(relation).map_err(internal)? else {
|
||||
return Ok(false);
|
||||
return Ok(None);
|
||||
};
|
||||
let manifest = state
|
||||
.vault
|
||||
.read()
|
||||
.await
|
||||
.get_snapshot(snapshot)
|
||||
.map_err(internal)?
|
||||
.map(|s| s.manifest);
|
||||
let Some(stored) = vault.get_snapshot(snapshot).map_err(internal)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let manifest = &stored.manifest;
|
||||
let target = match state.db.relation_target(relation).map_err(internal)? {
|
||||
Some(id) => Uuid::parse_str(&id)
|
||||
.ok()
|
||||
.and_then(|id| state.db.restore_target(id).ok().flatten()),
|
||||
None => None,
|
||||
};
|
||||
Ok(manifest.is_some_and(|manifest| {
|
||||
manifest.orbit_id.to_string() == source
|
||||
&& if manifest.is_restore_safety() {
|
||||
// a safety copy only ever goes back onto the target it was taken from
|
||||
target.as_ref().is_some_and(|target| {
|
||||
crate::api::rollback_artifact(&manifest, target).is_some()
|
||||
})
|
||||
} else {
|
||||
crate::api::artifact(&manifest).is_some()
|
||||
}
|
||||
}))
|
||||
let fits = manifest.orbit_id.to_string() == source
|
||||
&& if manifest.is_restore_safety() {
|
||||
// a safety copy only ever goes back onto the target it was taken from
|
||||
target
|
||||
.as_ref()
|
||||
.is_some_and(|target| crate::api::rollback_artifact(manifest, target).is_some())
|
||||
} else {
|
||||
crate::api::artifact(manifest).is_some()
|
||||
};
|
||||
Ok(fits.then(|| stored.taken_at.timestamp()))
|
||||
}
|
||||
|
||||
async fn snapshot_fits(
|
||||
state: &HubState,
|
||||
relation: &str,
|
||||
snapshot: Uuid,
|
||||
) -> Result<bool, StatusCode> {
|
||||
let vault = state.vault.read().await;
|
||||
Ok(fitting_snapshot(state, &vault, relation, snapshot)?.is_some())
|
||||
}
|
||||
|
||||
async fn start(
|
||||
@@ -217,7 +276,7 @@ async fn start(
|
||||
let relation = body.relation_id.to_string();
|
||||
// What to restore: a snapshot the person picked, the safety copy that undoes an earlier restore, or (neither)
|
||||
// a fresh capture.
|
||||
let mut chosen: Option<(Uuid, bool)> = None;
|
||||
let mut chosen: Option<(Uuid, Option<String>)> = None;
|
||||
if let Some(of) = body.undo_of {
|
||||
if body.snapshot_id.is_some() {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
@@ -233,7 +292,7 @@ async fn start(
|
||||
if !snapshot_fits(&state, &relation, safety).await? {
|
||||
return Ok(reason(StatusCode::UNPROCESSABLE_ENTITY, "nothing_to_undo"));
|
||||
}
|
||||
chosen = Some((safety, true));
|
||||
chosen = Some((safety, Some(of.to_string())));
|
||||
} else if let Some(snapshot) = body.snapshot_id {
|
||||
if !snapshot_fits(&state, &relation, snapshot).await? {
|
||||
return Ok(reason(
|
||||
@@ -241,7 +300,7 @@ async fn start(
|
||||
"snapshot_unusable",
|
||||
));
|
||||
}
|
||||
chosen = Some((snapshot, false));
|
||||
chosen = Some((snapshot, None));
|
||||
}
|
||||
// What authorised this run, recorded so it can be checked again before anything is overwritten.
|
||||
let authorized_by = if actor.subject.admin {
|
||||
@@ -270,7 +329,7 @@ async fn start(
|
||||
actor.subject.user_id.as_deref(),
|
||||
&authorized_by,
|
||||
&body.idempotency_key,
|
||||
chosen,
|
||||
chosen.as_ref().map(|(snapshot, of)| (*snapshot, of.as_deref())),
|
||||
state.refresh.ttl_secs,
|
||||
state.refresh.max_active,
|
||||
now(),
|
||||
@@ -293,10 +352,13 @@ async fn start(
|
||||
Ok((
|
||||
status,
|
||||
no_store(),
|
||||
Json(view(&state, &run, actor.subject.admin).await?),
|
||||
Json(view_one(&state, &run, actor.subject.admin).await?),
|
||||
)
|
||||
.into_response())
|
||||
}
|
||||
Err(StartError::NothingToUndo) => {
|
||||
Ok(reason(StatusCode::UNPROCESSABLE_ENTITY, "nothing_to_undo"))
|
||||
}
|
||||
Err(StartError::UnknownRelation) => Err(StatusCode::NOT_FOUND),
|
||||
Err(StartError::Unusable(why)) => Ok((
|
||||
StatusCode::CONFLICT,
|
||||
@@ -343,9 +405,10 @@ async fn list(
|
||||
}
|
||||
}
|
||||
.map_err(internal)?;
|
||||
let undo = undo_views(&state, &runs).await?;
|
||||
let mut views = Vec::with_capacity(runs.len());
|
||||
for run in &runs {
|
||||
views.push(view(&state, run, actor.subject.admin).await?);
|
||||
views.push(view(&state, run, actor.subject.admin, undo.get(&run.id))?);
|
||||
}
|
||||
Ok((no_store(), Json(views)))
|
||||
}
|
||||
@@ -380,7 +443,7 @@ async fn show(
|
||||
let run = run.ok_or(StatusCode::NOT_FOUND)?;
|
||||
Ok((
|
||||
no_store(),
|
||||
Json(view(&state, &run, actor.subject.admin).await?),
|
||||
Json(view_one(&state, &run, actor.subject.admin).await?),
|
||||
))
|
||||
}
|
||||
|
||||
@@ -429,7 +492,7 @@ async fn cancel(
|
||||
crate::refresh::audit_run(&state, &run.id, "cancelled");
|
||||
Ok((
|
||||
no_store(),
|
||||
Json(view(&state, &run, actor.subject.admin).await?),
|
||||
Json(view_one(&state, &run, actor.subject.admin).await?),
|
||||
)
|
||||
.into_response())
|
||||
}
|
||||
|
||||
@@ -2257,6 +2257,16 @@ async fn a_completed_restore_can_be_undone_from_its_safety_copy_and_the_undo_can
|
||||
lab.report_applied(&job, &token).await;
|
||||
lab.tick().await;
|
||||
assert_eq!(lab.run(&undo_id).status, "completed");
|
||||
// the undo says which restore it puts back, and the restore says which job it queued
|
||||
let (_, child) = lab
|
||||
.send(&qa, "GET", &format!("/api/v1/refresh-runs/{undo_id}"), None)
|
||||
.await;
|
||||
assert_eq!(child["undo_of"], json!(first), "{child}");
|
||||
assert!(child["restore_job_id"].is_string(), "{child}");
|
||||
let (_, parent) = lab
|
||||
.send(&qa, "GET", &format!("/api/v1/refresh-runs/{first}"), None)
|
||||
.await;
|
||||
assert!(parent.get("undo_of").is_none(), "{parent}");
|
||||
|
||||
// only the newest restore of a target can be undone: the first one no longer can, the undo can
|
||||
let (_, old) = lab
|
||||
@@ -2365,3 +2375,118 @@ async fn only_someone_who_may_use_the_relation_can_undo_through_it() {
|
||||
);
|
||||
assert_eq!(lab.scalar::<i64>("SELECT COUNT(*) FROM refresh_runs"), 1);
|
||||
}
|
||||
|
||||
// ---- why a restore can or cannot be put back, and rolling back a restore that failed ----
|
||||
|
||||
impl Lab {
|
||||
async fn run_view(&self, run: &str) -> Value {
|
||||
self.send(&self.admin(), "GET", &format!("/api/v1/refresh-runs/{run}"), None)
|
||||
.await
|
||||
.1
|
||||
}
|
||||
|
||||
fn safety_of(&self, run: &str) -> Uuid {
|
||||
Uuid::parse_str(&self.scalar::<String>(&format!(
|
||||
"SELECT safety_id FROM restore_jobs WHERE id=(SELECT restore_job_id FROM refresh_runs WHERE id='{run}')"
|
||||
)))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// A restore that got as far as overwriting the target and then failed, as the agent reports it.
|
||||
async fn failed_apply(&self, key: &str) -> (String, String) {
|
||||
let (_, run) = self.start(&self.admin(), key).await;
|
||||
let run = run["id"].as_str().unwrap().to_string();
|
||||
self.capture(&Lab::production_identity(), false).await.unwrap();
|
||||
self.tick().await;
|
||||
let (job, token) = self.restore_until_ready().await.expect("a restore job is waiting");
|
||||
assert_eq!(self.apply(&job, &token).await, StatusCode::NO_CONTENT);
|
||||
let (status, _) = self
|
||||
.agent_json(
|
||||
"POST",
|
||||
&format!("/api/v1/wormhole/restore/{job}/report"),
|
||||
&[("x-tessera-restore-token", token)],
|
||||
json!("apply_failed"),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::NO_CONTENT);
|
||||
self.tick().await;
|
||||
assert_eq!(self.run(&run).status, "recovery_required");
|
||||
(run, job)
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_restore_says_why_it_can_or_cannot_be_put_back_and_how_long_for() {
|
||||
let lab = fresh().await;
|
||||
let first = lab.restored_once("first").await;
|
||||
let view = lab.run_view(&first).await;
|
||||
assert_eq!((view["undo_available"].clone(), view["undo_state"].clone()), (json!(true), json!("available")), "{view}");
|
||||
let until = view["undo_kept_until"].as_i64().expect("a date while it can be undone");
|
||||
assert!(until > chrono::Utc::now().timestamp() + 6 * 86_400, "a week from when it was taken: {view}");
|
||||
|
||||
// a later restore of the same target supersedes it; only the newest can be undone
|
||||
let second = lab.restored_once("second").await;
|
||||
let (old, new) = (lab.run_view(&first).await, lab.run_view(&second).await);
|
||||
assert_eq!((old["undo_state"].clone(), old["undo_available"].clone()), (json!("superseded"), json!(false)), "{old}");
|
||||
assert_eq!(new["undo_state"], "available", "{new}");
|
||||
|
||||
// retention forgets the newest copy: it says so, instead of offering something that would be refused
|
||||
lab.state.vault.write().await.forget(&[lab.safety_of(&second)]).unwrap();
|
||||
let new = lab.run_view(&second).await;
|
||||
assert_eq!((new["undo_state"].clone(), new["undo_available"].clone()), (json!("expired"), json!(false)), "{new}");
|
||||
assert!(new.get("undo_kept_until").is_none(), "{new}");
|
||||
// expired wins over superseded, so nobody is told to look for a copy that is gone
|
||||
lab.state.vault.write().await.forget(&[lab.safety_of(&first)]).unwrap();
|
||||
assert_eq!(lab.run_view(&first).await["undo_state"], "expired");
|
||||
// the list says the same, for a person who may only use the relation
|
||||
let (qa, _) = lab.refresher("qa");
|
||||
let (_, list) = lab.send(&qa, "GET", "/api/v1/refresh-runs", None).await;
|
||||
let states: Vec<_> = list.as_array().unwrap().iter().map(|r| r["undo_state"].clone()).collect();
|
||||
assert_eq!(states, vec![json!("expired"), json!("expired")], "{list}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_restore_whose_apply_failed_is_rolled_back_from_its_safety_copy() {
|
||||
let lab = fresh().await;
|
||||
let (qa, _) = lab.refresher("qa");
|
||||
let (run, job) = lab.failed_apply("broken").await;
|
||||
let view = lab.run_view(&run).await;
|
||||
assert_eq!(view["undo_available"], true, "rolling back is offered: {view}");
|
||||
|
||||
// while the failed apply fences the target nothing else may start, but the rollback may
|
||||
let (status, other) = lab.start(&qa, "other").await;
|
||||
assert_eq!((status, other["reason"].clone()), (StatusCode::CONFLICT, json!("run_active")), "{other}");
|
||||
let (status, undo) = lab.start_undo(&qa, "rollback", &run).await;
|
||||
assert_eq!(status, StatusCode::ACCEPTED, "{undo}");
|
||||
assert_eq!(undo["undo_of"], json!(run));
|
||||
assert_eq!(lab.run(&run).status, "reconciled");
|
||||
assert_eq!(lab.scalar::<String>(&format!("SELECT phase FROM restore_jobs WHERE id='{job}'")), "rolled_back");
|
||||
assert!(lab.audit_log().iter().any(|(event, _)| event == "restore.rolled_back"));
|
||||
|
||||
// it goes through the same engine and puts the copy back
|
||||
lab.tick().await;
|
||||
lab.finish_restore().await;
|
||||
assert_eq!(lab.run(undo["id"].as_str().unwrap()).status, "completed");
|
||||
assert_eq!(lab.run_view(&run).await["undo_state"], "superseded", "it is not offered twice");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_apply_that_lost_its_agent_waits_for_an_administrator_before_it_can_be_rolled_back() {
|
||||
let lab = fresh().await;
|
||||
let (run, job) = lab.failed_apply("silent").await;
|
||||
// the agent did not say it stopped: the apply may still be writing
|
||||
lab.conn()
|
||||
.execute("UPDATE restore_jobs SET phase='lease_lost' WHERE id=?1", [&job])
|
||||
.unwrap();
|
||||
assert_eq!(lab.run_view(&run).await["undo_available"], false);
|
||||
let (status, body) = lab.start_undo(&lab.admin(), "early", &run).await;
|
||||
assert_eq!((status, body["reason"].clone()), (StatusCode::UNPROCESSABLE_ENTITY, json!("nothing_to_undo")), "{body}");
|
||||
|
||||
// once an administrator has verified it, the same safety copy can put the target back
|
||||
assert!(lab.state.db.reconcile_restore(Uuid::parse_str(&job).unwrap(), "admin", now()).unwrap());
|
||||
lab.tick().await;
|
||||
assert_eq!(lab.run(&run).status, "reconciled");
|
||||
assert_eq!(lab.run_view(&run).await["undo_available"], true);
|
||||
let (status, undo) = lab.start_undo(&lab.admin(), "after", &run).await;
|
||||
assert_eq!(status, StatusCode::ACCEPTED, "{undo}");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user