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:
2026-11-15 16:13:44 +07:00
parent f52fc1930f
commit 3bd0a1c9a3
20 changed files with 778 additions and 508 deletions

View File

@@ -167,6 +167,7 @@ async fn world_with(exports: Option<crate::exports::ExportGate>) -> World {
None, None,
"admin", "admin",
"seed-run", "seed-run",
None,
3600, 3600,
50, 50,
now(), now(),

View File

@@ -130,6 +130,10 @@ struct Start {
confirmation: String, confirmation: String,
/// Chosen by the client so a double click or a retry starts one run, not two. /// Chosen by the client so a double click or a retry starts one run, not two.
idempotency_key: String, 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 { 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)) .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( async fn start(
ConnectInfo(peer): ConnectInfo<SocketAddr>, ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>, State(state): State<HubState>,
@@ -151,6 +179,14 @@ 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 {
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. // 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 {
"admin".to_string() "admin".to_string()
@@ -178,6 +214,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,
state.refresh.ttl_secs, state.refresh.ttl_secs,
state.refresh.max_active, state.refresh.max_active,
now(), now(),

View File

@@ -1987,3 +1987,204 @@ async fn an_orbit_name_is_validated_unique_and_only_administrators_change_it() {
"{status}" "{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:?}"
);
}

View File

@@ -590,6 +590,8 @@ async fn revoke_access(
struct MyRelation { struct MyRelation {
id: String, id: String,
version: i64, 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_name: String,
source_environment: Option<String>, source_environment: Option<String>,
target_name: String, target_name: String,
@@ -614,6 +616,7 @@ async fn mine(
.map(|view| MyRelation { .map(|view| MyRelation {
id: view.relation.id, id: view.relation.id,
version: view.relation.version, version: view.relation.version,
source_orbit_id: view.relation.source_orbit_id,
source_name: view.source_name, source_name: view.source_name,
source_environment: view.source_environment, source_environment: view.source_environment,
target_name: view.target_name, target_name: view.target_name,

View File

@@ -74,6 +74,9 @@ struct SnapshotSummary {
orbit_name: String, orbit_name: String,
size_bytes: u64, size_bytes: u64,
capture: Option<CaptureSnapshotSummary>, 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>, stored_bytes: Option<u64>,
new_data_chunks: Option<u64>, new_data_chunks: Option<u64>,
} }
@@ -444,6 +447,11 @@ async fn list_snapshots(
orbit_id: s.manifest.orbit_id, orbit_id: s.manifest.orbit_id,
taken_at: s.taken_at, taken_at: s.taken_at,
capture: CaptureSnapshotSummary::from_manifest(&s.manifest), 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 // the orbit's current name; the manifest keeps the one it was written under
orbit_name: names orbit_name: names
.get(&s.manifest.orbit_id) .get(&s.manifest.orbit_id)

View File

@@ -82,6 +82,17 @@ 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.
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 { pub fn confirmation_text(source: &str, target: &str, version: i64) -> String {
format!("REFRESH {source} TO {target} v{version}") format!("REFRESH {source} TO {target} v{version}")
} }
@@ -271,6 +282,7 @@ 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>,
ttl_secs: i64, ttl_secs: i64,
max_active: i64, max_active: i64,
now: i64, now: i64,
@@ -308,18 +320,27 @@ impl Db {
if running >= max_active { if running >= max_active {
return Ok(Err(StartError::TooManyRuns)); 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(); 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( tx.execute(
"INSERT INTO refresh_runs(id,relation_id,relation_version,source_orbit_id,source_application_id,target_id,requester,requester_user_id, "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) 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,?12,?13)", 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.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)))
})()?; })()?;
@@ -425,17 +446,24 @@ 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 capture: Option<(String, Option<String>)> = tx let snapshot = if run.capture_job_id.starts_with(EXISTING) {
.query_row( let Some(snapshot) = run.snapshot_id.clone() else {
"SELECT status, snapshot_id FROM capture_jobs WHERE id=?1", return Ok(Linked::NotReady);
params![run.capture_job_id], };
|r| Ok((r.get(0)?, r.get(1)?)), snapshot
) } else {
.optional()?; let capture: Option<(String, Option<String>)> = tx
let Some((status, Some(snapshot))) = capture.filter(|c| c.0 == "completed") else { .query_row(
return Ok(Linked::NotReady); "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)? { if let Some(reason) = invalid_reason(&tx, &run, now)? {
block(&tx, &run, reason, now)?; block(&tx, &run, reason, now)?;
return Ok(Linked::Blocked(reason)); 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())) Ok(Sync::Moved(status.into()))
}; };
match run.status.as_str() { 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" => { "capturing" => {
let capture: Option<(String, Option<String>)> = tx let capture: Option<(String, Option<String>)> = tx
.query_row( .query_row(

View File

@@ -116,6 +116,17 @@ 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);
}; };
// 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 target = state.db.restore_target(Uuid::parse_str(&run.target_id)?)?;
let clash = match target { let clash = match target {
Some(target) => { Some(target) => {

View File

@@ -372,10 +372,20 @@ was shown: `REFRESH <source> TO <target> v<version>`. The caller never picks the
overwritten); overwritten);
3. follows the restore job to its end. 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 A run can also restore a snapshot somebody picked instead of capturing a new one: add `snapshot_id` to the request. The
only permission is a relation grant gets that single screen: the vault screens are not loaded for them, since every snapshot must be a restorable database capture of the relation's own source orbit (never a safety copy, never another
request would be refused. The screen shows what will be overwritten, requires an explicit confirmation, follows the orbit's); otherwise the answer is `422 snapshot_unusable` and nothing is started. Such a run has no capture step, but
run, and lets the person cancel until the target starts being overwritten. 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), 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 `expired`, `cancelled`, `recovery_required` (the restore was interrupted after it started overwriting: an administrator

View File

@@ -38,7 +38,7 @@ admin/browser. Semua status/data job hanya di scope owner/admin yang berizin.
| /api/v1/relations/:id/access | GET,POST | human | relation.manage | admin | grant refresh.run per relasi (user atau grup, expiry); diaudit | | /api/v1/relations/:id/access | GET,POST | human | relation.manage | admin | grant refresh.run per relasi (user atau grup, expiry); diaudit |
| /api/v1/relations/:id/access/:grant | DELETE | human | relation.manage | admin | berlaku pada request berikutnya; diaudit | | /api/v1/relations/:id/access/:grant | DELETE | human | relation.manage | admin | berlaku pada request berikutnya; diaudit |
| /api/v1/refresh-relations | GET | human | refresh.run | relasi yang di-grant | nama dan environment saja; tanpa identity, host, Outpost, application id; 403 bila tanpa grant | | /api/v1/refresh-relations | GET | human | refresh.run | relasi yang di-grant | nama dan environment saja; tanpa identity, host, Outpost, application id; 403 bila tanpa grant |
| /api/v1/refresh-runs | GET,POST | human | refresh.run | relasi yang di-grant | POST: relation_id + konfirmasi `REFRESH <sumber> TO <target> v<versi>` + kunci idempotensi; 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 <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/:id | GET,DELETE | human | refresh.run | admin, pemohon, atau pemegang grant relasinya | GET 404 bagi yang lain; DELETE hanya pemohon atau admin (pemegang grant lain 403) dan hanya sebelum apply, sesudahnya 409 | | /api/v1/refresh-runs/:id | GET,DELETE | human | refresh.run | admin, pemohon, atau pemegang grant relasinya | GET 404 bagi yang lain; DELETE hanya pemohon atau admin (pemegang grant lain 403) dan hanya sebelum apply, sesudahnya 409 |
| /api/v1/operator/login | POST | public | — | emergency account | cookie opaque dan CSRF; limiter, no-store | | /api/v1/operator/login | POST | public | — | emergency account | cookie opaque dan CSRF; limiter, no-store |
| /api/v1/snapshots | GET | human | snapshot.read | orbit | metadata aman terfilter | | /api/v1/snapshots | GET | human | snapshot.read | orbit | metadata aman terfilter |

View File

@@ -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.

View File

@@ -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");
});

View File

@@ -2,21 +2,20 @@ import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { AnimatePresence, useMotionValue } from "motion/react"; import { AnimatePresence, useMotionValue } from "motion/react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { import {
abortReconstitute, fetchCaptureJobs, fetchHealth, fetchOrbits, fetchPreferences, fetchSnapshots, pollReconstitute, savePreferences, fetchCaptureJobs, fetchHealth, fetchOrbits, fetchPreferences, fetchRefreshRelations, fetchSnapshots, savePreferences,
enqueueCapture, runOrbit, startReconstitute, type Orbit, enqueueCapture, runOrbit, type Orbit,
} from "./api"; } from "./api";
import { OrbitInspector, OrbitRegister, TelemetryStrip } from "./components/hud/DiegeticHUD"; import { OrbitInspector, OrbitRegister, TelemetryStrip } from "./components/hud/DiegeticHUD";
import { HUDPanel } from "./components/hud/HUDPanel"; import { HUDPanel } from "./components/hud/HUDPanel";
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 { AccessView } from "./components/access/AccessView";
import { RelationsView } from "./components/relations/RelationsView"; import { RelationsView } from "./components/relations/RelationsView";
import { RefreshView } from "./components/refresh/RefreshView";
import { SearchIcon, VaultSearch } from "./components/hud/VaultSearch"; import { SearchIcon, VaultSearch } from "./components/hud/VaultSearch";
import { OperatorGate, type Caps } from "./components/operator/OperatorGate"; import { OperatorGate, type Caps } from "./components/operator/OperatorGate";
import { OrbitsView } from "./components/orbits/OrbitsView"; import { OrbitsView } from "./components/orbits/OrbitsView";
import { WormholeView } from "./components/outposts/WormholeView"; import { WormholeView } from "./components/outposts/WormholeView";
import { ActivityView } from "./components/activity/ActivityView"; 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 { VaultScene } from "./components/scene/VaultScene";
import { EmptyState } from "./components/ui/EmptyState"; import { EmptyState } from "./components/ui/EmptyState";
import { PanelBoundary } from "./components/ui/PanelBoundary"; import { PanelBoundary } from "./components/ui/PanelBoundary";
@@ -38,7 +37,6 @@ const panelTitles: Record<HUDMode, string> = {
activity: "Activity", activity: "Activity",
access: "Access", access: "Access",
relations: "Refresh relations", relations: "Refresh relations",
refresh: "Refresh staging",
reconstitute: "Restore snapshot", reconstitute: "Restore snapshot",
snapshot: "Snapshot detail", snapshot: "Snapshot detail",
}; };
@@ -49,11 +47,10 @@ const panelLabels: Record<HUDMode, string> = {
activity: "Console 04 · Activity", activity: "Console 04 · Activity",
access: "Console 05 · Access", access: "Console 05 · Access",
relations: "Console 06 · Relations", relations: "Console 06 · Relations",
refresh: "Console 07 · Refresh",
reconstitute: "Restore from a snapshot", reconstitute: "Restore from a snapshot",
snapshot: "Recovery point", snapshot: "Recovery point",
}; };
const panelWidths: Record<HUDMode, number> = { scene: 640, orbits: 1120, wormhole: 760, activity: 1120, access: 1120, relations: 1120, refresh: 760, reconstitute: 760, snapshot: 640 }; const panelWidths: Record<HUDMode, number> = { scene: 640, orbits: 1120, wormhole: 760, activity: 1120, access: 1120, relations: 1120, reconstitute: 760, snapshot: 640 };
const LOOK_KEY = "tessera.look"; const LOOK_KEY = "tessera.look";
@@ -72,34 +69,7 @@ function priority(orbit: Orbit) {
} }
export default function App() { export default function App() {
return ( return <OperatorGate>{(operator) => <VaultApp {...operator} />}</OperatorGate>;
<OperatorGate>
{(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
? <RefreshOnly actor={operator.actor} onLogout={operator.onLogout} />
: <VaultApp {...operator} />}
</OperatorGate>
);
}
function RefreshOnly({ actor, onLogout }: { actor?: string; onLogout?: () => Promise<void> }) {
return (
<main className="vault-app mx-auto min-h-screen max-w-3xl p-5">
<header className="flex items-center justify-between py-4">
<div>
<p className="instrument-label">Tessera / Refresh</p>
<h1 className="text-2xl font-semibold text-star-100">Refresh staging</h1>
</div>
<div className="flex items-center gap-3 text-sm text-star-300">
{actor && <span>{actor}</span>}
{onLogout && <button type="button" className="console-control" onClick={() => void onLogout()}>Sign out</button>}
</div>
</header>
<RefreshView />
</main>
);
} }
function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () => Promise<void>; caps: Caps }) { function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () => Promise<void>; caps: Caps }) {
@@ -270,12 +240,13 @@ function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () =>
const activity = useActivity(snaps.data, orbits.data, caps.admin); const activity = useActivity(snaps.data, orbits.data, caps.admin);
// Consoles a non-administrator never sees: managing orbits and Outposts, restores, and access. // Consoles a non-administrator never sees: managing orbits and Outposts, restores, and access.
const railItems = useMemo( const railItems = useMemo(
() => { () => (caps.admin ? [...hudItems, relationsItem, accessItem] : hudItems.filter((item) => item.id === "scene" || item.id === "activity")),
const base = caps.admin ? [...hudItems, relationsItem, accessItem] : hudItems.filter((item) => item.id === "scene" || item.id === "activity"); [caps.admin],
return caps.refresh ? [...base.slice(0, 4), refreshItem, ...base.slice(4)] : base;
},
[caps.admin, caps.refresh],
); );
// 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 failedCount = sceneOrbits.filter(({ last_status }) => last_status === "failed").length;
const orbitMessage = orbits.isPending ? "Receiving orbit telemetry…" : orbits.isError 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) { 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 && if (next === "reconstitute" && !restoreBusy &&
(!restoreTarget || (target !== null && target !== restoreTarget.id))) { (!restoreTarget || (target !== null && target !== restoreTarget.id))) {
setRestoreTarget({ id: target }); setRestoreTarget({ id: target });
@@ -465,9 +436,6 @@ function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () =>
{mode === "wormhole" && caps.admin && ( {mode === "wormhole" && caps.admin && (
<SpringPane key="wormhole"><WormholeView pairing={pairing} onPaired={setPairing} /></SpringPane> <SpringPane key="wormhole"><WormholeView pairing={pairing} onPaired={setPairing} /></SpringPane>
)} )}
{mode === "refresh" && caps.refresh && (
<SpringPane key="refresh"><RefreshView /></SpringPane>
)}
{mode === "relations" && caps.admin && ( {mode === "relations" && caps.admin && (
<SpringPane key="relations"><RelationsView /></SpringPane> <SpringPane key="relations"><RelationsView /></SpringPane>
)} )}
@@ -477,23 +445,26 @@ function VaultApp({ actor, onLogout, caps }: { actor?: string; onLogout?: () =>
{mode === "snapshot" && ( {mode === "snapshot" && (
<SpringPane key="snapshot"> <SpringPane key="snapshot">
{snapshot {snapshot
? <SnapshotSheet snap={snapshot} siblings={snapshotSiblings} canManage={caps.admin} canDownload={caps.can("snapshot.download", snapshot.orbit_id)} onDeleted={() => openConsole("scene")} onReconstitute={() => openConsole("reconstitute", snapshot.id)} /> ? <SnapshotSheet snap={snapshot} siblings={snapshotSiblings} canManage={caps.admin} canDownload={caps.can("snapshot.download", snapshot.orbit_id)} onDeleted={() => 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} />
: <EmptyState title="Snapshot unavailable" body="It may have expired under the retention policy." />} : <EmptyState title="Snapshot unavailable" body="It may have expired under the retention policy." />}
</SpringPane> </SpringPane>
)} )}
</AnimatePresence> </AnimatePresence>
<SpringPane active={mode === "reconstitute"}> <SpringPane active={mode === "reconstitute"}>
{restoreTarget && (snaps.data?.length || restoreBusy ? ( {restoreSnapshot
<ReconstituteWizard ? (
key={restoreTarget.id ?? "manual"} <RestoreWizard
snapshots={snaps.data ?? []} selected={restoreTarget.id} scopedExport={!!actor} key={restoreSnapshot.id}
onStart={startReconstitute} onPoll={pollReconstitute} onAbort={abortReconstitute} onBusyChange={setRestoreBusy} snapshot={restoreSnapshot}
/> relations={restorePoints.filter((r) => r.source_orbit_id === restoreSnapshot.orbit_id)}
) : ( admin={caps.admin}
<QueryGate query={snaps} empty={<EmptyState title="No snapshots to restore" body="Capture an orbit to create a recovery point." />}> onBusyChange={setRestoreBusy}
{() => null} />
</QueryGate> )
))} : restoreTarget && <EmptyState title="Snapshot unavailable" body="Pick a snapshot of an orbit to restore it." />}
</SpringPane> </SpringPane>
</PanelBoundary> </PanelBoundary>
</HUDPanel> </HUDPanel>

View File

@@ -5,6 +5,8 @@ export type Snapshot = {
orbit_name: string; orbit_name: string;
size_bytes: number; size_bytes: number;
capture?: { job_id: string; application_id: string; engine: "postgres" | "mysql"; format: string; restore_ready: boolean } | null; 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"; 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<void>(`/api/v1/relations/${id}/access/${grant}`, { method: "DELETE" }); export const revokeRelationAccess = (id: string, grant: string) => api<void>(`/api/v1/relations/${id}/access/${grant}`, { method: "DELETE" });
export type RefreshRelation = { 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; target_name: string; target_environment: Environment | null; usable: boolean; unusable_reason: string | null;
}; };
export type RefreshRun = { export type RefreshRun = {
@@ -140,13 +142,16 @@ 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");
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<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 } : {}),
})); }));
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" });
export type Look = "window" | "radar"; export type Look = "window" | "radar";
@@ -246,7 +251,9 @@ export async function fetchHealth(): Promise<string> {
} }
export async function fetchSnapshots(): Promise<Snapshot[]> { export async function fetchSnapshots(): Promise<Snapshot[]> {
return api("/api/v1/snapshots"); const all = await api<Snapshot[]>("/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<Orbit[]> { export async function fetchOrbits(): Promise<Orbit[]> {
@@ -278,30 +285,6 @@ export async function runOrbit(id: string): Promise<string | null> {
return response.headers.get("X-Tessera-Snapshot-Id"); 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<void> {
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 = { export type CaptureProfile = {

View File

@@ -3,7 +3,7 @@ import { useCallback, useId, useLayoutEffect, useRef, type PointerEvent } from "
import { useScreenTransition } from "../../hooks/useScreenTransition"; import { useScreenTransition } from "../../hooks/useScreenTransition";
import { uiSpring } from "../../lib/motion"; 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 = [ export const hudItems = [
{ id: "scene", label: "Vault", icon: "M4 9l8-4 8 4v6l-8 4-8-4z M4 9l8 4 8-4 M12 13v6" }, { 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", 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. */ /** Only for administrators: which source may overwrite which target. */
export const relationsItem: HUDItem = { export const relationsItem: HUDItem = {
id: "relations", label: "Relations", id: "relations", label: "Relations",

View File

@@ -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<void>;
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<string | null>(null);
const [remaining, setRemaining] = useState(GRACE);
const [state, setState] = useState("idle");
const [action, setAction] = useState<"starting" | "aborting">();
const [error, setError] = useState<string>();
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 (
<div className="restore-layout">
<div className="restore-top">
<p className="restore-lead">Choose a recovery point and a destination.</p>
{snap && (
<div className="restore-snap">
<span className="restore-snap-glyph" aria-hidden="true">◇</span>
<div className="min-w-0">
<p className="restore-snap-name">{snap.orbit_name}</p>
<p className="restore-snap-meta">{formatWhen(snap.taken_at)} · {formatBytes(snap.size_bytes)} · {snap.id.slice(0, 8)}</p>
</div>
</div>
)}
<label className="block text-sm">
<span className="field-label">Snapshot</span>
<Select
value={snapId}
onChange={(e) => { setSnapId(e.target.value); setDatabaseMode(true); }}
disabled={busy}
>
{snapshots.map((s) => (
<option key={s.id} value={s.id}>
{s.orbit_name} · {formatWhen(s.taken_at)} · {formatBytes(s.size_bytes)}
</option>
))}
</Select>
</label>
{managed && (
<div>
<p className="field-label mb-1.5">Destination</p>
<Segmented label="Recovery destination" value={databaseMode ? "database" : "file"} disabled={busy}
onChange={(value) => setDatabaseMode(value === "database")}
options={[{ value: "database", label: "Restore to database" }, { value: "file", label: "Export file on hub" }]} />
</div>
)}
</div>
{managed && databaseMode ? (
<DatabaseRestore key={snapId} snapshot={snapId} application={managed.application_id} applicationName={snap?.orbit_name} engine={managed.engine} />
) : <>
<div className="restore-fields">
<label className="block text-sm">
<span className="field-label">{scopedExport ? "Export filename on hub" : "Export file path on hub"}</span>
<input className="field field-mono" value={target} onChange={(e) => setTarget(e.target.value)} disabled={busy} />
</label>
<Hint>{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."}</Hint>
<div className="flex gap-2.5">
<Button
variant="danger"
className="flex-1"
disabled={!sessionId || !inCountdown || !!action}
onClick={async () => {
if (!sessionId) return;
setAction("aborting");
setError(undefined);
try {
await onAbort(sessionId);
} catch {
setAction(undefined);
setError("Could not cancel the file export. Check the current session status.");
}
}}
>
Abort
</Button>
<Button
variant="primary"
className="flex-1"
disabled={!snap || !target.trim() || busy}
onClick={async () => {
setAction("starting");
setError(undefined);
try {
const res = await onStart(snapId, target);
setSessionId(res.session_id);
setState(res.session.state);
setRemaining(res.session.seconds_remaining);
} catch {
setError("Could not confirm that the hub started writing to the destination.");
} finally {
setAction(undefined);
}
}}
>
Begin file export
</Button>
</div>
{error && <p role="alert" className="text-orbit-red text-sm">{error}</p>}
</div>
<aside className="restore-status">
<p className="restore-status-label">Countdown</p>
{inCountdown ? (
<motion.div className="restore-count" initial={{ opacity: 0 }} animate={{ opacity: 1 }}>
<div className="restore-ring">
<svg viewBox="0 0 120 120" width="132" height="132" aria-hidden="true">
<circle cx="60" cy="60" r={radius} fill="none" stroke="#2a2218" strokeWidth="5" />
<motion.circle cx="60" cy="60" r={radius} fill="none" stroke="#e8b57e" strokeWidth="5" strokeLinecap="round"
strokeDasharray={circumference} initial={false} animate={{ strokeDashoffset: circumference * (1 - progress) }} />
</svg>
<span className="restore-ring-text"><b>{remaining}</b><i>seconds</i></span>
</div>
<p className="restore-count-note">Reconstituting in {remaining}s.<br />Abort restores nothing.</p>
</motion.div>
) : <p className="restore-idle">No export is running. Begin an export to start the countdown.</p>}
{reconnecting && <p role="status" className="text-orbit-amber text-sm">Reconnecting to the export session…</p>}
{state === "restoring" && <p role="status" className="text-orbit-amber text-sm">Exporting snapshot…</p>}
{state === "unavailable" && (
<p role="alert" className="text-orbit-red text-sm">The hub no longer has this export session. Check the destination before retrying.</p>
)}
{state === "completed" && <p className="text-orbit-green text-sm">File export complete.</p>}
{state === "aborted" && <p className="text-star-300 text-sm">File export cancelled.</p>}
{state === "failed" && <p className="text-orbit-red text-sm">File export failed. Check telemetry.</p>}
{sessionId && (
<TelemetryPanel label="Session">
{JSON.stringify({ sessionId, state, remaining }, null, 2)}
</TelemetryPanel>
)}
</aside>
</>}
</div>
);
}

View File

@@ -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<string, string> = {
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<string, string> = {
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<string, string> = {
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<string, string> = {
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 <p role="status" className="p-6 text-star-300">Loading…</p>;
if (relations.isError) {
return <p role="alert" className="p-6 text-star-300">You have not been given a database to refresh, or this hub does not support it.</p>;
}
return (
<div className="space-y-8 p-6">
<p className="text-sm text-star-300">
A refresh takes a new backup of the source and replaces the contents of its staging database with it. The source is only read.
</p>
{list.length === 0 && <p className="text-star-300">Nothing to refresh yet.</p>}
{list.map((relation) => (
<RelationCard key={relation.id} relation={relation} runs={history.filter((r) => r.relation_id === relation.id)}
onChanged={() => void qc.invalidateQueries({ queryKey: ["refresh-runs"] })} />
))}
</div>
);
}
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<string>(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 (
<section className="rounded-xl border border-space-700 p-5" aria-label={`${relation.source_name} to ${relation.target_name}`}>
<p className="text-xs uppercase tracking-wide text-star-300">Application: {relation.source_name}</p>
<div className="flex flex-wrap items-center justify-between gap-3">
<h3 className="text-lg font-semibold text-star-100">
{relation.target_name}
<span className="ml-2 text-sm font-normal text-star-300">({relation.target_environment ?? "?"}) is refreshed from {relation.source_name} ({relation.source_environment ?? "?"})</span>
</h3>
{!relation.usable && <p className="text-sm text-orbit-red">Not available right now. Ask an administrator.</p>}
</div>
{seen && (
<div className="mt-4" role="status" aria-live="polite">
<p className={seen.tone === "bad" ? "font-medium text-orbit-red" : "font-medium text-star-100"}>{seen.title}</p>
{seen.detail && <p className="mt-1 text-sm text-star-300">{seen.detail}</p>}
{running && (
<progress className="mt-3 block h-1 w-full" aria-label="Refresh progress"
value={latest.status === "capturing" ? 1 : latest.restore_phase === "applying" ? 3 : 2} max={4} />
)}
</div>
)}
<div className="mt-4 flex flex-wrap items-center gap-3">
{!confirming && !running && (
<Button variant="primary" disabled={!relation.usable} onClick={() => setConfirming(true)}>Refresh {relation.target_name}</Button>
)}
{running && latest && (
<Button disabled={cancel.isPending || overwriting} onClick={() => cancel.mutate(latest.id)}>
{overwriting ? "Overwriting: cannot cancel" : "Cancel"}
</Button>
)}
</div>
{confirming && !running && (
<form className="mt-4 space-y-3 rounded-lg border border-space-700 p-4" onSubmit={(e) => { e.preventDefault(); if (understood) start.mutate(); }}>
<p className="text-sm text-star-100">
This replaces <strong>everything</strong> in <strong>{relation.target_name}</strong> with a fresh copy of <strong>{relation.source_name}</strong>.
Anything that exists only in {relation.target_name} is lost. {relation.source_name} is only read.
</p>
<label className="flex items-start gap-2 text-sm text-star-300">
<input type="checkbox" checked={understood} onChange={(e) => setUnderstood(e.target.checked)} className="mt-1" />
<span>I understand that {relation.target_name} will be overwritten.</span>
</label>
<div className="flex gap-2">
<Button type="button" onClick={() => { setConfirming(false); setUnderstood(false); }}>Not now</Button>
<Button type="submit" variant="danger" disabled={!understood || start.isPending}>{start.isPending ? "Starting…" : `Overwrite ${relation.target_name}`}</Button>
</div>
</form>
)}
{refusal && <p role="alert" className="mt-3 text-sm text-orbit-red">{refusal}</p>}
{cancel.isError && <p role="alert" className="mt-3 text-sm text-orbit-red">It could not be cancelled: it has already started overwriting.</p>}
{runs.length > 1 && (
<details className="mt-4 text-sm text-star-300">
<summary className="cursor-pointer">Earlier refreshes</summary>
<ul className="mt-2 space-y-1">
{runs.slice(1, 8).map((run) => <li key={run.id}>{when(run.created_at)}: {describe(run).title}</li>)}
</ul>
</details>
)}
</section>
);
}

View File

@@ -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<string, string> = {
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<Phase>("idle");
const [left, setLeft] = useState(COUNTDOWN);
const [runId, setRunId] = useState<string>();
const [refusal, setRefusal] = useState<string>();
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 (
<div className="restore-layout">
<div className="restore-top">
<p className="restore-lead">Review the restore point before starting.</p>
<div className="restore-snap">
<span className="restore-snap-glyph" aria-hidden="true">◇</span>
<div className="min-w-0">
<p className="restore-snap-name">{snapshot.orbit_name}</p>
<p className="restore-snap-meta">{formatWhen(snapshot.taken_at)} · {formatBytes(snapshot.size_bytes)} · {snapshot.id.slice(0, 8)}</p>
</div>
</div>
</div>
{other && admin && database ? (
<DatabaseRestore snapshot={snapshot.id} application={database.application_id} applicationName={snapshot.orbit_name} engine={database.engine} />
) : (
<>
<div className="restore-fields">
<div>
<p className="field-label mb-1.5">Restore point</p>
{points.length > 1 ? (
<Segmented label="Restore point" value={point?.id ?? ""} disabled={phase !== "idle"} onChange={setPointId}
options={points.map((p) => ({ value: p.id, label: p.label }))} />
) : (
<p className="field field-mono" aria-label="Restore point">{point?.label ?? "None"}</p>
)}
</div>
<div className="restore-warning" role="note">
<svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M8 2 14.5 13.5h-13Z" /><path d="M8 6.5v3M8 11.5v.01" /></svg>
<p>Restoring replaces everything on {target} with this snapshot. Anything that exists only there is lost. {snapshot.orbit_name} itself is only read.</p>
</div>
<div className="flex gap-2.5">
<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"); }}>
Begin restore
</Button>
</div>
{refusal && <p role="alert" className="text-sm text-orbit-red">{refusal}</p>}
{admin && database && phase === "idle" && !runId && (
<button type="button" className="footer-link self-start" onClick={() => setOther(true)}>Other registered target…</button>
)}
</div>
<aside className="restore-status">
<p className="restore-status-label">{phase === "running" ? "Progress" : "Countdown"}</p>
{phase === "idle" && <p className="restore-idle">No restore is running. Begin restore to start the countdown.</p>}
{phase === "countdown" && (
<motion.div className="restore-count" initial={{ opacity: 0 }} animate={{ opacity: 1 }}>
<div className="restore-ring">
<svg viewBox="0 0 120 120" width="132" height="132" aria-hidden="true">
<circle cx="60" cy="60" r={radius} fill="none" stroke="#2a2218" strokeWidth="5" />
<motion.circle cx="60" cy="60" r={radius} fill="none" stroke="#e8b57e" strokeWidth="5" strokeLinecap="round"
strokeDasharray={circumference} initial={false} animate={{ strokeDashoffset: circumference * (1 - left / COUNTDOWN) }} />
</svg>
<span className="restore-ring-text"><b>{left}</b><i>seconds</i></span>
</div>
<p className="restore-count-note">Restoring to {target} in {left}s.<br />Abort restores nothing.</p>
</motion.div>
)}
{phase === "running" && (
<>
<ol className="restore-steps" aria-label="Restore progress">
{STAGES.map((name, i) => {
const done = i < progress.index || progress.state === "done";
const now = i === progress.index && progress.state === "running";
const bad = i === progress.index && progress.state === "failed";
return (
<li key={name} className={done ? "done" : now ? "now" : bad ? "bad" : ""} aria-current={now ? "step" : undefined}>
<span aria-hidden="true">{done ? "✓" : bad ? "!" : i + 1}</span>
{name}
</li>
);
})}
</ol>
{!finished && (
<p className="restore-idle" role="status">
{progress.index >= 2 ? "Overwriting has started. This can no longer be cancelled." : `Nothing on ${target} has changed yet. You can still abort.`}
</p>
)}
{outcome && (
<div role="status" className={`restore-outcome ${outcome.tone}`}>
<p>{outcome.title}</p>
<p>{outcome.detail}</p>
<Button onClick={again}>{outcome.tone === "good" ? "Restore again" : "Try again"}</Button>
</div>
)}
{run.isError && <p role="alert" className="text-sm text-orbit-amber">Reconnecting to the restore…</p>}
</>
)}
</aside>
</>
)}
</div>
);
}

View File

@@ -15,7 +15,7 @@ function signedBytes(delta: number) {
export function SnapshotSheet({ export function SnapshotSheet({
snap, snap,
siblings = [], siblings = [],
onReconstitute, restore,
onDeleted, onDeleted,
canManage = false, canManage = false,
canDownload = false, canDownload = false,
@@ -23,7 +23,8 @@ export function SnapshotSheet({
snap: Snapshot; snap: Snapshot;
/** Every snapshot of the same orbit, newest first, including this one. */ /** Every snapshot of the same orbit, newest first, including this one. */
siblings?: Snapshot[]; 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; onDeleted: () => void;
/** Administrators only: restore and delete. */ /** Administrators only: restore and delete. */
canManage?: boolean; canManage?: boolean;
@@ -90,7 +91,7 @@ export function SnapshotSheet({
</div> </div>
<div> <div>
<dt>Recovery</dt> <dt>Recovery</dt>
<dd>{database ? "Database ready" : "File export"}</dd> <dd>{database ? "Database ready" : "Download only"}</dd>
{snap.capture && <dd className="sheet-sub">{snap.capture.engine} · {snap.capture.format}</dd>} {snap.capture && <dd className="sheet-sub">{snap.capture.engine} · {snap.capture.format}</dd>}
</div> </div>
</dl> </dl>
@@ -104,10 +105,20 @@ export function SnapshotSheet({
</div> </div>
<div className="sheet-actions"> <div className="sheet-actions">
{canManage && <Button variant="primary" className="sheet-primary" onClick={onReconstitute}> {restore && (restore.available ? (
{database ? "Database recovery options" : "Export file on hub"} <Button variant="primary" className="sheet-primary" onClick={restore.onOpen}>
<span aria-hidden="true">→</span> Restore
</Button>} <span aria-hidden="true">→</span>
</Button>
) : (
<>
<Button className="sheet-primary" disabled>
No restore point
<span aria-hidden="true">⊘</span>
</Button>
<p className="mt-1 text-xs text-star-300">An administrator has not connected a staging or development database to this orbit yet.</p>
</>
))}
{canDownload && <a href={`/api/v1/snapshots/${snap.id}/download`} download className="console-control sheet-link"> {canDownload && <a href={`/api/v1/snapshots/${snap.id}/download`} download className="console-control sheet-link">
Download snapshot Download snapshot
<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"> <svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">

View File

@@ -1201,3 +1201,21 @@ button.act-row[data-group="needs"]:hover { background: #20161a; }
.big-screen .galaxy-frame { touch-action: none; } .big-screen .galaxy-frame { touch-action: none; }
.galaxy-frame[data-turning] { cursor: grabbing; } .galaxy-frame[data-turning] { cursor: grabbing; }
.galaxy-frame[data-turning] :is(.scene-labels, .snapshot-marker, .focus-leader, .focus-leader-big) { opacity: 0; } .galaxy-frame[data-turning] :is(.scene-labels, .snapshot-marker, .focus-leader, .focus-leader-big) { opacity: 0; }
/* Restore progress: four steps and the outcome, in the modal's right column. */
.restore-steps { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 14px; }
.restore-steps li { display: flex; align-items: center; gap: 12px; font-size: 14px; color: var(--quiet); }
.restore-steps li span { width: 22px; height: 22px; border-radius: 50%; border: 1.5px solid var(--line); display: inline-flex; align-items: center; justify-content: center; font: 600 11px/1 var(--font-mono); flex: none; }
.restore-steps li.done { color: var(--color-star-200, #c4c8d0); }
.restore-steps li.done span { background: var(--color-orbit-green, #8fd0b0); border-color: var(--color-orbit-green, #8fd0b0); color: #0b0d12; }
.restore-steps li.now { color: var(--color-orbit-amber); font-weight: 600; }
.restore-steps li.now span { border-color: var(--color-orbit-amber); color: var(--color-orbit-amber); }
.restore-steps li.bad { color: var(--color-orbit-red); font-weight: 600; }
.restore-steps li.bad span { border-color: var(--color-orbit-red); color: var(--color-orbit-red); }
.restore-outcome { display: flex; flex-direction: column; align-items: flex-start; gap: 8px; padding: 14px; border: 1px solid var(--line); border-radius: 12px; }
.restore-outcome p { margin: 0; font-size: 13.5px; line-height: 1.5; }
.restore-outcome p:first-child { font-weight: 600; font-size: 14.5px; }
.restore-outcome.good { border-color: #2d5a45; }
.restore-outcome.good p:first-child { color: var(--color-orbit-green, #8fd0b0); }
.restore-outcome.bad { border-color: #6b2f26; }
.restore-outcome.bad p:first-child { color: var(--color-orbit-red); }

95
web/src/lib/restoreRun.ts Normal file
View File

@@ -0,0 +1,95 @@
/** How a restore run is shown: which of four steps it is at, and what the person is told. Pure, so it is testable. */
export const STAGES = ["Checking", "Safety copy", "Applying", "Completed"] as const;
type RunLike = { status: string; restore_phase: string | null; blocked_reason?: string | null };
const STOPPED = new Set(["restore_failed", "recovery_required", "blocked", "expired", "capture_failed"]);
/** The step a restore job's phase belongs to. */
function stageOfPhase(phase: string | null): number {
switch (phase) {
case "safety": case "ready": case "safety_failed": return 1;
case "applying": case "apply_failed": return 2;
default: return 0; // queued, claimed, checking, invalid_payload, wrong_target, or no job yet
}
}
/** The run has reached a state it will not leave (as opposed to still capturing or restoring). */
export function isFinal(run: { status: string }): boolean {
return run.status !== "capturing" && run.status !== "restoring";
}
/** Where the run is: the index of the step in progress (4 once everything is done) and whether it is still going. */
export function progressOf(run: RunLike): { index: number; state: "running" | "done" | "failed" | "cancelled" } {
if (run.status === "completed" || run.status === "reconciled") return { index: 4, state: "done" };
if (run.status === "cancelled") return { index: stageOfPhase(run.restore_phase), state: "cancelled" };
if (STOPPED.has(run.status)) {
// An interrupted restore stopped while overwriting, whatever phase the job last showed.
const index = run.status === "recovery_required" ? 2 : stageOfPhase(run.restore_phase);
return { index, state: "failed" };
}
// The restore job finishes a moment before the run itself is marked completed.
if (run.restore_phase === "completed") return { index: 4, state: "done" };
return { index: stageOfPhase(run.restore_phase), state: "running" };
}
const BLOCKED: Record<string, string> = {
access_revoked: "your access to this restore was removed",
user_disabled: "your account was disabled",
relation_ended: "the restore point was removed or replaced",
relation_unusable: "the restore point 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",
};
export type Outcome = { tone: "busy" | "good" | "bad" | "plain"; title: string; detail: string };
/** What happened, in words, and what it means for the target. Never quotes the database. */
export function outcomeOf(
run: RunLike,
names: { target: string; orbit?: string; when?: string },
): Outcome {
const { target } = names;
switch (run.status) {
case "completed":
case "reconciled":
return {
tone: "good",
title: `${target} was restored`,
detail: names.orbit && names.when
? `${target} now holds ${names.orbit} as of ${names.when}. A safety copy of what it held before was kept.`
: "A safety copy of what it held before was kept.",
};
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 restore was stopped", detail: `${BLOCKED[run.blocked_reason ?? ""] ?? "something it depended on changed"}. ${target} was not overwritten.` };
case "expired":
return { tone: "bad", title: "The restore took too long to start", detail: `${target} was not changed. Start it again.` };
case "capture_failed":
return { tone: "bad", title: "The restore could not start", detail: `${target} was not changed.` };
case "cancelled":
return { tone: "plain", title: "The restore was cancelled", detail: `${target} was not overwritten.` };
default:
return { tone: "busy", title: "Restoring", detail: "" };
}
}
type RelationLike = { id: string; target_environment: string | null; target_name: string };
const environmentName = (value: string | null) => (value ? value[0].toUpperCase() + value.slice(1) : null);
/** Names for the restore points of one orbit: the environment, plus the target's name only when two would read the same. */
export function relationLabels<T extends RelationLike>(relations: T[]): (T & { label: string })[] {
const counts = new Map<string, number>();
for (const r of relations) counts.set(environmentName(r.target_environment) ?? r.target_name, (counts.get(environmentName(r.target_environment) ?? r.target_name) ?? 0) + 1);
return relations.map((r) => {
const env = environmentName(r.target_environment);
const base = env ?? r.target_name;
return { ...r, label: env && (counts.get(base) ?? 0) > 1 ? `${env} · ${r.target_name}` : base };
});
}