feat: restore inside the Vault; the Refresh page and file export UI are gone
- POST /refresh-runs accepts snapshot_id: restore a snapshot somebody picked (a restorable capture of the relation's own source, never a safety copy or another orbit's) through the same run engine - refresh-relations carries source_orbit_id; snapshots carry kind (capture|safety), and the UI hides safety copies - snapshot detail: Restore replaces Export file on hub (disabled with No restore point without a relation); modal with a restore point selector, a ten second countdown with Abort, and a four step progress view - administrators keep Other registered target; the Refresh menu and refresh-only screen are removed - proven with a real agent and PostgreSQL in the browser: capture, restore to Development, abort, no relation Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -167,6 +167,7 @@ async fn world_with(exports: Option<crate::exports::ExportGate>) -> World {
|
||||
None,
|
||||
"admin",
|
||||
"seed-run",
|
||||
None,
|
||||
3600,
|
||||
50,
|
||||
now(),
|
||||
|
||||
@@ -130,6 +130,10 @@ struct Start {
|
||||
confirmation: String,
|
||||
/// Chosen by the client so a double click or a retry starts one run, not two.
|
||||
idempotency_key: String,
|
||||
/// Restore this existing snapshot instead of capturing a new one. It must be a restorable capture of the
|
||||
/// relation's own source.
|
||||
#[serde(default)]
|
||||
snapshot_id: Option<Uuid>,
|
||||
}
|
||||
|
||||
fn valid_key(key: &str) -> bool {
|
||||
@@ -139,6 +143,30 @@ fn valid_key(key: &str) -> bool {
|
||||
.all(|b| b.is_ascii_alphanumeric() || b"-_.:".contains(&b))
|
||||
}
|
||||
|
||||
/// Is this snapshot one that a relation may restore: a database capture of the relation's own source orbit,
|
||||
/// never a safety copy of some target, with what a restore needs (format, checksum, source identity)?
|
||||
async fn snapshot_fits(
|
||||
state: &HubState,
|
||||
relation: &str,
|
||||
snapshot: Uuid,
|
||||
) -> Result<bool, StatusCode> {
|
||||
let Some(source) = state.db.relation_source_orbit(relation).map_err(internal)? else {
|
||||
return Ok(false);
|
||||
};
|
||||
let manifest = state
|
||||
.vault
|
||||
.read()
|
||||
.await
|
||||
.get_snapshot(snapshot)
|
||||
.map_err(internal)?
|
||||
.map(|s| s.manifest);
|
||||
Ok(manifest.is_some_and(|manifest| {
|
||||
manifest.orbit_id.to_string() == source
|
||||
&& !manifest.is_restore_safety()
|
||||
&& crate::api::artifact(&manifest).is_some()
|
||||
}))
|
||||
}
|
||||
|
||||
async fn start(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
@@ -151,6 +179,14 @@ async fn start(
|
||||
}
|
||||
super::gate::relation(&state, &actor, body.relation_id)?;
|
||||
let relation = body.relation_id.to_string();
|
||||
if let Some(snapshot) = body.snapshot_id {
|
||||
if !snapshot_fits(&state, &relation, snapshot).await? {
|
||||
return Ok(reason(
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"snapshot_unusable",
|
||||
));
|
||||
}
|
||||
}
|
||||
// What authorised this run, recorded so it can be checked again before anything is overwritten.
|
||||
let authorized_by = if actor.subject.admin {
|
||||
"admin".to_string()
|
||||
@@ -178,6 +214,7 @@ async fn start(
|
||||
actor.subject.user_id.as_deref(),
|
||||
&authorized_by,
|
||||
&body.idempotency_key,
|
||||
body.snapshot_id,
|
||||
state.refresh.ttl_secs,
|
||||
state.refresh.max_active,
|
||||
now(),
|
||||
|
||||
@@ -1987,3 +1987,204 @@ async fn an_orbit_name_is_validated_unique_and_only_administrators_change_it() {
|
||||
"{status}"
|
||||
);
|
||||
}
|
||||
|
||||
// ---- restoring a snapshot that already exists (the Restore button on a snapshot) ----
|
||||
|
||||
impl Lab {
|
||||
async fn start_snapshot(
|
||||
&self,
|
||||
caller: &Caller,
|
||||
key: &str,
|
||||
snapshot: Uuid,
|
||||
) -> (StatusCode, Value) {
|
||||
self.send(
|
||||
caller,
|
||||
"POST",
|
||||
"/api/v1/refresh-runs",
|
||||
Some(json!({"relation_id": self.relation, "confirmation": self.confirmation(), "idempotency_key": key, "snapshot_id": snapshot})),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// A snapshot written straight into the vault, to stand in for one of another orbit or a safety copy.
|
||||
async fn plant_snapshot(&self, orbit: Uuid, labels: &[&str], hints: Value) -> Uuid {
|
||||
let id = Uuid::new_v4();
|
||||
let manifest = tessera_core::manifest::SnapshotManifest {
|
||||
snapshot_id: id,
|
||||
orbit_id: orbit,
|
||||
orbit_name: "planted".into(),
|
||||
labels: labels.iter().map(|s| s.to_string()).collect(),
|
||||
provider: "postgres".into(),
|
||||
paths: vec![],
|
||||
restore_hints: hints,
|
||||
};
|
||||
self.state
|
||||
.vault
|
||||
.write()
|
||||
.await
|
||||
.snapshot(manifest, b"PGDMP planted", false)
|
||||
.unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
/// Walk a restore job through to the end the way the agent does.
|
||||
async fn finish_restore(&self) -> String {
|
||||
let (job, token) = self
|
||||
.restore_until_ready()
|
||||
.await
|
||||
.expect("a restore job is waiting");
|
||||
assert_eq!(self.apply(&job, &token).await, StatusCode::NO_CONTENT);
|
||||
self.report_applied(&job, &token).await;
|
||||
self.tick().await;
|
||||
job
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_existing_snapshot_is_restored_without_a_new_capture_and_can_be_restored_again() {
|
||||
let lab = fresh().await;
|
||||
let (qa, _) = lab.refresher("qa");
|
||||
// a snapshot exists from an earlier refresh
|
||||
lab.start(&lab.admin(), "seed").await;
|
||||
let snapshot = lab
|
||||
.capture(&Lab::production_identity(), false)
|
||||
.await
|
||||
.unwrap();
|
||||
lab.tick().await;
|
||||
lab.finish_restore().await;
|
||||
let captures = lab.capture_jobs();
|
||||
|
||||
let (status, run) = lab.start_snapshot(&qa, "again", snapshot).await;
|
||||
assert_eq!(status, StatusCode::ACCEPTED, "{run}");
|
||||
let run_id = run["id"].as_str().unwrap().to_string();
|
||||
lab.tick().await;
|
||||
assert_eq!(lab.run(&run_id).status, "restoring");
|
||||
assert_eq!(
|
||||
lab.run(&run_id).snapshot_id.as_deref(),
|
||||
Some(snapshot.to_string().as_str())
|
||||
);
|
||||
assert_eq!(
|
||||
lab.capture_jobs(),
|
||||
captures,
|
||||
"no new capture: the person picked a backup"
|
||||
);
|
||||
lab.finish_restore().await;
|
||||
assert_eq!(lab.run(&run_id).status, "completed");
|
||||
|
||||
// and the same snapshot can go to the target again
|
||||
let (status, again) = lab.start_snapshot(&qa, "third", snapshot).await;
|
||||
assert_eq!(status, StatusCode::ACCEPTED, "{again}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn only_a_restorable_snapshot_of_the_relations_own_source_is_accepted() {
|
||||
let lab = fresh().await;
|
||||
let admin = lab.admin();
|
||||
// a real capture, so the planted copies below are as restorable as it is
|
||||
lab.start(&admin, "seed").await;
|
||||
let real = lab
|
||||
.capture(&Lab::production_identity(), false)
|
||||
.await
|
||||
.unwrap();
|
||||
let hints = lab
|
||||
.state
|
||||
.vault
|
||||
.read()
|
||||
.await
|
||||
.get_snapshot(real)
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.manifest
|
||||
.restore_hints;
|
||||
let other_orbit = lab.plant_snapshot(Uuid::new_v4(), &[], hints.clone()).await;
|
||||
let safety = lab
|
||||
.plant_snapshot(lab.orbit, &["restore-safety"], hints)
|
||||
.await;
|
||||
lab.tick().await;
|
||||
lab.finish_restore().await;
|
||||
let runs = lab.scalar::<i64>("SELECT COUNT(*) FROM refresh_runs");
|
||||
let jobs = lab.restore_jobs();
|
||||
// the real one is accepted, so the refusals below are about the snapshot and nothing else
|
||||
assert_eq!(
|
||||
lab.start_snapshot(&admin, "good", real).await.0,
|
||||
StatusCode::ACCEPTED
|
||||
);
|
||||
lab.tick().await;
|
||||
lab.finish_restore().await;
|
||||
let runs = runs + 1;
|
||||
let jobs = jobs + 1;
|
||||
for (n, (what, snapshot)) in [
|
||||
("another orbit's", other_orbit),
|
||||
("a safety copy", safety),
|
||||
("an unknown one", Uuid::new_v4()),
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let (status, body) = lab
|
||||
.start_snapshot(&admin, &format!("bad-{n}"), snapshot)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "{what}: {body}");
|
||||
assert_eq!(body["reason"], "snapshot_unusable", "{what}");
|
||||
}
|
||||
assert_eq!(lab.restore_jobs(), jobs);
|
||||
assert_eq!(
|
||||
lab.scalar::<i64>("SELECT COUNT(*) FROM refresh_runs"),
|
||||
runs,
|
||||
"nothing was started"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_restore_of_an_existing_snapshot_is_stopped_when_the_grant_goes_before_it_is_queued() {
|
||||
let lab = fresh().await;
|
||||
let (qa, grant) = lab.refresher("qa");
|
||||
lab.start(&lab.admin(), "seed").await;
|
||||
let snapshot = lab
|
||||
.capture(&Lab::production_identity(), false)
|
||||
.await
|
||||
.unwrap();
|
||||
lab.tick().await;
|
||||
lab.finish_restore().await;
|
||||
let jobs = lab.restore_jobs();
|
||||
let (_, run) = lab.start_snapshot(&qa, "revoked", snapshot).await;
|
||||
let run_id = run["id"].as_str().unwrap().to_string();
|
||||
lab.revoke(Revoke::GrantDeleted, &qa, &grant).await;
|
||||
lab.tick().await;
|
||||
assert_eq!(lab.run(&run_id).status, "blocked");
|
||||
assert_eq!(
|
||||
lab.run(&run_id).blocked_reason.as_deref(),
|
||||
Some("access_revoked")
|
||||
);
|
||||
assert_eq!(lab.restore_jobs(), jobs, "no restore job was ever queued");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_screens_get_what_they_need_to_offer_restore_for_an_orbit() {
|
||||
let lab = fresh().await;
|
||||
let (qa, _) = lab.refresher("qa");
|
||||
let (_, mine) = lab
|
||||
.send(&qa, "GET", "/api/v1/refresh-relations", None)
|
||||
.await;
|
||||
assert_eq!(mine[0]["source_orbit_id"], lab.orbit.to_string(), "{mine}");
|
||||
// a snapshot knows whether it is a capture or a safety copy, so pickers can leave the latter out
|
||||
lab.start(&lab.admin(), "kind").await;
|
||||
lab.capture(&Lab::production_identity(), false)
|
||||
.await
|
||||
.unwrap();
|
||||
lab.tick().await;
|
||||
lab.restore_until_ready().await.unwrap();
|
||||
let (_, listed) = lab
|
||||
.send(&lab.admin(), "GET", "/api/v1/snapshots", None)
|
||||
.await;
|
||||
let kinds: Vec<_> = listed
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|s| s["kind"].as_str().unwrap().to_string())
|
||||
.collect();
|
||||
assert!(
|
||||
kinds.contains(&"capture".to_string()) && kinds.contains(&"safety".to_string()),
|
||||
"{kinds:?}"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -590,6 +590,8 @@ async fn revoke_access(
|
||||
struct MyRelation {
|
||||
id: String,
|
||||
version: i64,
|
||||
/// The orbit this relation restores from, so a screen can offer it on that orbit's snapshots.
|
||||
source_orbit_id: String,
|
||||
source_name: String,
|
||||
source_environment: Option<String>,
|
||||
target_name: String,
|
||||
@@ -614,6 +616,7 @@ async fn mine(
|
||||
.map(|view| MyRelation {
|
||||
id: view.relation.id,
|
||||
version: view.relation.version,
|
||||
source_orbit_id: view.relation.source_orbit_id,
|
||||
source_name: view.source_name,
|
||||
source_environment: view.source_environment,
|
||||
target_name: view.target_name,
|
||||
|
||||
@@ -74,6 +74,9 @@ struct SnapshotSummary {
|
||||
orbit_name: String,
|
||||
size_bytes: u64,
|
||||
capture: Option<CaptureSnapshotSummary>,
|
||||
/// `capture` for a backup of an orbit, `safety` for the copy a restore took of its target before
|
||||
/// overwriting it. Pickers leave the latter out.
|
||||
kind: &'static str,
|
||||
stored_bytes: Option<u64>,
|
||||
new_data_chunks: Option<u64>,
|
||||
}
|
||||
@@ -444,6 +447,11 @@ async fn list_snapshots(
|
||||
orbit_id: s.manifest.orbit_id,
|
||||
taken_at: s.taken_at,
|
||||
capture: CaptureSnapshotSummary::from_manifest(&s.manifest),
|
||||
kind: if s.manifest.is_restore_safety() {
|
||||
"safety"
|
||||
} else {
|
||||
"capture"
|
||||
},
|
||||
// the orbit's current name; the manifest keeps the one it was written under
|
||||
orbit_name: names
|
||||
.get(&s.manifest.orbit_id)
|
||||
|
||||
@@ -82,6 +82,17 @@ pub enum StartError {
|
||||
}
|
||||
|
||||
/// 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.
|
||||
const EXISTING: &str = "existing:";
|
||||
|
||||
/// A relation's source orbit, for checking that a snapshot belongs to it.
|
||||
impl Db {
|
||||
pub fn relation_source_orbit(&self, relation: &str) -> Result<Option<String>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
Ok(relation_of(&conn, relation)?.map(|r| r.source_orbit_id))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn confirmation_text(source: &str, target: &str, version: i64) -> String {
|
||||
format!("REFRESH {source} TO {target} v{version}")
|
||||
}
|
||||
@@ -271,6 +282,7 @@ impl Db {
|
||||
requester_user_id: Option<&str>,
|
||||
authorized_by: &str,
|
||||
idempotency_key: &str,
|
||||
snapshot: Option<Uuid>,
|
||||
ttl_secs: i64,
|
||||
max_active: i64,
|
||||
now: i64,
|
||||
@@ -308,18 +320,27 @@ impl Db {
|
||||
if running >= max_active {
|
||||
return Ok(Err(StartError::TooManyRuns));
|
||||
}
|
||||
let application = Uuid::parse_str(&relation.source_application_id)?;
|
||||
let Some(capture) = super::jobs::insert_capture_job(&tx, application, requester, now)?
|
||||
else {
|
||||
return Ok(Err(StartError::SourceUnavailable));
|
||||
};
|
||||
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
|
||||
// no capture job, only a placeholder, and the snapshot is recorded from the start.
|
||||
let capture = match snapshot {
|
||||
Some(_) => format!("{EXISTING}{id}"),
|
||||
None => {
|
||||
let application = Uuid::parse_str(&relation.source_application_id)?;
|
||||
let Some(capture) =
|
||||
super::jobs::insert_capture_job(&tx, application, requester, now)?
|
||||
else {
|
||||
return Ok(Err(StartError::SourceUnavailable));
|
||||
};
|
||||
capture.to_string()
|
||||
}
|
||||
};
|
||||
tx.execute(
|
||||
"INSERT INTO refresh_runs(id,relation_id,relation_version,source_orbit_id,source_application_id,target_id,requester,requester_user_id,
|
||||
authorized_by,idempotency_key,status,capture_job_id,created_at,updated_at,expires_at)
|
||||
VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,'capturing',?11,?12,?12,?13)",
|
||||
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)",
|
||||
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.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)))
|
||||
})()?;
|
||||
@@ -425,17 +446,24 @@ impl Db {
|
||||
if run.status != "capturing" || run.restore_job_id.is_some() {
|
||||
return Ok(Linked::NotReady);
|
||||
}
|
||||
let capture: Option<(String, Option<String>)> = tx
|
||||
.query_row(
|
||||
"SELECT status, snapshot_id FROM capture_jobs WHERE id=?1",
|
||||
params![run.capture_job_id],
|
||||
|r| Ok((r.get(0)?, r.get(1)?)),
|
||||
)
|
||||
.optional()?;
|
||||
let Some((status, Some(snapshot))) = capture.filter(|c| c.0 == "completed") else {
|
||||
return Ok(Linked::NotReady);
|
||||
let snapshot = if run.capture_job_id.starts_with(EXISTING) {
|
||||
let Some(snapshot) = run.snapshot_id.clone() else {
|
||||
return Ok(Linked::NotReady);
|
||||
};
|
||||
snapshot
|
||||
} else {
|
||||
let capture: Option<(String, Option<String>)> = tx
|
||||
.query_row(
|
||||
"SELECT status, snapshot_id FROM capture_jobs WHERE id=?1",
|
||||
params![run.capture_job_id],
|
||||
|r| Ok((r.get(0)?, r.get(1)?)),
|
||||
)
|
||||
.optional()?;
|
||||
let Some((_, Some(snapshot))) = capture.filter(|c| c.0 == "completed") else {
|
||||
return Ok(Linked::NotReady);
|
||||
};
|
||||
snapshot
|
||||
};
|
||||
let _ = status;
|
||||
if let Some(reason) = invalid_reason(&tx, &run, now)? {
|
||||
block(&tx, &run, reason, now)?;
|
||||
return Ok(Linked::Blocked(reason));
|
||||
@@ -585,6 +613,13 @@ fn sync_in(tx: &Transaction<'_>, id: &str, now: i64) -> Result<Sync> {
|
||||
Ok(Sync::Moved(status.into()))
|
||||
};
|
||||
match run.status.as_str() {
|
||||
"capturing" if run.capture_job_id.starts_with(EXISTING) => {
|
||||
// Nothing to capture: the snapshot was chosen when the run was started.
|
||||
match (&run.snapshot_id, &run.restore_job_id) {
|
||||
(Some(snapshot), None) => Ok(Sync::NeedRestore(snapshot.clone())),
|
||||
_ => Ok(Sync::Unchanged),
|
||||
}
|
||||
}
|
||||
"capturing" => {
|
||||
let capture: Option<(String, Option<String>)> = tx
|
||||
.query_row(
|
||||
|
||||
@@ -116,6 +116,17 @@ async fn queue_restore(state: &HubState, run: &RefreshRun, snapshot: &str) -> an
|
||||
audit_run(state, &run.id, "blocked");
|
||||
return Ok(true);
|
||||
};
|
||||
// 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| {
|
||||
manifest.orbit_id.to_string() == run.source_orbit_id && !manifest.is_restore_safety()
|
||||
});
|
||||
if !belongs {
|
||||
state
|
||||
.db
|
||||
.block_refresh_run(&run.id, "snapshot_not_restorable", now())?;
|
||||
audit_run(state, &run.id, "blocked");
|
||||
return Ok(true);
|
||||
}
|
||||
let target = state.db.restore_target(Uuid::parse_str(&run.target_id)?)?;
|
||||
let clash = match target {
|
||||
Some(target) => {
|
||||
|
||||
Reference in New Issue
Block a user