feat: undo a restore from the safety copy it took
- POST /refresh-runs accepts undo_of: restores the safety copy of a completed restore back onto the same target through the normal run engine (checks, countdown, progress, and a new safety copy so the undo can be undone); refused when something was restored after it or the copy is gone - a safety copy is accepted as a source only for the target it was taken from (hub and agent both check) - run views carry undo and undo_available; audited as refresh.undo_started - the modal offers Undo last restore and, after a restore, Undo this restore - proven with a real agent and PostgreSQL: restore, undo back to the original contents, undo of the undo Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -126,7 +126,8 @@ async fn run(
|
|||||||
let verified = tokio::time::timeout(timeout, async {
|
let verified = tokio::time::timeout(timeout, async {
|
||||||
let identity = target.identity().await?;
|
let identity = target.identity().await?;
|
||||||
ensure!(
|
ensure!(
|
||||||
identity == lease.job.target.identity && identity != lease.artifact.identity,
|
identity == lease.job.target.identity
|
||||||
|
&& (lease.artifact.rollback || identity != lease.artifact.identity),
|
||||||
"restore target identity does not match"
|
"restore target identity does not match"
|
||||||
);
|
);
|
||||||
if let Some(source) = source {
|
if let Some(source) = source {
|
||||||
|
|||||||
@@ -89,6 +89,10 @@ pub struct RestoreArtifact {
|
|||||||
pub format: CaptureFormat,
|
pub format: CaptureFormat,
|
||||||
pub identity: DatabaseIdentity,
|
pub identity: DatabaseIdentity,
|
||||||
pub sha256: String,
|
pub sha256: String,
|
||||||
|
/// The artifact is the safety copy a restore took of the very target it is now restored onto (an undo).
|
||||||
|
/// Its source identity is then the target's own, so the "target is the source" refusal does not apply.
|
||||||
|
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||||
|
pub rollback: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize, Serialize)]
|
#[derive(Deserialize, Serialize)]
|
||||||
|
|||||||
@@ -24,5 +24,5 @@ mod session;
|
|||||||
|
|
||||||
pub use orbit::run_orbit_internal;
|
pub use orbit::run_orbit_internal;
|
||||||
pub(crate) use relations::identity_facts;
|
pub(crate) use relations::identity_facts;
|
||||||
pub(crate) use restore::artifact;
|
pub(crate) use restore::{artifact, rollback_artifact};
|
||||||
pub use routes::router;
|
pub use routes::router;
|
||||||
|
|||||||
@@ -69,9 +69,27 @@ struct RunView {
|
|||||||
requested_by: Option<String>,
|
requested_by: Option<String>,
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
snapshot_id: Option<String>,
|
snapshot_id: Option<String>,
|
||||||
|
/// This run put a target back from the safety copy of an earlier restore.
|
||||||
|
undo: bool,
|
||||||
|
/// A completed restore that can still be undone: the newest restore of its target, with its safety copy in
|
||||||
|
/// the vault. Never says where the copy is.
|
||||||
|
undo_available: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn view(state: &HubState, run: &RefreshRun, admin: bool) -> Result<RunView, StatusCode> {
|
/// Can this run still be undone: see `Db::undo_candidate`, and the safety copy must still exist.
|
||||||
|
async fn can_undo(state: &HubState, run: &RefreshRun) -> bool {
|
||||||
|
if run.status != "completed" {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
match state.db.undo_candidate(&run.id, &run.relation_id) {
|
||||||
|
Ok(Ok(safety)) => snapshot_fits(state, &run.relation_id, safety)
|
||||||
|
.await
|
||||||
|
.unwrap_or(false),
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn view(state: &HubState, run: &RefreshRun, admin: bool) -> Result<RunView, StatusCode> {
|
||||||
let Progress {
|
let Progress {
|
||||||
capture_status,
|
capture_status,
|
||||||
capture_phase,
|
capture_phase,
|
||||||
@@ -98,6 +116,8 @@ fn view(state: &HubState, run: &RefreshRun, admin: bool) -> Result<RunView, Stat
|
|||||||
expires_at: run.expires_at,
|
expires_at: run.expires_at,
|
||||||
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_available: can_undo(state, run).await,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,6 +154,10 @@ struct Start {
|
|||||||
/// relation's own source.
|
/// relation's own source.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
snapshot_id: Option<Uuid>,
|
snapshot_id: Option<Uuid>,
|
||||||
|
/// Put the target back as it was before this earlier restore: restore that restore's safety copy onto the same
|
||||||
|
/// target. The run must be a completed restore of this relation and the newest one of its target.
|
||||||
|
#[serde(default)]
|
||||||
|
undo_of: Option<Uuid>,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn valid_key(key: &str) -> bool {
|
fn valid_key(key: &str) -> bool {
|
||||||
@@ -160,10 +184,22 @@ async fn snapshot_fits(
|
|||||||
.get_snapshot(snapshot)
|
.get_snapshot(snapshot)
|
||||||
.map_err(internal)?
|
.map_err(internal)?
|
||||||
.map(|s| s.manifest);
|
.map(|s| s.manifest);
|
||||||
|
let target = match state.db.relation_target(relation).map_err(internal)? {
|
||||||
|
Some(id) => Uuid::parse_str(&id)
|
||||||
|
.ok()
|
||||||
|
.and_then(|id| state.db.restore_target(id).ok().flatten()),
|
||||||
|
None => None,
|
||||||
|
};
|
||||||
Ok(manifest.is_some_and(|manifest| {
|
Ok(manifest.is_some_and(|manifest| {
|
||||||
manifest.orbit_id.to_string() == source
|
manifest.orbit_id.to_string() == source
|
||||||
&& !manifest.is_restore_safety()
|
&& if manifest.is_restore_safety() {
|
||||||
&& crate::api::artifact(&manifest).is_some()
|
// a safety copy only ever goes back onto the target it was taken from
|
||||||
|
target.as_ref().is_some_and(|target| {
|
||||||
|
crate::api::rollback_artifact(&manifest, target).is_some()
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
crate::api::artifact(&manifest).is_some()
|
||||||
|
}
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -179,13 +215,33 @@ async fn start(
|
|||||||
}
|
}
|
||||||
super::gate::relation(&state, &actor, body.relation_id)?;
|
super::gate::relation(&state, &actor, body.relation_id)?;
|
||||||
let relation = body.relation_id.to_string();
|
let relation = body.relation_id.to_string();
|
||||||
if let Some(snapshot) = body.snapshot_id {
|
// What to restore: a snapshot the person picked, the safety copy that undoes an earlier restore, or (neither)
|
||||||
|
// a fresh capture.
|
||||||
|
let mut chosen: Option<(Uuid, bool)> = None;
|
||||||
|
if let Some(of) = body.undo_of {
|
||||||
|
if body.snapshot_id.is_some() {
|
||||||
|
return Err(StatusCode::BAD_REQUEST);
|
||||||
|
}
|
||||||
|
let candidate = state
|
||||||
|
.db
|
||||||
|
.undo_candidate(&of.to_string(), &relation)
|
||||||
|
.map_err(internal)?;
|
||||||
|
let Ok(safety) = candidate else {
|
||||||
|
return Ok(reason(StatusCode::UNPROCESSABLE_ENTITY, "nothing_to_undo"));
|
||||||
|
};
|
||||||
|
// the copy may have been removed since
|
||||||
|
if !snapshot_fits(&state, &relation, safety).await? {
|
||||||
|
return Ok(reason(StatusCode::UNPROCESSABLE_ENTITY, "nothing_to_undo"));
|
||||||
|
}
|
||||||
|
chosen = Some((safety, true));
|
||||||
|
} 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(
|
||||||
StatusCode::UNPROCESSABLE_ENTITY,
|
StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
"snapshot_unusable",
|
"snapshot_unusable",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
chosen = Some((snapshot, false));
|
||||||
}
|
}
|
||||||
// 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 {
|
||||||
@@ -214,7 +270,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,
|
||||||
body.snapshot_id,
|
chosen,
|
||||||
state.refresh.ttl_secs,
|
state.refresh.ttl_secs,
|
||||||
state.refresh.max_active,
|
state.refresh.max_active,
|
||||||
now(),
|
now(),
|
||||||
@@ -223,7 +279,11 @@ async fn start(
|
|||||||
match started {
|
match started {
|
||||||
Ok((run, created)) => {
|
Ok((run, created)) => {
|
||||||
if created {
|
if created {
|
||||||
crate::refresh::audit_run(&state, &run.id, "capturing");
|
crate::refresh::audit_run(
|
||||||
|
&state,
|
||||||
|
&run.id,
|
||||||
|
if run.is_undo() { "undo" } else { "capturing" },
|
||||||
|
);
|
||||||
}
|
}
|
||||||
let status = if created {
|
let status = if created {
|
||||||
StatusCode::ACCEPTED
|
StatusCode::ACCEPTED
|
||||||
@@ -233,7 +293,7 @@ async fn start(
|
|||||||
Ok((
|
Ok((
|
||||||
status,
|
status,
|
||||||
no_store(),
|
no_store(),
|
||||||
Json(view(&state, &run, actor.subject.admin)?),
|
Json(view(&state, &run, actor.subject.admin).await?),
|
||||||
)
|
)
|
||||||
.into_response())
|
.into_response())
|
||||||
}
|
}
|
||||||
@@ -283,10 +343,10 @@ async fn list(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
.map_err(internal)?;
|
.map_err(internal)?;
|
||||||
let views = runs
|
let mut views = Vec::with_capacity(runs.len());
|
||||||
.iter()
|
for run in &runs {
|
||||||
.map(|run| view(&state, run, actor.subject.admin))
|
views.push(view(&state, run, actor.subject.admin).await?);
|
||||||
.collect::<Result<Vec<_>, _>>()?;
|
}
|
||||||
Ok((no_store(), Json(views)))
|
Ok((no_store(), Json(views)))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -318,7 +378,10 @@ async fn show(
|
|||||||
)
|
)
|
||||||
.map_err(internal)?;
|
.map_err(internal)?;
|
||||||
let run = run.ok_or(StatusCode::NOT_FOUND)?;
|
let run = run.ok_or(StatusCode::NOT_FOUND)?;
|
||||||
Ok((no_store(), Json(view(&state, &run, actor.subject.admin)?)))
|
Ok((
|
||||||
|
no_store(),
|
||||||
|
Json(view(&state, &run, actor.subject.admin).await?),
|
||||||
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cancel(
|
async fn cancel(
|
||||||
@@ -364,7 +427,11 @@ async fn cancel(
|
|||||||
{
|
{
|
||||||
Ok(run) => {
|
Ok(run) => {
|
||||||
crate::refresh::audit_run(&state, &run.id, "cancelled");
|
crate::refresh::audit_run(&state, &run.id, "cancelled");
|
||||||
Ok((no_store(), Json(view(&state, &run, actor.subject.admin)?)).into_response())
|
Ok((
|
||||||
|
no_store(),
|
||||||
|
Json(view(&state, &run, actor.subject.admin).await?),
|
||||||
|
)
|
||||||
|
.into_response())
|
||||||
}
|
}
|
||||||
Err(CancelError::Unknown) => Err(StatusCode::NOT_FOUND),
|
Err(CancelError::Unknown) => Err(StatusCode::NOT_FOUND),
|
||||||
Err(CancelError::TooLate) => Ok(reason(StatusCode::CONFLICT, "too_late")),
|
Err(CancelError::TooLate) => Ok(reason(StatusCode::CONFLICT, "too_late")),
|
||||||
|
|||||||
@@ -2188,3 +2188,180 @@ async fn the_screens_get_what_they_need_to_offer_restore_for_an_orbit() {
|
|||||||
"{kinds:?}"
|
"{kinds:?}"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- undoing a restore: put the target back from the safety copy the restore took ----
|
||||||
|
|
||||||
|
impl Lab {
|
||||||
|
async fn start_undo(&self, caller: &Caller, key: &str, run: &str) -> (StatusCode, Value) {
|
||||||
|
self.send(
|
||||||
|
caller,
|
||||||
|
"POST",
|
||||||
|
"/api/v1/refresh-runs",
|
||||||
|
Some(json!({"relation_id": self.relation, "confirmation": self.confirmation(), "idempotency_key": key, "undo_of": run})),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A completed restore of a fresh capture, with its safety copy in the vault.
|
||||||
|
async fn restored_once(&self, key: &str) -> 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;
|
||||||
|
self.finish_restore().await;
|
||||||
|
assert_eq!(self.run(&run).status, "completed");
|
||||||
|
run
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_completed_restore_can_be_undone_from_its_safety_copy_and_the_undo_can_be_undone() {
|
||||||
|
let lab = fresh().await;
|
||||||
|
let (qa, _) = lab.refresher("qa");
|
||||||
|
let first = lab.restored_once("first").await;
|
||||||
|
let (_, view) = lab
|
||||||
|
.send(&qa, "GET", &format!("/api/v1/refresh-runs/{first}"), None)
|
||||||
|
.await;
|
||||||
|
assert_eq!(view["undo_available"], true, "{view}");
|
||||||
|
assert!(
|
||||||
|
view.get("safety_snapshot_id").is_none(),
|
||||||
|
"no snapshot id reaches a non-administrator: {view}"
|
||||||
|
);
|
||||||
|
|
||||||
|
let (status, undo) = lab.start_undo(&qa, "undo-1", &first).await;
|
||||||
|
assert_eq!(status, StatusCode::ACCEPTED, "{undo}");
|
||||||
|
assert_eq!(undo["undo"], true);
|
||||||
|
let undo_id = undo["id"].as_str().unwrap().to_string();
|
||||||
|
let captures = lab.capture_jobs();
|
||||||
|
lab.tick().await;
|
||||||
|
// the restore job takes the first restore's safety copy back onto the same target
|
||||||
|
let (job, _) = lab
|
||||||
|
.restore_until_ready()
|
||||||
|
.await
|
||||||
|
.expect("an undo job is waiting");
|
||||||
|
let artifact: Value = serde_json::from_str(&lab.scalar::<String>(&format!(
|
||||||
|
"SELECT artifact FROM restore_jobs WHERE id='{job}'"
|
||||||
|
)))
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(artifact["rollback"], true, "{artifact}");
|
||||||
|
assert_eq!(lab.capture_jobs(), captures, "an undo captures nothing");
|
||||||
|
let (_, token) = (
|
||||||
|
job.clone(),
|
||||||
|
lab.scalar::<String>(&format!(
|
||||||
|
"SELECT lease_token FROM restore_jobs WHERE id='{job}'"
|
||||||
|
)),
|
||||||
|
);
|
||||||
|
assert_eq!(lab.apply(&job, &token).await, StatusCode::NO_CONTENT);
|
||||||
|
lab.report_applied(&job, &token).await;
|
||||||
|
lab.tick().await;
|
||||||
|
assert_eq!(lab.run(&undo_id).status, "completed");
|
||||||
|
|
||||||
|
// only the newest restore of a target can be undone: the first one no longer can, the undo can
|
||||||
|
let (_, old) = lab
|
||||||
|
.send(&qa, "GET", &format!("/api/v1/refresh-runs/{first}"), None)
|
||||||
|
.await;
|
||||||
|
let (_, new) = lab
|
||||||
|
.send(&qa, "GET", &format!("/api/v1/refresh-runs/{undo_id}"), None)
|
||||||
|
.await;
|
||||||
|
assert_eq!(
|
||||||
|
(old["undo_available"].clone(), new["undo_available"].clone()),
|
||||||
|
(json!(false), json!(true))
|
||||||
|
);
|
||||||
|
assert!(lab
|
||||||
|
.audit_log()
|
||||||
|
.iter()
|
||||||
|
.any(|(event, _)| event == "restore.queued"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn an_undo_is_refused_when_there_is_nothing_sound_to_go_back_to() {
|
||||||
|
let lab = fresh().await;
|
||||||
|
let admin = lab.admin();
|
||||||
|
// a run that has not finished, and one that does not exist
|
||||||
|
let (_, running) = lab.start(&admin, "running").await;
|
||||||
|
let running = running["id"].as_str().unwrap().to_string();
|
||||||
|
for (what, id) in [
|
||||||
|
("unfinished", running.clone()),
|
||||||
|
("unknown", Uuid::new_v4().to_string()),
|
||||||
|
] {
|
||||||
|
let (status, body) = lab.start_undo(&admin, &format!("u-{what}"), &id).await;
|
||||||
|
assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "{what}: {body}");
|
||||||
|
assert_eq!(body["reason"], "nothing_to_undo", "{what}");
|
||||||
|
}
|
||||||
|
lab.capture(&Lab::production_identity(), false)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
lab.tick().await;
|
||||||
|
lab.finish_restore().await;
|
||||||
|
|
||||||
|
// the safety copy has been removed from the vault
|
||||||
|
let safety = lab.scalar::<String>("SELECT safety_id FROM restore_jobs LIMIT 1");
|
||||||
|
lab.state
|
||||||
|
.vault
|
||||||
|
.write()
|
||||||
|
.await
|
||||||
|
.forget(&[Uuid::parse_str(&safety).unwrap()])
|
||||||
|
.unwrap();
|
||||||
|
let (status, body) = lab.start_undo(&admin, "gone", &running).await;
|
||||||
|
assert_eq!(
|
||||||
|
(status, body["reason"].clone()),
|
||||||
|
(StatusCode::UNPROCESSABLE_ENTITY, json!("nothing_to_undo")),
|
||||||
|
"{body}"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
lab.scalar::<i64>("SELECT COUNT(*) FROM refresh_runs"),
|
||||||
|
1,
|
||||||
|
"nothing was started"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_safety_copy_is_only_ever_restored_onto_the_target_it_came_from() {
|
||||||
|
let lab = fresh().await;
|
||||||
|
let admin = lab.admin();
|
||||||
|
let first = lab.restored_once("first").await;
|
||||||
|
let own_safety =
|
||||||
|
Uuid::parse_str(&lab.scalar::<String>("SELECT safety_id FROM restore_jobs LIMIT 1"))
|
||||||
|
.unwrap();
|
||||||
|
let hints = lab
|
||||||
|
.state
|
||||||
|
.vault
|
||||||
|
.read()
|
||||||
|
.await
|
||||||
|
.get_snapshot(own_safety)
|
||||||
|
.unwrap()
|
||||||
|
.unwrap()
|
||||||
|
.manifest
|
||||||
|
.restore_hints;
|
||||||
|
// the same kind of copy, but taken from some other target
|
||||||
|
let mut foreign_hints = hints.clone();
|
||||||
|
foreign_hints["target_id"] = json!(Uuid::new_v4());
|
||||||
|
let foreign = lab
|
||||||
|
.plant_snapshot(lab.orbit, &["restore-safety"], foreign_hints)
|
||||||
|
.await;
|
||||||
|
let (status, body) = lab.start_snapshot(&admin, "foreign", foreign).await;
|
||||||
|
assert_eq!(
|
||||||
|
(status, body["reason"].clone()),
|
||||||
|
(StatusCode::UNPROCESSABLE_ENTITY, json!("snapshot_unusable")),
|
||||||
|
"{body}"
|
||||||
|
);
|
||||||
|
// its own copy is fine, through the plain snapshot route as well
|
||||||
|
let (status, body) = lab.start_snapshot(&admin, "own", own_safety).await;
|
||||||
|
assert_eq!(status, StatusCode::ACCEPTED, "{body}");
|
||||||
|
let _ = first;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn only_someone_who_may_use_the_relation_can_undo_through_it() {
|
||||||
|
let lab = fresh().await;
|
||||||
|
let first = lab.restored_once("first").await;
|
||||||
|
let stranger = lab.person("stranger");
|
||||||
|
let status = lab.start_undo(&stranger, "s", &first).await.0;
|
||||||
|
assert!(
|
||||||
|
status == StatusCode::FORBIDDEN || status == StatusCode::NOT_FOUND,
|
||||||
|
"{status}"
|
||||||
|
);
|
||||||
|
assert_eq!(lab.scalar::<i64>("SELECT COUNT(*) FROM refresh_runs"), 1);
|
||||||
|
}
|
||||||
|
|||||||
@@ -234,10 +234,42 @@ pub(crate) fn artifact(manifest: &SnapshotManifest) -> Option<(Uuid, RestoreArti
|
|||||||
format,
|
format,
|
||||||
identity,
|
identity,
|
||||||
sha256,
|
sha256,
|
||||||
|
rollback: false,
|
||||||
},
|
},
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The artifact for putting a target back from the safety copy a restore took of it, or `None` when the
|
||||||
|
/// snapshot is not such a copy, was taken from some other target, or lacks what a restore needs. The copy is a
|
||||||
|
/// dump of the target itself, so its source identity is the target's own.
|
||||||
|
pub(crate) fn rollback_artifact(
|
||||||
|
manifest: &SnapshotManifest,
|
||||||
|
target: &tessera_core::restore::RestoreTarget,
|
||||||
|
) -> Option<RestoreArtifact> {
|
||||||
|
if !manifest.is_restore_safety() || manifest.safety_target()? != target.id.to_string() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let format = match (
|
||||||
|
manifest.provider.as_str(),
|
||||||
|
manifest.restore_hints.get("format")?.as_str()?,
|
||||||
|
) {
|
||||||
|
("postgres", "custom") => CaptureFormat::PostgresCustom,
|
||||||
|
("postgres", "plain") => CaptureFormat::PostgresSql,
|
||||||
|
("mysql", "plain") => CaptureFormat::MysqlSql,
|
||||||
|
_ => return None,
|
||||||
|
};
|
||||||
|
let sha256 = manifest.restore_hints.get("sha256")?.as_str()?.to_owned();
|
||||||
|
if sha256.len() != 64 || !sha256.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
(format.engine() == Some(target.engine)).then(|| RestoreArtifact {
|
||||||
|
format,
|
||||||
|
identity: target.identity.clone(),
|
||||||
|
sha256,
|
||||||
|
rollback: true,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
async fn job(
|
async fn job(
|
||||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||||
State(state): State<HubState>,
|
State(state): State<HubState>,
|
||||||
|
|||||||
@@ -84,9 +84,77 @@ pub enum StartError {
|
|||||||
/// 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.
|
||||||
/// `capture_job_id` of a run that restores a snapshot somebody picked instead of capturing a new one.
|
/// `capture_job_id` of a run that restores a snapshot somebody picked instead of capturing a new one.
|
||||||
const EXISTING: &str = "existing:";
|
const EXISTING: &str = "existing:";
|
||||||
|
/// Same, for a run that puts a target back from the safety copy of an earlier restore.
|
||||||
|
const UNDO: &str = "undo:";
|
||||||
|
|
||||||
|
/// Does this run take its snapshot from the request instead of from a capture of its own?
|
||||||
|
fn picked_snapshot(run: &RefreshRun) -> bool {
|
||||||
|
run.capture_job_id.starts_with(EXISTING) || run.capture_job_id.starts_with(UNDO)
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RefreshRun {
|
||||||
|
/// This run put a target back from a safety copy.
|
||||||
|
pub fn is_undo(&self) -> bool {
|
||||||
|
self.capture_job_id.starts_with(UNDO)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// A relation's source orbit, for checking that a snapshot belongs to it.
|
/// A relation's source orbit, for checking that a snapshot belongs to it.
|
||||||
|
/// Why a restore cannot be undone.
|
||||||
|
#[derive(Debug, PartialEq, Eq)]
|
||||||
|
pub enum UndoRefusal {
|
||||||
|
/// No such run, not of this relation, not completed, or it took no safety copy.
|
||||||
|
NothingToUndo,
|
||||||
|
/// Something else was restored onto the target after it. Undoing an older restore would also undo that.
|
||||||
|
NotTheLatest,
|
||||||
|
}
|
||||||
|
|
||||||
impl Db {
|
impl Db {
|
||||||
|
/// The safety copy that undoes `run`, if the run is a completed restore of this relation and the newest
|
||||||
|
/// restore of its target. Whether the copy still exists in the vault is for the caller to check.
|
||||||
|
pub fn undo_candidate(
|
||||||
|
&self,
|
||||||
|
run: &str,
|
||||||
|
relation: &str,
|
||||||
|
) -> Result<std::result::Result<Uuid, UndoRefusal>> {
|
||||||
|
let conn = self.conn.lock().unwrap();
|
||||||
|
let Some(run) =
|
||||||
|
get(&conn, run)?.filter(|r| r.relation_id == relation && r.status == "completed")
|
||||||
|
else {
|
||||||
|
return Ok(Err(UndoRefusal::NothingToUndo));
|
||||||
|
};
|
||||||
|
let Some(job) = &run.restore_job_id else {
|
||||||
|
return Ok(Err(UndoRefusal::NothingToUndo));
|
||||||
|
};
|
||||||
|
let safety: Option<Option<String>> = conn
|
||||||
|
.query_row(
|
||||||
|
"SELECT safety_id FROM restore_jobs WHERE id = ?1 AND status = 'completed'",
|
||||||
|
params![job],
|
||||||
|
|r| r.get(0),
|
||||||
|
)
|
||||||
|
.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>> {
|
||||||
|
let conn = self.conn.lock().unwrap();
|
||||||
|
Ok(relation_of(&conn, relation)?.map(|r| r.target_id))
|
||||||
|
}
|
||||||
|
|
||||||
pub fn relation_source_orbit(&self, relation: &str) -> Result<Option<String>> {
|
pub fn relation_source_orbit(&self, relation: &str) -> Result<Option<String>> {
|
||||||
let conn = self.conn.lock().unwrap();
|
let conn = self.conn.lock().unwrap();
|
||||||
Ok(relation_of(&conn, relation)?.map(|r| r.source_orbit_id))
|
Ok(relation_of(&conn, relation)?.map(|r| r.source_orbit_id))
|
||||||
@@ -282,7 +350,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,
|
||||||
snapshot: Option<Uuid>,
|
// a snapshot to restore instead of capturing one, and whether it is an undo of an earlier restore
|
||||||
|
snapshot: Option<(Uuid, bool)>,
|
||||||
ttl_secs: i64,
|
ttl_secs: i64,
|
||||||
max_active: i64,
|
max_active: i64,
|
||||||
now: i64,
|
now: i64,
|
||||||
@@ -324,7 +393,8 @@ impl Db {
|
|||||||
// 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(_) => format!("{EXISTING}{id}"),
|
Some((_, true)) => format!("{UNDO}{id}"),
|
||||||
|
Some((_, false)) => 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) =
|
||||||
@@ -340,7 +410,7 @@ impl Db {
|
|||||||
authorized_by,idempotency_key,status,capture_job_id,snapshot_id,created_at,updated_at,expires_at)
|
authorized_by,idempotency_key,status,capture_job_id,snapshot_id,created_at,updated_at,expires_at)
|
||||||
VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,'capturing',?11,?12,?13,?13,?14)",
|
VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,'capturing',?11,?12,?13,?13,?14)",
|
||||||
params![id, relation.id, relation.version, relation.source_orbit_id, relation.source_application_id, relation.target_id,
|
params![id, relation.id, relation.version, relation.source_orbit_id, relation.source_application_id, relation.target_id,
|
||||||
requester, requester_user_id, authorized_by, idempotency_key, capture, snapshot.map(|s| s.to_string()), now, now + ttl_secs],
|
requester, requester_user_id, authorized_by, idempotency_key, capture, snapshot.map(|(s, _)| s.to_string()), now, now + ttl_secs],
|
||||||
)?;
|
)?;
|
||||||
Ok(Ok((get(&tx, &id)?.expect("just inserted"), true)))
|
Ok(Ok((get(&tx, &id)?.expect("just inserted"), true)))
|
||||||
})()?;
|
})()?;
|
||||||
@@ -446,7 +516,7 @@ impl Db {
|
|||||||
if run.status != "capturing" || run.restore_job_id.is_some() {
|
if run.status != "capturing" || run.restore_job_id.is_some() {
|
||||||
return Ok(Linked::NotReady);
|
return Ok(Linked::NotReady);
|
||||||
}
|
}
|
||||||
let snapshot = if run.capture_job_id.starts_with(EXISTING) {
|
let snapshot = if picked_snapshot(&run) {
|
||||||
let Some(snapshot) = run.snapshot_id.clone() else {
|
let Some(snapshot) = run.snapshot_id.clone() else {
|
||||||
return Ok(Linked::NotReady);
|
return Ok(Linked::NotReady);
|
||||||
};
|
};
|
||||||
@@ -613,7 +683,7 @@ fn sync_in(tx: &Transaction<'_>, id: &str, now: i64) -> Result<Sync> {
|
|||||||
Ok(Sync::Moved(status.into()))
|
Ok(Sync::Moved(status.into()))
|
||||||
};
|
};
|
||||||
match run.status.as_str() {
|
match run.status.as_str() {
|
||||||
"capturing" if run.capture_job_id.starts_with(EXISTING) => {
|
"capturing" if picked_snapshot(&run) => {
|
||||||
// Nothing to capture: the snapshot was chosen when the run was started.
|
// Nothing to capture: the snapshot was chosen when the run was started.
|
||||||
match (&run.snapshot_id, &run.restore_job_id) {
|
match (&run.snapshot_id, &run.restore_job_id) {
|
||||||
(Some(snapshot), None) => Ok(Sync::NeedRestore(snapshot.clone())),
|
(Some(snapshot), None) => Ok(Sync::NeedRestore(snapshot.clone())),
|
||||||
|
|||||||
@@ -76,7 +76,7 @@ pub(crate) fn restore_target_mismatch(
|
|||||||
) -> Option<&'static str> {
|
) -> Option<&'static str> {
|
||||||
if Some(target.engine) != artifact.format.engine() {
|
if Some(target.engine) != artifact.format.engine() {
|
||||||
Some("Database engine differs from the snapshot")
|
Some("Database engine differs from the snapshot")
|
||||||
} else if target.identity == artifact.identity {
|
} else if target.identity == artifact.identity && !artifact.rollback {
|
||||||
Some("Target is the source database")
|
Some("Target is the source database")
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
@@ -562,6 +562,7 @@ mod tests {
|
|||||||
let artifact = RestoreArtifact {
|
let artifact = RestoreArtifact {
|
||||||
format: CaptureFormat::PostgresCustom,
|
format: CaptureFormat::PostgresCustom,
|
||||||
sha256: "0".repeat(64),
|
sha256: "0".repeat(64),
|
||||||
|
rollback: false,
|
||||||
identity: DatabaseIdentity {
|
identity: DatabaseIdentity {
|
||||||
instance: "123".into(),
|
instance: "123".into(),
|
||||||
database: "source".into(),
|
database: "source".into(),
|
||||||
|
|||||||
@@ -47,6 +47,7 @@ fn now() -> i64 {
|
|||||||
pub fn audit_name(status: &str) -> (&'static str, AuditOutcome) {
|
pub fn audit_name(status: &str) -> (&'static str, AuditOutcome) {
|
||||||
match status {
|
match status {
|
||||||
"capturing" => ("refresh.started", AuditOutcome::Succeeded),
|
"capturing" => ("refresh.started", AuditOutcome::Succeeded),
|
||||||
|
"undo" => ("refresh.undo_started", AuditOutcome::Succeeded),
|
||||||
"restoring" => ("refresh.restore_queued", AuditOutcome::Succeeded),
|
"restoring" => ("refresh.restore_queued", AuditOutcome::Succeeded),
|
||||||
"completed" => ("refresh.completed", AuditOutcome::Succeeded),
|
"completed" => ("refresh.completed", AuditOutcome::Succeeded),
|
||||||
"reconciled" => ("refresh.reconciled", AuditOutcome::Succeeded),
|
"reconciled" => ("refresh.reconciled", AuditOutcome::Succeeded),
|
||||||
@@ -104,10 +105,18 @@ async fn queue_restore(state: &HubState, run: &RefreshRun, snapshot: &str) -> an
|
|||||||
.await
|
.await
|
||||||
.get_snapshot(snapshot_id)?
|
.get_snapshot(snapshot_id)?
|
||||||
.map(|s| s.manifest);
|
.map(|s| s.manifest);
|
||||||
let artifact = manifest
|
let target = state.db.restore_target(Uuid::parse_str(&run.target_id)?)?;
|
||||||
|
// A safety copy is restorable only onto the target it was taken from (an undo); anything else must be a
|
||||||
|
// capture with its source identity.
|
||||||
|
let artifact = manifest.as_ref().and_then(|manifest| {
|
||||||
|
if manifest.is_restore_safety() {
|
||||||
|
target
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.and_then(crate::api::artifact)
|
.and_then(|target| crate::api::rollback_artifact(manifest, target))
|
||||||
.map(|(_, artifact)| artifact);
|
} else {
|
||||||
|
crate::api::artifact(manifest).map(|(_, artifact)| artifact)
|
||||||
|
}
|
||||||
|
});
|
||||||
let Some(artifact) = artifact else {
|
let Some(artifact) = artifact else {
|
||||||
// The snapshot is missing or lacks what a restore needs (format, checksum, source identity).
|
// The snapshot is missing or lacks what a restore needs (format, checksum, source identity).
|
||||||
state
|
state
|
||||||
@@ -117,9 +126,9 @@ async fn queue_restore(state: &HubState, run: &RefreshRun, snapshot: &str) -> an
|
|||||||
return Ok(true);
|
return Ok(true);
|
||||||
};
|
};
|
||||||
// The driver looks again: a run that was told to restore a snapshot only restores one of its own source.
|
// The driver looks again: a run that was told to restore a snapshot only restores one of its own source.
|
||||||
let belongs = manifest.as_ref().is_some_and(|manifest| {
|
let belongs = manifest
|
||||||
manifest.orbit_id.to_string() == run.source_orbit_id && !manifest.is_restore_safety()
|
.as_ref()
|
||||||
});
|
.is_some_and(|manifest| manifest.orbit_id.to_string() == run.source_orbit_id);
|
||||||
if !belongs {
|
if !belongs {
|
||||||
state
|
state
|
||||||
.db
|
.db
|
||||||
@@ -127,7 +136,6 @@ async fn queue_restore(state: &HubState, run: &RefreshRun, snapshot: &str) -> an
|
|||||||
audit_run(state, &run.id, "blocked");
|
audit_run(state, &run.id, "blocked");
|
||||||
return Ok(true);
|
return Ok(true);
|
||||||
}
|
}
|
||||||
let target = state.db.restore_target(Uuid::parse_str(&run.target_id)?)?;
|
|
||||||
let clash = match target {
|
let clash = match target {
|
||||||
Some(target) => {
|
Some(target) => {
|
||||||
let source = Uuid::parse_str(&run.source_orbit_id)?;
|
let source = Uuid::parse_str(&run.source_orbit_id)?;
|
||||||
|
|||||||
@@ -378,12 +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
|
||||||
|
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
|
||||||
|
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
|
||||||
|
`rollback`). Run views say `undo` and `undo_available`, never where the copy is. The run is audited as
|
||||||
|
`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
|
||||||
latest data (or click a snapshot that is already there), and in the snapshot detail press **Restore**. The button is
|
latest data (or click a snapshot that is already there), and in the snapshot detail press **Restore**. The button is
|
||||||
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. Safety copies are not listed with the
|
Applying, Completed) from the run, and Abort still works until Applying starts. A finished restore offers **Undo this restore**, and the modal offers
|
||||||
|
**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.
|
||||||
|
|
||||||
|
|||||||
@@ -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; `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 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/: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 |
|
||||||
|
|||||||
@@ -39,6 +39,14 @@ test("what the person is told never contains the database's own words", () => {
|
|||||||
assert.equal(outcomeOf(run("restoring", "safety"), { target: "Staging" }).tone, "busy");
|
assert.equal(outcomeOf(run("restoring", "safety"), { target: "Staging" }).tone, "busy");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("an undo is worded as putting the target back, and its own safety copy keeps it undoable", () => {
|
||||||
|
const done = outcomeOf({ ...run("completed"), undo: true }, { target: "Staging", orbit: "ledger", when: "Nov 15, 11:57 AM" });
|
||||||
|
assert.equal(done.tone, "good");
|
||||||
|
assert.match(done.title, /Staging was rolled back/);
|
||||||
|
assert.match(done.detail, /holds what it held before that restore/);
|
||||||
|
assert.match(outcomeOf({ ...run("restore_failed", "apply_failed"), undo: true }, { target: "Staging" }).title, /undo failed/i);
|
||||||
|
});
|
||||||
|
|
||||||
test("restore points are named by environment, and by target only when two share one", () => {
|
test("restore points are named by environment, and by target only when two share one", () => {
|
||||||
const rel = (id, env, name) => ({ id, target_environment: env, target_name: name, usable: true });
|
const rel = (id, env, name) => ({ id, target_environment: env, target_name: name, usable: true });
|
||||||
assert.deepEqual(
|
assert.deepEqual(
|
||||||
|
|||||||
@@ -135,6 +135,10 @@ export type RefreshRelation = {
|
|||||||
target_name: string; target_environment: Environment | null; usable: boolean; unusable_reason: string | null;
|
target_name: string; target_environment: Environment | null; usable: boolean; unusable_reason: string | null;
|
||||||
};
|
};
|
||||||
export type RefreshRun = {
|
export type RefreshRun = {
|
||||||
|
/** Put a target back from the safety copy of an earlier restore. */
|
||||||
|
undo?: boolean;
|
||||||
|
/** A completed restore that can still be undone (the newest of its target, safety copy still there). */
|
||||||
|
undo_available?: boolean;
|
||||||
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;
|
||||||
@@ -143,13 +147,13 @@ export type RefreshRun = {
|
|||||||
export const fetchRefreshRelations = () => api<RefreshRelation[]>("/api/v1/refresh-relations");
|
export const fetchRefreshRelations = () => api<RefreshRelation[]>("/api/v1/refresh-relations");
|
||||||
export const fetchRefreshRuns = () => api<RefreshRun[]>("/api/v1/refresh-runs");
|
export const fetchRefreshRuns = () => api<RefreshRun[]>("/api/v1/refresh-runs");
|
||||||
/** Restore `snapshot_id` onto the relation's target (or, without one, capture first and restore that). */
|
/** Restore `snapshot_id` onto the relation's target (or, without one, capture first and restore that). */
|
||||||
export const startRefresh = (relation: RefreshRelation, idempotency_key: string, snapshot_id?: string) =>
|
export const startRefresh = (relation: RefreshRelation, idempotency_key: string, pick: { snapshot_id?: string; undo_of?: string } = {}) =>
|
||||||
api<RefreshRun>("/api/v1/refresh-runs", json("POST", {
|
api<RefreshRun>("/api/v1/refresh-runs", json("POST", {
|
||||||
relation_id: relation.id,
|
relation_id: relation.id,
|
||||||
// exactly what the person was shown, so a relation changed in the meantime is refused
|
// exactly what the person was shown, so a relation changed in the meantime is refused
|
||||||
confirmation: `REFRESH ${relation.source_name} TO ${relation.target_name} v${relation.version}`,
|
confirmation: `REFRESH ${relation.source_name} TO ${relation.target_name} v${relation.version}`,
|
||||||
idempotency_key,
|
idempotency_key,
|
||||||
...(snapshot_id ? { snapshot_id } : {}),
|
...(pick.undo_of ? { undo_of: pick.undo_of } : pick.snapshot_id ? { snapshot_id: pick.snapshot_id } : {}),
|
||||||
}));
|
}));
|
||||||
export const fetchRefreshRun = (id: string) => api<RefreshRun>(`/api/v1/refresh-runs/${id}`);
|
export const fetchRefreshRun = (id: string) => api<RefreshRun>(`/api/v1/refresh-runs/${id}`);
|
||||||
export const cancelRefresh = (id: string) => api<RefreshRun>(`/api/v1/refresh-runs/${id}`, { method: "DELETE" });
|
export const cancelRefresh = (id: string) => api<RefreshRun>(`/api/v1/refresh-runs/${id}`, { method: "DELETE" });
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { useEffect, useMemo, useRef, useState } from "react";
|
import { useEffect, useMemo, useRef, useState } from "react";
|
||||||
import { motion } from "motion/react";
|
import { motion } from "motion/react";
|
||||||
import { useQuery } from "@tanstack/react-query";
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import { cancelRefresh, fetchRefreshRun, 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 } from "../../lib/restoreRun";
|
||||||
import { Button } from "../ui/Button";
|
import { Button } from "../ui/Button";
|
||||||
@@ -17,6 +17,7 @@ const REFUSALS: Record<string, string> = {
|
|||||||
relation_unusable: "This restore point cannot be used right now. Ask an administrator.",
|
relation_unusable: "This restore point cannot be used right now. Ask an administrator.",
|
||||||
too_many_runs: "Too many restores are running at once. Try again in a few minutes.",
|
too_many_runs: "Too many restores are running at once. Try again in a few minutes.",
|
||||||
snapshot_unusable: "This backup cannot be restored to that database.",
|
snapshot_unusable: "This backup cannot be restored to that database.",
|
||||||
|
nothing_to_undo: "There is nothing to undo any more: something was restored after it, or its safety copy was removed.",
|
||||||
source_unavailable: "The source cannot be reached right now.",
|
source_unavailable: "The source cannot be reached right now.",
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -42,6 +43,8 @@ export function RestoreWizard({ snapshot, relations, admin, onBusyChange }: {
|
|||||||
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.
|
||||||
|
const [undoOf, setUndoOf] = useState<string>();
|
||||||
// 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()));
|
||||||
|
|
||||||
@@ -66,7 +69,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, 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.");
|
||||||
@@ -77,7 +80,7 @@ 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]);
|
}, [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 () => {
|
||||||
@@ -89,7 +92,15 @@ export function RestoreWizard({ snapshot, relations, admin, onBusyChange }: {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
const again = () => {
|
const again = () => {
|
||||||
setPhase("idle"); setLeft(COUNTDOWN); setRunId(undefined); setRefusal(undefined);
|
setPhase("idle"); setLeft(COUNTDOWN); setRunId(undefined); setRefusal(undefined); setUndoOf(undefined);
|
||||||
|
attempt.current = globalThis.crypto?.randomUUID?.() ?? String(Math.random());
|
||||||
|
};
|
||||||
|
|
||||||
|
// 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 undoable = Array.isArray(recent.data) ? recent.data.find((r) => r.relation_id === point?.id && r.undo_available) : undefined;
|
||||||
|
const beginUndo = (of: string) => {
|
||||||
|
setRefusal(undefined); setRunId(undefined); setUndoOf(of); setLeft(COUNTDOWN); setPhase("countdown");
|
||||||
attempt.current = globalThis.crypto?.randomUUID?.() ?? String(Math.random());
|
attempt.current = globalThis.crypto?.randomUUID?.() ?? String(Math.random());
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -132,11 +143,17 @@ export function RestoreWizard({ snapshot, relations, admin, onBusyChange }: {
|
|||||||
</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); setLeft(COUNTDOWN); setPhase("countdown"); }}>
|
<Button variant="primary" className="flex-1" disabled={!point || phase !== "idle"} onClick={() => { setRefusal(undefined); setUndoOf(undefined); setLeft(COUNTDOWN); setPhase("countdown"); }}>
|
||||||
Begin restore
|
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 && (
|
||||||
|
<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>
|
||||||
|
<Button onClick={() => beginUndo(undoable.id)}>Undo last restore</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
{admin && database && phase === "idle" && !runId && (
|
{admin && database && phase === "idle" && !runId && (
|
||||||
<button type="button" className="footer-link self-start" onClick={() => setOther(true)}>Other registered target…</button>
|
<button type="button" className="footer-link self-start" onClick={() => setOther(true)}>Other registered target…</button>
|
||||||
)}
|
)}
|
||||||
@@ -155,7 +172,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">Restoring to {target} in {left}s.<br />Abort restores nothing.</p>
|
<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>
|
||||||
</motion.div>
|
</motion.div>
|
||||||
)}
|
)}
|
||||||
{phase === "running" && (
|
{phase === "running" && (
|
||||||
@@ -182,8 +199,11 @@ export function RestoreWizard({ snapshot, relations, admin, onBusyChange }: {
|
|||||||
<div role="status" className={`restore-outcome ${outcome.tone}`}>
|
<div role="status" className={`restore-outcome ${outcome.tone}`}>
|
||||||
<p>{outcome.title}</p>
|
<p>{outcome.title}</p>
|
||||||
<p>{outcome.detail}</p>
|
<p>{outcome.detail}</p>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{run.data?.undo_available && <Button onClick={() => beginUndo(run.data!.id)}>Undo this restore</Button>}
|
||||||
<Button onClick={again}>{outcome.tone === "good" ? "Restore again" : "Try again"}</Button>
|
<Button onClick={again}>{outcome.tone === "good" ? "Restore again" : "Try again"}</Button>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
{run.isError && <p role="alert" className="text-sm text-orbit-amber">Reconnecting to the restore…</p>}
|
{run.isError && <p role="alert" className="text-sm text-orbit-amber">Reconnecting to the restore…</p>}
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -1219,3 +1219,6 @@ button.act-row[data-group="needs"]:hover { background: #20161a; }
|
|||||||
.restore-outcome.good p:first-child { color: var(--color-orbit-green, #8fd0b0); }
|
.restore-outcome.good p:first-child { color: var(--color-orbit-green, #8fd0b0); }
|
||||||
.restore-outcome.bad { border-color: #6b2f26; }
|
.restore-outcome.bad { border-color: #6b2f26; }
|
||||||
.restore-outcome.bad p:first-child { color: var(--color-orbit-red); }
|
.restore-outcome.bad p:first-child { color: var(--color-orbit-red); }
|
||||||
|
|
||||||
|
.restore-undo { display: flex; flex-direction: column; align-items: flex-start; gap: 8px; padding: 12px; border: 1px dashed var(--line); border-radius: 12px; }
|
||||||
|
.restore-undo p { margin: 0; font-size: 13px; line-height: 1.5; color: var(--quiet); }
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
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 };
|
type RunLike = { status: string; restore_phase: string | null; blocked_reason?: string | null; undo?: 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"]);
|
||||||
|
|
||||||
@@ -52,6 +52,17 @@ export function outcomeOf(
|
|||||||
names: { target: string; orbit?: string; when?: string },
|
names: { target: string; orbit?: string; when?: string },
|
||||||
): Outcome {
|
): Outcome {
|
||||||
const { target } = names;
|
const { target } = names;
|
||||||
|
if (run.undo) {
|
||||||
|
switch (run.status) {
|
||||||
|
case "completed":
|
||||||
|
case "reconciled":
|
||||||
|
return { tone: "good", title: `${target} was rolled back`, detail: `${target} holds what it held before that restore. A safety copy of the state you undid was kept, so this can be undone too.` };
|
||||||
|
case "restore_failed":
|
||||||
|
return { tone: "bad", title: "The undo failed", detail: `${target} was most likely not changed, but ask an administrator to check it before you rely on it.` };
|
||||||
|
default:
|
||||||
|
break; // the other outcomes read the same for an undo
|
||||||
|
}
|
||||||
|
}
|
||||||
switch (run.status) {
|
switch (run.status) {
|
||||||
case "completed":
|
case "completed":
|
||||||
case "reconciled":
|
case "reconciled":
|
||||||
|
|||||||
Reference in New Issue
Block a user