//! Durable refresh runs: capture a fresh dump of a source, then restore exactly that snapshot onto //! the target of a relation. //! //! Every step is one transaction and can be repeated safely after a crash: //! * the run and its capture job are created together, so there is never a run without a capture or the reverse; //! * the restore job is queued and linked in one transaction guarded by `restore_job_id IS NULL`; //! * a run follows its own capture job (`capture_job_id`), never "the latest snapshot", and that id is a //! retention pin for as long as the run is active; //! * everything that can change is checked again right before anything destructive: this module's //! [`invalid_reason`] is also called from `authorize_apply`, in the same transaction that flips the //! restore job to `applying`. use super::*; use crate::db::relations::{read_relation, unusable, Relation, RELATION_COLUMNS}; use rusqlite::{Transaction, TransactionBehavior}; use tessera_core::restore::RestoreArtifact; /// While a run is in one of these states its target is locked and its snapshot is pinned. pub const ACTIVE: [&str; 3] = ["capturing", "restoring", "recovery_required"]; #[derive(Clone, Debug, serde::Serialize)] pub struct RefreshRun { pub id: String, pub relation_id: String, pub relation_version: i64, pub source_orbit_id: String, pub source_application_id: String, pub target_id: String, pub requester: String, pub requester_user_id: Option, /// `admin`, or `grant:`. Group membership can only be verified as of the request. pub authorized_by: String, pub status: String, pub blocked_reason: Option, pub capture_job_id: String, pub snapshot_id: Option, pub restore_job_id: Option, pub created_at: i64, pub updated_at: i64, pub expires_at: i64, } const COLUMNS: &str = "id,relation_id,relation_version,source_orbit_id,source_application_id,target_id,requester,requester_user_id,authorized_by,status,blocked_reason,capture_job_id,snapshot_id,restore_job_id,created_at,updated_at,expires_at"; fn read_run(r: &rusqlite::Row<'_>) -> rusqlite::Result { Ok(RefreshRun { id: r.get(0)?, relation_id: r.get(1)?, relation_version: r.get(2)?, source_orbit_id: r.get(3)?, source_application_id: r.get(4)?, target_id: r.get(5)?, requester: r.get(6)?, requester_user_id: r.get(7)?, authorized_by: r.get(8)?, status: r.get(9)?, blocked_reason: r.get(10)?, capture_job_id: r.get(11)?, snapshot_id: r.get(12)?, restore_job_id: r.get(13)?, created_at: r.get(14)?, updated_at: r.get(15)?, expires_at: r.get(16)?, }) } #[derive(Debug, PartialEq, Eq)] pub enum StartError { /// No such active relation. UnknownRelation, /// The relation exists but cannot be used right now (target relabelled, Outpost gone, ...). Unusable(&'static str), /// The caller confirmed a different source, target or version than the relation has now. StaleConfirmation, /// The source's Outpost cannot take a capture job. SourceUnavailable, /// This target already has a run in progress; the id is returned so the caller can be shown it if allowed. TargetBusy(String), /// The same idempotency key was used for a different relation. KeyReused, /// Too many refreshes are running at once. TooManyRuns, /// The restore to undo is not one that can be undone (any more). NothingToUndo, } /// 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:"; /// Same, for a run that puts a target back from the safety copy of an earlier restore. const UNDO: &str = "undo:"; /// Does this run take its snapshot from the request instead of from a capture of its own? fn picked_snapshot(run: &RefreshRun) -> bool { run.capture_job_id.starts_with(EXISTING) || run.capture_job_id.starts_with(UNDO) } impl RefreshRun { /// This run put a target back from a safety copy. pub fn is_undo(&self) -> bool { self.capture_job_id.starts_with(UNDO) } } /// The safety copy a restore took before it overwrote its target, and whether it is still the newest restore there. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct UndoInfo { pub safety: Uuid, /// Nothing was restored onto the target after it. Undoing an older restore would also undo what came later. pub latest: bool, } /// Does this run have a safety copy that puts its target back? A restore that finished, one an administrator /// has since reconciled, and one whose apply failed (the agent says it stopped, so nothing is still writing) all /// 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. fn undo_info(conn: &Connection, run: &RefreshRun) -> Result> { if !matches!(run.status.as_str(), "completed" | "reconciled" | "recovery_required") { return Ok(None); } let Some(job) = &run.restore_job_id else { return Ok(None); }; let row: Option<(String, String, Option)> = conn .query_row( "SELECT status, phase, safety_id FROM restore_jobs WHERE id = ?1", params![job], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)), ) .optional()?; let Some((status, phase, Some(safety))) = row else { return Ok(None); }; let sound = match status.as_str() { "completed" | "reconciled" => true, "recovery_required" => phase == "apply_failed", _ => false, }; if !sound { return Ok(None); } // Jobs are numbered in the order they were queued. let later: bool = conn.query_row( "SELECT EXISTS(SELECT 1 FROM restore_jobs WHERE target_id = ?1 AND rowid > (SELECT rowid FROM restore_jobs WHERE id = ?2) AND status IN ('queued','running','applying','completed','reconciled','recovery_required'))", params![run.target_id, job], |r| r.get(0), )?; Ok(Some(UndoInfo { safety: Uuid::parse_str(&safety)?, latest: !later, })) } fn undo_check( conn: &Connection, run: &str, relation: &str, ) -> Result> { let Some(run) = get(conn, run)?.filter(|r| r.relation_id == relation) else { return Ok(Err(UndoRefusal::NothingToUndo)); }; Ok(match undo_info(conn, &run)? { None => Err(UndoRefusal::NothingToUndo), Some(info) if !info.latest => Err(UndoRefusal::NotTheLatest), Some(info) => Ok(info.safety), }) } /// Why a restore cannot be undone. #[derive(Debug, PartialEq, Eq)] pub enum UndoRefusal { /// No such run, not of this relation, not a restore that can be put back, or it took no safety copy. NothingToUndo, /// Something else was restored onto the target after it. Undoing an older restore would also undo that. NotTheLatest, } impl Db { /// The safety copy that undoes `run`, if the run is a restore of this relation that can be put back and the /// newest restore of its target. Whether the copy still exists in the vault is for the caller to check. pub fn undo_candidate( &self, run: &str, relation: &str, ) -> Result> { undo_check(&self.conn.lock().unwrap(), run, relation) } /// 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`. pub fn undo_infos(&self, runs: &[RefreshRun]) -> Result> { let conn = self.conn.lock().unwrap(); let mut infos = std::collections::HashMap::new(); for run in runs { if let Some(info) = undo_info(&conn, run)? { infos.insert(run.id.clone(), info); } } Ok(infos) } /// The restore this undo puts back: the run whose restore took the safety copy that `run` restores. pub fn undo_parent(&self, run: &RefreshRun) -> Result> { let Some(safety) = run.snapshot_id.as_deref().filter(|_| run.is_undo()) else { return Ok(None); }; let conn = self.conn.lock().unwrap(); Ok(conn .query_row( "SELECT r.id FROM refresh_runs r JOIN restore_jobs j ON j.id = r.restore_job_id WHERE j.safety_id = ?1 AND r.target_id = ?2 AND r.id <> ?3", params![safety, run.target_id, run.id], |r| r.get(0), ) .optional()?) } pub fn relation_target(&self, relation: &str) -> Result> { let conn = self.conn.lock().unwrap(); Ok(relation_of(&conn, relation)?.map(|r| r.target_id)) } pub fn relation_source_orbit(&self, relation: &str) -> Result> { let conn = self.conn.lock().unwrap(); Ok(relation_of(&conn, relation)?.map(|r| r.source_orbit_id)) } } pub fn confirmation_text(source: &str, target: &str, version: i64) -> String { format!("REFRESH {source} TO {target} v{version}") } pub(super) fn migrate(conn: &Connection) -> Result<()> { conn.execute_batch( "CREATE TABLE IF NOT EXISTS refresh_runs ( id TEXT PRIMARY KEY, relation_id TEXT NOT NULL, relation_version INTEGER NOT NULL, source_orbit_id TEXT NOT NULL, source_application_id TEXT NOT NULL, target_id TEXT NOT NULL, requester TEXT NOT NULL, requester_user_id TEXT, authorized_by TEXT NOT NULL, idempotency_key TEXT NOT NULL, status TEXT NOT NULL CHECK(status IN ('capturing','restoring','recovery_required','completed','capture_failed', 'restore_failed','blocked','cancelled','expired','reconciled')), blocked_reason TEXT, capture_job_id TEXT NOT NULL UNIQUE, snapshot_id TEXT, restore_job_id TEXT UNIQUE, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL, expires_at INTEGER NOT NULL, UNIQUE(requester, idempotency_key) ); CREATE UNIQUE INDEX IF NOT EXISTS refresh_runs_one_active_per_target ON refresh_runs(target_id) WHERE status IN ('capturing','restoring','recovery_required'); CREATE INDEX IF NOT EXISTS refresh_runs_recent ON refresh_runs(created_at);", )?; Ok(()) } fn get(conn: &Connection, id: &str) -> Result> { Ok(conn .query_row( &format!("SELECT {COLUMNS} FROM refresh_runs WHERE id=?1"), params![id], read_run, ) .optional()?) } /// The run that owns a restore job, if the job was queued by a refresh. Admin restores have none. pub(super) fn run_for_restore(conn: &Connection, restore_job: &str) -> Result> { Ok(conn .query_row( &format!("SELECT {COLUMNS} FROM refresh_runs WHERE restore_job_id=?1"), params![restore_job], read_run, ) .optional()?) } fn relation_of(conn: &Connection, id: &str) -> Result> { Ok(conn .query_row( &format!("SELECT {RELATION_COLUMNS} FROM orbit_relations WHERE id=?1"), params![id], read_relation, ) .optional()?) } fn names(conn: &Connection, relation: &Relation) -> rusqlite::Result<(String, String)> { let source: String = conn .query_row( "SELECT name FROM orbits WHERE id=?1", params![relation.source_orbit_id], |r| r.get(0), ) .optional()? .unwrap_or_default(); let target_profile: Option = conn .query_row( "SELECT profile FROM restore_targets WHERE id=?1", params![relation.target_id], |r| r.get(0), ) .optional()?; let target = target_profile .and_then(|p| serde_json::from_str::(&p).ok()) .and_then(|p| p["name"].as_str().map(str::to_string)) .unwrap_or_default(); Ok((source, target)) } /// Why this run must not go on, if anything has changed since it was started. Nothing here is cached: /// the relation, the requester and the grant that authorised the run are read again each time. pub(super) fn invalid_reason( conn: &Connection, run: &RefreshRun, now: i64, ) -> Result> { let Some(relation) = relation_of(conn, &run.relation_id)? else { return Ok(Some("relation_ended")); }; if !relation.active { return Ok(Some("relation_ended")); } if unusable(conn, &relation, now)?.is_some() { return Ok(Some("relation_unusable")); } if let Some(user) = &run.requester_user_id { let active: bool = conn.query_row( "SELECT EXISTS(SELECT 1 FROM users WHERE id=?1 AND active=1)", params![user], |r| r.get(0), )?; if !active { return Ok(Some("user_disabled")); } } if let Some(grant) = run.authorized_by.strip_prefix("grant:") { let alive: bool = conn.query_row( "SELECT EXISTS(SELECT 1 FROM relation_grants WHERE id=?1 AND relation_id=?2 AND (expires_at IS NULL OR expires_at > ?3))", params![grant, run.relation_id, now], |r| r.get(0), )?; if !alive { return Ok(Some("access_revoked")); } } if now >= run.expires_at { return Ok(Some("expired")); } Ok(None) } fn finish( conn: &Connection, run: &str, status: &str, reason: Option<&str>, now: i64, ) -> Result<()> { conn.execute( "UPDATE refresh_runs SET status=?2, blocked_reason=?3, updated_at=?4 WHERE id=?1 AND status IN ('capturing','restoring','recovery_required')", params![run, status, reason, now], )?; Ok(()) } /// Stop a run that is no longer allowed to continue. A restore that has not started applying is cancelled; /// one that has is left to finish (a half-applied restore must be finished or reconciled, not abandoned). pub(super) fn block(conn: &Connection, run: &RefreshRun, reason: &str, now: i64) -> Result<()> { if let Some(job) = &run.restore_job_id { conn.execute( "UPDATE restore_jobs SET status='cancelled', phase='cancelled', updated_at=?2 WHERE id=?1 AND status IN ('queued','running')", params![job, now], )?; } finish( conn, &run.id, if reason == "expired" { "expired" } else { "blocked" }, Some(reason), now, ) } fn restore_status(conn: &Connection, job: &str) -> Result> { Ok(conn .query_row( "SELECT status FROM restore_jobs WHERE id=?1", params![job], |r| r.get(0), ) .optional()?) } impl Db { /// Start a run. Returns the run and whether it was newly created (`false` = the same idempotency key /// from the same requester, so the existing run is returned and nothing else happens). #[allow(clippy::too_many_arguments)] pub fn create_refresh_run( &self, relation_id: &str, confirmation: &str, requester: &str, requester_user_id: Option<&str>, authorized_by: &str, idempotency_key: &str, // a snapshot to restore instead of capturing one, and the run it undoes when it is the safety copy of one snapshot: Option<(Uuid, Option<&str>)>, ttl_secs: i64, max_active: i64, now: i64, ) -> Result> { let mut conn = self.conn.lock().unwrap(); let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?; let result = (|| -> Result> { let existing: Option = tx .query_row(&format!("SELECT {COLUMNS} FROM refresh_runs WHERE requester=?1 AND idempotency_key=?2"), params![requester, idempotency_key], read_run) .optional()?; if let Some(run) = existing { return Ok(if run.relation_id == relation_id { Ok((run, false)) } else { Err(StartError::KeyReused) }); } let Some(relation) = relation_of(&tx, relation_id)?.filter(|r| r.active) else { return Ok(Err(StartError::UnknownRelation)); }; if let Some(reason) = unusable(&tx, &relation, now)? { return Ok(Err(StartError::Unusable(reason))); } let (source, target) = names(&tx, &relation)?; if confirmation != confirmation_text(&source, &target, relation.version) { return Ok(Err(StartError::StaleConfirmation)); } let undoing = snapshot.and_then(|(_, of)| of); // The run being undone does not count as busy: if its apply failed, undoing it is how it is recovered. let busy: Option = tx .query_row("SELECT id FROM refresh_runs WHERE target_id=?1 AND status IN ('capturing','restoring','recovery_required') AND id IS NOT ?2", params![relation.target_id, undoing], |r| r.get(0)) .optional()?; if let Some(id) = busy { return Ok(Err(StartError::TargetBusy(id))); } let running: i64 = tx.query_row("SELECT COUNT(*) FROM refresh_runs WHERE status IN ('capturing','restoring','recovery_required')", [], |r| r.get(0))?; if running >= max_active { return Ok(Err(StartError::TooManyRuns)); } if let Some((safety, Some(of))) = snapshot { // Checked again inside this transaction: what was true when the request was read may not be now. if !matches!(undo_check(&tx, of, relation_id)?, Ok(found) if found == safety) { return Ok(Err(StartError::NothingToUndo)); } if let Some(parent) = get(&tx, of)?.filter(|r| r.status == "recovery_required") { // The failed apply no longer fences the target: this undo takes over from it, and puts back what // the restore replaced. What it leaves behind is kept as this undo's own safety copy. if let Some(job) = &parent.restore_job_id { tx.execute( "UPDATE restore_jobs SET status='reconciled', phase='rolled_back', updated_at=?2 WHERE id=?1 AND status='recovery_required' AND phase='apply_failed'", params![job, now], )?; } finish(&tx, &parent.id, "reconciled", None, now)?; tx.execute( "INSERT INTO audit_log(at, event, detail) VALUES (datetime('now'), 'restore.rolled_back', ?1)", params![format!("run={} by={requester}", parent.id)], )?; } } 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((_, Some(_))) => format!("{UNDO}{id}"), Some((_, None)) => format!("{EXISTING}{id}"), None => { let application = Uuid::parse_str(&relation.source_application_id)?; let Some(capture) = super::jobs::insert_capture_job(&tx, application, requester, now)? else { return Ok(Err(StartError::SourceUnavailable)); }; capture.to_string() } }; tx.execute( "INSERT INTO refresh_runs(id,relation_id,relation_version,source_orbit_id,source_application_id,target_id,requester,requester_user_id, authorized_by,idempotency_key,status,capture_job_id,snapshot_id,created_at,updated_at,expires_at) VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,'capturing',?11,?12,?13,?13,?14)", params![id, relation.id, relation.version, relation.source_orbit_id, relation.source_application_id, relation.target_id, requester, requester_user_id, authorized_by, idempotency_key, capture, snapshot.map(|(s, _)| s.to_string()), now, now + ttl_secs], )?; Ok(Ok((get(&tx, &id)?.expect("just inserted"), true))) })()?; if result.is_ok() { tx.commit()?; } Ok(result) } pub fn refresh_run(&self, id: &str) -> Result> { get(&self.conn.lock().unwrap(), id) } /// Runs still in progress, oldest first. pub fn active_refresh_runs(&self) -> Result> { let conn = self.conn.lock().unwrap(); let mut stmt = conn.prepare(&format!("SELECT {COLUMNS} FROM refresh_runs WHERE status IN ('capturing','restoring','recovery_required') ORDER BY created_at"))?; let rows = stmt .query_map([], read_run)? .collect::>()?; Ok(rows) } /// Recent runs (all of them, or only those of one requester / a set of relations), newest first. pub fn refresh_runs( &self, requester_user: Option<&str>, relations: Option<&[String]>, limit: i64, ) -> Result> { let conn = self.conn.lock().unwrap(); let mut stmt = conn.prepare(&format!( "SELECT {COLUMNS} FROM refresh_runs WHERE (?1 IS NULL AND ?2 IS NULL) OR requester_user_id = ?1 OR relation_id IN (SELECT value FROM json_each(?2)) ORDER BY created_at DESC, rowid DESC LIMIT ?3" ))?; let relations_json = relations.map(serde_json::to_string).transpose()?; let rows = stmt .query_map(params![requester_user, relations_json, limit], read_run)? .collect::>()?; Ok(rows) } /// Everything the status screens need about a run, with the capture and restore job state it follows. pub fn refresh_progress(&self, run: &RefreshRun) -> Result { let conn = self.conn.lock().unwrap(); let capture: Option<(String, String, i64)> = conn .query_row( "SELECT status, phase, updated_at FROM capture_jobs WHERE id=?1", params![run.capture_job_id], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)), ) .optional()?; let restore: Option<(String, String)> = match &run.restore_job_id { Some(job) => conn .query_row( "SELECT status, phase FROM restore_jobs WHERE id=?1", params![job], |r| Ok((r.get(0)?, r.get(1)?)), ) .optional()?, None => None, }; let relation = relation_of(&conn, &run.relation_id)?; let (source_name, target_name) = match &relation { Some(r) => names(&conn, r)?, None => Default::default(), }; Ok(Progress { capture_status: capture.as_ref().map(|c| c.0.clone()), capture_phase: capture.as_ref().map(|c| c.1.clone()), snapshot_taken_at: capture.filter(|c| c.0 == "completed").map(|c| c.2), restore_status: restore.as_ref().map(|r| r.0.clone()), restore_phase: restore.map(|r| r.1), source_name, target_name, }) } /// Advance one run by looking at what its jobs and its authorisation say now. Idempotent. pub fn sync_refresh_run(&self, id: &str, now: i64) -> Result { let mut conn = self.conn.lock().unwrap(); let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?; let outcome = sync_in(&tx, id, now)?; tx.commit()?; Ok(outcome) } /// Queue the restore of the run's own snapshot. Everything is checked again inside the transaction, the /// restore job is linked only if the run does not have one yet, and a second call changes nothing. pub fn enqueue_refresh_restore( &self, id: &str, artifact: &RestoreArtifact, identity_clash: bool, now: i64, ) -> Result { let mut conn = self.conn.lock().unwrap(); let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?; let outcome = (|| -> Result { let Some(run) = get(&tx, id)? else { return Ok(Linked::NotReady); }; if run.status != "capturing" || run.restore_job_id.is_some() { return Ok(Linked::NotReady); } let snapshot = if picked_snapshot(&run) { let Some(snapshot) = run.snapshot_id.clone() else { return Ok(Linked::NotReady); }; snapshot } else { let capture: Option<(String, Option)> = tx .query_row( "SELECT status, snapshot_id FROM capture_jobs WHERE id=?1", params![run.capture_job_id], |r| Ok((r.get(0)?, r.get(1)?)), ) .optional()?; let Some((_, Some(snapshot))) = capture.filter(|c| c.0 == "completed") else { return Ok(Linked::NotReady); }; snapshot }; if let Some(reason) = invalid_reason(&tx, &run, now)? { block(&tx, &run, reason, now)?; return Ok(Linked::Blocked(reason)); } if identity_clash { block(&tx, &run, "target_matches_a_production_source", now)?; return Ok(Linked::Blocked("target_matches_a_production_source")); } let snapshot = Uuid::parse_str(&snapshot)?; let job = super::restore::enqueue_restore_in( &tx, snapshot, Uuid::parse_str(&run.source_application_id)?, Uuid::parse_str(&run.target_id)?, &run.requester, artifact, now, )?; let Some(job) = job else { block(&tx, &run, "target_rejected", now)?; return Ok(Linked::Blocked("target_rejected")); }; let changed = tx.execute( "UPDATE refresh_runs SET status='restoring', snapshot_id=?2, restore_job_id=?3, updated_at=?4 WHERE id=?1 AND status='capturing' AND restore_job_id IS NULL", params![run.id, snapshot.to_string(), job.id.to_string(), now], )?; if changed != 1 { return Ok(Linked::NotReady); } Ok(Linked::Queued(job.id.to_string())) })()?; tx.commit()?; Ok(outcome) } /// Stop a run for a reason found outside the database (for example its snapshot cannot be restored). pub fn block_refresh_run(&self, id: &str, reason: &str, now: i64) -> Result<()> { let mut conn = self.conn.lock().unwrap(); let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?; if let Some(run) = get(&tx, id)? { block(&tx, &run, reason, now)?; } tx.commit()?; Ok(()) } /// Cancel a run before anything has been applied. `Err` carries why it could not be. pub fn cancel_refresh_run( &self, id: &str, now: i64, ) -> Result> { let mut conn = self.conn.lock().unwrap(); let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?; let result = (|| -> Result> { let Some(run) = get(&tx, id)? else { return Ok(Err(CancelError::Unknown)); }; if !ACTIVE.contains(&run.status.as_str()) || run.status == "recovery_required" { return Ok(Err(CancelError::TooLate)); } if let Some(job) = &run.restore_job_id { match restore_status(&tx, job)?.as_deref() { Some("applying") | Some("recovery_required") | Some("completed") => { return Ok(Err(CancelError::TooLate)) } _ => {} } } if let Some(job) = &run.restore_job_id { tx.execute("UPDATE restore_jobs SET status='cancelled', phase='cancelled', updated_at=?2 WHERE id=?1 AND status IN ('queued','running')", params![job, now])?; } finish(&tx, &run.id, "cancelled", None, now)?; Ok(Ok(get(&tx, id)?.expect("exists"))) })()?; tx.commit()?; Ok(result) } } #[derive(Debug, PartialEq, Eq)] pub enum CancelError { Unknown, TooLate, } #[derive(Debug, PartialEq, Eq)] pub enum Linked { Queued(String), Blocked(&'static str), /// Nothing to do: not at that step yet, or it was already done. NotReady, } #[derive(Debug, PartialEq, Eq)] pub enum Sync { Unchanged, /// The run moved to this status. Moved(String), /// The capture finished; the caller must now read the snapshot and call `enqueue_refresh_restore`. NeedRestore(String), } #[derive(Clone, Debug, serde::Serialize)] pub struct Progress { pub capture_status: Option, pub capture_phase: Option, pub snapshot_taken_at: Option, pub restore_status: Option, pub restore_phase: Option, pub source_name: String, pub target_name: String, } fn sync_in(tx: &Transaction<'_>, id: &str, now: i64) -> Result { let Some(run) = get(tx, id)? else { return Ok(Sync::Unchanged); }; if !ACTIVE.contains(&run.status.as_str()) { return Ok(Sync::Unchanged); } let restore = match &run.restore_job_id { Some(job) => restore_status(tx, job)?, None => None, }; // Until the restore starts applying, any change in what authorised the run stops it. let past_the_point_of_no_return = matches!( restore.as_deref(), Some("applying" | "recovery_required" | "completed" | "failed" | "reconciled") ); if !past_the_point_of_no_return { if let Some(reason) = invalid_reason(tx, &run, now)? { block(tx, &run, reason, now)?; return Ok(Sync::Moved( if reason == "expired" { "expired" } else { "blocked" } .into(), )); } } let move_to = |status: &str| -> Result { finish(tx, &run.id, status, None, now)?; Ok(Sync::Moved(status.into())) }; match run.status.as_str() { "capturing" if picked_snapshot(&run) => { // Nothing to capture: the snapshot was chosen when the run was started. match (&run.snapshot_id, &run.restore_job_id) { (Some(snapshot), None) => Ok(Sync::NeedRestore(snapshot.clone())), _ => Ok(Sync::Unchanged), } } "capturing" => { let capture: Option<(String, Option)> = tx .query_row( "SELECT status, snapshot_id FROM capture_jobs WHERE id=?1", params![run.capture_job_id], |r| Ok((r.get(0)?, r.get(1)?)), ) .optional()?; match capture { Some((status, _)) if status == "failed" => move_to("capture_failed"), Some((status, Some(snapshot))) if status == "completed" && run.restore_job_id.is_none() => { Ok(Sync::NeedRestore(snapshot)) } None => move_to("capture_failed"), _ => Ok(Sync::Unchanged), } } "restoring" | "recovery_required" => match restore.as_deref() { Some("completed") => move_to("completed"), Some("failed") => move_to("restore_failed"), Some("cancelled") => move_to("cancelled"), Some("reconciled") => move_to("reconciled"), Some("recovery_required") if run.status == "restoring" => move_to("recovery_required"), None => move_to("restore_failed"), _ => Ok(Sync::Unchanged), }, _ => Ok(Sync::Unchanged), } }