Compare commits

...

2 Commits

Author SHA1 Message Date
d356c313ce feat: restore history, undo and redo in the Activity log for everyone who may refresh
Some checks failed
ci / rust (push) Has been cancelled
ci / supply-chain (push) Has been cancelled
ci / web (push) Has been cancelled
- Activity lists restores from refresh runs, so the Refresh permission is enough to see them; an administrator's
  restore jobs add the database, the person and the snapshot
- an undo is listed under the restore it reverses, and a redo under that undo; opening a restore or an undo opens
  its undo or redo dialog
- the dialog has an explicit undo mode: it describes what is put back instead of the snapshot that was open, and
  an interrupted restore offers Roll back
- a restore whose safety backup retention has forgotten shows "Safety backup expired" instead of a link, and the
  dialog says how long a safety copy is kept

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 20:37:21 +07:00
62f0c68e89 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>
2026-11-16 20:37:21 +07:00
15 changed files with 792 additions and 166 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 |

View File

@@ -78,3 +78,112 @@ test("labels days relative to now", () => {
assert.equal(dayLabel(NOW - 86_400_000, NOW), "Yesterday"); assert.equal(dayLabel(NOW - 86_400_000, NOW), "Yesterday");
assert.notEqual(dayLabel(NOW - 5 * 86_400_000, NOW), "Today"); assert.notEqual(dayLabel(NOW - 5 * 86_400_000, NOW), "Today");
}); });
test("lists an undo under the restore it reverses, and a redo under that undo", () => {
const snapshots = [snapshot("s1", "ledger", "2026-11-14T02:00:00Z")];
const run = (id, job, extra = {}) => ({ id, restore_job_id: job, relation_id: "r", status: "completed", ...extra });
const refreshRuns = [
run("r1", "j1", { undo_available: false }),
run("r2", "j2", { undo: true, undo_of: "r1", undo_available: false }),
run("r3", "j3", { undo: true, undo_of: "r2", undo_available: true }),
];
const restoreJobs = [
restore("j1", "completed", "completed", "2026-11-14T03:00:00Z"),
restore("j2", "completed", "completed", "2026-11-14T04:00:00Z", { snapshot_id: "safety-1" }),
restore("j3", "completed", "completed", "2026-11-14T05:00:00Z", { snapshot_id: "safety-2" }),
];
const entries = build({ snapshots, restoreJobs, refreshRuns });
const roots = entries.filter(({ kind }) => kind === "restore");
assert.deepEqual(roots.map(({ id }) => id), ["restore-j1"], "only the restore is on its own");
const [undo] = roots[0].children;
assert.equal(undo.id, "restore-j2");
assert.equal(undo.variant, "undo");
assert.equal(undo.children[0].variant, "redo");
// the newest one can be put back, and what opening it offers is the opposite of what it did
assert.equal(undo.opens, null);
assert.equal(undo.children[0].opens.kind, "undo");
assert.equal(activityCounts(entries).running, 0);
});
test("a restore sits where its most urgent undo does, and an undo whose restore is missing stands alone", () => {
const refreshRuns = [
{ id: "r1", restore_job_id: "j1", relation_id: "r" },
{ id: "r2", restore_job_id: "j2", relation_id: "r", undo: true, undo_of: "r1" },
{ id: "r9", restore_job_id: "j9", relation_id: "r", undo: true, undo_of: "gone" },
];
const restoreJobs = [
restore("j1", "completed", "completed", "2026-11-10T03:00:00Z"),
restore("j2", "running", "safety", "2026-11-14T10:00:00Z"),
restore("j9", "completed", "completed", "2026-11-12T03:00:00Z"),
];
const entries = build({ restoreJobs, refreshRuns });
assert.deepEqual(entries.map(({ id, slotGroup }) => [id, slotGroup]), [["restore-j1", "running"], ["restore-j9", "history"]]);
assert.equal(activityCounts(entries).running, 1);
});
test("someone who may only read runs still gets the restore history, with undos under their restores", () => {
const run = (id, extra = {}) => ({ id, relation_id: "r", source_name: "ledger", target_name: "staging", status: "completed", restore_phase: "completed", snapshot_taken_at: sec("2026-11-14T02:00:00Z"), created_at: sec("2026-11-14T03:00:00Z"), ...extra });
const refreshRuns = [
run("r1"),
run("r2", { undo: true, undo_of: "r1", created_at: sec("2026-11-14T04:00:00Z"), undo_available: false }),
run("r3", { undo: true, undo_of: "r2", created_at: sec("2026-11-14T05:00:00Z"), undo_available: true }),
run("r4", { status: "restoring", restore_phase: "safety", created_at: sec("2026-11-14T11:00:00Z") }),
run("r5", { status: "recovery_required", restore_phase: "apply_failed", created_at: sec("2026-11-13T01:00:00Z") }),
run("r6", { status: "cancelled", restore_phase: null, created_at: sec("2026-11-12T01:00:00Z") }),
];
const entries = build({ refreshRuns });
assert.deepEqual(entries.map(({ id }) => id), ["restore-run-r5", "restore-run-r4", "restore-run-r1", "restore-run-r6"]);
const [locked, live, restored] = entries;
assert.equal(locked.group, "needs");
assert.equal(live.progress, 2);
assert.match(restored.title, /^ledger · .+ → staging$/);
assert.equal(restored.opens, null, "no snapshot id reaches them, and it cannot be undone any more");
const [undo] = restored.children;
assert.equal(undo.variant, "undo");
assert.equal(undo.children[0].variant, "redo");
assert.equal(undo.children[0].opens.kind, "undo");
assert.deepEqual(activityCounts(entries), { running: 1, needs: 1 });
});
test("a restore known by its run and its job is one entry, with the job's detail", () => {
const refreshRuns = [{ id: "r1", restore_job_id: "j1", relation_id: "r", source_name: "x", target_name: "y", status: "completed", created_at: sec("2026-11-14T03:00:00Z") }];
const entries = build({
snapshots: [snapshot("s1", "media-vault", "2026-11-14T02:00:00Z")],
restoreJobs: [restore("j1", "completed", "completed", "2026-11-14T03:00:00Z")],
refreshRuns,
}).filter(({ kind }) => kind === "restore");
assert.equal(entries.length, 1);
assert.match(entries[0].title, /pg-staging \/ orders$/);
});
test("a restore whose safety backup expired says so instead of leading anywhere", () => {
const run = (id, extra = {}) => ({ id, relation_id: "r", source_name: "ledger", target_name: "staging", status: "completed", restore_phase: "completed", created_at: sec("2026-11-14T03:00:00Z"), ...extra });
const gone = build({ refreshRuns: [run("r1", { undo_state: "expired", undo_available: false })] })[0];
assert.equal(gone.opens, null);
assert.equal(gone.note, "Safety backup expired");
// an administrator's restore job would normally open its snapshot; expired, it must not suggest the copy is there
const withJob = build({
snapshots: [snapshot("s1", "ledger", "2026-11-14T02:00:00Z")],
restoreJobs: [restore("j1", "completed", "completed", "2026-11-14T03:00:00Z")],
refreshRuns: [run("r1", { restore_job_id: "j1", undo_state: "expired" })],
}).find(({ id }) => id === "restore-j1");
assert.equal(withJob.opens, null);
assert.equal(withJob.note, "Safety backup expired");
// superseded is not expired: its copy may still be there, and it keeps its normal link
const old = build({
snapshots: [snapshot("s1", "ledger", "2026-11-14T02:00:00Z")],
restoreJobs: [restore("j1", "completed", "completed", "2026-11-14T03:00:00Z")],
refreshRuns: [run("r1", { restore_job_id: "j1", undo_state: "superseded" })],
}).find(({ id }) => id === "restore-j1");
assert.deepEqual(old.opens, { kind: "snapshot", id: "s1" });
});
test("an interrupted restore that can be rolled back says so, and a rolled back one is marked", () => {
const run = (id, extra) => ({ id, relation_id: "r", source_name: "ledger", target_name: "staging", created_at: sec("2026-11-14T03:00:00Z"), ...extra });
const [locked] = build({ refreshRuns: [run("r1", { status: "recovery_required", restore_phase: "apply_failed", undo_available: true })] });
assert.equal(locked.group, "needs");
assert.match(locked.meta, /roll back available/);
assert.equal(locked.opens.kind, "undo");
const [done] = build({ refreshRuns: [run("r2", { status: "reconciled", restore_phase: "rolled_back" })] });
assert.equal(done.state, "Rolled back");
});

View File

@@ -59,3 +59,10 @@ test("restore points are named by environment, and by target only when two share
); );
assert.equal(relationLabels([rel("a", null, "odd")])[0].label, "odd"); assert.equal(relationLabels([rel("a", null, "odd")])[0].label, "odd");
}); });
test("an interrupted restore offers a rollback only when its safety copy can be used", () => {
const names = { target: "Staging" };
const stuck = { status: "recovery_required", restore_phase: "apply_failed" };
assert.match(outcomeOf({ ...stuck, undo_available: true }, names).detail, /roll it back/i);
assert.match(outcomeOf(stuck, names).detail, /administrator has to recover/i);
});

View File

@@ -3,7 +3,7 @@ import { AnimatePresence, useMotionValue } from "motion/react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { import {
fetchCaptureJobs, fetchHealth, fetchOrbits, fetchPreferences, fetchRefreshRelations, fetchSnapshots, savePreferences, fetchCaptureJobs, fetchHealth, fetchOrbits, fetchPreferences, fetchRefreshRelations, fetchSnapshots, savePreferences,
enqueueCapture, runOrbit, type Orbit, enqueueCapture, runOrbit, type Orbit, type RefreshRun,
} from "./api"; } from "./api";
import { OrbitInspector, OrbitRegister, TelemetryStrip } from "./components/hud/DiegeticHUD"; import { OrbitInspector, OrbitRegister, TelemetryStrip } from "./components/hud/DiegeticHUD";
import { HUDPanel } from "./components/hud/HUDPanel"; import { HUDPanel } from "./components/hud/HUDPanel";
@@ -91,7 +91,7 @@ function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () =>
const [pairing, setPairing] = useState<{ code: string; expires_at: string } | null>(null); const [pairing, setPairing] = useState<{ code: string; expires_at: string } | null>(null);
const [play, setPlay] = useState(true); const [play, setPlay] = useState(true);
const [restoreBusy, setRestoreBusy] = useState(false); const [restoreBusy, setRestoreBusy] = useState(false);
const [restoreTarget, setRestoreTarget] = useState<{ id: string | null }>(); const [restoreTarget, setRestoreTarget] = useState<{ id: string | null; undo?: RefreshRun }>();
const reducedMotion = useReducedMotion(); const reducedMotion = useReducedMotion();
const tools = useRef<HTMLDivElement>(null); const tools = useRef<HTMLDivElement>(null);
useScreenTransition(tools, bigScreen, reducedMotion); useScreenTransition(tools, bigScreen, reducedMotion);
@@ -237,7 +237,7 @@ function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () =>
? { orbitId: captureOrbitId, key: capture.submittedAt, snapshotId: capture.data ?? undefined } ? { orbitId: captureOrbitId, key: capture.submittedAt, snapshotId: capture.data ?? undefined }
: undefined, [captureOrbitId, capture.submittedAt, capture.isError, capture.data]); : undefined, [captureOrbitId, capture.submittedAt, capture.isError, capture.data]);
const captureReady = !!captureEffect?.snapshotId && !!snaps.data?.some(({ id }) => id === captureEffect.snapshotId); const captureReady = !!captureEffect?.snapshotId && !!snaps.data?.some(({ id }) => id === captureEffect.snapshotId);
const activity = useActivity(snaps.data, orbits.data, caps.admin); const activity = useActivity(snaps.data, orbits.data, { admin: caps.admin, refresh: caps.refresh });
// Consoles a non-administrator never sees: managing orbits and Outposts, restores, and access. // Consoles a non-administrator never sees: managing orbits and Outposts, restores, and access.
const railItems = useMemo( const railItems = useMemo(
() => (caps.admin ? [...hudItems, relationsItem, accessItem] : hudItems.filter((item) => item.id === "scene" || item.id === "activity")), () => (caps.admin ? [...hudItems, relationsItem, accessItem] : hudItems.filter((item) => item.id === "scene" || item.id === "activity")),
@@ -293,6 +293,12 @@ function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () =>
setMode(next); setMode(next);
} }
/** Open the dialog that puts back a restore (or undo) shown in the Activity log. */
function openUndo(run: RefreshRun) {
if (!restoreBusy) setRestoreTarget({ id: null, undo: run });
setMode("reconstitute");
}
function selectSearchResult(result: SearchResult) { function selectSearchResult(result: SearchResult) {
if (result.kind === "navigation") openConsole(result.id); if (result.kind === "navigation") openConsole(result.id);
else if (result.kind === "snapshot") openSnapshot(result.id); else if (result.kind === "snapshot") openSnapshot(result.id);
@@ -424,7 +430,8 @@ function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () =>
entries={activity.entries} counts={activity.counts} updatedAt={activity.updatedAt} entries={activity.entries} counts={activity.counts} updatedAt={activity.updatedAt}
restoresUnavailable={activity.restoresUnavailable} capturesUnavailable={activity.capturesUnavailable} restoresUnavailable={activity.restoresUnavailable} capturesUnavailable={activity.capturesUnavailable}
onOpen={(target) => { onOpen={(target) => {
if (target.kind === "snapshot") openSnapshot(target.id); if ("run" in target) openUndo(target.run);
else if (target.kind === "snapshot") openSnapshot(target.id);
else { else {
selectOrbit(target.id); selectOrbit(target.id);
setMode("scene"); setMode("scene");
@@ -454,7 +461,18 @@ function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () =>
)} )}
</AnimatePresence> </AnimatePresence>
<SpringPane active={mode === "reconstitute"}> <SpringPane active={mode === "reconstitute"}>
{restoreSnapshot {restoreTarget?.undo
? (
<RestoreWizard
key={restoreTarget.undo.id}
undo={restoreTarget.undo}
relations={restorePoints.filter((r) => r.id === restoreTarget.undo!.relation_id)}
admin={caps.admin}
onBusyChange={setRestoreBusy}
onDone={() => setMode("activity")}
/>
)
: restoreSnapshot
? ( ? (
<RestoreWizard <RestoreWizard
key={restoreSnapshot.id} key={restoreSnapshot.id}

View File

@@ -139,6 +139,14 @@ export type RefreshRun = {
undo?: boolean; undo?: boolean;
/** A completed restore that can still be undone (the newest of its target, safety copy still there). */ /** A completed restore that can still be undone (the newest of its target, safety copy still there). */
undo_available?: boolean; undo_available?: boolean;
/** Why a restore with a safety copy can or cannot be put back: `expired` means retention has forgotten the copy. */
undo_state?: "available" | "superseded" | "expired";
/** While it can be undone: when its safety copy is first at risk of being forgotten (seconds since the epoch). */
undo_kept_until?: number;
/** For an undo: the run whose restore it puts back. */
undo_of?: string;
/** The restore job this run queued. */
restore_job_id?: string;
id: string; relation_id: string; source_name: string; target_name: string; status: string; blocked_reason: string | null; id: string; relation_id: string; source_name: string; target_name: string; status: string; blocked_reason: string | null;
capture_status: string | null; capture_phase: string | null; snapshot_taken_at: number | null; capture_status: string | null; capture_phase: string | null; snapshot_taken_at: number | null;
restore_status: string | null; restore_phase: string | null; restore_status: string | null; restore_phase: string | null;

View File

@@ -6,14 +6,14 @@ import { Segmented } from "../ui/Segmented";
type Kind = "all" | "backup" | "restore"; type Kind = "all" | "backup" | "restore";
const PAGE = 80; const PAGE = 80;
function Row({ entry, now, onOpen }: { entry: ActivityEntry; now: number; onOpen: (target: ActivityTarget) => void }) { function Row({ entry, now, onOpen, depth = 0 }: { entry: ActivityEntry; now: number; onOpen: (target: ActivityTarget) => void; depth?: number }) {
const opens = entry.opens; const opens = entry.opens;
const content = ( const content = (
<> <>
<span className="act-time">{entry.group === "running" && entry.id.startsWith("orbit-") ? "now" : entry.at === null ? "—" : clock(entry.at)}</span> <span className="act-time">{entry.group === "running" && entry.id.startsWith("orbit-") ? "now" : entry.at === null ? "—" : clock(entry.at)}</span>
<span className="act-kind" data-kind={entry.kind}> <span className="act-kind" data-kind={entry.kind}>
<i className="act-glyph" data-tone={entry.tone} aria-hidden="true" /> <i className="act-glyph" data-tone={entry.tone} aria-hidden="true" />
{entry.kind === "backup" ? "Backup" : "Restore"} {entry.kind === "backup" ? "Backup" : entry.variant === "redo" ? "Redo" : entry.variant === "undo" ? "Undo" : "Restore"}
</span> </span>
<span className="act-text"> <span className="act-text">
<span className="act-title">{entry.title}</span> <span className="act-title">{entry.title}</span>
@@ -29,14 +29,24 @@ function Row({ entry, now, onOpen }: { entry: ActivityEntry; now: number; onOpen
</span> </span>
)} )}
</span> </span>
<span className="act-open">{opens ? `${opens.kind} ›` : "removed"}</span> <span className="act-open" data-note={!opens && entry.note ? "true" : undefined}>{opens ? `${opens.kind} ›` : entry.note ?? (depth ? "" : "removed")}</span>
</> </>
); );
void now; void now;
return opens ? ( return opens ? (
<button type="button" className="act-row" data-group={entry.group} data-tone={entry.tone} onClick={() => onOpen(opens)}>{content}</button> <button type="button" className="act-row" data-group={entry.group} data-tone={entry.tone} data-child={depth || undefined} style={depth ? { "--depth": depth } as React.CSSProperties : undefined} onClick={() => onOpen(opens)}>{content}</button>
) : ( ) : (
<div className="act-row" data-group={entry.group} data-tone={entry.tone} data-static="true">{content}</div> <div className="act-row" data-group={entry.group} data-tone={entry.tone} data-child={depth || undefined} style={depth ? { "--depth": depth } as React.CSSProperties : undefined} data-static="true">{content}</div>
);
}
/** A restore with its undos beneath it, each indented one step under what it reverses. */
function Tree({ entry, now, onOpen, depth = 0 }: { entry: ActivityEntry; now: number; onOpen: (target: ActivityTarget) => void; depth?: number }) {
return (
<>
<Row entry={entry} now={now} onOpen={onOpen} depth={depth} />
{entry.children?.map((next) => <Tree key={next.id} entry={next} now={now} onOpen={onOpen} depth={depth + 1} />)}
</>
); );
} }
@@ -58,23 +68,26 @@ export function ActivityView({ entries, counts, restoresUnavailable, capturesUna
}, []); }, []);
const term = query.trim().toLowerCase(); const term = query.trim().toLowerCase();
const matching = entries.filter((entry) => // A restore stays in the log when it or any undo under it matches, so an undo is never shown without its restore.
(kind === "all" || entry.kind === kind) && (!term || `${entry.title} ${entry.meta}`.toLowerCase().includes(term))); const matches = (entry: ActivityEntry): boolean =>
const visible = matching.slice(0, Math.max(shown, matching.filter(({ group }) => group !== "history").length)); ((kind === "all" || entry.kind === kind) && (!term || `${entry.title} ${entry.meta}`.toLowerCase().includes(term)))
|| (entry.children ?? []).some(matches);
const matching = entries.filter(matches);
const visible = matching.slice(0, Math.max(shown, matching.filter(({ slotGroup }) => slotGroup !== "history").length));
const sections: { label: string; tone?: string; items: ActivityEntry[] }[] = []; const sections: { label: string; tone?: string; items: ActivityEntry[] }[] = [];
for (const entry of visible) { for (const entry of visible) {
const label = entry.group === "needs" ? "Needs you" : entry.group === "running" ? "Running now" const label = entry.slotGroup === "needs" ? "Needs you" : entry.slotGroup === "running" ? "Running now"
: entry.at === null ? "Earlier" : dayLabel(entry.at, now); : entry.slotAt === null ? "Earlier" : dayLabel(entry.slotAt, now);
const last = sections.at(-1); const last = sections.at(-1);
if (last?.label === label) last.items.push(entry); if (last?.label === label) last.items.push(entry);
else sections.push({ label, tone: entry.group === "history" ? undefined : entry.group, items: [entry] }); else sections.push({ label, tone: entry.slotGroup === "history" ? undefined : entry.slotGroup, items: [entry] });
} }
const age = updatedAt ? Math.max(0, Math.round((now - updatedAt) / 1000)) : undefined; const age = updatedAt ? Math.max(0, Math.round((now - updatedAt) / 1000)) : undefined;
return ( return (
<div className="activity"> <div className="activity">
<div className="activity-bar"> <div className="activity-bar">
<p className="activity-lead">One log of everything that has run or is running. Open an entry to see its snapshot; restores and exports start there.</p> <p className="activity-lead">One log of everything that has run or is running. Open a backup to restore it; open a restore to undo it. Undos are listed under the restore they reverse.</p>
<dl className="activity-counts"> <dl className="activity-counts">
<div><dt><i className="act-glyph" data-tone="amber" aria-hidden="true" />Running</dt><dd>{counts.running}</dd></div> <div><dt><i className="act-glyph" data-tone="amber" aria-hidden="true" />Running</dt><dd>{counts.running}</dd></div>
<div data-alert={counts.needs > 0}><dt><i className="act-glyph" data-tone="red" aria-hidden="true" />Needs you</dt><dd>{counts.needs}</dd></div> <div data-alert={counts.needs > 0}><dt><i className="act-glyph" data-tone="red" aria-hidden="true" />Needs you</dt><dd>{counts.needs}</dd></div>
@@ -94,7 +107,7 @@ export function ActivityView({ entries, counts, restoresUnavailable, capturesUna
</div> </div>
{(restoresUnavailable || capturesUnavailable) && ( {(restoresUnavailable || capturesUnavailable) && (
<p role="alert" className="activity-warning"> <p role="alert" className="activity-warning">
{restoresUnavailable ? "Restore history is unavailable. This hub may be too old to list restore jobs." : "Outpost backup jobs are unavailable."} {restoresUnavailable ? "Restore history is unavailable. This hub may be too old to list restore runs." : "Outpost backup jobs are unavailable."}
{" "}The rest of the log is still shown. {" "}The rest of the log is still shown.
</p> </p>
)} )}
@@ -102,7 +115,7 @@ export function ActivityView({ entries, counts, restoresUnavailable, capturesUna
{sections.map((section) => ( {sections.map((section) => (
<section key={section.label} aria-label={section.label}> <section key={section.label} aria-label={section.label}>
<h3 data-tone={section.tone}>{section.label}</h3> <h3 data-tone={section.tone}>{section.label}</h3>
{section.items.map((entry) => <Row key={entry.id} entry={entry} now={now} onOpen={onOpen} />)} {section.items.map((entry) => <Tree key={entry.id} entry={entry} now={now} onOpen={onOpen} />)}
</section> </section>
))} ))}
{!sections.length && ( {!sections.length && (

View File

@@ -3,7 +3,7 @@ import { motion } from "motion/react";
import { useQuery } from "@tanstack/react-query"; import { useQuery } from "@tanstack/react-query";
import { cancelRefresh, fetchRefreshRun, fetchRefreshRuns, refusalReason, startRefresh, type RefreshRelation, type RefreshRun, type Snapshot } from "../../api"; import { cancelRefresh, fetchRefreshRun, fetchRefreshRuns, refusalReason, startRefresh, type RefreshRelation, type RefreshRun, type Snapshot } from "../../api";
import { formatBytes, formatWhen } from "../../lib/format"; import { formatBytes, formatWhen } from "../../lib/format";
import { isFinal, outcomeOf, progressOf, relationLabels, STAGES } from "../../lib/restoreRun"; import { isFinal, outcomeOf, progressOf, relationLabels, STAGES, undoDepth, undoVerb } from "../../lib/restoreRun";
import { Button } from "../ui/Button"; import { Button } from "../ui/Button";
import { Segmented } from "../ui/Segmented"; import { Segmented } from "../ui/Segmented";
import { DatabaseRestore } from "../reconstitute/DatabaseRestore"; import { DatabaseRestore } from "../reconstitute/DatabaseRestore";
@@ -28,23 +28,30 @@ type Phase = "idle" | "countdown" | "running";
* when there are several), presses Begin restore, has ten seconds to abort, and then follows four steps until the * when there are several), presses Begin restore, has ten seconds to abort, and then follows four steps until the
* target holds the backup. Administrators can still restore to any other registered target. * target holds the backup. Administrators can still restore to any other registered target.
*/ */
export function RestoreWizard({ snapshot, relations, admin, onBusyChange }: { export function RestoreWizard({ snapshot, undo, relations, admin, onBusyChange, onDone }: {
snapshot: Snapshot; /** The snapshot to restore. Absent when the dialog was opened from a restore in the Activity log, to undo it. */
snapshot?: Snapshot;
/** The restore (or undo) this dialog was opened to put back. */
undo?: RefreshRun;
/** The relations from this snapshot's orbit that the person may restore through. */ /** The relations from this snapshot's orbit that the person may restore through. */
relations: RefreshRelation[]; relations: RefreshRelation[];
admin: boolean; admin: boolean;
onBusyChange: (busy: boolean) => void; onBusyChange: (busy: boolean) => void;
/** Leave the dialog once a run opened for an undo has finished. */
onDone?: () => void;
}) { }) {
const points = useMemo(() => relationLabels(relations.filter((r) => r.usable)), [relations]); const points = useMemo(() => relationLabels(relations.filter((r) => r.usable)), [relations]);
const [pointId, setPointId] = useState(points[0]?.id ?? ""); const [pointId, setPointId] = useState(undo?.relation_id ?? points[0]?.id ?? "");
const point = points.find((p) => p.id === pointId) ?? points[0]; const point = points.find((p) => p.id === pointId) ?? points[0];
const [phase, setPhase] = useState<Phase>("idle"); const [phase, setPhase] = useState<Phase>("idle");
const [left, setLeft] = useState(COUNTDOWN); const [left, setLeft] = useState(COUNTDOWN);
const [runId, setRunId] = useState<string>(); const [runId, setRunId] = useState<string>();
const [refusal, setRefusal] = useState<string>(); const [refusal, setRefusal] = useState<string>();
const [other, setOther] = useState(false); const [other, setOther] = useState(false);
// Set while an undo is being started or followed: the run whose restore is being put back. // Set while an undo is being started or followed: the restore (or undo) being put back. Its presence is the
const [undoOf, setUndoOf] = useState<string>(); // wizard's undo mode, which shows what is being put back instead of the snapshot the person opened.
const [undoRun, setUndoRun] = useState<RefreshRun | undefined>(undo);
const undoOf = undoRun?.id;
// One key per attempt: the same press can never start two restores, even if the request is retried. // One key per attempt: the same press can never start two restores, even if the request is retried.
const attempt = useRef(globalThis.crypto?.randomUUID?.() ?? String(Math.random())); const attempt = useRef(globalThis.crypto?.randomUUID?.() ?? String(Math.random()));
@@ -69,7 +76,7 @@ export function RestoreWizard({ snapshot, relations, admin, onBusyChange }: {
if (left <= 0) { if (left <= 0) {
setPhase("running"); setPhase("running");
if (!point) return; if (!point) return;
startRefresh(point, attempt.current, undoOf ? { undo_of: undoOf } : { snapshot_id: snapshot.id }) startRefresh(point, attempt.current, undoOf ? { undo_of: undoOf } : { snapshot_id: snapshot!.id })
.then((started) => setRunId(started.id)) .then((started) => setRunId(started.id))
.catch((error) => { .catch((error) => {
setRefusal(REFUSALS[refusalReason(error) ?? ""] ?? "The restore could not be started."); setRefusal(REFUSALS[refusalReason(error) ?? ""] ?? "The restore could not be started.");
@@ -80,55 +87,80 @@ export function RestoreWizard({ snapshot, relations, admin, onBusyChange }: {
} }
const timer = window.setTimeout(() => setLeft((value) => value - 1), 1000); const timer = window.setTimeout(() => setLeft((value) => value - 1), 1000);
return () => clearTimeout(timer); return () => clearTimeout(timer);
}, [phase, left, point, snapshot.id, undoOf]); }, [phase, left, point, snapshot?.id, undoOf]);
const abortable = phase === "countdown" || (phase === "running" && !finished && progress.index < 2); const abortable = phase === "countdown" || (phase === "running" && !finished && progress.index < 2);
const abort = async () => { const abort = async () => {
if (phase === "countdown") { if (phase === "countdown") {
setPhase("idle"); setPhase("idle");
setUndoRun(undo);
setLeft(COUNTDOWN); setLeft(COUNTDOWN);
} else if (runId) { } else if (runId) {
try { await cancelRefresh(runId); } catch { /* it moved past the point where it can be cancelled */ } try { await cancelRefresh(runId); } catch { /* it moved past the point where it can be cancelled */ }
} }
}; };
const again = () => { const again = () => {
setPhase("idle"); setLeft(COUNTDOWN); setRunId(undefined); setRefusal(undefined); setUndoOf(undefined); // Opened to undo one restore: once it is done there is nothing left to do here.
if (!snapshot && onDone) { onDone(); return; }
setPhase("idle"); setLeft(COUNTDOWN); setRunId(undefined); setRefusal(undefined); setUndoRun(undefined);
attempt.current = globalThis.crypto?.randomUUID?.() ?? String(Math.random()); attempt.current = globalThis.crypto?.randomUUID?.() ?? String(Math.random());
}; };
// The newest restore on the chosen restore point, if it can still be undone. // The newest restore on the chosen restore point, if it can still be undone.
const recent = useQuery({ queryKey: ["restore-runs"], queryFn: fetchRefreshRuns, enabled: phase === "idle", retry: false, refetchInterval: 15_000 }); const recent = useQuery({ queryKey: ["restore-runs"], queryFn: fetchRefreshRuns, retry: false, refetchInterval: 15_000 });
const runsById = new Map((Array.isArray(recent.data) ? recent.data : []).map((r) => [r.id, r]));
const undoable = Array.isArray(recent.data) ? recent.data.find((r) => r.relation_id === point?.id && r.undo_available) : undefined; const undoable = Array.isArray(recent.data) ? recent.data.find((r) => r.relation_id === point?.id && r.undo_available) : undefined;
const beginUndo = (of: string) => { const beginUndo = (of: RefreshRun) => {
setRefusal(undefined); setRunId(undefined); setUndoOf(of); setLeft(COUNTDOWN); setPhase("countdown"); setRefusal(undefined); setRunId(undefined); setUndoRun(of); setLeft(COUNTDOWN); setPhase("countdown");
attempt.current = globalThis.crypto?.randomUUID?.() ?? String(Math.random()); attempt.current = globalThis.crypto?.randomUUID?.() ?? String(Math.random());
}; };
const radius = 52; const radius = 52;
const circumference = 2 * Math.PI * radius; const circumference = 2 * Math.PI * radius;
const target = point?.label ?? "the database"; const target = point?.label ?? "the database";
const outcome = run.data && finished ? outcomeOf(run.data, { target, orbit: snapshot.orbit_name, when: formatWhen(snapshot.taken_at) }) : undefined; const outcome = run.data && finished ? outcomeOf(run.data, { target, orbit: snapshot?.orbit_name, when: snapshot ? formatWhen(snapshot.taken_at) : undefined }) : undefined;
const database = snapshot.capture; const database = snapshot?.capture;
const undoing = !!undoRun;
// An undo of an undo puts back what the first undo replaced, so it is a redo.
const verb = (r: RefreshRun) => undoVerb(undoDepth(r, runsById));
// What a run was: a restore, the undo of one, or the redo of that undo.
const what = (r: RefreshRun) => { const depth = undoDepth(r, runsById); return depth === 0 ? "restore" : depth % 2 === 1 ? "undo" : "redo"; };
const undoneAt = undoRun ? formatWhen(new Date(undoRun.updated_at * 1000).toISOString()) : "";
return ( return (
<div className="restore-layout"> <div className="restore-layout">
<div className="restore-top"> <div className="restore-top">
<p className="restore-lead">Review the restore point before starting.</p> {undoRun ? (
<div className="restore-snap"> <>
<span className="restore-snap-glyph" aria-hidden="true">◇</span> <p className="restore-lead">{verb(undoRun)} the last {what(undoRun)} on {target}.</p>
<div className="min-w-0"> <div className="restore-snap">
<p className="restore-snap-name">{snapshot.orbit_name}</p> <span className="restore-snap-glyph" aria-hidden="true">↺</span>
<p className="restore-snap-meta">{formatWhen(snapshot.taken_at)} · {formatBytes(snapshot.size_bytes)} · {snapshot.id.slice(0, 8)}</p> <div className="min-w-0">
</div> <p className="restore-snap-name">{target} as it was before {undoneAt}</p>
</div> <p className="restore-snap-meta">From the safety copy taken just before that {what(undoRun)}</p>
</div>
</div>
</>
) : snapshot && (
<>
<p className="restore-lead">Review the restore point before starting.</p>
<div className="restore-snap">
<span className="restore-snap-glyph" aria-hidden="true">◇</span>
<div className="min-w-0">
<p className="restore-snap-name">{snapshot.orbit_name}</p>
<p className="restore-snap-meta">{formatWhen(snapshot.taken_at)} · {formatBytes(snapshot.size_bytes)} · {snapshot.id.slice(0, 8)}</p>
</div>
</div>
</>
)}
</div> </div>
{other && admin && database ? ( {other && admin && database && snapshot ? (
<DatabaseRestore snapshot={snapshot.id} application={database.application_id} applicationName={snapshot.orbit_name} engine={database.engine} /> <DatabaseRestore snapshot={snapshot!.id} application={database.application_id} applicationName={snapshot?.orbit_name ?? ""} engine={database.engine} />
) : ( ) : (
<> <>
<div className="restore-fields"> <div className="restore-fields">
<div> <div hidden={undoing}>
<p className="field-label mb-1.5">Restore point</p> <p className="field-label mb-1.5">Restore point</p>
{points.length > 1 ? ( {points.length > 1 ? (
<Segmented label="Restore point" value={point?.id ?? ""} disabled={phase !== "idle"} onChange={setPointId} <Segmented label="Restore point" value={point?.id ?? ""} disabled={phase !== "idle"} onChange={setPointId}
@@ -139,19 +171,27 @@ export function RestoreWizard({ snapshot, relations, admin, onBusyChange }: {
</div> </div>
<div className="restore-warning" role="note"> <div className="restore-warning" role="note">
<svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M8 2 14.5 13.5h-13Z" /><path d="M8 6.5v3M8 11.5v.01" /></svg> <svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M8 2 14.5 13.5h-13Z" /><path d="M8 6.5v3M8 11.5v.01" /></svg>
<p>Restoring replaces everything on {target} with this snapshot. Anything that exists only there is lost. {snapshot.orbit_name} itself is only read.</p> {undoing ? (
<p>This replaces everything on {target} with its state from before {undoneAt}. Whatever changed on {target} since is lost, but its current state is kept as a new safety copy, so this can be reversed too.</p>
) : (
<p>Restoring replaces everything on {target} with this snapshot. Anything that exists only there is lost. {snapshot?.orbit_name} itself is only read. What {target} holds now is kept as a safety copy first, for at least a week, so the restore can be undone.</p>
)}
</div> </div>
<div className="flex gap-2.5"> <div className="flex gap-2.5">
<Button variant="danger" className="flex-1" disabled={!abortable} onClick={() => void abort()}>Abort</Button> <Button variant="danger" className="flex-1" disabled={!abortable} onClick={() => void abort()}>Abort</Button>
<Button variant="primary" className="flex-1" disabled={!point || phase !== "idle"} onClick={() => { setRefusal(undefined); setUndoOf(undefined); setLeft(COUNTDOWN); setPhase("countdown"); }}> <Button variant="primary" className="flex-1" disabled={!point || phase !== "idle"} onClick={() => { setRefusal(undefined); setLeft(COUNTDOWN); setPhase("countdown"); }}>
Begin restore {undoRun ? `Begin ${verb(undoRun).toLowerCase()}` : "Begin restore"}
</Button> </Button>
</div> </div>
{refusal && <p role="alert" className="text-sm text-orbit-red">{refusal}</p>} {refusal && <p role="alert" className="text-sm text-orbit-red">{refusal}</p>}
{undoable && phase === "idle" && !runId && ( {undoable && !undoRun && phase === "idle" && !runId && (
<div className="restore-undo"> <div className="restore-undo">
<p>The last restore on {target} was {formatWhen(new Date(undoable.updated_at * 1000).toISOString())}. Its safety copy can put {target} back as it was before.</p> <p>
<Button onClick={() => beginUndo(undoable.id)}>Undo last restore</Button> {undoable.undo ? `${target} was last put back (${what(undoable)}) on` : `${target} was last restored on`} {formatWhen(new Date(undoable.updated_at * 1000).toISOString())}.
{" "}{`${verb(undoable)} returns it to what it held before.`}
{undoable.undo_kept_until ? ` Its safety copy is kept at least until ${formatWhen(new Date(undoable.undo_kept_until * 1000).toISOString())}.` : ""}
</p>
<Button onClick={() => beginUndo(undoable)}>{`${verb(undoable)} last ${what(undoable)}`}</Button>
</div> </div>
)} )}
{admin && database && phase === "idle" && !runId && ( {admin && database && phase === "idle" && !runId && (
@@ -161,7 +201,7 @@ export function RestoreWizard({ snapshot, relations, admin, onBusyChange }: {
<aside className="restore-status"> <aside className="restore-status">
<p className="restore-status-label">{phase === "running" ? "Progress" : "Countdown"}</p> <p className="restore-status-label">{phase === "running" ? "Progress" : "Countdown"}</p>
{phase === "idle" && <p className="restore-idle">No restore is running. Begin restore to start the countdown.</p>} {phase === "idle" && <p className="restore-idle">Nothing is running. Begin to start the countdown.</p>}
{phase === "countdown" && ( {phase === "countdown" && (
<motion.div className="restore-count" initial={{ opacity: 0 }} animate={{ opacity: 1 }}> <motion.div className="restore-count" initial={{ opacity: 0 }} animate={{ opacity: 1 }}>
<div className="restore-ring"> <div className="restore-ring">
@@ -172,7 +212,7 @@ export function RestoreWizard({ snapshot, relations, admin, onBusyChange }: {
</svg> </svg>
<span className="restore-ring-text"><b>{left}</b><i>seconds</i></span> <span className="restore-ring-text"><b>{left}</b><i>seconds</i></span>
</div> </div>
<p className="restore-count-note">{undoOf ? `Undoing the last restore on ${target} in ${left}s.` : `Restoring to ${target} in ${left}s.`}<br />Abort restores nothing.</p> <p className="restore-count-note">{undoRun ? `${verb(undoRun)}ing on ${target} in ${left}s.` : `Restoring to ${target} in ${left}s.`}<br />Abort restores nothing.</p>
</motion.div> </motion.div>
)} )}
{phase === "running" && ( {phase === "running" && (
@@ -200,8 +240,8 @@ export function RestoreWizard({ snapshot, relations, admin, onBusyChange }: {
<p>{outcome.title}</p> <p>{outcome.title}</p>
<p>{outcome.detail}</p> <p>{outcome.detail}</p>
<div className="flex flex-wrap gap-2"> <div className="flex flex-wrap gap-2">
{run.data?.undo_available && <Button onClick={() => beginUndo(run.data!.id)}>Undo this restore</Button>} {run.data?.undo_available && <Button variant="primary" onClick={() => beginUndo(run.data!)}>{run.data.status === "recovery_required" ? "Roll back" : run.data.undo ? verb(run.data) : "Undo this restore"}</Button>}
<Button onClick={again}>{outcome.tone === "good" ? "Restore again" : "Try again"}</Button> <Button onClick={again}>{outcome.tone === "good" ? "Done" : "Try again"}</Button>
</div> </div>
</div> </div>
)} )}

View File

@@ -1,27 +1,32 @@
import { useMemo } from "react"; import { useMemo } from "react";
import { useQuery } from "@tanstack/react-query"; import { useQuery } from "@tanstack/react-query";
import { fetchCaptureJobs, fetchRecentRestoreJobs, type Orbit, type Snapshot } from "../api"; import { fetchCaptureJobs, fetchRecentRestoreJobs, fetchRefreshRuns, type Orbit, type Snapshot } from "../api";
import { activityCounts, buildActivity } from "../lib/activity"; import { activityCounts, buildActivity } from "../lib/activity";
/** Everything the hub reports as backups and restores, folded into one log. Polling shares keys with the Orbits console. */ /** Everything the hub reports as backups and restores, folded into one log. Polling shares keys with the Orbits console. */
export function useActivity(snapshots?: Snapshot[], orbits?: Orbit[], canSeeRestores = true) { export function useActivity(snapshots?: Snapshot[], orbits?: Orbit[], { admin = true, refresh = true } = {}) {
// Restore history is administrator-only; asking would only produce a 403. // Restore jobs carry databases and people, so only administrators may read them; asking would only produce a 403.
const restores = useQuery({ queryKey: ["restore-jobs-recent"], queryFn: () => fetchRecentRestoreJobs(100), refetchInterval: 5_000, retry: false, enabled: canSeeRestores }); const restores = useQuery({ queryKey: ["restore-jobs-recent"], queryFn: () => fetchRecentRestoreJobs(100), refetchInterval: 5_000, retry: false, enabled: admin });
// Which restore an undo reverses, and which of them can still be put back.
const runs = useQuery({ queryKey: ["restore-runs"], queryFn: fetchRefreshRuns, refetchInterval: 5_000, retry: false, enabled: refresh });
const captures = useQuery({ queryKey: ["capture-jobs", "", ""], queryFn: () => fetchCaptureJobs("", ""), refetchInterval: 5_000, retry: 1 }); const captures = useQuery({ queryKey: ["capture-jobs", "", ""], queryFn: () => fetchCaptureJobs("", ""), refetchInterval: 5_000, retry: 1 });
const restoreData = restores.data; const restoreData = restores.data;
const captureData = captures.data; const captureData = captures.data;
const runData = Array.isArray(runs.data) ? runs.data : undefined;
const entries = useMemo(() => buildActivity({ const entries = useMemo(() => buildActivity({
snapshots: snapshots ?? [], snapshots: snapshots ?? [],
orbits: orbits ?? [], orbits: orbits ?? [],
captureJobs: captureData ?? [], captureJobs: captureData ?? [],
restoreJobs: restoreData ?? [], restoreJobs: restoreData ?? [],
refreshRuns: runData ?? [],
now: Date.now(), now: Date.now(),
}), [snapshots, orbits, captureData, restoreData]); }), [snapshots, orbits, captureData, restoreData, runData]);
return { return {
entries, entries,
counts: activityCounts(entries), counts: activityCounts(entries),
restoresUnavailable: canSeeRestores && restores.isError, // Runs are enough to list restores; jobs only add detail for an administrator.
restoresUnavailable: refresh ? runs.isError && (!admin || restores.isError) : admin && restores.isError,
capturesUnavailable: captures.isError, capturesUnavailable: captures.isError,
updatedAt: Math.max(restores.dataUpdatedAt, captures.dataUpdatedAt), updatedAt: Math.max(restores.dataUpdatedAt, runs.dataUpdatedAt, captures.dataUpdatedAt),
}; };
} }

View File

@@ -979,11 +979,14 @@ button:disabled { cursor: default; }
.activity-list h3 { padding: 10px 16px 6px; background: #0b0d10; border-bottom: 1px solid #1f2327; font: 500 9.5px/1.4 var(--font-mono); letter-spacing: .14em; text-transform: uppercase; color: var(--quiet); } .activity-list h3 { padding: 10px 16px 6px; background: #0b0d10; border-bottom: 1px solid #1f2327; font: 500 9.5px/1.4 var(--font-mono); letter-spacing: .14em; text-transform: uppercase; color: var(--quiet); }
.activity-list h3[data-tone="needs"] { color: var(--color-orbit-red); } .activity-list h3[data-tone="needs"] { color: var(--color-orbit-red); }
.activity-list h3[data-tone="running"] { color: var(--color-orbit-amber); } .activity-list h3[data-tone="running"] { color: var(--color-orbit-amber); }
.act-row { width: 100%; box-sizing: border-box; display: grid; grid-template-columns: 56px 82px minmax(0, 1fr) 188px 84px; gap: 14px; align-items: center; min-height: 52px; padding: 6px 16px; border-bottom: 1px solid #1a1d21; text-align: left; } .act-row { width: 100%; box-sizing: border-box; display: grid; grid-template-columns: 56px 82px minmax(0, 1fr) 188px minmax(84px, max-content); gap: 14px; align-items: center; min-height: 52px; padding: 6px 16px; border-bottom: 1px solid #1a1d21; text-align: left; }
button.act-row:hover { background: #14171b; } button.act-row:hover { background: #14171b; }
.act-row[data-group="needs"] { background: #1a1214; box-shadow: inset 2px 0 var(--color-orbit-red); } .act-row[data-group="needs"] { background: #1a1214; box-shadow: inset 2px 0 var(--color-orbit-red); }
button.act-row[data-group="needs"]:hover { background: #20161a; } button.act-row[data-group="needs"]:hover { background: #20161a; }
.act-row[data-static] { opacity: .65; } .act-row[data-static] { opacity: .65; }
.act-row[data-child] { position: relative; padding-left: calc(16px + 24px * var(--depth, 1)); background: #0c0e11; }
.act-row[data-child]::before { content: ""; position: absolute; left: calc(24px * var(--depth, 1)); top: 0; bottom: 50%; width: 10px; border-left: 1px solid #3a3f46; border-bottom: 1px solid #3a3f46; border-bottom-left-radius: 6px; }
.act-open[data-note] { color: var(--quiet); font-style: italic; text-align: right; }
.act-time { font: 11px var(--font-mono); color: var(--quiet); } .act-time { font: 11px var(--font-mono); color: var(--quiet); }
.act-kind { display: flex; align-items: center; gap: 7px; font: 500 9.5px/1 var(--font-mono); letter-spacing: .1em; text-transform: uppercase; } .act-kind { display: flex; align-items: center; gap: 7px; font: 500 9.5px/1 var(--font-mono); letter-spacing: .1em; text-transform: uppercase; }
.act-kind[data-kind="backup"] { color: #9db8e8; } .act-kind[data-kind="backup"] { color: #9db8e8; }

View File

@@ -1,8 +1,12 @@
import type { CaptureJob, Orbit, RestoreJob, Snapshot } from "../api"; import type { CaptureJob, Orbit, RefreshRun, RestoreJob, Snapshot } from "../api";
import { formatBytes, formatWhen } from "./format.ts"; import { formatBytes, formatWhen } from "./format.ts";
import { undoDepth } from "./restoreRun.ts";
/** Where an entry leads. Restores and exports start from a snapshot, so that is where most entries go. */ /** Where an entry leads. Restores and exports start from a snapshot, so that is where most entries go. */
export type ActivityTarget = { kind: "snapshot" | "orbit"; id: string }; export type ActivityTarget =
| { kind: "snapshot" | "orbit"; id: string }
/** A restore (or undo) that can still be put back: opens the undo (or redo) dialog for this run. */
| { kind: "undo" | "redo"; run: RefreshRun };
export type ActivityEntry = { export type ActivityEntry = {
id: string; id: string;
@@ -17,8 +21,19 @@ export type ActivityEntry = {
opens: ActivityTarget | null; opens: ActivityTarget | null;
/** Position along the five phases of a job in flight, 0 to 4. */ /** Position along the five phases of a job in flight, 0 to 4. */
progress?: number; progress?: number;
/** Said in place of the link, when the entry leads nowhere on purpose (for instance, its safety backup expired). */
note?: string;
/** An undo (a restore put back) or a redo (an undo put back), shown under the restore it reverses. */
variant?: "undo" | "redo";
/** The undo or redo of this restore, oldest first. They are listed under it, not on their own. */
children?: ActivityEntry[];
/** Where the entry sits in the log: its own group and time, or the most urgent and newest of its subtree. */
slotGroup: "needs" | "running" | "history";
slotAt: number | null;
}; };
type Draft = Omit<ActivityEntry, "slotGroup" | "slotAt" | "children"> & { children?: Draft[] };
const captureLabels: Record<string, string> = { const captureLabels: Record<string, string> = {
queued: "Waiting for outpost", queued: "Waiting for outpost",
claimed: "Assigned to agent", claimed: "Assigned to agent",
@@ -41,6 +56,7 @@ const restoreLabels: Record<string, string> = {
wrong_target: "Target identity check failed", wrong_target: "Target identity check failed",
invalid_payload: "Archive check failed", invalid_payload: "Archive check failed",
safety_failed: "Safety copy could not be verified", safety_failed: "Safety copy could not be verified",
rolled_back: "Rolled back",
apply_failed: "Apply failed", apply_failed: "Apply failed",
lease_lost: "Agent disconnected during apply", lease_lost: "Agent disconnected during apply",
reconciled: "Recovery verified", reconciled: "Recovery verified",
@@ -48,23 +64,36 @@ const restoreLabels: Record<string, string> = {
}; };
const restoreOrder: string[][] = [["queued", "claimed"], ["checking"], ["safety"], ["ready", "applying"], ["completed", "reconciled"]]; const restoreOrder: string[][] = [["queued", "claimed"], ["checking"], ["safety"], ["ready", "applying"], ["completed", "reconciled"]];
const EXPIRED = "Safety backup expired";
const shortId = (id: string) => id.slice(0, 8); const shortId = (id: string) => id.slice(0, 8);
const inFlight = (status: string) => status === "queued" || status === "running" || status === "applying"; const inFlight = (status: string) => status === "queued" || status === "running" || status === "applying";
function restoreEntry(job: RestoreJob, snapshots: Map<string, Snapshot>): ActivityEntry { function restoreEntry(job: RestoreJob, snapshots: Map<string, Snapshot>, run: RefreshRun | undefined, runs: Map<string, RefreshRun>): Draft {
const source = snapshots.get(job.snapshot_id); const source = snapshots.get(job.snapshot_id);
const from = source ? `${source.orbit_name} · ${formatWhen(source.taken_at)}` : `Snapshot ${shortId(job.snapshot_id)}`; const from = source ? `${source.orbit_name} · ${formatWhen(source.taken_at)}` : `Snapshot ${shortId(job.snapshot_id)}`;
const phase = restoreLabels[job.phase] ?? job.status; const phase = restoreLabels[job.phase] ?? job.status;
const depth = run ? undoDepth(run, runs) : 0;
// What this row did (an undo, then a redo of it, then an undo of that) and what opening it offers are opposites.
const variant = depth === 0 ? undefined : depth % 2 === 1 ? "undo" as const : "redo" as const;
const where = `${job.target.name} / ${job.target.identity.database}`;
// An undo restores the safety copy of an earlier restore, which has no snapshot to open: it opens its own dialog.
// A restore whose safety backup retention has forgotten says so, instead of leading anywhere that suggests it is there.
const expired = run?.undo_state === "expired";
const opens: ActivityTarget | null = expired ? null : run?.undo_available ? { kind: variant === "undo" ? "redo" : "undo", run }
: source ? { kind: "snapshot", id: source.id } : null;
const base = { const base = {
id: `restore-${job.id}`, id: `restore-${job.id}`,
kind: "restore" as const, kind: "restore" as const,
variant,
at: job.created_at * 1000, at: job.created_at * 1000,
title: `${from} → ${job.target.name} / ${job.target.identity.database}`, title: variant ? `${variant === "redo" ? "Redo" : "Undo"} → ${where}` : `${from} → ${where}`,
opens: source ? { kind: "snapshot" as const, id: source.id } : null, opens,
note: expired ? EXPIRED : undefined,
}; };
if (job.status === "recovery_required") { if (job.status === "recovery_required") {
return { ...base, group: "needs", tone: "red", state: "Recovery required", return { ...base, group: "needs", tone: "red", state: "Recovery required",
meta: `Restore · ${phase.toLowerCase()} · target locked until verified · open the snapshot` }; meta: `Restore · ${phase.toLowerCase()} · ${run?.undo_available ? "roll back available" : "target locked until verified · open the snapshot"}` };
} }
if (inFlight(job.status)) { if (inFlight(job.status)) {
const progress = Math.max(0, restoreOrder.findIndex((phases) => phases.includes(job.phase))); const progress = Math.max(0, restoreOrder.findIndex((phases) => phases.includes(job.phase)));
@@ -78,11 +107,54 @@ function restoreEntry(job: RestoreJob, snapshots: Map<string, Snapshot>): Activi
return { ...base, group: "history", tone: "grey", state: "Cancelled", meta: `Restore · by ${job.actor}` }; return { ...base, group: "history", tone: "grey", state: "Cancelled", meta: `Restore · by ${job.actor}` };
} }
const recovered = job.status === "reconciled"; const recovered = job.status === "reconciled";
return { ...base, group: "history", tone: "green", state: recovered ? "Recovered" : "Complete", const rolledBack = job.phase === "rolled_back";
meta: `Restore · ${job.safety_snapshot_id ? "safety copy kept · " : ""}by ${job.actor}` }; const noun = variant === "redo" ? "Redo" : variant === "undo" ? "Undo" : "Restore";
const undoable = run?.undo_available ? ` · ${variant === "undo" ? "redo" : "undo"} available` : "";
return { ...base, group: "history", tone: "green", state: rolledBack ? "Rolled back" : recovered ? "Recovered" : "Complete",
meta: `${noun} · ${job.safety_snapshot_id ? "safety copy kept · " : ""}by ${job.actor}${undoable}` };
} }
function captureEntry(job: CaptureJob, orbits: Map<string, Orbit>): ActivityEntry | undefined { /** The id a restore has in the log: its job's when it has one, so a run and its job are one entry. */
const restoreId = (run: RefreshRun) => (run.restore_job_id ? `restore-${run.restore_job_id}` : `restore-run-${run.id}`);
const runStopped: Record<string, string> = { restore_failed: "Failed", blocked: "Stopped", expired: "Expired", capture_failed: "Could not start" };
/**
* A restore as the run shows it, for people who may not read restore jobs (those are administrator-only): what was
* restored where, how far it got, and whether it can be put back. It carries no database names or who started it.
*/
function runEntry(run: RefreshRun, runs: Map<string, RefreshRun>): Draft {
const depth = undoDepth(run, runs);
const variant = depth === 0 ? undefined : depth % 2 === 1 ? "undo" as const : "redo" as const;
const taken = run.snapshot_taken_at ? formatWhen(new Date(run.snapshot_taken_at * 1000).toISOString()) : undefined;
const noun = variant === "redo" ? "Redo" : variant === "undo" ? "Undo" : "Restore";
const base = {
id: restoreId(run),
kind: "restore" as const,
variant,
at: run.created_at * 1000,
title: variant ? `${noun} → ${run.target_name}` : `${run.source_name}${taken ? ` · ${taken}` : ""} → ${run.target_name}`,
opens: run.undo_available ? { kind: variant === "undo" ? "redo" as const : "undo" as const, run } : null,
// A restore known only by its run has nothing to open unless it can be put back; that is not "removed".
note: run.undo_state === "expired" ? EXPIRED : run.undo_available ? undefined : "",
};
const phase = (run.restore_phase && restoreLabels[run.restore_phase]) || undefined;
if (run.status === "recovery_required") {
return { ...base, group: "needs", tone: "red", state: "Recovery required",
meta: `${noun} · ${(phase ?? "interrupted").toLowerCase()} · ${run.undo_available ? "roll back available" : "target locked until an administrator verifies it"}` };
}
if (run.status === "capturing" || run.status === "restoring") {
const progress = Math.max(0, restoreOrder.findIndex((phases) => phases.includes(run.restore_phase ?? "queued")));
return { ...base, group: "running", tone: "amber", state: phase ?? "Running", progress, meta: `${noun} · step ${progress + 1} of 5` };
}
if (run.status === "cancelled") return { ...base, group: "history", tone: "grey", state: "Cancelled", meta: noun };
const stopped = runStopped[run.status];
if (stopped) return { ...base, group: "history", tone: "red", state: stopped, meta: `${noun}${phase && run.status === "restore_failed" ? ` · ${phase.toLowerCase()}` : ""}` };
return { ...base, group: "history", tone: "green", state: run.restore_phase === "rolled_back" ? "Rolled back" : run.status === "reconciled" ? "Recovered" : "Complete",
meta: `${noun}${run.undo_available ? ` · ${variant === "undo" ? "redo" : "undo"} available` : ""}` };
}
function captureEntry(job: CaptureJob, orbits: Map<string, Orbit>): Draft | undefined {
const orbit = orbits.get(job.profile.orbit_id); const orbit = orbits.get(job.profile.orbit_id);
const name = orbit?.name ?? job.profile.application_id; const name = orbit?.name ?? job.profile.application_id;
const base = { const base = {
@@ -104,17 +176,35 @@ function captureEntry(job: CaptureJob, orbits: Map<string, Orbit>): ActivityEntr
return undefined; return undefined;
} }
export function buildActivity({ snapshots, orbits, captureJobs, restoreJobs, now }: { const urgency = { needs: 0, running: 1, history: 2 } as const;
/** Entries sit in the log by their own group and time, except a restore, which sits by its most urgent and newest undo. */
function place(entry: Draft): ActivityEntry {
const children = entry.children?.map(place);
let slotGroup = entry.group;
let slotAt = entry.at;
for (const child of children ?? []) {
if (urgency[child.slotGroup] < urgency[slotGroup]) slotGroup = child.slotGroup;
if ((child.slotAt ?? -Infinity) > (slotAt ?? -Infinity)) slotAt = child.slotAt;
}
return { ...entry, children, slotGroup, slotAt };
}
export function buildActivity({ snapshots, orbits, captureJobs, restoreJobs, refreshRuns = [], now }: {
snapshots: readonly Snapshot[]; snapshots: readonly Snapshot[];
orbits: readonly Orbit[]; orbits: readonly Orbit[];
captureJobs: readonly CaptureJob[]; captureJobs: readonly CaptureJob[];
restoreJobs: readonly RestoreJob[]; restoreJobs: readonly RestoreJob[];
/** The hub's restore runs: they say which restore an undo reverses. */
refreshRuns?: readonly RefreshRun[];
now: number; now: number;
}): ActivityEntry[] { }): ActivityEntry[] {
const snapshotById = new Map(snapshots.map((snapshot) => [snapshot.id, snapshot])); const snapshotById = new Map(snapshots.map((snapshot) => [snapshot.id, snapshot]));
const orbitById = new Map(orbits.map((orbit) => [orbit.id, orbit])); const orbitById = new Map(orbits.map((orbit) => [orbit.id, orbit]));
const jobForSnapshot = new Map(captureJobs.filter((job) => job.snapshot_id).map((job) => [job.snapshot_id!, job])); const jobForSnapshot = new Map(captureJobs.filter((job) => job.snapshot_id).map((job) => [job.snapshot_id!, job]));
const entries: ActivityEntry[] = []; const runByJob = new Map(refreshRuns.filter((run) => run.restore_job_id).map((run) => [run.restore_job_id!, run]));
const runById = new Map(refreshRuns.map((run) => [run.id, run]));
const entries: Draft[] = [];
for (const snapshot of snapshots) { for (const snapshot of snapshots) {
const job = jobForSnapshot.get(snapshot.id); const job = jobForSnapshot.get(snapshot.id);
@@ -146,13 +236,40 @@ export function buildActivity({ snapshots, orbits, captureJobs, restoreJobs, now
opens: { kind: "orbit", id: orbit.id } }); opens: { kind: "orbit", id: orbit.id } });
} }
} }
for (const job of restoreJobs) entries.push(restoreEntry(job, snapshotById)); // Every restore comes from its run, which anyone with the refresh permission may read; an administrator's restore
// job adds the database, the person and the snapshot, and restores started without a run (another registered
// target) are only known by their job.
const jobById = new Map(restoreJobs.map((job) => [job.id, job]));
const parentOf = new Map<string, string>();
for (const run of refreshRuns) {
const job = run.restore_job_id ? jobById.get(run.restore_job_id) : undefined;
entries.push(job ? restoreEntry(job, snapshotById, run, runById) : runEntry(run, runById));
const parent = run.undo_of ? runById.get(run.undo_of) : undefined;
if (parent) parentOf.set(restoreId(run), restoreId(parent));
}
for (const job of restoreJobs) if (!runByJob.has(job.id)) entries.push(restoreEntry(job, snapshotById, undefined, runById));
const rank = { needs: 0, running: 1, history: 2 } as const; // An undo hangs under the restore it reverses, and a redo under that undo, when that restore is in the log.
return entries.sort((a, b) => rank[a.group] - rank[b.group] || (b.at ?? -Infinity) - (a.at ?? -Infinity) || a.id.localeCompare(b.id)); const byId = new Map(entries.map((entry) => [entry.id, entry]));
const top: Draft[] = [];
for (const entry of entries) {
const parent = byId.get(parentOf.get(entry.id) ?? "");
if (parent && parent !== entry) (parent.children ??= []).push(entry);
else top.push(entry);
}
const oldestFirst = (entry: Draft) => { entry.children?.sort((x, y) => (x.at ?? 0) - (y.at ?? 0)); entry.children?.forEach(oldestFirst); };
top.forEach(oldestFirst);
return top.map(place)
.sort((a, b) => urgency[a.slotGroup] - urgency[b.slotGroup] || (b.slotAt ?? -Infinity) - (a.slotAt ?? -Infinity) || a.id.localeCompare(b.id));
} }
export function activityCounts(entries: readonly ActivityEntry[]) { /** Every entry in the log, undos included. */
export function flatten(entries: readonly ActivityEntry[]): ActivityEntry[] {
return entries.flatMap((entry) => [entry, ...flatten(entry.children ?? [])]);
}
export function activityCounts(all: readonly ActivityEntry[]) {
const entries = flatten(all);
return { return {
running: entries.filter(({ group }) => group === "running").length, running: entries.filter(({ group }) => group === "running").length,
needs: entries.filter(({ group }) => group === "needs").length, needs: entries.filter(({ group }) => group === "needs").length,

View File

@@ -2,10 +2,23 @@
export const STAGES = ["Checking", "Safety copy", "Applying", "Completed"] as const; export const STAGES = ["Checking", "Safety copy", "Applying", "Completed"] as const;
type RunLike = { status: string; restore_phase: string | null; blocked_reason?: string | null; undo?: boolean }; type RunLike = { status: string; restore_phase: string | null; blocked_reason?: string | null; undo?: boolean; undo_available?: boolean };
const STOPPED = new Set(["restore_failed", "recovery_required", "blocked", "expired", "capture_failed"]); const STOPPED = new Set(["restore_failed", "recovery_required", "blocked", "expired", "capture_failed"]);
/** How many undos deep a run is: a restore is 0, its undo 1, the undo of that undo 2. */
export function undoDepth(run: { undo_of?: string | null; undo?: boolean }, byId: ReadonlyMap<string, { undo_of?: string | null; undo?: boolean }>): number {
let depth = 0;
for (let at: typeof run | undefined = run, seen = 0; at?.undo && seen < 50; seen++) {
depth++;
at = at.undo_of ? byId.get(at.undo_of) : undefined;
}
return depth;
}
/** What opening a run offers: putting back a restore is an undo, putting back an undo is a redo, and so on. */
export const undoVerb = (depth: number) => (depth % 2 === 0 ? "Undo" : "Redo");
/** The step a restore job's phase belongs to. */ /** The step a restore job's phase belongs to. */
function stageOfPhase(phase: string | null): number { function stageOfPhase(phase: string | null): number {
switch (phase) { switch (phase) {
@@ -76,7 +89,13 @@ export function outcomeOf(
case "restore_failed": case "restore_failed":
return { tone: "bad", title: "The restore failed", detail: `${target} was most likely not changed, but ask an administrator to check it before you rely on it.` }; return { tone: "bad", title: "The restore failed", detail: `${target} was most likely not changed, but ask an administrator to check it before you rely on it.` };
case "recovery_required": case "recovery_required":
return { tone: "bad", title: "The restore was interrupted", detail: `It stopped while overwriting ${target}. Do not use that database; an administrator has to recover it.` }; return {
tone: "bad",
title: "The restore was interrupted",
detail: run.undo_available
? `It stopped while overwriting ${target}, which may be half restored. Do not use that database: roll it back to what it held before, or ask an administrator to recover it.`
: `It stopped while overwriting ${target}. Do not use that database; an administrator has to recover it.`,
};
case "blocked": case "blocked":
return { tone: "bad", title: "The restore was stopped", detail: `${BLOCKED[run.blocked_reason ?? ""] ?? "something it depended on changed"}. ${target} was not overwritten.` }; return { tone: "bad", title: "The restore was stopped", detail: `${BLOCKED[run.blocked_reason ?? ""] ?? "something it depended on changed"}. ${target} was not overwritten.` };
case "expired": case "expired":