use crate::{ http, jobs::{digest_file, Hub, Source}, }; use anyhow::{ensure, Context, Result}; use serde::Deserialize; use std::{collections::HashMap, fs::File, sync::Arc, time::Duration}; use tessera_core::{ job::{CaptureFormat, CAPTURE_HEARTBEAT_SECONDS}, restore::{DatabaseIdentity, RestoreLease, RestoreProgress}, }; use tessera_providers::{MysqlRestore, PostgresRestore}; use uuid::Uuid; #[derive(Deserialize)] #[serde(tag = "engine", rename_all = "snake_case")] pub(super) enum Target { Postgres(PostgresRestore), Mysql(MysqlRestore), } impl Target { async fn identity(&self) -> Result { match self { Self::Postgres(target) => target.connection.identity().await, Self::Mysql(target) => target.connection.identity().await, } } async fn prepare(&self, input: File, lease: &RestoreLease) -> Result { match (self, lease.artifact.format) { ( Self::Postgres(target), format @ (CaptureFormat::PostgresCustom | CaptureFormat::PostgresSql), ) => { target .prepare(input, format, &lease.job.target.identity) .await } (Self::Mysql(target), CaptureFormat::MysqlSql) => { target.prepare(input, &lease.job.target.identity).await } _ => anyhow::bail!("local restore target engine does not match the assignment"), } } async fn safety(&self, stage: File) -> Result<()> { match self { Self::Postgres(target) => target.connection.safety_dump_to(stage).await, Self::Mysql(target) => target.connection.dump_to(stage).await, } } async fn apply(&self, script: File) -> Result<()> { match self { Self::Postgres(target) => target.apply(script).await, Self::Mysql(target) => target.apply(script).await, } } } pub(super) async fn poll( hub: &Arc, application: Uuid, source: Option<&Source>, targets: &HashMap, timeout_seconds: u64, ) -> Result { for (target_id, target) in targets { let reply = hub .post( format!("restore-targets/{target_id}/claim"), serde_json::Value::Null, None, ) .await?; let Some(lease) = serde_json::from_str::>(&reply)? else { continue; }; ensure!( lease.job.target.id == *target_id && lease.job.target.application_id == application, "hub returned an unexpected restore target" ); let work = run( hub, &lease, target, source, Duration::from_secs(timeout_seconds), ); tokio::pin!(work); loop { tokio::select! { biased; result = &mut work => return result.map(|()| true), _ = tokio::time::sleep(Duration::from_secs(CAPTURE_HEARTBEAT_SECONDS)) => { report(hub, &lease, RestoreProgress::Heartbeat).await?; } } } } Ok(false) } async fn run( hub: &Arc, lease: &RestoreLease, target: &Target, source: Option<&Source>, timeout: Duration, ) -> Result<()> { report(hub, lease, RestoreProgress::Checking).await?; let downloaded = tokio::time::timeout(timeout, async { let input = download(hub, lease, timeout).await?; target.prepare(input, lease).await }) .await; let script = match downloaded { Ok(Ok(script)) => script, _ => { report(hub, lease, RestoreProgress::InvalidPayload).await?; return Ok(()); } }; let verified = tokio::time::timeout(timeout, async { let identity = target.identity().await?; ensure!( identity == lease.job.target.identity && identity != lease.artifact.identity, "restore target identity does not match" ); if let Some(source) = source { if let Ok(Ok(source_identity)) = tokio::time::timeout(Duration::from_secs(10), source.identity()).await { ensure!( source_identity != identity, "target resolves to the local backup source" ); } } Ok::<_, anyhow::Error>(identity) }) .await; let identity = match verified { Ok(Ok(identity)) => identity, _ => { report(hub, lease, RestoreProgress::WrongTarget).await?; return Ok(()); } }; report(hub, lease, RestoreProgress::Safety).await?; let safety = tokio::time::timeout(timeout, async { let stage = tempfile::tempfile().context("create private safety staging")?; target.safety(stage.try_clone()?).await?; ensure!( target.identity().await? == identity, "target changed during safety capture" ); hub.upload( format!("restore/{}/safety", lease.job.id), stage, timeout, "x-tessera-restore-token", lease.token, None, ) .await?; Ok::<_, anyhow::Error>(()) }) .await; if !matches!(safety, Ok(Ok(()))) { report(hub, lease, RestoreProgress::SafetyFailed).await?; return Ok(()); } // The permit is single-use. A lost response leaves the target locked for reconciliation. hub.post( format!("restore/{}/apply", lease.job.id), serde_json::Value::Null, Some(lease.token), ) .await?; let applied = matches!( tokio::time::timeout(timeout, target.apply(script)).await, Ok(Ok(())) ); report( hub, lease, if applied { RestoreProgress::Applied } else { RestoreProgress::ApplyFailed }, ) .await } async fn report(hub: &Arc, lease: &RestoreLease, progress: RestoreProgress) -> Result<()> { hub.post( format!("restore/{}/report", lease.job.id), serde_json::to_value(progress)?, Some(lease.token), ) .await?; Ok(()) } async fn download(hub: &Arc, lease: &RestoreLease, timeout: Duration) -> Result { let hub = hub.clone(); let id = lease.job.id; let token = lease.token.to_string(); let digest = lease.artifact.sha256.clone(); tokio::task::spawn_blocking(move || { let mut file = tempfile::tempfile().context("create private restore staging")?; let size = http::get_file( &format!("{}/api/v1/wormhole/restore/{id}/payload", hub.url), &mut file, &[ ("x-tessera-upload-token", &hub.token), ("x-tessera-restore-token", &token), ], timeout, )?; let (bytes, computed) = digest_file(&mut file)?; ensure!( size == bytes && computed == digest, "restore payload checksum mismatch" ); Ok(file) }) .await? }