From 3bd0a1c9a3b69697766a3e37bee16405d75aa896 Mon Sep 17 00:00:00 2001 From: Adnan Zahir Date: Sun, 15 Nov 2026 16:13:44 +0700 Subject: [PATCH] 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 --- crates/tessera-hub/src/api/access_tests.rs | 1 + crates/tessera-hub/src/api/refresh.rs | 37 ++++ crates/tessera-hub/src/api/refresh_tests.rs | 201 +++++++++++++++++ crates/tessera-hub/src/api/relations.rs | 3 + crates/tessera-hub/src/api/routes.rs | 8 + crates/tessera-hub/src/db/refresh.rs | 71 ++++-- crates/tessera-hub/src/refresh.rs | 11 + docs/DATABASE-CAPTURE.md | 18 +- docs/auth-endpoint-contract.md | 2 +- tasks/restore-ux-design.md | 30 +++ web/scripts/restoreRun.test.mjs | 53 +++++ web/src/App.tsx | 85 +++----- web/src/api.ts | 37 +--- web/src/components/hud/HUDRail.tsx | 8 +- .../reconstitute/ReconstituteWizard.tsx | 203 ------------------ web/src/components/refresh/RefreshView.tsx | 184 ---------------- web/src/components/restore/RestoreWizard.tsx | 196 +++++++++++++++++ web/src/components/vault/SnapshotSheet.tsx | 25 ++- web/src/index.css | 18 ++ web/src/lib/restoreRun.ts | 95 ++++++++ 20 files changed, 778 insertions(+), 508 deletions(-) create mode 100644 tasks/restore-ux-design.md create mode 100644 web/scripts/restoreRun.test.mjs delete mode 100644 web/src/components/reconstitute/ReconstituteWizard.tsx delete mode 100644 web/src/components/refresh/RefreshView.tsx create mode 100644 web/src/components/restore/RestoreWizard.tsx create mode 100644 web/src/lib/restoreRun.ts diff --git a/crates/tessera-hub/src/api/access_tests.rs b/crates/tessera-hub/src/api/access_tests.rs index 8fe01b5..0b36128 100644 --- a/crates/tessera-hub/src/api/access_tests.rs +++ b/crates/tessera-hub/src/api/access_tests.rs @@ -167,6 +167,7 @@ async fn world_with(exports: Option) -> World { None, "admin", "seed-run", + None, 3600, 50, now(), diff --git a/crates/tessera-hub/src/api/refresh.rs b/crates/tessera-hub/src/api/refresh.rs index 40686a4..e9825b5 100644 --- a/crates/tessera-hub/src/api/refresh.rs +++ b/crates/tessera-hub/src/api/refresh.rs @@ -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, } 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 { + 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, State(state): State, @@ -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(), diff --git a/crates/tessera-hub/src/api/refresh_tests.rs b/crates/tessera-hub/src/api/refresh_tests.rs index 0dd8ebe..f9d6981 100644 --- a/crates/tessera-hub/src/api/refresh_tests.rs +++ b/crates/tessera-hub/src/api/refresh_tests.rs @@ -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::("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::("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:?}" + ); +} diff --git a/crates/tessera-hub/src/api/relations.rs b/crates/tessera-hub/src/api/relations.rs index 38c227b..5d2ac59 100644 --- a/crates/tessera-hub/src/api/relations.rs +++ b/crates/tessera-hub/src/api/relations.rs @@ -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, 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, diff --git a/crates/tessera-hub/src/api/routes.rs b/crates/tessera-hub/src/api/routes.rs index 15e6618..8c67717 100644 --- a/crates/tessera-hub/src/api/routes.rs +++ b/crates/tessera-hub/src/api/routes.rs @@ -74,6 +74,9 @@ struct SnapshotSummary { orbit_name: String, size_bytes: u64, capture: Option, + /// `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, new_data_chunks: Option, } @@ -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) diff --git a/crates/tessera-hub/src/db/refresh.rs b/crates/tessera-hub/src/db/refresh.rs index 9c1137d..e870ee6 100644 --- a/crates/tessera-hub/src/db/refresh.rs +++ b/crates/tessera-hub/src/db/refresh.rs @@ -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> { + 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, 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)> = 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)> = 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 { 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)> = tx .query_row( diff --git a/crates/tessera-hub/src/refresh.rs b/crates/tessera-hub/src/refresh.rs index 7266727..f52cbf3 100644 --- a/crates/tessera-hub/src/refresh.rs +++ b/crates/tessera-hub/src/refresh.rs @@ -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) => { diff --git a/docs/DATABASE-CAPTURE.md b/docs/DATABASE-CAPTURE.md index 2365c45..d96ee09 100644 --- a/docs/DATABASE-CAPTURE.md +++ b/docs/DATABASE-CAPTURE.md @@ -372,10 +372,20 @@ was shown: `REFRESH TO v`. The caller never picks the overwritten); 3. follows the restore job to its end. -In the web UI, people holding a relation grant use **Refresh** (administrators find it in the rail too). Someone whose -only permission is a relation grant gets that single screen: the vault screens are not loaded for them, since every -request would be refused. The screen shows what will be overwritten, requires an explicit confirmation, follows the -run, and lets the person cancel until the target starts being overwritten. +A run can also restore a snapshot somebody picked instead of capturing a new one: add `snapshot_id` to the request. The +snapshot must be a restorable database capture of the relation's own source orbit (never a safety copy, never another +orbit's); otherwise the answer is `422 snapshot_unusable` and nothing is started. Such a run has no capture step, but +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. + +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 +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 +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 +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. States: `capturing`, `restoring`, then `completed`, or `capture_failed`, `restore_failed`, `blocked` (with a reason), `expired`, `cancelled`, `recovery_required` (the restore was interrupted after it started overwriting: an administrator diff --git a/docs/auth-endpoint-contract.md b/docs/auth-endpoint-contract.md index 4ff9f15..311a44b 100644 --- a/docs/auth-endpoint-contract.md +++ b/docs/auth-endpoint-contract.md @@ -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/: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-runs | GET,POST | human | refresh.run | relasi yang di-grant | POST: relation_id + konfirmasi `REFRESH TO v` + kunci idempotensi; tidak memilih snapshot atau 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 TO v` + 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/: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/snapshots | GET | human | snapshot.read | orbit | metadata aman terfilter | diff --git a/tasks/restore-ux-design.md b/tasks/restore-ux-design.md new file mode 100644 index 0000000..3626d6f --- /dev/null +++ b/tasks/restore-ux-design.md @@ -0,0 +1,30 @@ +# Restore di dalam Vault (dibangun) + +Keputusan Sen: tidak ada menu baru. Halaman Refresh dihapus; di detail snapshot tombol "Export file on hub" diganti +"Restore", modal restore mendapat selector restore point, lalu hitung mundur dan stepper. + +## Alur + +1. Klik orbit. 2. Capture bila ingin yang terbaru, atau klik snapshot yang ada. 3. Detail snapshot: tombol Restore +(nonaktif dengan teks "No restore point" bila admin belum membuat relasi). 4. Modal: selector Development/Staging bila +keduanya ada. 5. Begin restore -> hitung mundur 10 detik (Abort tidak mengirim apa pun) -> stepper Checking, Safety copy, +Applying, Completed (Abort masih bisa sampai Applying). + +## Yang dibangun + +- Izin: tanpa skema baru. Melihat snapshot dan menekan Capture memakai grant orbit yang sudah ada (viewer + capture.run); + Restore memakai grant relasi `refresh.run` yang sudah ada. Pemegang hanya grant relasi tidak lagi punya layar sendiri. +- `POST /api/v1/refresh-runs` menerima `snapshot_id`: restore snapshot yang sudah ada milik orbit sumber relasi (bukan + safety, bukan orbit lain), memakai mesin run yang sama (idempotensi, satu run per target, batal sampai applying, + otorisasi ulang sebelum menimpa). Tanpa `snapshot_id` perilaku lama (capture baru) tetap ada sebagai API. +- `GET /api/v1/refresh-relations` memuat `source_orbit_id`; `GET /api/v1/snapshots` memuat `kind` (capture|safety); UI + menyembunyikan safety. +- Admin: modal yang sama, plus "Other registered target..." (jalur lama dengan ketik konfirmasi). +- Dihapus dari UI: halaman Refresh, layar khusus pemegang refresh, "Export file on hub". + +## Belum dikerjakan + +- Endpoint `POST /api/v1/reconstitute` (export ke berkas hub) masih ada sebagai API admin: CLI dan fixture `tests/mbu` + masih memakainya. Hapus (beserta folder exports) sebagai keputusan terpisah sebelum rilis publik. +- "Restore ke dua target sekaligus" dilakukan sebagai dua restore berurutan oleh orang yang sama (modal tetap terbuka + setelah selesai: "Restore again" / ganti restore point). Belum ada tombol "keduanya" sekali klik. diff --git a/web/scripts/restoreRun.test.mjs b/web/scripts/restoreRun.test.mjs new file mode 100644 index 0000000..4990b29 --- /dev/null +++ b/web/scripts/restoreRun.test.mjs @@ -0,0 +1,53 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { STAGES, isFinal, outcomeOf, progressOf, relationLabels } from "../src/lib/restoreRun.ts"; + +const run = (status, restore_phase = null, blocked_reason = null) => ({ status, restore_phase, blocked_reason }); + +test("the four stages follow the restore job's phase", () => { + assert.deepEqual(STAGES, ["Checking", "Safety copy", "Applying", "Completed"]); + // the run is created first; the restore job appears a moment later + assert.equal(progressOf(run("capturing")).index, 0); + for (const phase of ["queued", "claimed", "checking"]) assert.equal(progressOf(run("restoring", phase)).index, 0, phase); + for (const phase of ["safety", "ready"]) assert.equal(progressOf(run("restoring", phase)).index, 1, phase); + assert.equal(progressOf(run("restoring", "applying")).index, 2); + assert.deepEqual(progressOf(run("completed", "completed")), { index: 4, state: "done" }); + assert.equal(progressOf(run("restoring", "applying")).state, "running"); + // the restore job finishes a moment before the run is marked completed: that gap must not look like a restart + assert.deepEqual(progressOf(run("restoring", "completed")), { index: 4, state: "done" }); + assert.equal(isFinal(run("restoring")), false); + assert.equal(isFinal(run("completed")), true); +}); + +test("a run that stopped says at which stage and why it counts as failed or merely cancelled", () => { + assert.deepEqual(progressOf(run("restore_failed", "invalid_payload")), { index: 0, state: "failed" }); + assert.deepEqual(progressOf(run("restore_failed", "safety_failed")), { index: 1, state: "failed" }); + assert.deepEqual(progressOf(run("recovery_required", "apply_failed")), { index: 2, state: "failed" }); + assert.deepEqual(progressOf(run("blocked", "checking", "access_revoked")), { index: 0, state: "failed" }); + assert.deepEqual(progressOf(run("cancelled", "safety")), { index: 1, state: "cancelled" }); + assert.equal(progressOf(run("expired")).state, "failed"); +}); + +test("what the person is told never contains the database's own words", () => { + const done = outcomeOf(run("completed"), { target: "Development", orbit: "broiler", when: "Nov 15, 11:57 AM" }); + assert.equal(done.tone, "good"); + assert.match(done.detail, /Development now holds broiler as of Nov 15, 11:57 AM/); + assert.match(outcomeOf(run("restore_failed", "apply_failed"), { target: "Development" }).detail, /ask an administrator/i); + assert.match(outcomeOf(run("recovery_required"), { target: "Staging" }).title, /interrupted/i); + assert.match(outcomeOf(run("blocked", null, "access_revoked"), { target: "Staging" }).detail, /access to this restore was removed/); + assert.equal(outcomeOf(run("cancelled"), { target: "Staging" }).tone, "plain"); + assert.equal(outcomeOf(run("restoring", "safety"), { target: "Staging" }).tone, "busy"); +}); + +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 }); + assert.deepEqual( + relationLabels([rel("a", "staging", "s1"), rel("b", "development", "d1")]).map((r) => r.label), + ["Staging", "Development"], + ); + assert.deepEqual( + relationLabels([rel("a", "staging", "s1"), rel("b", "staging", "s2")]).map((r) => r.label), + ["Staging · s1", "Staging · s2"], + ); + assert.equal(relationLabels([rel("a", null, "odd")])[0].label, "odd"); +}); diff --git a/web/src/App.tsx b/web/src/App.tsx index ae155aa..e95165a 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -2,21 +2,20 @@ import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import { AnimatePresence, useMotionValue } from "motion/react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { - abortReconstitute, fetchCaptureJobs, fetchHealth, fetchOrbits, fetchPreferences, fetchSnapshots, pollReconstitute, savePreferences, - enqueueCapture, runOrbit, startReconstitute, type Orbit, + fetchCaptureJobs, fetchHealth, fetchOrbits, fetchPreferences, fetchRefreshRelations, fetchSnapshots, savePreferences, + enqueueCapture, runOrbit, type Orbit, } from "./api"; import { OrbitInspector, OrbitRegister, TelemetryStrip } from "./components/hud/DiegeticHUD"; import { HUDPanel } from "./components/hud/HUDPanel"; -import { accessItem, HUDRail, hudItems, refreshItem, relationsItem, type HUDMode } from "./components/hud/HUDRail"; +import { accessItem, HUDRail, hudItems, relationsItem, type HUDMode } from "./components/hud/HUDRail"; import { AccessView } from "./components/access/AccessView"; import { RelationsView } from "./components/relations/RelationsView"; -import { RefreshView } from "./components/refresh/RefreshView"; import { SearchIcon, VaultSearch } from "./components/hud/VaultSearch"; import { OperatorGate, type Caps } from "./components/operator/OperatorGate"; import { OrbitsView } from "./components/orbits/OrbitsView"; import { WormholeView } from "./components/outposts/WormholeView"; import { ActivityView } from "./components/activity/ActivityView"; -import { ReconstituteWizard } from "./components/reconstitute/ReconstituteWizard"; +import { RestoreWizard } from "./components/restore/RestoreWizard"; import { VaultScene } from "./components/scene/VaultScene"; import { EmptyState } from "./components/ui/EmptyState"; import { PanelBoundary } from "./components/ui/PanelBoundary"; @@ -38,7 +37,6 @@ const panelTitles: Record = { activity: "Activity", access: "Access", relations: "Refresh relations", - refresh: "Refresh staging", reconstitute: "Restore snapshot", snapshot: "Snapshot detail", }; @@ -49,11 +47,10 @@ const panelLabels: Record = { activity: "Console 04 · Activity", access: "Console 05 · Access", relations: "Console 06 · Relations", - refresh: "Console 07 · Refresh", reconstitute: "Restore from a snapshot", snapshot: "Recovery point", }; -const panelWidths: Record = { scene: 640, orbits: 1120, wormhole: 760, activity: 1120, access: 1120, relations: 1120, refresh: 760, reconstitute: 760, snapshot: 640 }; +const panelWidths: Record = { scene: 640, orbits: 1120, wormhole: 760, activity: 1120, access: 1120, relations: 1120, reconstitute: 760, snapshot: 640 }; const LOOK_KEY = "tessera.look"; @@ -72,34 +69,7 @@ function priority(orbit: Orbit) { } export default function App() { - return ( - - {(operator) => - // Someone who may only refresh a staging database has no orbits to show: give them that one screen, - // and do not load the vault screens at all (every request they make would be refused). - !operator.caps.admin && !operator.caps.orbits && operator.caps.refresh - ? - : } - - ); -} - -function RefreshOnly({ actor, onLogout }: { actor?: string; onLogout?: () => Promise }) { - return ( -
-
-
-

Tessera / Refresh

-

Refresh staging

-
-
- {actor && {actor}} - {onLogout && } -
-
- -
- ); + return {(operator) => }; } function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () => Promise; caps: Caps }) { @@ -270,12 +240,13 @@ function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () => const activity = useActivity(snaps.data, orbits.data, caps.admin); // Consoles a non-administrator never sees: managing orbits and Outposts, restores, and access. const railItems = useMemo( - () => { - const base = caps.admin ? [...hudItems, relationsItem, accessItem] : hudItems.filter((item) => item.id === "scene" || item.id === "activity"); - return caps.refresh ? [...base.slice(0, 4), refreshItem, ...base.slice(4)] : base; - }, - [caps.admin, caps.refresh], + () => (caps.admin ? [...hudItems, relationsItem, accessItem] : hudItems.filter((item) => item.id === "scene" || item.id === "activity")), + [caps.admin], ); + // The staging and development databases this person may restore onto, from the orbit's backups. + const relations = useQuery({ queryKey: ["refresh-relations"], queryFn: fetchRefreshRelations, enabled: caps.refresh, retry: false, refetchInterval: 15_000 }); + const restorePoints = Array.isArray(relations.data) ? relations.data : []; + const restoreSnapshot = restoreTarget?.id ? snaps.data?.find(({ id }) => id === restoreTarget.id) : undefined; const failedCount = sceneOrbits.filter(({ last_status }) => last_status === "failed").length; const orbitMessage = orbits.isPending ? "Receiving orbit telemetry…" : orbits.isError @@ -314,7 +285,7 @@ function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () => } function openConsole(next: HUDMode, target: string | null = null) { - if (!caps.admin && next !== "scene" && next !== "activity" && next !== "snapshot" && !(next === "refresh" && caps.refresh)) return; + if (!caps.admin && next !== "scene" && next !== "activity" && next !== "snapshot" && !(next === "reconstitute" && caps.refresh)) return; if (next === "reconstitute" && !restoreBusy && (!restoreTarget || (target !== null && target !== restoreTarget.id))) { setRestoreTarget({ id: target }); @@ -465,9 +436,6 @@ function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () => {mode === "wormhole" && caps.admin && ( )} - {mode === "refresh" && caps.refresh && ( - - )} {mode === "relations" && caps.admin && ( )} @@ -477,23 +445,26 @@ function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () => {mode === "snapshot" && ( {snapshot - ? openConsole("scene")} onReconstitute={() => openConsole("reconstitute", snapshot.id)} /> + ? openConsole("scene")} + restore={snapshot.capture?.restore_ready + ? { available: restorePoints.some((r) => r.usable && r.source_orbit_id === snapshot.orbit_id), onOpen: () => openConsole("reconstitute", snapshot.id) } + : undefined} /> : } )} - {restoreTarget && (snaps.data?.length || restoreBusy ? ( - - ) : ( - }> - {() => null} - - ))} + {restoreSnapshot + ? ( + r.source_orbit_id === restoreSnapshot.orbit_id)} + admin={caps.admin} + onBusyChange={setRestoreBusy} + /> + ) + : restoreTarget && } diff --git a/web/src/api.ts b/web/src/api.ts index d76cd20..4374a05 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -5,6 +5,8 @@ export type Snapshot = { orbit_name: string; size_bytes: number; capture?: { job_id: string; application_id: string; engine: "postgres" | "mysql"; format: string; restore_ready: boolean } | null; + /** `safety` is the copy a restore took of its target before overwriting it; it is not a backup of an orbit. */ + kind?: "capture" | "safety"; }; export type BackupSource = "filesystem" | "database"; @@ -129,7 +131,7 @@ export const grantRelationAccess = (id: string, grant: { principal_type: "user" export const revokeRelationAccess = (id: string, grant: string) => api(`/api/v1/relations/${id}/access/${grant}`, { method: "DELETE" }); export type RefreshRelation = { - id: string; version: number; source_name: string; source_environment: Environment | null; + id: string; version: number; source_orbit_id: string; source_name: string; source_environment: Environment | null; target_name: string; target_environment: Environment | null; usable: boolean; unusable_reason: string | null; }; export type RefreshRun = { @@ -140,13 +142,16 @@ export type RefreshRun = { }; export const fetchRefreshRelations = () => api("/api/v1/refresh-relations"); export const fetchRefreshRuns = () => api("/api/v1/refresh-runs"); -export const startRefresh = (relation: RefreshRelation, idempotency_key: string) => +/** 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) => api("/api/v1/refresh-runs", json("POST", { relation_id: relation.id, // 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}`, idempotency_key, + ...(snapshot_id ? { snapshot_id } : {}), })); +export const fetchRefreshRun = (id: string) => api(`/api/v1/refresh-runs/${id}`); export const cancelRefresh = (id: string) => api(`/api/v1/refresh-runs/${id}`, { method: "DELETE" }); export type Look = "window" | "radar"; @@ -246,7 +251,9 @@ export async function fetchHealth(): Promise { } export async function fetchSnapshots(): Promise { - return api("/api/v1/snapshots"); + const all = await api("/api/v1/snapshots"); + // Safety copies are for rolling a target back, never something to browse or restore from here. + return Array.isArray(all) ? all.filter((snapshot) => snapshot.kind !== "safety") : all; } export async function fetchOrbits(): Promise { @@ -278,30 +285,6 @@ export async function runOrbit(id: string): Promise { return response.headers.get("X-Tessera-Snapshot-Id"); } -export async function startReconstitute( - snapshotId: string, - target: string, -): Promise<{ - session_id: string; - session: { seconds_remaining: number; state: string }; -}> { - return api("/api/v1/reconstitute", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ snapshot_id: snapshotId, target_path: target }), - }); -} - -export async function abortReconstitute(sessionId: string): Promise { - await api(`/api/v1/reconstitute/${sessionId}`, { method: "DELETE" }); -} - -export async function pollReconstitute(sessionId: string) { - const response = await fetch(`/api/v1/reconstitute/${sessionId}`); - if (response.status === 404) return { state: "unavailable", seconds_remaining: 0 }; - if (!response.ok) throw new Error("Could not read restore status"); - return response.json() as Promise<{ state: string; seconds_remaining: number }>; -} export type CaptureProfile = { diff --git a/web/src/components/hud/HUDRail.tsx b/web/src/components/hud/HUDRail.tsx index aa959b2..643cfb2 100644 --- a/web/src/components/hud/HUDRail.tsx +++ b/web/src/components/hud/HUDRail.tsx @@ -3,7 +3,7 @@ import { useCallback, useId, useLayoutEffect, useRef, type PointerEvent } from " import { useScreenTransition } from "../../hooks/useScreenTransition"; import { uiSpring } from "../../lib/motion"; -export type HUDMode = "scene" | "orbits" | "wormhole" | "activity" | "access" | "relations" | "refresh" | "reconstitute" | "snapshot"; +export type HUDMode = "scene" | "orbits" | "wormhole" | "activity" | "access" | "relations" | "reconstitute" | "snapshot"; export const hudItems = [ { id: "scene", label: "Vault", icon: "M4 9l8-4 8 4v6l-8 4-8-4z M4 9l8 4 8-4 M12 13v6" }, @@ -20,12 +20,6 @@ export const accessItem: HUDItem = { icon: "M12 3l7 3v5c0 4.5-3 8-7 10-4-2-7-5.5-7-10V6z M9.5 12l2 2 3.5-4", }; -/** Start a refresh of a staging database from its production source. */ -export const refreshItem: HUDItem = { - id: "refresh", label: "Refresh", - icon: "M20 12a8 8 0 1 1-2.3-5.6 M20 4v4.5h-4.5", -}; - /** Only for administrators: which source may overwrite which target. */ export const relationsItem: HUDItem = { id: "relations", label: "Relations", diff --git a/web/src/components/reconstitute/ReconstituteWizard.tsx b/web/src/components/reconstitute/ReconstituteWizard.tsx deleted file mode 100644 index 1629c44..0000000 --- a/web/src/components/reconstitute/ReconstituteWizard.tsx +++ /dev/null @@ -1,203 +0,0 @@ -import { useEffect, useState } from "react"; -import { motion } from "motion/react"; -import type { Snapshot } from "../../api"; -import { DatabaseRestore } from "./DatabaseRestore"; -import { formatBytes, formatWhen } from "../../lib/format"; -import { Button } from "../ui/Button"; -import { Hint } from "../ui/EmptyState"; -import { TelemetryPanel } from "../ui/Telemetry"; -import { Segmented } from "../ui/Segmented"; -import { Select } from "../ui/Select"; - -const GRACE = 12; - -export function ReconstituteWizard({ - snapshots, - selected, - scopedExport, - onStart, - onPoll, - onAbort, - onBusyChange, -}: { - snapshots: Snapshot[]; - selected: string | null; - scopedExport?: boolean; - onStart: (snapId: string, target: string) => Promise<{ - session_id: string; - session: { seconds_remaining: number; state: string }; - }>; - onPoll: (id: string) => Promise<{ state: string; seconds_remaining: number }>; - onAbort: (id: string) => Promise; - onBusyChange: (busy: boolean) => void; -}) { - const [snapId, setSnapId] = useState(selected ?? snapshots[0]?.id ?? ""); - const [databaseMode, setDatabaseMode] = useState(true); - const [target, setTarget] = useState(scopedExport ? "restored.dump" : "./restore/out"); - const [sessionId, setSessionId] = useState(null); - const [remaining, setRemaining] = useState(GRACE); - const [state, setState] = useState("idle"); - const [action, setAction] = useState<"starting" | "aborting">(); - const [error, setError] = useState(); - const [reconnecting, setReconnecting] = useState(false); - - const snap = snapshots.find((s) => s.id === snapId); - const managed = snap?.capture?.restore_ready ? snap.capture : undefined; - const inCountdown = state === "countdown" || state === "confirming"; - const busy = !!action || inCountdown || state === "restoring"; - - useEffect(() => { onBusyChange(busy); }, [busy, onBusyChange]); - - useEffect(() => { - if (!sessionId) return; - let cancelled = false; - let timer: number; - const poll = async () => { - try { - const s = await onPoll(sessionId); - if (cancelled) return; - setReconnecting(false); - setState(s.state); - setRemaining(s.seconds_remaining ?? 0); - if (["completed", "aborted", "failed", "unavailable"].includes(s.state)) { - setAction(undefined); - return; - } - } catch { - if (cancelled) return; - setReconnecting(true); - } - timer = window.setTimeout(poll, 400); - }; - timer = window.setTimeout(poll, 400); - return () => { - cancelled = true; - clearTimeout(timer); - }; - }, [sessionId, onPoll]); - - const radius = 52; - const circumference = 2 * Math.PI * radius; - const progress = Math.max(0, Math.min(1, remaining / GRACE)); - return ( -
-
-

Choose a recovery point and a destination.

- {snap && ( -
- -
-

{snap.orbit_name}

-

{formatWhen(snap.taken_at)} · {formatBytes(snap.size_bytes)} · {snap.id.slice(0, 8)}

-
-
- )} - - {managed && ( -
-

Destination

- setDatabaseMode(value === "database")} - options={[{ value: "database", label: "Restore to database" }, { value: "file", label: "Export file on hub" }]} /> -
- )} -
- - {managed && databaseMode ? ( - - ) : <> -
- - {scopedExport ? "The hub writes to its exports directory after the countdown." : "The hub writes after the countdown. An existing file at the destination may be overwritten."} -
- - -
- {error &&

{error}

} -
- - } -
- ); -} diff --git a/web/src/components/refresh/RefreshView.tsx b/web/src/components/refresh/RefreshView.tsx deleted file mode 100644 index 0b5526c..0000000 --- a/web/src/components/refresh/RefreshView.tsx +++ /dev/null @@ -1,184 +0,0 @@ -import { useRef, useState } from "react"; -import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import { - cancelRefresh, fetchRefreshRelations, fetchRefreshRuns, refusalReason, startRefresh, - type RefreshRelation, type RefreshRun, -} from "../../api"; -import { Button } from "../ui/Button"; - -const ACTIVE = new Set(["capturing", "restoring"]); - -const START_REFUSALS: Record = { - run_active: "A refresh of this database is already running.", - stale_confirmation: "This relation was changed while you were looking at it. Reload and check it again.", - source_unavailable: "The source cannot take a backup request right now (its Outpost is not available).", - relation_unusable: "This refresh cannot be used right now. Ask an administrator.", - too_many_runs: "Too many refreshes are running at once. Try again in a few minutes.", - key_reused: "That request was already used. Reload and try again.", -}; - -const BLOCKED: Record = { - access_revoked: "your access to this refresh was removed", - user_disabled: "your account was disabled", - relation_ended: "the relation was ended or replaced", - relation_unusable: "the relation can no longer be used", - target_matches_a_production_source: "the target looks like a production database", - target_rejected: "the target did not match the backup", - snapshot_not_restorable: "the backup could not be restored", -}; - -const CAPTURE_STEPS: Record = { - queued: "waiting for the Outpost", claimed: "the Outpost picked it up", dumping: "reading the database", - uploading: "sending the backup", completed: "done", -}; -const RESTORE_STEPS: Record = { - queued: "waiting for the Outpost", claimed: "the Outpost picked it up", checking: "checking the backup and the target", - safety: "saving a safety copy of the target", ready: "ready to overwrite", applying: "overwriting the target", - completed: "done", -}; - -function when(seconds: number | null) { - return seconds ? new Date(seconds * 1000).toLocaleString() : ""; -} - -/** What happened, in words, and what it means for the target database. */ -export function describe(run: RefreshRun): { tone: "busy" | "good" | "bad" | "plain"; title: string; detail: string } { - const target = run.target_name; - switch (run.status) { - case "capturing": - return { tone: "busy", title: "Taking a fresh backup", detail: `Reading ${run.source_name}: ${CAPTURE_STEPS[run.capture_phase ?? "queued"] ?? run.capture_phase}. ${target} is not touched yet.` }; - case "restoring": { - const phase = run.restore_phase ?? "queued"; - const overwriting = phase === "applying"; - return { tone: "busy", title: overwriting ? `Overwriting ${target}` : "Preparing the restore", - detail: `${RESTORE_STEPS[phase] ?? phase}.${overwriting ? " This can no longer be cancelled." : ` ${target} has not been changed yet.`}` }; - } - case "completed": - return { tone: "good", title: `${target} was refreshed`, detail: run.snapshot_taken_at ? `It now holds the data of ${run.source_name} as of ${when(run.snapshot_taken_at)}.` : "" }; - case "capture_failed": - return { tone: "bad", title: "The backup failed", detail: `${target} was not changed. Try again, or ask an administrator if it keeps failing.` }; - 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.` }; - 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.` }; - case "blocked": - return { tone: "bad", title: "The refresh was stopped", detail: `${BLOCKED[run.blocked_reason ?? ""] ?? "something it depended on changed"}. ${target} was not overwritten.` }; - case "expired": - return { tone: "bad", title: "The refresh took too long to start", detail: `${target} was not changed. Start it again.` }; - case "cancelled": - return { tone: "plain", title: "The refresh was cancelled", detail: `${target} was not overwritten.` }; - case "reconciled": - return { tone: "plain", title: "An administrator recovered the target", detail: "" }; - default: - return { tone: "plain", title: run.status, detail: "" }; - } -} - -/** Start a refresh of a staging database and follow it. Everyone sees only what their grants allow. */ -export function RefreshView() { - const qc = useQueryClient(); - const relations = useQuery({ queryKey: ["refresh-relations"], queryFn: fetchRefreshRelations, refetchInterval: 15_000, retry: false }); - const runs = useQuery({ - queryKey: ["refresh-runs"], queryFn: fetchRefreshRuns, retry: false, - refetchInterval: (query) => (Array.isArray(query.state.data) && query.state.data.some((r) => ACTIVE.has(r.status)) ? 2_000 : 15_000), - }); - const list = Array.isArray(relations.data) ? relations.data : []; - const history = Array.isArray(runs.data) ? runs.data : []; - - if (relations.isPending) return

Loading…

; - if (relations.isError) { - return

You have not been given a database to refresh, or this hub does not support it.

; - } - return ( -
-

- A refresh takes a new backup of the source and replaces the contents of its staging database with it. The source is only read. -

- {list.length === 0 &&

Nothing to refresh yet.

} - {list.map((relation) => ( - r.relation_id === relation.id)} - onChanged={() => void qc.invalidateQueries({ queryKey: ["refresh-runs"] })} /> - ))} -
- ); -} - -function RelationCard({ relation, runs, onChanged }: { relation: RefreshRelation; runs: RefreshRun[]; onChanged: () => void }) { - const latest = runs[0]; - const running = !!latest && ACTIVE.has(latest.status); - const [confirming, setConfirming] = useState(false); - const [understood, setUnderstood] = useState(false); - // One key per attempt: a double click or a retry after a network error starts a single run. - const key = useRef(crypto.randomUUID()); - const start = useMutation({ - mutationFn: () => startRefresh(relation, key.current), - onSuccess: () => { setConfirming(false); setUnderstood(false); key.current = crypto.randomUUID(); onChanged(); }, - }); - const cancel = useMutation({ mutationFn: (id: string) => cancelRefresh(id), onSuccess: onChanged }); - const seen = latest ? describe(latest) : undefined; - const overwriting = running && latest?.restore_phase === "applying"; - const refusal = start.isError ? START_REFUSALS[refusalReason(start.error) ?? ""] ?? "The refresh could not be started." : undefined; - - return ( -
-

Application: {relation.source_name}

-
-

- {relation.target_name} - ({relation.target_environment ?? "?"}) is refreshed from {relation.source_name} ({relation.source_environment ?? "?"}) -

- {!relation.usable &&

Not available right now. Ask an administrator.

} -
- - {seen && ( -
-

{seen.title}

- {seen.detail &&

{seen.detail}

} - {running && ( - - )} -
- )} - -
- {!confirming && !running && ( - - )} - {running && latest && ( - - )} -
- - {confirming && !running && ( -
{ e.preventDefault(); if (understood) start.mutate(); }}> -

- This replaces everything in {relation.target_name} with a fresh copy of {relation.source_name}. - Anything that exists only in {relation.target_name} is lost. {relation.source_name} is only read. -

- -
- - -
-
- )} - {refusal &&

{refusal}

} - {cancel.isError &&

It could not be cancelled: it has already started overwriting.

} - - {runs.length > 1 && ( -
- Earlier refreshes -
    - {runs.slice(1, 8).map((run) =>
  • {when(run.created_at)}: {describe(run).title}
  • )} -
-
- )} -
- ); -} diff --git a/web/src/components/restore/RestoreWizard.tsx b/web/src/components/restore/RestoreWizard.tsx new file mode 100644 index 0000000..be803a0 --- /dev/null +++ b/web/src/components/restore/RestoreWizard.tsx @@ -0,0 +1,196 @@ +import { useEffect, useMemo, useRef, useState } from "react"; +import { motion } from "motion/react"; +import { useQuery } from "@tanstack/react-query"; +import { cancelRefresh, fetchRefreshRun, refusalReason, startRefresh, type RefreshRelation, type RefreshRun, type Snapshot } from "../../api"; +import { formatBytes, formatWhen } from "../../lib/format"; +import { isFinal, outcomeOf, progressOf, relationLabels, STAGES } from "../../lib/restoreRun"; +import { Button } from "../ui/Button"; +import { Segmented } from "../ui/Segmented"; +import { DatabaseRestore } from "../reconstitute/DatabaseRestore"; + +/** Seconds between pressing Begin restore and the request being sent. Abort works until then. */ +const COUNTDOWN = 10; + +const REFUSALS: Record = { + run_active: "A restore of this database is already running.", + stale_confirmation: "This restore point was changed while you were looking at it. Close this and open it again.", + 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.", + snapshot_unusable: "This backup cannot be restored to that database.", + source_unavailable: "The source cannot be reached right now.", +}; + +type Phase = "idle" | "countdown" | "running"; + +/** + * Restore one snapshot onto a staging or development database. The person picks the restore point (shown only + * 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. + */ +export function RestoreWizard({ snapshot, relations, admin, onBusyChange }: { + snapshot: Snapshot; + /** The relations from this snapshot's orbit that the person may restore through. */ + relations: RefreshRelation[]; + admin: boolean; + onBusyChange: (busy: boolean) => void; +}) { + const points = useMemo(() => relationLabels(relations.filter((r) => r.usable)), [relations]); + const [pointId, setPointId] = useState(points[0]?.id ?? ""); + const point = points.find((p) => p.id === pointId) ?? points[0]; + const [phase, setPhase] = useState("idle"); + const [left, setLeft] = useState(COUNTDOWN); + const [runId, setRunId] = useState(); + const [refusal, setRefusal] = useState(); + const [other, setOther] = useState(false); + // 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 run = useQuery({ + queryKey: ["restore-run", runId], + queryFn: () => fetchRefreshRun(runId as string), + enabled: !!runId, + refetchInterval: (query) => { + const data = query.state.data as RefreshRun | undefined; + return data && isFinal(data) ? false : 1500; + }, + retry: false, + }); + const progress = run.data ? progressOf(run.data) : { index: 0, state: "running" as const }; + // Finished means the run itself has stopped changing; the steps may all be done a moment before that. + const finished = !!run.data && isFinal(run.data); + const busy = phase === "countdown" || (phase === "running" && !finished); + useEffect(() => { onBusyChange(busy); }, [busy, onBusyChange]); + + useEffect(() => { + if (phase !== "countdown") return; + if (left <= 0) { + setPhase("running"); + if (!point) return; + startRefresh(point, attempt.current, snapshot.id) + .then((started) => setRunId(started.id)) + .catch((error) => { + setRefusal(REFUSALS[refusalReason(error) ?? ""] ?? "The restore could not be started."); + setPhase("idle"); + attempt.current = globalThis.crypto?.randomUUID?.() ?? String(Math.random()); + }); + return; + } + const timer = window.setTimeout(() => setLeft((value) => value - 1), 1000); + return () => clearTimeout(timer); + }, [phase, left, point, snapshot.id]); + + const abortable = phase === "countdown" || (phase === "running" && !finished && progress.index < 2); + const abort = async () => { + if (phase === "countdown") { + setPhase("idle"); + setLeft(COUNTDOWN); + } else if (runId) { + try { await cancelRefresh(runId); } catch { /* it moved past the point where it can be cancelled */ } + } + }; + const again = () => { + setPhase("idle"); setLeft(COUNTDOWN); setRunId(undefined); setRefusal(undefined); + attempt.current = globalThis.crypto?.randomUUID?.() ?? String(Math.random()); + }; + + const radius = 52; + const circumference = 2 * Math.PI * radius; + 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 database = snapshot.capture; + + return ( +
+
+

Review the restore point before starting.

+
+ +
+

{snapshot.orbit_name}

+

{formatWhen(snapshot.taken_at)} · {formatBytes(snapshot.size_bytes)} · {snapshot.id.slice(0, 8)}

+
+
+
+ + {other && admin && database ? ( + + ) : ( + <> +
+
+

Restore point

+ {points.length > 1 ? ( + ({ value: p.id, label: p.label }))} /> + ) : ( +

{point?.label ?? "None"}

+ )} +
+
+ +

Restoring replaces everything on {target} with this snapshot. Anything that exists only there is lost. {snapshot.orbit_name} itself is only read.

+
+
+ + +
+ {refusal &&

{refusal}

} + {admin && database && phase === "idle" && !runId && ( + + )} +
+ + + + )} +
+ ); +} diff --git a/web/src/components/vault/SnapshotSheet.tsx b/web/src/components/vault/SnapshotSheet.tsx index 26874da..e16c013 100644 --- a/web/src/components/vault/SnapshotSheet.tsx +++ b/web/src/components/vault/SnapshotSheet.tsx @@ -15,7 +15,7 @@ function signedBytes(delta: number) { export function SnapshotSheet({ snap, siblings = [], - onReconstitute, + restore, onDeleted, canManage = false, canDownload = false, @@ -23,7 +23,8 @@ export function SnapshotSheet({ snap: Snapshot; /** Every snapshot of the same orbit, newest first, including this one. */ siblings?: Snapshot[]; - onReconstitute: () => void; + /** Restore this snapshot onto a staging or development database. Absent when it is not a database backup. */ + restore?: { available: boolean; onOpen: () => void }; onDeleted: () => void; /** Administrators only: restore and delete. */ canManage?: boolean; @@ -90,7 +91,7 @@ export function SnapshotSheet({
Recovery
-
{database ? "Database ready" : "File export"}
+
{database ? "Database ready" : "Download only"}
{snap.capture &&
{snap.capture.engine} · {snap.capture.format}
}
@@ -104,10 +105,20 @@ export function SnapshotSheet({
- {canManage && } + {restore && (restore.available ? ( + + ) : ( + <> + +

An administrator has not connected a staging or development database to this orbit yet.

+ + ))} {canDownload && Download snapshot