use super::{jobs::invalid_column, *}; use rusqlite::{Row, Transaction, TransactionBehavior}; use tessera_core::{ job::CAPTURE_LEASE_SECONDS, restore::{RestoreArtifact, RestoreJob, RestoreLease, RestoreProgress, RestoreTarget}, }; pub(super) fn migrate(conn: &Connection) -> Result<()> { conn.execute_batch( "CREATE TABLE IF NOT EXISTS restore_targets ( id TEXT PRIMARY KEY, application_id TEXT NOT NULL, outpost_id TEXT NOT NULL, identity TEXT NOT NULL UNIQUE, profile TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS restore_jobs ( id TEXT PRIMARY KEY, snapshot_id TEXT NOT NULL, target_id TEXT NOT NULL, actor TEXT NOT NULL, artifact TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'queued', phase TEXT NOT NULL DEFAULT 'queued', created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL, lease_token TEXT, lease_until INTEGER, attempt_safety_id TEXT, safety_id TEXT ); CREATE INDEX IF NOT EXISTS restore_jobs_target ON restore_jobs(target_id, status); CREATE INDEX IF NOT EXISTS restore_jobs_snapshot ON restore_jobs(snapshot_id, safety_id, status);", )?; Ok(()) } const VIEW: &str = "SELECT j.id, j.snapshot_id, t.profile, j.actor, j.status, j.phase, j.safety_id, j.created_at, j.updated_at, j.artifact, j.attempt_safety_id FROM restore_jobs j JOIN restore_targets t ON t.id = j.target_id"; fn uuid(row: &Row<'_>, index: usize) -> rusqlite::Result { Uuid::parse_str(&row.get::<_, String>(index)?).map_err(|err| invalid_column(index, err)) } fn json(row: &Row<'_>, index: usize) -> rusqlite::Result { serde_json::from_str(&row.get::<_, String>(index)?).map_err(|err| invalid_column(index, err)) } fn read_job(row: &Row<'_>) -> rusqlite::Result { Ok(RestoreJob { id: uuid(row, 0)?, snapshot_id: uuid(row, 1)?, target: json(row, 2)?, actor: row.get(3)?, status: row.get(4)?, phase: row.get(5)?, safety_snapshot_id: row .get::<_, Option>(6)? .map(|id| Uuid::parse_str(&id)) .transpose() .map_err(|err| invalid_column(6, err))?, created_at: row.get(7)?, updated_at: row.get(8)?, }) } pub(crate) fn restore_target_mismatch( target: &RestoreTarget, artifact: &RestoreArtifact, ) -> Option<&'static str> { if Some(target.engine) != artifact.format.engine() { Some("Database engine differs from the snapshot") } else if target.identity == artifact.identity { Some("Target is the source database") } else { None } } impl Db { pub fn register_restore_target(&self, target: &RestoreTarget) -> Result { let conn = self.conn.lock().unwrap(); let changed = conn.execute( "INSERT INTO restore_targets(id, application_id, outpost_id, identity, profile) SELECT ?1, ?2, ?3, ?4, ?5 WHERE EXISTS (SELECT 1 FROM capture_profiles WHERE application_id = ?2) AND EXISTS (SELECT 1 FROM outpost_credentials WHERE outpost_id = ?3 AND state = 'active' AND expires_at > ?6) ON CONFLICT DO NOTHING", params![ target.id.to_string(), target.application_id.to_string(), target.outpost_id.to_string(), serde_json::to_string(&(target.engine, &target.identity))?, serde_json::to_string(target)?, chrono::Utc::now().timestamp(), ], )?; Ok(changed == 1) } pub fn restore_targets(&self, application: Uuid) -> Result> { Ok(self.restore_targets_with_activity(application)? .into_iter().map(|(target, _)| target).collect()) } pub fn restore_targets_with_activity(&self, application: Uuid) -> Result> { let conn = self.conn.lock().unwrap(); let mut stmt = conn.prepare( "SELECT t.profile, EXISTS (SELECT 1 FROM outpost_credentials WHERE outpost_id = t.outpost_id AND state = 'active' AND expires_at > ?2) FROM restore_targets t WHERE t.application_id = ?1 ORDER BY t.id", )?; let rows = stmt.query_map(params![application.to_string(), chrono::Utc::now().timestamp()], |row| Ok((json(row, 0)?, row.get(1)?)))?; Ok(rows.collect::>()?) } pub fn enqueue_restore( &self, snapshot: Uuid, application: Uuid, target: Uuid, actor: &str, artifact: &RestoreArtifact, now: i64, ) -> Result> { let mut conn = self.conn.lock().unwrap(); let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?; let registered: Option = tx.query_row( "SELECT t.profile FROM restore_targets t WHERE t.id = ?1 AND t.application_id = ?2 AND EXISTS (SELECT 1 FROM outpost_credentials WHERE outpost_id = t.outpost_id AND state = 'active' AND expires_at > ?3)", params![target.to_string(), application.to_string(), now], |row| json(row, 0), ).optional()?; let Some(registered) = registered else { return Ok(None); }; if restore_target_mismatch(®istered, artifact).is_some() { return Ok(None); } let id = Uuid::new_v4(); tx.execute( "INSERT INTO restore_jobs(id, snapshot_id, target_id, actor, artifact, created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?6)", params![id.to_string(), snapshot.to_string(), target.to_string(), actor, serde_json::to_string(artifact)?, now], )?; audit( &tx, "restore.queued", &format!("actor={actor} job={id} snapshot={snapshot} target={target}"), )?; let job = tx.query_row( &format!("{VIEW} WHERE j.id = ?1"), [id.to_string()], read_job, )?; tx.commit()?; Ok(Some(job)) } pub fn restore_job(&self, id: Uuid, now: i64) -> Result> { let conn = self.conn.lock().unwrap(); expire_destructive(&conn, now)?; Ok(conn .query_row( &format!("{VIEW} WHERE j.id = ?1"), [id.to_string()], read_job, ) .optional()?) } pub fn restore_history(&self, snapshot: Uuid, now: i64) -> Result> { let conn = self.conn.lock().unwrap(); expire_destructive(&conn, now)?; let mut stmt = conn.prepare(&format!( "{VIEW} WHERE j.snapshot_id = ?1 ORDER BY j.rowid DESC LIMIT 25" ))?; let rows = stmt.query_map([snapshot.to_string()], read_job)?; Ok(rows.collect::>()?) } /// The newest restore jobs across every snapshot, newest first, for the activity log. pub fn restore_recent(&self, limit: u32, now: i64) -> Result> { let conn = self.conn.lock().unwrap(); expire_destructive(&conn, now)?; let mut stmt = conn.prepare(&format!("{VIEW} ORDER BY j.rowid DESC LIMIT ?1"))?; let rows = stmt.query_map([limit], read_job)?; Ok(rows.collect::>()?) } pub fn snapshot_in_restore(&self, id: Uuid) -> Result { let conn = self.conn.lock().unwrap(); Ok(conn.query_row( "SELECT EXISTS(SELECT 1 FROM restore_jobs WHERE (snapshot_id = ?1 OR safety_id = ?1 OR attempt_safety_id = ?1) AND status IN ('queued','running','applying','recovery_required'))", [id.to_string()], |row| row.get(0), )?) } pub fn claim_restore( &self, outpost: Uuid, target: Uuid, now: i64, ) -> Result> { let mut conn = self.conn.lock().unwrap(); let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?; expire_destructive(&tx, now)?; let selected = tx.query_row( &format!("{VIEW} WHERE t.id = ?1 AND t.outpost_id = ?2 AND (j.status = 'queued' OR (j.status = 'running' AND j.lease_until <= ?3)) AND NOT EXISTS ( SELECT 1 FROM restore_jobs active JOIN restore_targets owner ON owner.id = active.target_id WHERE owner.application_id = t.application_id AND (active.status IN ('applying','recovery_required') OR (active.status = 'running' AND active.lease_until > ?3)) ) AND NOT EXISTS ( SELECT 1 FROM capture_jobs c WHERE c.application_id = t.application_id AND c.status = 'running' AND c.lease_until > ?3 ) ORDER BY j.created_at, j.rowid LIMIT 1"), params![target.to_string(), outpost.to_string(), now], |row| Ok((read_job(row)?, json(row, 9)?)), ).optional()?; let Some((mut job, artifact)) = selected else { tx.commit()?; return Ok(None); }; let token = Uuid::new_v4(); tx.execute( "UPDATE restore_jobs SET status = 'running', phase = 'claimed', lease_token = ?2, lease_until = ?3, attempt_safety_id = ?4, safety_id = NULL, updated_at = ?5 WHERE id = ?1", params![job.id.to_string(), token.to_string(), now + CAPTURE_LEASE_SECONDS, Uuid::new_v4().to_string(), now], )?; job.status = "running".into(); job.phase = "claimed".into(); job.safety_snapshot_id = None; job.updated_at = now; tx.commit()?; Ok(Some(RestoreLease { job, token, artifact, })) } pub fn restore_access( &self, outpost: Uuid, id: Uuid, token: Uuid, now: i64, ) -> Result> { restore_access(&self.conn.lock().unwrap(), outpost, id, token, now) } pub fn record_safety( &self, outpost: Uuid, id: Uuid, token: Uuid, now: i64, publish: impl FnOnce(Uuid) -> Result<()>, ) -> Result> { let mut conn = self.conn.lock().unwrap(); let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?; let Some((job, _, expected)) = restore_access(&tx, outpost, id, token, now)? else { return Ok(None); }; if job.status != "running" { return Ok(None); } if let Some(safety) = job.safety_snapshot_id { return Ok(Some(safety)); } if job.phase != "safety" { return Ok(None); } publish(expected)?; tx.execute("UPDATE restore_jobs SET phase = 'ready', safety_id = ?2, updated_at = ?3 WHERE id = ?1", params![id.to_string(), expected.to_string(), now])?; audit( &tx, "restore.safety_committed", &format!("job={id} snapshot={expected}"), )?; tx.commit()?; Ok(Some(expected)) } pub fn authorize_apply(&self, outpost: Uuid, id: Uuid, token: Uuid, now: i64) -> Result { let mut conn = self.conn.lock().unwrap(); let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?; let Some((job, _, _)) = restore_access(&tx, outpost, id, token, now)? else { return Ok(false); }; if job.status != "running" || job.phase != "ready" || job.safety_snapshot_id.is_none() { return Ok(false); } tx.execute("UPDATE restore_jobs SET status = 'applying', phase = 'applying', updated_at = ?2, lease_until = ?3 WHERE id = ?1", params![id.to_string(), now, now + CAPTURE_LEASE_SECONDS])?; audit( &tx, "restore.apply_authorized", &format!("job={id} target={}", job.target.id), )?; tx.commit()?; Ok(true) } pub fn report_restore( &self, outpost: Uuid, id: Uuid, token: Uuid, progress: RestoreProgress, now: i64, ) -> Result { let mut conn = self.conn.lock().unwrap(); let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?; let Some((job, _, _)) = restore_access(&tx, outpost, id, token, now)? else { return Ok(false); }; let (status, phase) = match progress { RestoreProgress::Heartbeat => (job.status.as_str(), job.phase.as_str()), RestoreProgress::Checking if job.phase == "claimed" => ("running", "checking"), RestoreProgress::Safety if job.phase == "checking" => ("running", "safety"), RestoreProgress::InvalidPayload if job.phase == "checking" => { ("failed", "invalid_payload") } RestoreProgress::WrongTarget if job.phase == "checking" => ("failed", "wrong_target"), RestoreProgress::SafetyFailed if matches!(job.phase.as_str(), "safety" | "ready") => { ("failed", "safety_failed") } RestoreProgress::Applied if job.status == "applying" => ("completed", "completed"), RestoreProgress::ApplyFailed if job.status == "applying" => { ("recovery_required", "apply_failed") } _ => return Ok(false), }; tx.execute("UPDATE restore_jobs SET status = ?2, phase = ?3, updated_at = ?4, lease_until = ?5 WHERE id = ?1", params![id.to_string(), status, phase, now, now + CAPTURE_LEASE_SECONDS])?; if !matches!(progress, RestoreProgress::Heartbeat) { audit(&tx, "restore.phase", &format!("job={id} phase={phase}"))?; } tx.commit()?; Ok(true) } pub fn reconcile_restore(&self, id: Uuid, actor: &str, now: i64) -> Result { let mut conn = self.conn.lock().unwrap(); let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?; expire_destructive(&tx, now)?; let changed = tx.execute( "UPDATE restore_jobs SET status = 'reconciled', phase = 'reconciled', updated_at = ?2 WHERE id = ?1 AND status = 'recovery_required'", params![id.to_string(), now], )?; if changed == 1 { audit( &tx, "restore.reconciled", &format!("actor={actor} job={id}"), )?; } tx.commit()?; Ok(changed == 1) } pub fn cancel_restore(&self, id: Uuid, actor: &str, now: i64) -> Result { let mut conn = self.conn.lock().unwrap(); let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?; let changed = tx.execute( "UPDATE restore_jobs SET status = 'cancelled', phase = 'cancelled', updated_at = ?2 WHERE id = ?1 AND status IN ('queued','running')", params![id.to_string(), now], )?; if changed == 1 { audit(&tx, "restore.cancelled", &format!("actor={actor} job={id}"))?; } tx.commit()?; Ok(changed == 1) } } fn restore_access( conn: &Connection, outpost: Uuid, id: Uuid, token: Uuid, now: i64, ) -> Result> { Ok(conn .query_row( &format!( "{VIEW} WHERE j.id = ?1 AND t.outpost_id = ?2 AND j.lease_token = ?3 AND j.lease_until > ?4 AND j.status IN ('running', 'applying')" ), params![id.to_string(), outpost.to_string(), token.to_string(), now], |row| Ok((read_job(row)?, json(row, 9)?, uuid(row, 10)?)), ) .optional()?) } fn expire_destructive(conn: &Connection, now: i64) -> Result<()> { conn.execute( "UPDATE restore_jobs SET status = 'recovery_required', phase = 'lease_lost', updated_at = ?1 WHERE status = 'applying' AND lease_until <= ?1", [now], )?; Ok(()) } fn audit(tx: &Transaction<'_>, event: &str, detail: &str) -> Result<()> { tx.execute( "INSERT INTO audit_log(at, event, detail) VALUES (datetime('now'), ?1, ?2)", params![event, detail], )?; Ok(()) } #[cfg(test)] mod tests { use super::*; use tessera_core::{ job::{CaptureFormat, CaptureProfile}, restore::{DatabaseIdentity, Engine}, }; #[tokio::test] async fn expired_apply_survives_restart_and_fences_the_target_until_reconciled() { let root = tempfile::tempdir().unwrap(); let path = root.path().join("restore.db"); let db = Db::connect(&path).await.unwrap(); db.migrate().await.unwrap(); let outpost = Uuid::new_v4(); db.insert_test_credential("synthetic-token", &outpost.to_string(), "agent"); let orbit = Uuid::new_v4(); db.upsert_orbit(&OrbitRow { id: orbit, name: "fixture".into(), provider: "wormhole".into(), provider_config: "{}".into(), schedule: None, decay_preset: "week-of-dailies".into(), retention: None, dry_run: false, last_status: "idle".into(), }) .await .unwrap(); let app = Uuid::new_v4(); assert!(db .register_capture_profile( &CaptureProfile { application_id: app, orbit_id: orbit, outpost_id: outpost, format: CaptureFormat::PostgresCustom, schedule: None, retention: None, }, 100 ) .unwrap()); let target = Uuid::new_v4(); assert!(db .register_restore_target(&RestoreTarget { id: target, application_id: app, outpost_id: outpost, name: "target".into(), engine: Engine::Postgres, identity: DatabaseIdentity { instance: "123".into(), database: "target".into() }, }) .unwrap()); let snapshot = Uuid::new_v4(); let artifact = RestoreArtifact { format: CaptureFormat::PostgresCustom, sha256: "0".repeat(64), identity: DatabaseIdentity { instance: "123".into(), database: "source".into(), }, }; let registered = db.restore_targets_with_activity(app).unwrap().pop().unwrap(); assert!(registered.1); let same_source = RestoreArtifact { identity: registered.0.identity.clone(), ..artifact.clone() }; assert_eq!(restore_target_mismatch(®istered.0, &same_source), Some("Target is the source database")); assert!(db.enqueue_restore(snapshot, app, target, "fixture", &same_source, 100).unwrap().is_none()); let job = db .enqueue_restore(snapshot, app, target, "fixture", &artifact, 100) .unwrap() .unwrap(); let next_snapshot = Uuid::new_v4(); let next = db .enqueue_restore(next_snapshot, app, target, "fixture", &artifact, 101) .unwrap() .unwrap(); let lease = db.claim_restore(outpost, target, 102).unwrap().unwrap(); assert_eq!(lease.job.id, job.id); assert!(db.claim_restore(outpost, target, 103).unwrap().is_none()); assert!(db.snapshot_in_restore(snapshot).unwrap()); assert!(!db .authorize_apply(outpost, job.id, lease.token, 104) .unwrap()); assert!(db .report_restore(outpost, job.id, lease.token, RestoreProgress::Checking, 104) .unwrap()); assert!(db .report_restore(outpost, job.id, lease.token, RestoreProgress::Safety, 105) .unwrap()); assert!(db .record_safety(outpost, job.id, lease.token, 106, |_| anyhow::bail!( "synthetic write failure" )) .is_err()); assert!(!db .authorize_apply(outpost, job.id, lease.token, 107) .unwrap()); let safety = db .record_safety(outpost, job.id, lease.token, 108, |_| Ok(())) .unwrap() .unwrap(); assert!(db .authorize_apply(outpost, job.id, lease.token, 109) .unwrap()); assert!(!db .authorize_apply(outpost, job.id, lease.token, 110) .unwrap()); drop(db); let db = Db::connect(&path).await.unwrap(); db.migrate().await.unwrap(); let late = 109 + CAPTURE_LEASE_SECONDS; assert!(db.claim_restore(outpost, target, late).unwrap().is_none()); assert!(db .restore_access(outpost, job.id, lease.token, late) .unwrap() .is_none()); assert!(!db .authorize_apply(outpost, job.id, lease.token, late) .unwrap()); let interrupted = db.restore_job(job.id, late).unwrap().unwrap(); assert_eq!(interrupted.status, "recovery_required"); let recent = db.restore_recent(10, late).unwrap(); assert_eq!(recent.iter().map(|item| item.id).collect::>(), vec![next.id, job.id]); assert_eq!(db.restore_recent(1, late).unwrap().len(), 1); assert_eq!(interrupted.safety_snapshot_id, Some(safety)); assert!(db.snapshot_in_restore(snapshot).unwrap()); assert!(db.snapshot_in_restore(safety).unwrap()); assert!(db.reconcile_restore(job.id, "fixture", late + 1).unwrap()); assert!(!db.snapshot_in_restore(snapshot).unwrap()); assert!(!db.snapshot_in_restore(safety).unwrap()); let retry = db .claim_restore(outpost, target, late + 2) .unwrap() .unwrap(); assert_eq!(retry.job.id, next.id); assert_ne!(retry.token, lease.token); } }