From b2d5e4d71a4fcbc0b5f67c016042842c8667c4bb Mon Sep 17 00:00:00 2001 From: Adnan Zahir Date: Mon, 16 Nov 2026 20:55:13 +0700 Subject: [PATCH] test: add trait seams to the agent restore flow (no behaviour change) RestoreTarget, RestoreHub and BackupSource let the destructive restore sequence be driven by fakes. poll takes the heartbeat interval as a parameter instead of reading the constant. Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 1 + crates/tessera-agent/Cargo.toml | 1 + crates/tessera-agent/src/jobs.rs | 12 +- crates/tessera-agent/src/restore.rs | 183 +++++++++++++++++++--------- 4 files changed, 140 insertions(+), 57 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d626b56..d81c6a4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3083,6 +3083,7 @@ name = "tessera-agent" version = "0.1.0" dependencies = [ "anyhow", + "async-trait", "base64 0.22.1", "clap", "hex", diff --git a/crates/tessera-agent/Cargo.toml b/crates/tessera-agent/Cargo.toml index 84a3abb..ff943a5 100644 --- a/crates/tessera-agent/Cargo.toml +++ b/crates/tessera-agent/Cargo.toml @@ -13,6 +13,7 @@ path = "src/main.rs" tessera-core = { path = "../tessera-core" } tessera-providers = { path = "../tessera-providers" } anyhow.workspace = true +async-trait.workspace = true clap.workspace = true serde.workspace = true serde_json.workspace = true diff --git a/crates/tessera-agent/src/jobs.rs b/crates/tessera-agent/src/jobs.rs index b9dbeb2..bf4467d 100644 --- a/crates/tessera-agent/src/jobs.rs +++ b/crates/tessera-agent/src/jobs.rs @@ -46,8 +46,15 @@ pub(super) enum Source { Mysql(MysqlSource), } -impl Source { - pub(super) async fn identity(&self) -> Result { +/// The local backup source, as far as the restore guard cares: which database it is. +#[async_trait::async_trait] +pub(super) trait BackupSource: Sync { + async fn identity(&self) -> Result; +} + +#[async_trait::async_trait] +impl BackupSource for Source { + async fn identity(&self) -> Result { match self { Self::Postgres(source) => source.identity().await, Self::Mysql(source) => source.identity().await, @@ -119,6 +126,7 @@ pub async fn run(cli: &Cli, path: &Path) -> Result<()> { profile.source.as_ref(), &profile.targets, profile.timeout_seconds, + Duration::from_secs(CAPTURE_HEARTBEAT_SECONDS), ) .await?; if !restored && (profile.source.is_some() || !profile.paths.is_empty()) { diff --git a/crates/tessera-agent/src/restore.rs b/crates/tessera-agent/src/restore.rs index 0c0cef8..db4235b 100644 --- a/crates/tessera-agent/src/restore.rs +++ b/crates/tessera-agent/src/restore.rs @@ -1,12 +1,13 @@ use crate::{ http, - jobs::{digest_file, Hub, Source}, + jobs::{digest_file, BackupSource, Hub}, }; use anyhow::{ensure, Context, Result}; +use async_trait::async_trait; use serde::Deserialize; use std::{collections::HashMap, fs::File, sync::Arc, time::Duration}; use tessera_core::{ - job::{CaptureFormat, CAPTURE_HEARTBEAT_SECONDS}, + job::CaptureFormat, restore::{DatabaseIdentity, RestoreLease, RestoreProgress}, }; use tessera_providers::{MysqlRestore, PostgresRestore}; @@ -19,7 +20,108 @@ pub(super) enum Target { Mysql(MysqlRestore), } -impl Target { +/// The local database a restore is applied to. A seam so the destructive sequence in `run` can be driven +/// by fakes in tests; the real implementation is `Target`. +#[async_trait] +pub(super) trait RestoreTarget: Sync { + async fn identity(&self) -> Result; + async fn prepare(&self, input: File, lease: &RestoreLease) -> Result; + async fn safety(&self, stage: File) -> Result<()>; + async fn apply(&self, script: File) -> Result<()>; +} + +/// What the restore flow needs from the hub. A seam for tests; the real implementation is `Arc`. +#[async_trait] +pub(super) trait RestoreHub: Sync { + async fn send( + &self, + path: String, + body: serde_json::Value, + restore: Option, + ) -> Result; + async fn send_with_reason( + &self, + path: String, + body: serde_json::Value, + restore: Uuid, + reason: Option, + ) -> Result; + async fn upload_safety( + &self, + lease: &RestoreLease, + stage: File, + timeout: Duration, + ) -> Result<()>; + async fn download(&self, lease: &RestoreLease, timeout: Duration) -> Result; +} + +#[async_trait] +impl RestoreHub for Arc { + async fn send( + &self, + path: String, + body: serde_json::Value, + restore: Option, + ) -> Result { + self.post(path, body, restore).await + } + + async fn send_with_reason( + &self, + path: String, + body: serde_json::Value, + restore: Uuid, + reason: Option, + ) -> Result { + self.post_with_reason(path, body, restore, reason).await + } + + async fn upload_safety( + &self, + lease: &RestoreLease, + stage: File, + timeout: Duration, + ) -> Result<()> { + self.upload( + format!("restore/{}/safety", lease.job.id), + stage, + timeout, + "x-tessera-restore-token", + lease.token, + None, + ) + .await + } + + async fn download(&self, lease: &RestoreLease, timeout: Duration) -> Result { + let hub = self.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? + } +} + +#[async_trait] +impl RestoreTarget for Target { async fn identity(&self) -> Result { match self { Self::Postgres(target) => target.connection.identity().await, @@ -59,16 +161,17 @@ impl Target { } } -pub(super) async fn poll( - hub: &Arc, +pub(super) async fn poll( + hub: &H, application: Uuid, - source: Option<&Source>, - targets: &HashMap, + source: Option<&S>, + targets: &HashMap, timeout_seconds: u64, + heartbeat: Duration, ) -> Result { for (target_id, target) in targets { let reply = hub - .post( + .send( format!("restore-targets/{target_id}/claim"), serde_json::Value::Null, None, @@ -93,7 +196,7 @@ pub(super) async fn poll( tokio::select! { biased; result = &mut work => return result.map(|()| true), - _ = tokio::time::sleep(Duration::from_secs(CAPTURE_HEARTBEAT_SECONDS)) => { + _ = tokio::time::sleep(heartbeat) => { report(hub, &lease, RestoreProgress::Heartbeat).await?; } } @@ -102,16 +205,16 @@ pub(super) async fn poll( Ok(false) } -async fn run( - hub: &Arc, +async fn run( + hub: &H, lease: &RestoreLease, - target: &Target, - source: Option<&Source>, + target: &T, + source: Option<&S>, timeout: Duration, ) -> Result<()> { report(hub, lease, RestoreProgress::Checking).await?; let downloaded = tokio::time::timeout(timeout, async { - let input = download(hub, lease, timeout).await?; + let input = hub.download(lease, timeout).await?; target.prepare(input, lease).await }) .await; @@ -159,15 +262,7 @@ async fn run( 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?; + hub.upload_safety(lease, stage, timeout).await?; Ok::<_, anyhow::Error>(()) }) .await; @@ -177,7 +272,7 @@ async fn run( } // The permit is single-use. A lost response leaves the target locked for reconciliation. - hub.post( + hub.send( format!("restore/{}/apply", lease.job.id), serde_json::Value::Null, Some(lease.token), @@ -198,13 +293,13 @@ fn why(result: Result, tokio::time::error::Elapsed>) -> String { } } -async fn report_failed( - hub: &Arc, +async fn report_failed( + hub: &H, lease: &RestoreLease, progress: RestoreProgress, reason: String, ) -> Result<()> { - hub.post_with_reason( + hub.send_with_reason( format!("restore/{}/report", lease.job.id), serde_json::to_value(progress)?, lease.token, @@ -214,8 +309,12 @@ async fn report_failed( Ok(()) } -async fn report(hub: &Arc, lease: &RestoreLease, progress: RestoreProgress) -> Result<()> { - hub.post( +async fn report( + hub: &H, + lease: &RestoreLease, + progress: RestoreProgress, +) -> Result<()> { + hub.send( format!("restore/{}/report", lease.job.id), serde_json::to_value(progress)?, Some(lease.token), @@ -223,29 +322,3 @@ async fn report(hub: &Arc, lease: &RestoreLease, progress: RestoreProgress) .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? -}