//! 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, } /// What the confirmation must say: it names exactly what the person saw, including the version. 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, 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 busy: Option = tx .query_row("SELECT id FROM refresh_runs WHERE target_id=?1 AND status IN ('capturing','restoring','recovery_required')", params![relation.target_id], |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)); } 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(); tx.execute( "INSERT INTO refresh_runs(id,relation_id,relation_version,source_orbit_id,source_application_id,target_id,requester,requester_user_id, authorized_by,idempotency_key,status,capture_job_id,created_at,updated_at,expires_at) VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,'capturing',?11,?12,?12,?13)", 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], )?; 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 capture: Option<(String, Option)> = tx .query_row("SELECT status, snapshot_id FROM capture_jobs WHERE id=?1", params![run.capture_job_id], |r| Ok((r.get(0)?, r.get(1)?))) .optional()?; let Some((status, Some(snapshot))) = capture.filter(|c| c.0 == "completed") else { return Ok(Linked::NotReady) }; let _ = status; 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" => { 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), } }