chore: rustfmt the refresh modules

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 20:48:44 +07:00
parent d356c313ce
commit 170b4130d9
3 changed files with 129 additions and 29 deletions

View File

@@ -115,13 +115,35 @@ async fn undo_views(
continue; continue;
}; };
// Safety copies are forgotten by retention: the restore stays in the log, but there is nothing to go back to. // Safety copies are forgotten by retention: the restore stays in the log, but there is nothing to go back to.
if !vault.has_published_snapshot(info.safety).map_err(internal)? { if !vault
views.insert(run.id.clone(), Undo { state: "expired", kept_until: None }); .has_published_snapshot(info.safety)
.map_err(internal)?
{
views.insert(
run.id.clone(),
Undo {
state: "expired",
kept_until: None,
},
);
} else if !info.latest { } else if !info.latest {
views.insert(run.id.clone(), Undo { state: "superseded", kept_until: None }); views.insert(
} else if let Some(taken) = fitting_snapshot(state, &vault, &run.relation_id, info.safety)? { run.id.clone(),
Undo {
state: "superseded",
kept_until: None,
},
);
} else if let Some(taken) = fitting_snapshot(state, &vault, &run.relation_id, info.safety)?
{
let kept = taken + tessera_core::decay::SAFETY_KEEP_DAYS * 86_400; let kept = taken + tessera_core::decay::SAFETY_KEEP_DAYS * 86_400;
views.insert(run.id.clone(), Undo { state: "available", kept_until: Some(kept) }); views.insert(
run.id.clone(),
Undo {
state: "available",
kept_until: Some(kept),
},
);
} }
} }
Ok(views) Ok(views)
@@ -329,7 +351,9 @@ async fn start(
actor.subject.user_id.as_deref(), actor.subject.user_id.as_deref(),
&authorized_by, &authorized_by,
&body.idempotency_key, &body.idempotency_key,
chosen.as_ref().map(|(snapshot, of)| (*snapshot, of.as_deref())), chosen
.as_ref()
.map(|(snapshot, of)| (*snapshot, of.as_deref())),
state.refresh.ttl_secs, state.refresh.ttl_secs,
state.refresh.max_active, state.refresh.max_active,
now(), now(),

View File

@@ -2380,7 +2380,12 @@ async fn only_someone_who_may_use_the_relation_can_undo_through_it() {
impl Lab { impl Lab {
async fn run_view(&self, run: &str) -> Value { async fn run_view(&self, run: &str) -> Value {
self.send(&self.admin(), "GET", &format!("/api/v1/refresh-runs/{run}"), None) self.send(
&self.admin(),
"GET",
&format!("/api/v1/refresh-runs/{run}"),
None,
)
.await .await
.1 .1
} }
@@ -2396,9 +2401,14 @@ impl Lab {
async fn failed_apply(&self, key: &str) -> (String, String) { async fn failed_apply(&self, key: &str) -> (String, String) {
let (_, run) = self.start(&self.admin(), key).await; let (_, run) = self.start(&self.admin(), key).await;
let run = run["id"].as_str().unwrap().to_string(); let run = run["id"].as_str().unwrap().to_string();
self.capture(&Lab::production_identity(), false).await.unwrap(); self.capture(&Lab::production_identity(), false)
.await
.unwrap();
self.tick().await; self.tick().await;
let (job, token) = self.restore_until_ready().await.expect("a restore job is waiting"); let (job, token) = self
.restore_until_ready()
.await
.expect("a restore job is waiting");
assert_eq!(self.apply(&job, &token).await, StatusCode::NO_CONTENT); assert_eq!(self.apply(&job, &token).await, StatusCode::NO_CONTENT);
let (status, _) = self let (status, _) = self
.agent_json( .agent_json(
@@ -2420,28 +2430,60 @@ async fn a_restore_says_why_it_can_or_cannot_be_put_back_and_how_long_for() {
let lab = fresh().await; let lab = fresh().await;
let first = lab.restored_once("first").await; let first = lab.restored_once("first").await;
let view = lab.run_view(&first).await; let view = lab.run_view(&first).await;
assert_eq!((view["undo_available"].clone(), view["undo_state"].clone()), (json!(true), json!("available")), "{view}"); assert_eq!(
let until = view["undo_kept_until"].as_i64().expect("a date while it can be undone"); (view["undo_available"].clone(), view["undo_state"].clone()),
assert!(until > chrono::Utc::now().timestamp() + 6 * 86_400, "a week from when it was taken: {view}"); (json!(true), json!("available")),
"{view}"
);
let until = view["undo_kept_until"]
.as_i64()
.expect("a date while it can be undone");
assert!(
until > chrono::Utc::now().timestamp() + 6 * 86_400,
"a week from when it was taken: {view}"
);
// a later restore of the same target supersedes it; only the newest can be undone // a later restore of the same target supersedes it; only the newest can be undone
let second = lab.restored_once("second").await; let second = lab.restored_once("second").await;
let (old, new) = (lab.run_view(&first).await, lab.run_view(&second).await); let (old, new) = (lab.run_view(&first).await, lab.run_view(&second).await);
assert_eq!((old["undo_state"].clone(), old["undo_available"].clone()), (json!("superseded"), json!(false)), "{old}"); assert_eq!(
(old["undo_state"].clone(), old["undo_available"].clone()),
(json!("superseded"), json!(false)),
"{old}"
);
assert_eq!(new["undo_state"], "available", "{new}"); assert_eq!(new["undo_state"], "available", "{new}");
// retention forgets the newest copy: it says so, instead of offering something that would be refused // retention forgets the newest copy: it says so, instead of offering something that would be refused
lab.state.vault.write().await.forget(&[lab.safety_of(&second)]).unwrap(); lab.state
.vault
.write()
.await
.forget(&[lab.safety_of(&second)])
.unwrap();
let new = lab.run_view(&second).await; let new = lab.run_view(&second).await;
assert_eq!((new["undo_state"].clone(), new["undo_available"].clone()), (json!("expired"), json!(false)), "{new}"); assert_eq!(
(new["undo_state"].clone(), new["undo_available"].clone()),
(json!("expired"), json!(false)),
"{new}"
);
assert!(new.get("undo_kept_until").is_none(), "{new}"); assert!(new.get("undo_kept_until").is_none(), "{new}");
// expired wins over superseded, so nobody is told to look for a copy that is gone // expired wins over superseded, so nobody is told to look for a copy that is gone
lab.state.vault.write().await.forget(&[lab.safety_of(&first)]).unwrap(); lab.state
.vault
.write()
.await
.forget(&[lab.safety_of(&first)])
.unwrap();
assert_eq!(lab.run_view(&first).await["undo_state"], "expired"); assert_eq!(lab.run_view(&first).await["undo_state"], "expired");
// the list says the same, for a person who may only use the relation // the list says the same, for a person who may only use the relation
let (qa, _) = lab.refresher("qa"); let (qa, _) = lab.refresher("qa");
let (_, list) = lab.send(&qa, "GET", "/api/v1/refresh-runs", None).await; let (_, list) = lab.send(&qa, "GET", "/api/v1/refresh-runs", None).await;
let states: Vec<_> = list.as_array().unwrap().iter().map(|r| r["undo_state"].clone()).collect(); let states: Vec<_> = list
.as_array()
.unwrap()
.iter()
.map(|r| r["undo_state"].clone())
.collect();
assert_eq!(states, vec![json!("expired"), json!("expired")], "{list}"); assert_eq!(states, vec![json!("expired"), json!("expired")], "{list}");
} }
@@ -2451,23 +2493,40 @@ async fn a_restore_whose_apply_failed_is_rolled_back_from_its_safety_copy() {
let (qa, _) = lab.refresher("qa"); let (qa, _) = lab.refresher("qa");
let (run, job) = lab.failed_apply("broken").await; let (run, job) = lab.failed_apply("broken").await;
let view = lab.run_view(&run).await; let view = lab.run_view(&run).await;
assert_eq!(view["undo_available"], true, "rolling back is offered: {view}"); assert_eq!(
view["undo_available"], true,
"rolling back is offered: {view}"
);
// while the failed apply fences the target nothing else may start, but the rollback may // while the failed apply fences the target nothing else may start, but the rollback may
let (status, other) = lab.start(&qa, "other").await; let (status, other) = lab.start(&qa, "other").await;
assert_eq!((status, other["reason"].clone()), (StatusCode::CONFLICT, json!("run_active")), "{other}"); assert_eq!(
(status, other["reason"].clone()),
(StatusCode::CONFLICT, json!("run_active")),
"{other}"
);
let (status, undo) = lab.start_undo(&qa, "rollback", &run).await; let (status, undo) = lab.start_undo(&qa, "rollback", &run).await;
assert_eq!(status, StatusCode::ACCEPTED, "{undo}"); assert_eq!(status, StatusCode::ACCEPTED, "{undo}");
assert_eq!(undo["undo_of"], json!(run)); assert_eq!(undo["undo_of"], json!(run));
assert_eq!(lab.run(&run).status, "reconciled"); assert_eq!(lab.run(&run).status, "reconciled");
assert_eq!(lab.scalar::<String>(&format!("SELECT phase FROM restore_jobs WHERE id='{job}'")), "rolled_back"); assert_eq!(
assert!(lab.audit_log().iter().any(|(event, _)| event == "restore.rolled_back")); lab.scalar::<String>(&format!("SELECT phase FROM restore_jobs WHERE id='{job}'")),
"rolled_back"
);
assert!(lab
.audit_log()
.iter()
.any(|(event, _)| event == "restore.rolled_back"));
// it goes through the same engine and puts the copy back // it goes through the same engine and puts the copy back
lab.tick().await; lab.tick().await;
lab.finish_restore().await; lab.finish_restore().await;
assert_eq!(lab.run(undo["id"].as_str().unwrap()).status, "completed"); assert_eq!(lab.run(undo["id"].as_str().unwrap()).status, "completed");
assert_eq!(lab.run_view(&run).await["undo_state"], "superseded", "it is not offered twice"); assert_eq!(
lab.run_view(&run).await["undo_state"],
"superseded",
"it is not offered twice"
);
} }
#[tokio::test] #[tokio::test]
@@ -2476,14 +2535,25 @@ async fn an_apply_that_lost_its_agent_waits_for_an_administrator_before_it_can_b
let (run, job) = lab.failed_apply("silent").await; let (run, job) = lab.failed_apply("silent").await;
// the agent did not say it stopped: the apply may still be writing // the agent did not say it stopped: the apply may still be writing
lab.conn() lab.conn()
.execute("UPDATE restore_jobs SET phase='lease_lost' WHERE id=?1", [&job]) .execute(
"UPDATE restore_jobs SET phase='lease_lost' WHERE id=?1",
[&job],
)
.unwrap(); .unwrap();
assert_eq!(lab.run_view(&run).await["undo_available"], false); assert_eq!(lab.run_view(&run).await["undo_available"], false);
let (status, body) = lab.start_undo(&lab.admin(), "early", &run).await; let (status, body) = lab.start_undo(&lab.admin(), "early", &run).await;
assert_eq!((status, body["reason"].clone()), (StatusCode::UNPROCESSABLE_ENTITY, json!("nothing_to_undo")), "{body}"); assert_eq!(
(status, body["reason"].clone()),
(StatusCode::UNPROCESSABLE_ENTITY, json!("nothing_to_undo")),
"{body}"
);
// once an administrator has verified it, the same safety copy can put the target back // once an administrator has verified it, the same safety copy can put the target back
assert!(lab.state.db.reconcile_restore(Uuid::parse_str(&job).unwrap(), "admin", now()).unwrap()); assert!(lab
.state
.db
.reconcile_restore(Uuid::parse_str(&job).unwrap(), "admin", now())
.unwrap());
lab.tick().await; lab.tick().await;
assert_eq!(lab.run(&run).status, "reconciled"); assert_eq!(lab.run(&run).status, "reconciled");
assert_eq!(lab.run_view(&run).await["undo_available"], true); assert_eq!(lab.run_view(&run).await["undo_available"], true);

View File

@@ -114,7 +114,10 @@ pub struct UndoInfo {
/// do: in the last case, rolling back is the recovery. An apply whose agent went silent may still be running, so /// do: in the last case, rolling back is the recovery. An apply whose agent went silent may still be running, so
/// it waits for an administrator to reconcile it. /// it waits for an administrator to reconcile it.
fn undo_info(conn: &Connection, run: &RefreshRun) -> Result<Option<UndoInfo>> { fn undo_info(conn: &Connection, run: &RefreshRun) -> Result<Option<UndoInfo>> {
if !matches!(run.status.as_str(), "completed" | "reconciled" | "recovery_required") { if !matches!(
run.status.as_str(),
"completed" | "reconciled" | "recovery_required"
) {
return Ok(None); return Ok(None);
} }
let Some(job) = &run.restore_job_id else { let Some(job) = &run.restore_job_id else {
@@ -189,7 +192,10 @@ impl Db {
/// What can be done about each run's restore, for a whole list under one lock: only runs that took a safety /// What can be done about each run's restore, for a whole list under one lock: only runs that took a safety
/// copy appear. See `UndoInfo`. /// copy appear. See `UndoInfo`.
pub fn undo_infos(&self, runs: &[RefreshRun]) -> Result<std::collections::HashMap<String, UndoInfo>> { pub fn undo_infos(
&self,
runs: &[RefreshRun],
) -> Result<std::collections::HashMap<String, UndoInfo>> {
let conn = self.conn.lock().unwrap(); let conn = self.conn.lock().unwrap();
let mut infos = std::collections::HashMap::new(); let mut infos = std::collections::HashMap::new();
for run in runs { for run in runs {