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:
2026-11-16 20:37:21 +07:00
parent 648c8c6a2a
commit 62f0c68e89
5 changed files with 374 additions and 87 deletions

View File

@@ -71,25 +71,73 @@ struct RunView {
snapshot_id: Option<String>, snapshot_id: Option<String>,
/// This run put a target back from the safety copy of an earlier restore. /// This run put a target back from the safety copy of an earlier restore.
undo: bool, undo: bool,
/// A completed restore that can still be undone: the newest restore of its target, with its safety copy in /// For an undo, the run whose restore it puts back; the Activity log shows the undo under it.
/// the vault. Never says where the copy is. #[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, 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. /// What `undo_views` found out about one run.
async fn can_undo(state: &HubState, run: &RefreshRun) -> bool { #[derive(Clone, Copy)]
if run.status != "completed" { struct Undo {
return false; state: &'static str,
} kept_until: Option<i64>,
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,
}
} }
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 { let Progress {
capture_status, capture_status,
capture_phase, capture_phase,
@@ -117,7 +165,11 @@ async fn view(state: &HubState, run: &RefreshRun, admin: bool) -> Result<RunView
requested_by: admin.then(|| run.requester.clone()), requested_by: admin.then(|| run.requester.clone()),
snapshot_id: admin.then(|| run.snapshot_id.clone()).flatten(), snapshot_id: admin.then(|| run.snapshot_id.clone()).flatten(),
undo: run.is_undo(), 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, /// 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)? /// never a safety copy of some target, with what a restore needs (format, checksum, source identity)? When it is,
async fn snapshot_fits( /// when it was taken (seconds since the epoch).
fn fitting_snapshot(
state: &HubState, state: &HubState,
vault: &tessera_store::Vault,
relation: &str, relation: &str,
snapshot: Uuid, snapshot: Uuid,
) -> Result<bool, StatusCode> { ) -> Result<Option<i64>, StatusCode> {
let Some(source) = state.db.relation_source_orbit(relation).map_err(internal)? else { let Some(source) = state.db.relation_source_orbit(relation).map_err(internal)? else {
return Ok(false); return Ok(None);
}; };
let manifest = state let Some(stored) = vault.get_snapshot(snapshot).map_err(internal)? else {
.vault return Ok(None);
.read() };
.await let manifest = &stored.manifest;
.get_snapshot(snapshot)
.map_err(internal)?
.map(|s| s.manifest);
let target = match state.db.relation_target(relation).map_err(internal)? { let target = match state.db.relation_target(relation).map_err(internal)? {
Some(id) => Uuid::parse_str(&id) Some(id) => Uuid::parse_str(&id)
.ok() .ok()
.and_then(|id| state.db.restore_target(id).ok().flatten()), .and_then(|id| state.db.restore_target(id).ok().flatten()),
None => None, None => None,
}; };
Ok(manifest.is_some_and(|manifest| { let fits = manifest.orbit_id.to_string() == source
manifest.orbit_id.to_string() == source && if manifest.is_restore_safety() {
&& if manifest.is_restore_safety() { // a safety copy only ever goes back onto the target it was taken from
// a safety copy only ever goes back onto the target it was taken from target
target.as_ref().is_some_and(|target| { .as_ref()
crate::api::rollback_artifact(&manifest, target).is_some() .is_some_and(|target| crate::api::rollback_artifact(manifest, target).is_some())
}) } else {
} else { crate::api::artifact(manifest).is_some()
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( async fn start(
@@ -217,7 +276,7 @@ async fn start(
let relation = body.relation_id.to_string(); 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) // What to restore: a snapshot the person picked, the safety copy that undoes an earlier restore, or (neither)
// a fresh capture. // 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 let Some(of) = body.undo_of {
if body.snapshot_id.is_some() { if body.snapshot_id.is_some() {
return Err(StatusCode::BAD_REQUEST); return Err(StatusCode::BAD_REQUEST);
@@ -233,7 +292,7 @@ async fn start(
if !snapshot_fits(&state, &relation, safety).await? { if !snapshot_fits(&state, &relation, safety).await? {
return Ok(reason(StatusCode::UNPROCESSABLE_ENTITY, "nothing_to_undo")); 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 { } else if let Some(snapshot) = body.snapshot_id {
if !snapshot_fits(&state, &relation, snapshot).await? { if !snapshot_fits(&state, &relation, snapshot).await? {
return Ok(reason( return Ok(reason(
@@ -241,7 +300,7 @@ async fn start(
"snapshot_unusable", "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. // What authorised this run, recorded so it can be checked again before anything is overwritten.
let authorized_by = if actor.subject.admin { let authorized_by = if actor.subject.admin {
@@ -270,7 +329,7 @@ async fn start(
actor.subject.user_id.as_deref(), actor.subject.user_id.as_deref(),
&authorized_by, &authorized_by,
&body.idempotency_key, &body.idempotency_key,
chosen, chosen.as_ref().map(|(snapshot, of)| (*snapshot, of.as_deref())),
state.refresh.ttl_secs, state.refresh.ttl_secs,
state.refresh.max_active, state.refresh.max_active,
now(), now(),
@@ -293,10 +352,13 @@ async fn start(
Ok(( Ok((
status, status,
no_store(), no_store(),
Json(view(&state, &run, actor.subject.admin).await?), Json(view_one(&state, &run, actor.subject.admin).await?),
) )
.into_response()) .into_response())
} }
Err(StartError::NothingToUndo) => {
Ok(reason(StatusCode::UNPROCESSABLE_ENTITY, "nothing_to_undo"))
}
Err(StartError::UnknownRelation) => Err(StatusCode::NOT_FOUND), Err(StartError::UnknownRelation) => Err(StatusCode::NOT_FOUND),
Err(StartError::Unusable(why)) => Ok(( Err(StartError::Unusable(why)) => Ok((
StatusCode::CONFLICT, StatusCode::CONFLICT,
@@ -343,9 +405,10 @@ async fn list(
} }
} }
.map_err(internal)?; .map_err(internal)?;
let undo = undo_views(&state, &runs).await?;
let mut views = Vec::with_capacity(runs.len()); let mut views = Vec::with_capacity(runs.len());
for run in &runs { 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))) Ok((no_store(), Json(views)))
} }
@@ -380,7 +443,7 @@ async fn show(
let run = run.ok_or(StatusCode::NOT_FOUND)?; let run = run.ok_or(StatusCode::NOT_FOUND)?;
Ok(( Ok((
no_store(), 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"); crate::refresh::audit_run(&state, &run.id, "cancelled");
Ok(( Ok((
no_store(), no_store(),
Json(view(&state, &run, actor.subject.admin).await?), Json(view_one(&state, &run, actor.subject.admin).await?),
) )
.into_response()) .into_response())
} }

View File

@@ -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.report_applied(&job, &token).await;
lab.tick().await; lab.tick().await;
assert_eq!(lab.run(&undo_id).status, "completed"); 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 // only the newest restore of a target can be undone: the first one no longer can, the undo can
let (_, old) = lab 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); 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}");
}

View File

@@ -79,6 +79,8 @@ pub enum StartError {
KeyReused, KeyReused,
/// Too many refreshes are running at once. /// Too many refreshes are running at once.
TooManyRuns, TooManyRuns,
/// The restore to undo is not one that can be undone (any more).
NothingToUndo,
} }
/// What the confirmation must say: it names exactly what the person saw, including the version. /// What the confirmation must say: it names exactly what the person saw, including the version.
@@ -99,55 +101,119 @@ impl RefreshRun {
} }
} }
/// A relation's source orbit, for checking that a snapshot belongs to it. /// The safety copy a restore took before it overwrote its target, and whether it is still the newest restore there.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UndoInfo {
pub safety: Uuid,
/// Nothing was restored onto the target after it. Undoing an older restore would also undo what came later.
pub latest: bool,
}
/// Does this run have a safety copy that puts its target back? A restore that finished, one an administrator
/// has since reconciled, and one whose apply failed (the agent says it stopped, so nothing is still writing) all
/// do: in the last case, rolling back is the recovery. An apply whose agent went silent may still be running, so
/// it waits for an administrator to reconcile it.
fn undo_info(conn: &Connection, run: &RefreshRun) -> Result<Option<UndoInfo>> {
if !matches!(run.status.as_str(), "completed" | "reconciled" | "recovery_required") {
return Ok(None);
}
let Some(job) = &run.restore_job_id else {
return Ok(None);
};
let row: Option<(String, String, Option<String>)> = conn
.query_row(
"SELECT status, phase, safety_id FROM restore_jobs WHERE id = ?1",
params![job],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
)
.optional()?;
let Some((status, phase, Some(safety))) = row else {
return Ok(None);
};
let sound = match status.as_str() {
"completed" | "reconciled" => true,
"recovery_required" => phase == "apply_failed",
_ => false,
};
if !sound {
return Ok(None);
}
// Jobs are numbered in the order they were queued.
let later: bool = conn.query_row(
"SELECT EXISTS(SELECT 1 FROM restore_jobs WHERE target_id = ?1
AND rowid > (SELECT rowid FROM restore_jobs WHERE id = ?2)
AND status IN ('queued','running','applying','completed','reconciled','recovery_required'))",
params![run.target_id, job],
|r| r.get(0),
)?;
Ok(Some(UndoInfo {
safety: Uuid::parse_str(&safety)?,
latest: !later,
}))
}
fn undo_check(
conn: &Connection,
run: &str,
relation: &str,
) -> Result<std::result::Result<Uuid, UndoRefusal>> {
let Some(run) = get(conn, run)?.filter(|r| r.relation_id == relation) else {
return Ok(Err(UndoRefusal::NothingToUndo));
};
Ok(match undo_info(conn, &run)? {
None => Err(UndoRefusal::NothingToUndo),
Some(info) if !info.latest => Err(UndoRefusal::NotTheLatest),
Some(info) => Ok(info.safety),
})
}
/// Why a restore cannot be undone. /// Why a restore cannot be undone.
#[derive(Debug, PartialEq, Eq)] #[derive(Debug, PartialEq, Eq)]
pub enum UndoRefusal { pub enum UndoRefusal {
/// No such run, not of this relation, not completed, or it took no safety copy. /// No such run, not of this relation, not a restore that can be put back, or it took no safety copy.
NothingToUndo, NothingToUndo,
/// Something else was restored onto the target after it. Undoing an older restore would also undo that. /// Something else was restored onto the target after it. Undoing an older restore would also undo that.
NotTheLatest, NotTheLatest,
} }
impl Db { impl Db {
/// The safety copy that undoes `run`, if the run is a completed restore of this relation and the newest /// The safety copy that undoes `run`, if the run is a restore of this relation that can be put back and the
/// restore of its target. Whether the copy still exists in the vault is for the caller to check. /// newest restore of its target. Whether the copy still exists in the vault is for the caller to check.
pub fn undo_candidate( pub fn undo_candidate(
&self, &self,
run: &str, run: &str,
relation: &str, relation: &str,
) -> Result<std::result::Result<Uuid, UndoRefusal>> { ) -> Result<std::result::Result<Uuid, UndoRefusal>> {
undo_check(&self.conn.lock().unwrap(), run, relation)
}
/// What can be done about each run's restore, for a whole list under one lock: only runs that took a safety
/// copy appear. See `UndoInfo`.
pub fn undo_infos(&self, runs: &[RefreshRun]) -> Result<std::collections::HashMap<String, UndoInfo>> {
let conn = self.conn.lock().unwrap(); let conn = self.conn.lock().unwrap();
let Some(run) = let mut infos = std::collections::HashMap::new();
get(&conn, run)?.filter(|r| r.relation_id == relation && r.status == "completed") for run in runs {
else { if let Some(info) = undo_info(&conn, run)? {
return Ok(Err(UndoRefusal::NothingToUndo)); infos.insert(run.id.clone(), info);
}
}
Ok(infos)
}
/// The restore this undo puts back: the run whose restore took the safety copy that `run` restores.
pub fn undo_parent(&self, run: &RefreshRun) -> Result<Option<String>> {
let Some(safety) = run.snapshot_id.as_deref().filter(|_| run.is_undo()) else {
return Ok(None);
}; };
let Some(job) = &run.restore_job_id else { let conn = self.conn.lock().unwrap();
return Ok(Err(UndoRefusal::NothingToUndo)); Ok(conn
};
let safety: Option<Option<String>> = conn
.query_row( .query_row(
"SELECT safety_id FROM restore_jobs WHERE id = ?1 AND status = 'completed'", "SELECT r.id FROM refresh_runs r JOIN restore_jobs j ON j.id = r.restore_job_id
params![job], WHERE j.safety_id = ?1 AND r.target_id = ?2 AND r.id <> ?3",
params![safety, run.target_id, run.id],
|r| r.get(0), |r| r.get(0),
) )
.optional()?; .optional()?)
let Some(Some(safety)) = safety else {
return Ok(Err(UndoRefusal::NothingToUndo));
};
// Jobs are numbered in the order they were queued.
let later: bool = conn.query_row(
"SELECT EXISTS(SELECT 1 FROM restore_jobs WHERE target_id = ?1
AND rowid > (SELECT rowid FROM restore_jobs WHERE id = ?2)
AND status IN ('queued','running','applying','completed','recovery_required'))",
params![run.target_id, job],
|r| r.get(0),
)?;
if later {
return Ok(Err(UndoRefusal::NotTheLatest));
}
Ok(Ok(Uuid::parse_str(&safety)?))
} }
pub fn relation_target(&self, relation: &str) -> Result<Option<String>> { pub fn relation_target(&self, relation: &str) -> Result<Option<String>> {
@@ -350,8 +416,8 @@ impl Db {
requester_user_id: Option<&str>, requester_user_id: Option<&str>,
authorized_by: &str, authorized_by: &str,
idempotency_key: &str, idempotency_key: &str,
// a snapshot to restore instead of capturing one, and whether it is an undo of an earlier restore // a snapshot to restore instead of capturing one, and the run it undoes when it is the safety copy of one
snapshot: Option<(Uuid, bool)>, snapshot: Option<(Uuid, Option<&str>)>,
ttl_secs: i64, ttl_secs: i64,
max_active: i64, max_active: i64,
now: i64, now: i64,
@@ -379,8 +445,10 @@ impl Db {
if confirmation != confirmation_text(&source, &target, relation.version) { if confirmation != confirmation_text(&source, &target, relation.version) {
return Ok(Err(StartError::StaleConfirmation)); return Ok(Err(StartError::StaleConfirmation));
} }
let undoing = snapshot.and_then(|(_, of)| of);
// The run being undone does not count as busy: if its apply failed, undoing it is how it is recovered.
let busy: Option<String> = tx let busy: Option<String> = tx
.query_row("SELECT id FROM refresh_runs WHERE target_id=?1 AND status IN ('capturing','restoring','recovery_required')", params![relation.target_id], |r| r.get(0)) .query_row("SELECT id FROM refresh_runs WHERE target_id=?1 AND status IN ('capturing','restoring','recovery_required') AND id IS NOT ?2", params![relation.target_id, undoing], |r| r.get(0))
.optional()?; .optional()?;
if let Some(id) = busy { if let Some(id) = busy {
return Ok(Err(StartError::TargetBusy(id))); return Ok(Err(StartError::TargetBusy(id)));
@@ -389,12 +457,34 @@ impl Db {
if running >= max_active { if running >= max_active {
return Ok(Err(StartError::TooManyRuns)); return Ok(Err(StartError::TooManyRuns));
} }
if let Some((safety, Some(of))) = snapshot {
// Checked again inside this transaction: what was true when the request was read may not be now.
if !matches!(undo_check(&tx, of, relation_id)?, Ok(found) if found == safety) {
return Ok(Err(StartError::NothingToUndo));
}
if let Some(parent) = get(&tx, of)?.filter(|r| r.status == "recovery_required") {
// The failed apply no longer fences the target: this undo takes over from it, and puts back what
// the restore replaced. What it leaves behind is kept as this undo's own safety copy.
if let Some(job) = &parent.restore_job_id {
tx.execute(
"UPDATE restore_jobs SET status='reconciled', phase='rolled_back', updated_at=?2
WHERE id=?1 AND status='recovery_required' AND phase='apply_failed'",
params![job, now],
)?;
}
finish(&tx, &parent.id, "reconciled", None, now)?;
tx.execute(
"INSERT INTO audit_log(at, event, detail) VALUES (datetime('now'), 'restore.rolled_back', ?1)",
params![format!("run={} by={requester}", parent.id)],
)?;
}
}
let id = Uuid::new_v4().to_string(); let id = Uuid::new_v4().to_string();
// A run either takes a fresh backup first, or restores a snapshot the person picked: then it has // A run either takes a fresh backup first, or restores a snapshot the person picked: then it has
// no capture job, only a placeholder, and the snapshot is recorded from the start. // no capture job, only a placeholder, and the snapshot is recorded from the start.
let capture = match snapshot { let capture = match snapshot {
Some((_, true)) => format!("{UNDO}{id}"), Some((_, Some(_))) => format!("{UNDO}{id}"),
Some((_, false)) => format!("{EXISTING}{id}"), Some((_, None)) => format!("{EXISTING}{id}"),
None => { None => {
let application = Uuid::parse_str(&relation.source_application_id)?; let application = Uuid::parse_str(&relation.source_application_id)?;
let Some(capture) = let Some(capture) =

View File

@@ -378,13 +378,22 @@ orbit's); otherwise the answer is `422 snapshot_unusable` and nothing is started
everything else is the same: one run per target at a time, idempotency, cancelling until the target is overwritten, and everything else is the same: one run per target at a time, idempotency, cancelling until the target is overwritten, and
the authorisation checks right before overwriting. The same snapshot can be restored to several targets, and again later. the authorisation checks right before overwriting. The same snapshot can be restored to several targets, and again later.
A completed restore can be undone: `undo_of` (the id of that run) restores the safety copy the restore took of its target A restore can be undone: `undo_of` (the id of that run) restores the safety copy the restore took of its target
back onto the same target, through the same checks, countdown, progress and a new safety copy, so the undo can itself be back onto the same target, through the same checks, countdown, progress and a new safety copy, so the undo can itself be
undone. It is refused with `422 nothing_to_undo` when the run is not a completed restore of this relation, when something undone. A restore that completed, one an administrator reconciled, and one whose apply failed (the agent reported it) can
was restored onto the target after it (only the newest restore of a target can be undone), or when the safety copy has be undone; for the last, undoing is the recovery: the failed apply stops fencing the target in the same transaction
been removed. A safety copy is only ever accepted as a source for the target it was taken from, whether it arrives through that starts the undo (job phase `rolled_back`, audited as `restore.rolled_back`). An apply whose agent went silent
(`lease_lost`) may still be writing, so it waits for an administrator to reconcile it first. The request is refused with
`422 nothing_to_undo` when the run is none of these for this relation, when something was restored onto the target after
it (only the newest restore of a target can be undone), or when the safety copy has been removed. A safety copy is only ever accepted as a source for the target it was taken from, whether it arrives through
`undo_of` or `snapshot_id`; the check is made by the hub, and again by the agent (its restore artifact carries `undo_of` or `snapshot_id`; the check is made by the hub, and again by the agent (its restore artifact carries
`rollback`). Run views say `undo` and `undo_available`, never where the copy is. The run is audited as `rollback`). Run views say `undo`, `undo_of` (the restore an undo puts back), `restore_job_id` and `undo_available`, never where
the copy is. A restore that took a safety copy also says `undo_state`: `available` (with `undo_kept_until`, when retention
may first forget the copy: a week after it was taken, and later while it is one of the target's newest few),
`superseded` (something was restored after it) or `expired` (retention has forgotten the copy; this wins over
`superseded`). The Activity log shows `expired` as "Safety backup expired" in place of a link, and lists an undo
under the restore it reverses. Run lists work out all of this with one database pass and a file lookup per copy, and
read the vault only for the newest restore of each target. The run is audited as
`refresh.undo_started`. Undoing needs the same permission as restoring. `refresh.undo_started`. Undoing needs the same permission as restoring.
In the web UI there is no separate Refresh screen. Restoring lives in the Vault: pick an orbit, capture it if you want the In the web UI there is no separate Refresh screen. Restoring lives in the Vault: pick an orbit, capture it if you want the
@@ -392,7 +401,7 @@ latest data (or click a snapshot that is already there), and in the snapshot det
disabled with "No restore point" when no relation has been set up for the orbit. The modal offers the restore points disabled with "No restore point" when no relation has been set up for the orbit. The modal offers the restore points
(Development and/or Staging) that the person may use, shows what will be overwritten, and after **Begin restore** counts (Development and/or Staging) that the person may use, shows what will be overwritten, and after **Begin restore** counts
ten seconds in the browser, during which **Abort** sends nothing. Then it follows four steps (Checking, Safety copy, ten seconds in the browser, during which **Abort** sends nothing. Then it follows four steps (Checking, Safety copy,
Applying, Completed) from the run, and Abort still works until Applying starts. A finished restore offers **Undo this restore**, and the modal offers Applying, Completed) from the run, and Abort still works until Applying starts. A finished restore offers **Undo this restore** (**Roll back** when it was interrupted), and the modal offers
**Undo last restore** for the chosen restore point while that is still possible. Safety copies are not listed with the **Undo last restore** for the chosen restore point while that is still possible. Safety copies are not listed with the
backups. A person needs to see the orbit's snapshots (for example the viewer role on the orbit) and a relation grant; backups. A person needs to see the orbit's snapshots (for example the viewer role on the orbit) and a relation grant;
administrators can also restore to any other registered target from the same modal. administrators can also restore to any other registered target from the same modal.

View File

@@ -38,7 +38,7 @@ admin/browser. Semua status/data job hanya di scope owner/admin yang berizin.
| /api/v1/relations/:id/access | GET,POST | human | relation.manage | admin | grant refresh.run per relasi (user atau grup, expiry); diaudit | | /api/v1/relations/:id/access | GET,POST | human | relation.manage | admin | grant refresh.run per relasi (user atau grup, expiry); diaudit |
| /api/v1/relations/:id/access/:grant | DELETE | human | relation.manage | admin | berlaku pada request berikutnya; diaudit | | /api/v1/relations/:id/access/:grant | DELETE | human | relation.manage | admin | berlaku pada request berikutnya; diaudit |
| /api/v1/refresh-relations | GET | human | refresh.run | relasi yang di-grant | nama dan environment saja; tanpa identity, host, Outpost, application id; 403 bila tanpa grant | | /api/v1/refresh-relations | GET | human | refresh.run | relasi yang di-grant | nama dan environment saja; tanpa identity, host, Outpost, application id; 403 bila tanpa grant |
| /api/v1/refresh-runs | GET,POST | human | refresh.run | relasi yang di-grant | POST: relation_id + konfirmasi `REFRESH <sumber> TO <target> v<versi>` + kunci idempotensi; `undo_of` opsional (id run restore selesai terbaru pada targetnya): kembalikan target dari safety copy restore itu (422 `nothing_to_undo`; safety hanya diterima untuk target asalnya); `snapshot_id` opsional: restore snapshot yang sudah ada milik orbit sumber relasi itu (bukan safety, bukan orbit lain; 422 `snapshot_unusable`), tanpa itu run mengambil capture baru; tidak memilih target; 404 bila bukan pemegang grant; GET: run milik sendiri atau relasi yang di-grant (admin: semua), tanpa snapshot id dan pemohon untuk non-admin | | /api/v1/refresh-runs | GET,POST | human | refresh.run | relasi yang di-grant | POST: relation_id + konfirmasi `REFRESH <sumber> TO <target> v<versi>` + kunci idempotensi; `undo_of` opsional (id run restore terbaru pada targetnya yang selesai, direkonsiliasi, atau gagal saat apply): kembalikan target dari safety copy restore itu (422 `nothing_to_undo`; safety hanya diterima untuk target asalnya); `snapshot_id` opsional: restore snapshot yang sudah ada milik orbit sumber relasi itu (bukan safety, bukan orbit lain; 422 `snapshot_unusable`), tanpa itu run mengambil capture baru; tidak memilih target; 404 bila bukan pemegang grant; GET: run milik sendiri atau relasi yang di-grant (admin: semua), tanpa snapshot id dan pemohon untuk non-admin |
| /api/v1/refresh-runs/:id | GET,DELETE | human | refresh.run | admin, pemohon, atau pemegang grant relasinya | GET 404 bagi yang lain; DELETE hanya pemohon atau admin (pemegang grant lain 403) dan hanya sebelum apply, sesudahnya 409 | | /api/v1/refresh-runs/:id | GET,DELETE | human | refresh.run | admin, pemohon, atau pemegang grant relasinya | GET 404 bagi yang lain; DELETE hanya pemohon atau admin (pemegang grant lain 403) dan hanya sebelum apply, sesudahnya 409 |
| /api/v1/operator/login | POST | public | — | emergency account | cookie opaque dan CSRF; limiter, no-store | | /api/v1/operator/login | POST | public | — | emergency account | cookie opaque dan CSRF; limiter, no-store |
| /api/v1/snapshots | GET | human | snapshot.read | orbit | metadata aman terfilter | | /api/v1/snapshots | GET | human | snapshot.read | orbit | metadata aman terfilter |