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 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 20:55:13 +07:00
parent d356c313ce
commit b2d5e4d71a
4 changed files with 140 additions and 57 deletions

1
Cargo.lock generated
View File

@@ -3083,6 +3083,7 @@ name = "tessera-agent"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"async-trait",
"base64 0.22.1", "base64 0.22.1",
"clap", "clap",
"hex", "hex",

View File

@@ -13,6 +13,7 @@ path = "src/main.rs"
tessera-core = { path = "../tessera-core" } tessera-core = { path = "../tessera-core" }
tessera-providers = { path = "../tessera-providers" } tessera-providers = { path = "../tessera-providers" }
anyhow.workspace = true anyhow.workspace = true
async-trait.workspace = true
clap.workspace = true clap.workspace = true
serde.workspace = true serde.workspace = true
serde_json.workspace = true serde_json.workspace = true

View File

@@ -46,8 +46,15 @@ pub(super) enum Source {
Mysql(MysqlSource), Mysql(MysqlSource),
} }
impl Source { /// The local backup source, as far as the restore guard cares: which database it is.
pub(super) async fn identity(&self) -> Result<DatabaseIdentity> { #[async_trait::async_trait]
pub(super) trait BackupSource: Sync {
async fn identity(&self) -> Result<DatabaseIdentity>;
}
#[async_trait::async_trait]
impl BackupSource for Source {
async fn identity(&self) -> Result<DatabaseIdentity> {
match self { match self {
Self::Postgres(source) => source.identity().await, Self::Postgres(source) => source.identity().await,
Self::Mysql(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.source.as_ref(),
&profile.targets, &profile.targets,
profile.timeout_seconds, profile.timeout_seconds,
Duration::from_secs(CAPTURE_HEARTBEAT_SECONDS),
) )
.await?; .await?;
if !restored && (profile.source.is_some() || !profile.paths.is_empty()) { if !restored && (profile.source.is_some() || !profile.paths.is_empty()) {

View File

@@ -1,12 +1,13 @@
use crate::{ use crate::{
http, http,
jobs::{digest_file, Hub, Source}, jobs::{digest_file, BackupSource, Hub},
}; };
use anyhow::{ensure, Context, Result}; use anyhow::{ensure, Context, Result};
use async_trait::async_trait;
use serde::Deserialize; use serde::Deserialize;
use std::{collections::HashMap, fs::File, sync::Arc, time::Duration}; use std::{collections::HashMap, fs::File, sync::Arc, time::Duration};
use tessera_core::{ use tessera_core::{
job::{CaptureFormat, CAPTURE_HEARTBEAT_SECONDS}, job::CaptureFormat,
restore::{DatabaseIdentity, RestoreLease, RestoreProgress}, restore::{DatabaseIdentity, RestoreLease, RestoreProgress},
}; };
use tessera_providers::{MysqlRestore, PostgresRestore}; use tessera_providers::{MysqlRestore, PostgresRestore};
@@ -19,7 +20,108 @@ pub(super) enum Target {
Mysql(MysqlRestore), 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<DatabaseIdentity>;
async fn prepare(&self, input: File, lease: &RestoreLease) -> Result<File>;
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<Hub>`.
#[async_trait]
pub(super) trait RestoreHub: Sync {
async fn send(
&self,
path: String,
body: serde_json::Value,
restore: Option<Uuid>,
) -> Result<String>;
async fn send_with_reason(
&self,
path: String,
body: serde_json::Value,
restore: Uuid,
reason: Option<String>,
) -> Result<String>;
async fn upload_safety(
&self,
lease: &RestoreLease,
stage: File,
timeout: Duration,
) -> Result<()>;
async fn download(&self, lease: &RestoreLease, timeout: Duration) -> Result<File>;
}
#[async_trait]
impl RestoreHub for Arc<Hub> {
async fn send(
&self,
path: String,
body: serde_json::Value,
restore: Option<Uuid>,
) -> Result<String> {
self.post(path, body, restore).await
}
async fn send_with_reason(
&self,
path: String,
body: serde_json::Value,
restore: Uuid,
reason: Option<String>,
) -> Result<String> {
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<File> {
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<DatabaseIdentity> { async fn identity(&self) -> Result<DatabaseIdentity> {
match self { match self {
Self::Postgres(target) => target.connection.identity().await, Self::Postgres(target) => target.connection.identity().await,
@@ -59,16 +161,17 @@ impl Target {
} }
} }
pub(super) async fn poll( pub(super) async fn poll<H: RestoreHub, T: RestoreTarget, S: BackupSource>(
hub: &Arc<Hub>, hub: &H,
application: Uuid, application: Uuid,
source: Option<&Source>, source: Option<&S>,
targets: &HashMap<Uuid, Target>, targets: &HashMap<Uuid, T>,
timeout_seconds: u64, timeout_seconds: u64,
heartbeat: Duration,
) -> Result<bool> { ) -> Result<bool> {
for (target_id, target) in targets { for (target_id, target) in targets {
let reply = hub let reply = hub
.post( .send(
format!("restore-targets/{target_id}/claim"), format!("restore-targets/{target_id}/claim"),
serde_json::Value::Null, serde_json::Value::Null,
None, None,
@@ -93,7 +196,7 @@ pub(super) async fn poll(
tokio::select! { tokio::select! {
biased; biased;
result = &mut work => return result.map(|()| true), 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?; report(hub, &lease, RestoreProgress::Heartbeat).await?;
} }
} }
@@ -102,16 +205,16 @@ pub(super) async fn poll(
Ok(false) Ok(false)
} }
async fn run( async fn run<H: RestoreHub, T: RestoreTarget, S: BackupSource>(
hub: &Arc<Hub>, hub: &H,
lease: &RestoreLease, lease: &RestoreLease,
target: &Target, target: &T,
source: Option<&Source>, source: Option<&S>,
timeout: Duration, timeout: Duration,
) -> Result<()> { ) -> Result<()> {
report(hub, lease, RestoreProgress::Checking).await?; report(hub, lease, RestoreProgress::Checking).await?;
let downloaded = tokio::time::timeout(timeout, async { 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 target.prepare(input, lease).await
}) })
.await; .await;
@@ -159,15 +262,7 @@ async fn run(
target.identity().await? == identity, target.identity().await? == identity,
"target changed during safety capture" "target changed during safety capture"
); );
hub.upload( hub.upload_safety(lease, stage, timeout).await?;
format!("restore/{}/safety", lease.job.id),
stage,
timeout,
"x-tessera-restore-token",
lease.token,
None,
)
.await?;
Ok::<_, anyhow::Error>(()) Ok::<_, anyhow::Error>(())
}) })
.await; .await;
@@ -177,7 +272,7 @@ async fn run(
} }
// The permit is single-use. A lost response leaves the target locked for reconciliation. // The permit is single-use. A lost response leaves the target locked for reconciliation.
hub.post( hub.send(
format!("restore/{}/apply", lease.job.id), format!("restore/{}/apply", lease.job.id),
serde_json::Value::Null, serde_json::Value::Null,
Some(lease.token), Some(lease.token),
@@ -198,13 +293,13 @@ fn why<T>(result: Result<Result<T>, tokio::time::error::Elapsed>) -> String {
} }
} }
async fn report_failed( async fn report_failed<H: RestoreHub>(
hub: &Arc<Hub>, hub: &H,
lease: &RestoreLease, lease: &RestoreLease,
progress: RestoreProgress, progress: RestoreProgress,
reason: String, reason: String,
) -> Result<()> { ) -> Result<()> {
hub.post_with_reason( hub.send_with_reason(
format!("restore/{}/report", lease.job.id), format!("restore/{}/report", lease.job.id),
serde_json::to_value(progress)?, serde_json::to_value(progress)?,
lease.token, lease.token,
@@ -214,8 +309,12 @@ async fn report_failed(
Ok(()) Ok(())
} }
async fn report(hub: &Arc<Hub>, lease: &RestoreLease, progress: RestoreProgress) -> Result<()> { async fn report<H: RestoreHub>(
hub.post( hub: &H,
lease: &RestoreLease,
progress: RestoreProgress,
) -> Result<()> {
hub.send(
format!("restore/{}/report", lease.job.id), format!("restore/{}/report", lease.job.id),
serde_json::to_value(progress)?, serde_json::to_value(progress)?,
Some(lease.token), Some(lease.token),
@@ -223,29 +322,3 @@ async fn report(hub: &Arc<Hub>, lease: &RestoreLease, progress: RestoreProgress)
.await?; .await?;
Ok(()) Ok(())
} }
async fn download(hub: &Arc<Hub>, lease: &RestoreLease, timeout: Duration) -> Result<File> {
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?
}