merge: worktree-agent-ae4267aa66ffa0b0a
This commit is contained in:
1
Cargo.lock
generated
1
Cargo.lock
generated
@@ -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",
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -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()) {
|
||||||
|
|||||||
@@ -1,12 +1,21 @@
|
|||||||
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::{
|
||||||
|
atomic::{AtomicBool, Ordering},
|
||||||
|
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 +28,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 +169,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,
|
||||||
@@ -81,20 +192,32 @@ pub(super) async fn poll(
|
|||||||
lease.job.target.id == *target_id && lease.job.target.application_id == application,
|
lease.job.target.id == *target_id && lease.job.target.application_id == application,
|
||||||
"hub returned an unexpected restore target"
|
"hub returned an unexpected restore target"
|
||||||
);
|
);
|
||||||
|
let permit_taken = AtomicBool::new(false);
|
||||||
let work = run(
|
let work = run(
|
||||||
hub,
|
hub,
|
||||||
&lease,
|
&lease,
|
||||||
target,
|
target,
|
||||||
source,
|
source,
|
||||||
Duration::from_secs(timeout_seconds),
|
Duration::from_secs(timeout_seconds),
|
||||||
|
&permit_taken,
|
||||||
);
|
);
|
||||||
tokio::pin!(work);
|
tokio::pin!(work);
|
||||||
loop {
|
loop {
|
||||||
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?;
|
if let Err(error) = report(hub, &lease, RestoreProgress::Heartbeat).await {
|
||||||
|
// Once the apply permit is spent, dropping `work` would kill the apply
|
||||||
|
// half way (its children are `kill_on_drop`) and leave the target
|
||||||
|
// half-restored with no terminal report. Keep going and let the outcome
|
||||||
|
// report decide. Before the permit nothing destructive has happened,
|
||||||
|
// so give up and let the lease expire.
|
||||||
|
if !permit_taken.load(Ordering::SeqCst) {
|
||||||
|
return Err(error);
|
||||||
|
}
|
||||||
|
tracing::warn!(restore = %lease.job.id, %error, "heartbeat failed during apply; letting the restore finish");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -102,16 +225,17 @@ 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,
|
||||||
|
permit_taken: &AtomicBool,
|
||||||
) -> 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 +283,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;
|
||||||
@@ -176,8 +292,10 @@ async fn run(
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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. Mark it
|
||||||
hub.post(
|
// taken before asking: from here on the hub may consider the apply started.
|
||||||
|
permit_taken.store(true, Ordering::SeqCst);
|
||||||
|
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 +316,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 +332,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),
|
||||||
@@ -224,28 +346,5 @@ async fn report(hub: &Arc<Hub>, lease: &RestoreLease, progress: RestoreProgress)
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn download(hub: &Arc<Hub>, lease: &RestoreLease, timeout: Duration) -> Result<File> {
|
#[cfg(test)]
|
||||||
let hub = hub.clone();
|
mod tests;
|
||||||
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?
|
|
||||||
}
|
|
||||||
|
|||||||
863
crates/tessera-agent/src/restore/tests.rs
Normal file
863
crates/tessera-agent/src/restore/tests.rs
Normal file
@@ -0,0 +1,863 @@
|
|||||||
|
//! The restore sequence is destructive, so these tests drive `run` and `poll` with in-process fakes and
|
||||||
|
//! assert what the agent does (and above all never does) at each step. Every fake appends to one shared
|
||||||
|
//! event log so tests can assert on ordering and absence.
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
use std::{
|
||||||
|
collections::VecDeque,
|
||||||
|
io::{Read, Write},
|
||||||
|
sync::Mutex,
|
||||||
|
};
|
||||||
|
use tessera_core::restore::{RestoreArtifact, RestoreJob, RestoreTarget as JobTarget};
|
||||||
|
|
||||||
|
type Log = Arc<Mutex<Vec<String>>>;
|
||||||
|
|
||||||
|
fn identity(instance: &str, database: &str) -> DatabaseIdentity {
|
||||||
|
DatabaseIdentity {
|
||||||
|
instance: instance.into(),
|
||||||
|
database: database.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn target_identity() -> DatabaseIdentity {
|
||||||
|
identity("1", "target")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn source_identity() -> DatabaseIdentity {
|
||||||
|
identity("2", "source")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lease_for(target: Uuid, application: Uuid, rollback: bool) -> RestoreLease {
|
||||||
|
RestoreLease {
|
||||||
|
job: RestoreJob {
|
||||||
|
id: Uuid::new_v4(),
|
||||||
|
snapshot_id: Uuid::new_v4(),
|
||||||
|
target: JobTarget {
|
||||||
|
id: target,
|
||||||
|
application_id: application,
|
||||||
|
outpost_id: Uuid::new_v4(),
|
||||||
|
name: "target".into(),
|
||||||
|
engine: tessera_core::restore::Engine::Postgres,
|
||||||
|
identity: target_identity(),
|
||||||
|
},
|
||||||
|
actor: "admin".into(),
|
||||||
|
status: "running".into(),
|
||||||
|
phase: "queued".into(),
|
||||||
|
safety_snapshot_id: None,
|
||||||
|
created_at: 0,
|
||||||
|
updated_at: 0,
|
||||||
|
failure_reason: None,
|
||||||
|
},
|
||||||
|
token: Uuid::new_v4(),
|
||||||
|
artifact: RestoreArtifact {
|
||||||
|
format: CaptureFormat::PostgresCustom,
|
||||||
|
// A normal restore comes from another database; a rollback comes from the target itself.
|
||||||
|
identity: if rollback {
|
||||||
|
target_identity()
|
||||||
|
} else {
|
||||||
|
source_identity()
|
||||||
|
},
|
||||||
|
sha256: "00".into(),
|
||||||
|
rollback,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lease() -> RestoreLease {
|
||||||
|
lease_for(Uuid::new_v4(), Uuid::new_v4(), false)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, PartialEq)]
|
||||||
|
enum Step {
|
||||||
|
Ok,
|
||||||
|
Fail,
|
||||||
|
Hang,
|
||||||
|
/// Succeeds after this many milliseconds.
|
||||||
|
Slow(u64),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Step {
|
||||||
|
async fn run(self, what: &str) -> Result<()> {
|
||||||
|
match self {
|
||||||
|
Step::Ok => Ok(()),
|
||||||
|
Step::Fail => anyhow::bail!("{what} exploded"),
|
||||||
|
Step::Hang => std::future::pending().await,
|
||||||
|
Step::Slow(ms) => {
|
||||||
|
tokio::time::sleep(Duration::from_millis(ms)).await;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type Answer = Result<DatabaseIdentity, &'static str>;
|
||||||
|
|
||||||
|
struct FakeTarget {
|
||||||
|
log: Log,
|
||||||
|
/// Answers for successive `identity` calls; the last one repeats.
|
||||||
|
identities: Mutex<VecDeque<Answer>>,
|
||||||
|
hang_identity: bool,
|
||||||
|
prepare: Step,
|
||||||
|
safety: Step,
|
||||||
|
apply: Step,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FakeTarget {
|
||||||
|
fn new(log: &Log) -> Self {
|
||||||
|
Self {
|
||||||
|
log: log.clone(),
|
||||||
|
identities: Mutex::new(VecDeque::from([Ok(target_identity())])),
|
||||||
|
hang_identity: false,
|
||||||
|
prepare: Step::Ok,
|
||||||
|
safety: Step::Ok,
|
||||||
|
apply: Step::Ok,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn identities(self, answers: Vec<Answer>) -> Self {
|
||||||
|
*self.identities.lock().unwrap() = answers.into();
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl RestoreTarget for FakeTarget {
|
||||||
|
async fn identity(&self) -> Result<DatabaseIdentity> {
|
||||||
|
self.log.lock().unwrap().push("target.identity".into());
|
||||||
|
if self.hang_identity {
|
||||||
|
std::future::pending::<()>().await;
|
||||||
|
}
|
||||||
|
let answer = {
|
||||||
|
let mut answers = self.identities.lock().unwrap();
|
||||||
|
if answers.len() > 1 {
|
||||||
|
answers.pop_front().unwrap()
|
||||||
|
} else {
|
||||||
|
answers.front().cloned().unwrap()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
answer.map_err(|why| anyhow::anyhow!(why))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn prepare(&self, mut input: File, _: &RestoreLease) -> Result<File> {
|
||||||
|
self.log.lock().unwrap().push("target.prepare".into());
|
||||||
|
self.prepare.run("prepare").await?;
|
||||||
|
let mut script = tempfile::tempfile()?;
|
||||||
|
let mut body = Vec::new();
|
||||||
|
input.read_to_end(&mut body)?;
|
||||||
|
script.write_all(&body)?;
|
||||||
|
Ok(script)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn safety(&self, _: File) -> Result<()> {
|
||||||
|
self.log.lock().unwrap().push("target.safety".into());
|
||||||
|
self.safety.run("safety dump").await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn apply(&self, _: File) -> Result<()> {
|
||||||
|
self.log.lock().unwrap().push("target.apply".into());
|
||||||
|
self.apply.run("apply").await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct FakeSource(Answer);
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl BackupSource for FakeSource {
|
||||||
|
async fn identity(&self) -> Result<DatabaseIdentity> {
|
||||||
|
self.0.clone().map_err(|why| anyhow::anyhow!(why))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct FakeHub {
|
||||||
|
log: Log,
|
||||||
|
/// Queue of claim replies; empty means "nothing to restore".
|
||||||
|
claims: Mutex<VecDeque<String>>,
|
||||||
|
download: Step,
|
||||||
|
upload: Step,
|
||||||
|
/// A request whose path ends with this fails (the response is "lost").
|
||||||
|
fail_path: Option<&'static str>,
|
||||||
|
/// Reports with this progress fail (used to break heartbeats).
|
||||||
|
fail_progress: Option<&'static str>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FakeHub {
|
||||||
|
fn new(log: &Log) -> Self {
|
||||||
|
Self {
|
||||||
|
log: log.clone(),
|
||||||
|
claims: Mutex::default(),
|
||||||
|
download: Step::Ok,
|
||||||
|
upload: Step::Ok,
|
||||||
|
fail_path: None,
|
||||||
|
fail_progress: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl RestoreHub for FakeHub {
|
||||||
|
async fn send(
|
||||||
|
&self,
|
||||||
|
path: String,
|
||||||
|
body: serde_json::Value,
|
||||||
|
restore: Option<Uuid>,
|
||||||
|
) -> Result<String> {
|
||||||
|
if path.ends_with("/claim") {
|
||||||
|
return Ok(self
|
||||||
|
.claims
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.pop_front()
|
||||||
|
.unwrap_or_else(|| "null".into()));
|
||||||
|
}
|
||||||
|
if path.ends_with("/apply") {
|
||||||
|
assert!(restore.is_some(), "the apply permit needs the lease token");
|
||||||
|
self.log.lock().unwrap().push("hub.apply-permit".into());
|
||||||
|
} else {
|
||||||
|
let progress = body.as_str().unwrap_or("?").to_owned();
|
||||||
|
self.log.lock().unwrap().push(format!("report:{progress}"));
|
||||||
|
if self.fail_progress == Some(progress.as_str()) {
|
||||||
|
anyhow::bail!("hub unreachable");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if self.fail_path.is_some_and(|suffix| path.ends_with(suffix)) {
|
||||||
|
anyhow::bail!("response lost");
|
||||||
|
}
|
||||||
|
Ok(String::new())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn send_with_reason(
|
||||||
|
&self,
|
||||||
|
_: String,
|
||||||
|
body: serde_json::Value,
|
||||||
|
_: Uuid,
|
||||||
|
reason: Option<String>,
|
||||||
|
) -> Result<String> {
|
||||||
|
self.log.lock().unwrap().push(format!(
|
||||||
|
"failed:{}:{}",
|
||||||
|
body.as_str().unwrap_or("?"),
|
||||||
|
reason.unwrap_or_default()
|
||||||
|
));
|
||||||
|
Ok(String::new())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn upload_safety(&self, _: &RestoreLease, _: File, _: Duration) -> Result<()> {
|
||||||
|
self.log.lock().unwrap().push("hub.safety-upload".into());
|
||||||
|
self.upload.run("upload").await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn download(&self, _: &RestoreLease, _: Duration) -> Result<File> {
|
||||||
|
self.log.lock().unwrap().push("hub.download".into());
|
||||||
|
self.download.run("download").await?;
|
||||||
|
Ok(tempfile::tempfile()?)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const SHORT: Duration = Duration::from_millis(60);
|
||||||
|
|
||||||
|
struct Outcome {
|
||||||
|
result: Result<()>,
|
||||||
|
log: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Outcome {
|
||||||
|
fn did(&self, event: &str) -> bool {
|
||||||
|
self.log.iter().any(|entry| entry == event)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn failed(&self, progress: &str) -> Option<&str> {
|
||||||
|
self.log
|
||||||
|
.iter()
|
||||||
|
.find_map(|entry| entry.strip_prefix(&format!("failed:{progress}:")))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The agent never reached the destructive step.
|
||||||
|
fn never_applied(&self) -> bool {
|
||||||
|
!self.did("hub.apply-permit") && !self.did("target.apply")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn drive(
|
||||||
|
lease: &RestoreLease,
|
||||||
|
log: &Log,
|
||||||
|
hub: FakeHub,
|
||||||
|
target: FakeTarget,
|
||||||
|
source: Option<FakeSource>,
|
||||||
|
) -> Outcome {
|
||||||
|
let result = run(
|
||||||
|
&hub,
|
||||||
|
lease,
|
||||||
|
&target,
|
||||||
|
source.as_ref(),
|
||||||
|
SHORT,
|
||||||
|
&AtomicBool::new(false),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let log = log.lock().unwrap().clone();
|
||||||
|
Outcome { result, log }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn log() -> Log {
|
||||||
|
Log::default()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn full_restore_runs_in_order_and_reports_applied() {
|
||||||
|
let log = log();
|
||||||
|
let out = drive(
|
||||||
|
&lease(),
|
||||||
|
&log,
|
||||||
|
FakeHub::new(&log),
|
||||||
|
FakeTarget::new(&log),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
out.result.as_ref().unwrap();
|
||||||
|
let steps: Vec<&str> = out
|
||||||
|
.log
|
||||||
|
.iter()
|
||||||
|
.map(String::as_str)
|
||||||
|
.filter(|entry| *entry != "target.identity")
|
||||||
|
.collect();
|
||||||
|
assert_eq!(
|
||||||
|
steps,
|
||||||
|
[
|
||||||
|
"report:checking",
|
||||||
|
"hub.download",
|
||||||
|
"target.prepare",
|
||||||
|
"report:safety",
|
||||||
|
"target.safety",
|
||||||
|
"hub.safety-upload",
|
||||||
|
"hub.apply-permit",
|
||||||
|
"target.apply",
|
||||||
|
"report:applied",
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- safety capture: nothing destructive may happen unless the safety copy is stored ----
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn safety_dump_failure_never_applies() {
|
||||||
|
let log = log();
|
||||||
|
let mut target = FakeTarget::new(&log);
|
||||||
|
target.safety = Step::Fail;
|
||||||
|
let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await;
|
||||||
|
out.result.as_ref().unwrap();
|
||||||
|
assert!(out.never_applied());
|
||||||
|
assert!(out
|
||||||
|
.failed("safety_failed")
|
||||||
|
.unwrap()
|
||||||
|
.contains("safety dump exploded"));
|
||||||
|
assert!(!out.did("hub.safety-upload"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn safety_upload_failure_never_applies() {
|
||||||
|
let log = log();
|
||||||
|
let mut hub = FakeHub::new(&log);
|
||||||
|
hub.upload = Step::Fail;
|
||||||
|
let out = drive(&lease(), &log, hub, FakeTarget::new(&log), None).await;
|
||||||
|
out.result.as_ref().unwrap();
|
||||||
|
assert!(out.never_applied());
|
||||||
|
assert!(out
|
||||||
|
.failed("safety_failed")
|
||||||
|
.unwrap()
|
||||||
|
.contains("upload exploded"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn target_changed_during_safety_capture_never_applies() {
|
||||||
|
let log = log();
|
||||||
|
// Verified as the expected target, then a different database answers after the dump.
|
||||||
|
let target =
|
||||||
|
FakeTarget::new(&log).identities(vec![Ok(target_identity()), Ok(source_identity())]);
|
||||||
|
let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await;
|
||||||
|
out.result.as_ref().unwrap();
|
||||||
|
assert!(out.never_applied());
|
||||||
|
assert!(out
|
||||||
|
.failed("safety_failed")
|
||||||
|
.unwrap()
|
||||||
|
.contains("target changed during safety capture"));
|
||||||
|
assert!(
|
||||||
|
!out.did("hub.safety-upload"),
|
||||||
|
"a dump of the wrong database must not be stored"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn target_unreachable_after_safety_capture_never_applies() {
|
||||||
|
let log = log();
|
||||||
|
let target = FakeTarget::new(&log).identities(vec![Ok(target_identity()), Err("gone")]);
|
||||||
|
let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await;
|
||||||
|
out.result.as_ref().unwrap();
|
||||||
|
assert!(out.never_applied());
|
||||||
|
assert!(out.failed("safety_failed").is_some());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- identity checks ----
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn identity_mismatch_refuses_before_any_dump() {
|
||||||
|
let log = log();
|
||||||
|
let target = FakeTarget::new(&log).identities(vec![Ok(identity("1", "other"))]);
|
||||||
|
let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await;
|
||||||
|
out.result.as_ref().unwrap();
|
||||||
|
assert!(out
|
||||||
|
.failed("wrong_target")
|
||||||
|
.unwrap()
|
||||||
|
.contains("identity does not match"));
|
||||||
|
assert!(out.never_applied());
|
||||||
|
assert!(
|
||||||
|
!out.did("target.safety"),
|
||||||
|
"must refuse before touching the target"
|
||||||
|
);
|
||||||
|
assert!(!out.did("report:safety"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn identity_probe_error_is_a_wrong_target() {
|
||||||
|
let log = log();
|
||||||
|
let target = FakeTarget::new(&log).identities(vec![Err("connection refused")]);
|
||||||
|
let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await;
|
||||||
|
out.result.as_ref().unwrap();
|
||||||
|
assert!(out
|
||||||
|
.failed("wrong_target")
|
||||||
|
.unwrap()
|
||||||
|
.contains("connection refused"));
|
||||||
|
assert!(out.never_applied());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn restoring_a_backup_onto_its_own_source_database_is_refused() {
|
||||||
|
let log = log();
|
||||||
|
let mut lease = lease();
|
||||||
|
lease.artifact.identity = target_identity(); // artifact was taken from the target itself
|
||||||
|
let out = drive(
|
||||||
|
&lease,
|
||||||
|
&log,
|
||||||
|
FakeHub::new(&log),
|
||||||
|
FakeTarget::new(&log),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
out.result.as_ref().unwrap();
|
||||||
|
assert!(out.failed("wrong_target").is_some());
|
||||||
|
assert!(out.never_applied());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn rollback_may_restore_onto_the_database_the_copy_came_from() {
|
||||||
|
let log = log();
|
||||||
|
let lease = lease_for(Uuid::new_v4(), Uuid::new_v4(), true);
|
||||||
|
assert_eq!(lease.artifact.identity, lease.job.target.identity);
|
||||||
|
let out = drive(
|
||||||
|
&lease,
|
||||||
|
&log,
|
||||||
|
FakeHub::new(&log),
|
||||||
|
FakeTarget::new(&log),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
out.result.as_ref().unwrap();
|
||||||
|
assert!(out.did("report:applied"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn rollback_still_requires_the_target_identity_to_match() {
|
||||||
|
let log = log();
|
||||||
|
let lease = lease_for(Uuid::new_v4(), Uuid::new_v4(), true);
|
||||||
|
let target = FakeTarget::new(&log).identities(vec![Ok(identity("1", "impostor"))]);
|
||||||
|
let out = drive(&lease, &log, FakeHub::new(&log), target, None).await;
|
||||||
|
out.result.as_ref().unwrap();
|
||||||
|
assert!(out.failed("wrong_target").is_some());
|
||||||
|
assert!(out.never_applied());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn target_that_is_the_local_backup_source_is_refused() {
|
||||||
|
let log = log();
|
||||||
|
let source = FakeSource(Ok(target_identity()));
|
||||||
|
let out = drive(
|
||||||
|
&lease(),
|
||||||
|
&log,
|
||||||
|
FakeHub::new(&log),
|
||||||
|
FakeTarget::new(&log),
|
||||||
|
Some(source),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
out.result.as_ref().unwrap();
|
||||||
|
assert!(out
|
||||||
|
.failed("wrong_target")
|
||||||
|
.unwrap()
|
||||||
|
.contains("target resolves to the local backup source"));
|
||||||
|
assert!(out.never_applied());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_different_local_source_does_not_block_a_restore() {
|
||||||
|
let log = log();
|
||||||
|
let source = FakeSource(Ok(source_identity()));
|
||||||
|
let out = drive(
|
||||||
|
&lease(),
|
||||||
|
&log,
|
||||||
|
FakeHub::new(&log),
|
||||||
|
FakeTarget::new(&log),
|
||||||
|
Some(source),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
out.result.as_ref().unwrap();
|
||||||
|
assert!(out.did("report:applied"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Documented as designed: the source guard is best effort. If the local source cannot be identified (its
|
||||||
|
/// probe errors), the restore proceeds on the strength of the target identity checks alone.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn unidentifiable_local_source_does_not_block_a_restore() {
|
||||||
|
let log = log();
|
||||||
|
let source = FakeSource(Err("source down"));
|
||||||
|
let out = drive(
|
||||||
|
&lease(),
|
||||||
|
&log,
|
||||||
|
FakeHub::new(&log),
|
||||||
|
FakeTarget::new(&log),
|
||||||
|
Some(source),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
out.result.as_ref().unwrap();
|
||||||
|
assert!(out.did("report:applied"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- per-step timeouts map to their own failure state, and never reach apply ----
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn download_timeout_is_invalid_payload() {
|
||||||
|
let log = log();
|
||||||
|
let mut hub = FakeHub::new(&log);
|
||||||
|
hub.download = Step::Hang;
|
||||||
|
let out = drive(&lease(), &log, hub, FakeTarget::new(&log), None).await;
|
||||||
|
out.result.as_ref().unwrap();
|
||||||
|
assert_eq!(out.failed("invalid_payload"), Some("timed out"));
|
||||||
|
assert!(out.never_applied());
|
||||||
|
assert!(!out.did("target.safety"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn prepare_timeout_is_invalid_payload() {
|
||||||
|
let log = log();
|
||||||
|
let mut target = FakeTarget::new(&log);
|
||||||
|
target.prepare = Step::Hang;
|
||||||
|
let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await;
|
||||||
|
out.result.as_ref().unwrap();
|
||||||
|
assert_eq!(out.failed("invalid_payload"), Some("timed out"));
|
||||||
|
assert!(out.never_applied());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn prepare_error_is_invalid_payload_with_its_reason() {
|
||||||
|
let log = log();
|
||||||
|
let mut target = FakeTarget::new(&log);
|
||||||
|
target.prepare = Step::Fail;
|
||||||
|
let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await;
|
||||||
|
out.result.as_ref().unwrap();
|
||||||
|
assert!(out
|
||||||
|
.failed("invalid_payload")
|
||||||
|
.unwrap()
|
||||||
|
.contains("prepare exploded"));
|
||||||
|
assert!(out.never_applied());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn identity_check_timeout_is_wrong_target() {
|
||||||
|
let log = log();
|
||||||
|
let mut target = FakeTarget::new(&log);
|
||||||
|
target.hang_identity = true;
|
||||||
|
let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await;
|
||||||
|
out.result.as_ref().unwrap();
|
||||||
|
assert_eq!(out.failed("wrong_target"), Some("timed out"));
|
||||||
|
assert!(out.never_applied());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn safety_dump_timeout_is_safety_failed() {
|
||||||
|
let log = log();
|
||||||
|
let mut target = FakeTarget::new(&log);
|
||||||
|
target.safety = Step::Hang;
|
||||||
|
let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await;
|
||||||
|
out.result.as_ref().unwrap();
|
||||||
|
assert_eq!(out.failed("safety_failed"), Some("timed out"));
|
||||||
|
assert!(out.never_applied());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn safety_upload_timeout_is_safety_failed() {
|
||||||
|
let log = log();
|
||||||
|
let mut hub = FakeHub::new(&log);
|
||||||
|
hub.upload = Step::Hang;
|
||||||
|
let out = drive(&lease(), &log, hub, FakeTarget::new(&log), None).await;
|
||||||
|
out.result.as_ref().unwrap();
|
||||||
|
assert_eq!(out.failed("safety_failed"), Some("timed out"));
|
||||||
|
assert!(out.never_applied());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn apply_timeout_is_apply_failed_after_the_permit() {
|
||||||
|
let log = log();
|
||||||
|
let mut target = FakeTarget::new(&log);
|
||||||
|
target.apply = Step::Hang;
|
||||||
|
let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await;
|
||||||
|
out.result.as_ref().unwrap();
|
||||||
|
assert_eq!(out.failed("apply_failed"), Some("timed out"));
|
||||||
|
assert!(out.did("hub.apply-permit") && out.did("target.apply"));
|
||||||
|
assert!(!out.did("report:applied"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn apply_error_is_apply_failed_with_its_reason() {
|
||||||
|
let log = log();
|
||||||
|
let mut target = FakeTarget::new(&log);
|
||||||
|
target.apply = Step::Fail;
|
||||||
|
let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await;
|
||||||
|
out.result.as_ref().unwrap();
|
||||||
|
assert!(out
|
||||||
|
.failed("apply_failed")
|
||||||
|
.unwrap()
|
||||||
|
.contains("apply exploded"));
|
||||||
|
assert!(!out.did("report:applied"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- the permit ----
|
||||||
|
|
||||||
|
/// The permit is single-use and the agent does not retry it. If the response is lost (or the hub refuses),
|
||||||
|
/// `run` returns the error WITHOUT applying and without reporting anything further: the hub has consumed
|
||||||
|
/// (or may have consumed) the permit, so the target stays locked until the hub reconciles the lease.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn lost_apply_permit_response_does_not_apply_and_leaves_the_lease_for_reconciliation() {
|
||||||
|
let log = log();
|
||||||
|
let mut hub = FakeHub::new(&log);
|
||||||
|
hub.fail_path = Some("/apply");
|
||||||
|
let out = drive(&lease(), &log, hub, FakeTarget::new(&log), None).await;
|
||||||
|
assert!(out
|
||||||
|
.result
|
||||||
|
.as_ref()
|
||||||
|
.unwrap_err()
|
||||||
|
.to_string()
|
||||||
|
.contains("response lost"));
|
||||||
|
assert!(out.did("hub.apply-permit"));
|
||||||
|
assert!(
|
||||||
|
!out.did("target.apply"),
|
||||||
|
"no permit response, no destructive step"
|
||||||
|
);
|
||||||
|
assert_eq!(out.log.last().map(String::as_str), Some("hub.apply-permit"));
|
||||||
|
assert!(out
|
||||||
|
.log
|
||||||
|
.iter()
|
||||||
|
.all(|e| !e.starts_with("failed:") && e != "report:applied"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Agent dies (or is cancelled) after the permit but before the restore finishes. The hub has seen the
|
||||||
|
/// permit but never a terminal report, so the lease is left mid-flight for the hub to expire.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn crash_between_permit_and_apply_leaves_no_terminal_report() {
|
||||||
|
let log = log();
|
||||||
|
let hub = FakeHub::new(&log);
|
||||||
|
let mut target = FakeTarget::new(&log);
|
||||||
|
target.apply = Step::Hang;
|
||||||
|
let lease = lease();
|
||||||
|
let crashed = tokio::time::timeout(
|
||||||
|
Duration::from_millis(200),
|
||||||
|
run(
|
||||||
|
&hub,
|
||||||
|
&lease,
|
||||||
|
&target,
|
||||||
|
None::<&FakeSource>,
|
||||||
|
Duration::from_secs(30),
|
||||||
|
&AtomicBool::new(false),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert!(crashed.is_err(), "the run was dropped mid-apply");
|
||||||
|
let log = log.lock().unwrap().clone();
|
||||||
|
assert!(log.contains(&"hub.apply-permit".to_owned()));
|
||||||
|
assert!(log.contains(&"target.apply".to_owned()));
|
||||||
|
assert!(log
|
||||||
|
.iter()
|
||||||
|
.all(|e| e != "report:applied" && !e.starts_with("failed:")));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn failure_reasons_are_cleaned_before_they_are_reported() {
|
||||||
|
let log = log();
|
||||||
|
let target = FakeTarget::new(&log).identities(vec![Err("line one\nline\ttwo \u{1F4A5}")]);
|
||||||
|
let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await;
|
||||||
|
out.result.as_ref().unwrap();
|
||||||
|
assert_eq!(out.failed("wrong_target"), Some("line one line two ?"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- poll ----
|
||||||
|
|
||||||
|
fn poll_fixture(
|
||||||
|
log: &Log,
|
||||||
|
lease: &RestoreLease,
|
||||||
|
target_id: Uuid,
|
||||||
|
) -> (FakeHub, HashMap<Uuid, FakeTarget>) {
|
||||||
|
let hub = FakeHub::new(log);
|
||||||
|
hub.claims
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.push_back(serde_json::to_string(lease).unwrap());
|
||||||
|
let targets = HashMap::from([(target_id, FakeTarget::new(log))]);
|
||||||
|
(hub, targets)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn poll_with_nothing_to_claim_does_nothing() {
|
||||||
|
let log = log();
|
||||||
|
let hub = FakeHub::new(&log);
|
||||||
|
let targets = HashMap::from([(Uuid::new_v4(), FakeTarget::new(&log))]);
|
||||||
|
let did = poll(
|
||||||
|
&hub,
|
||||||
|
Uuid::new_v4(),
|
||||||
|
None::<&FakeSource>,
|
||||||
|
&targets,
|
||||||
|
1,
|
||||||
|
SHORT,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert!(!did);
|
||||||
|
assert!(log.lock().unwrap().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn poll_refuses_a_lease_for_another_target_or_application() {
|
||||||
|
for swap_target in [true, false] {
|
||||||
|
let log = log();
|
||||||
|
let (target_id, application) = (Uuid::new_v4(), Uuid::new_v4());
|
||||||
|
let lease = if swap_target {
|
||||||
|
lease_for(Uuid::new_v4(), application, false)
|
||||||
|
} else {
|
||||||
|
lease_for(target_id, Uuid::new_v4(), false)
|
||||||
|
};
|
||||||
|
let (hub, targets) = poll_fixture(&log, &lease, target_id);
|
||||||
|
let err = poll(&hub, application, None::<&FakeSource>, &targets, 1, SHORT)
|
||||||
|
.await
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(err.to_string().contains("unexpected restore target"));
|
||||||
|
assert!(
|
||||||
|
log.lock().unwrap().is_empty(),
|
||||||
|
"nothing may run for a mismatched lease"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn poll_runs_a_matching_lease() {
|
||||||
|
let log = log();
|
||||||
|
let (target_id, application) = (Uuid::new_v4(), Uuid::new_v4());
|
||||||
|
let lease = lease_for(target_id, application, false);
|
||||||
|
let (hub, targets) = poll_fixture(&log, &lease, target_id);
|
||||||
|
let did = poll(
|
||||||
|
&hub,
|
||||||
|
application,
|
||||||
|
None::<&FakeSource>,
|
||||||
|
&targets,
|
||||||
|
5,
|
||||||
|
Duration::from_secs(60),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert!(did);
|
||||||
|
assert!(log.lock().unwrap().contains(&"report:applied".to_owned()));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Before the apply permit nothing destructive has happened, so a failed heartbeat gives up on the lease
|
||||||
|
/// (the hub will expire it) rather than carrying on unobserved.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn failed_heartbeat_before_the_permit_abandons_the_restore() {
|
||||||
|
let log = log();
|
||||||
|
let (target_id, application) = (Uuid::new_v4(), Uuid::new_v4());
|
||||||
|
let lease = lease_for(target_id, application, false);
|
||||||
|
let (mut hub, targets) = poll_fixture(&log, &lease, target_id);
|
||||||
|
hub.fail_progress = Some("heartbeat");
|
||||||
|
hub.download = Step::Hang;
|
||||||
|
let err = tokio::time::timeout(
|
||||||
|
Duration::from_secs(5),
|
||||||
|
poll(
|
||||||
|
&hub,
|
||||||
|
application,
|
||||||
|
None::<&FakeSource>,
|
||||||
|
&targets,
|
||||||
|
30,
|
||||||
|
Duration::from_millis(50),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect("poll returns once the heartbeat fails")
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(err.to_string().contains("hub unreachable"));
|
||||||
|
let log = log.lock().unwrap().clone();
|
||||||
|
assert!(log.contains(&"hub.download".to_owned()));
|
||||||
|
assert!(log.iter().all(|e| e != "hub.apply-permit"
|
||||||
|
&& e != "target.apply"
|
||||||
|
&& e != "report:applied"
|
||||||
|
&& !e.starts_with("failed:")));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// After the permit is spent, dropping the restore would kill the apply half way (its children are
|
||||||
|
/// `kill_on_drop`). A failed heartbeat is only logged and the apply runs to its terminal report.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn failed_heartbeat_after_the_permit_lets_the_apply_finish() {
|
||||||
|
let log = log();
|
||||||
|
let (target_id, application) = (Uuid::new_v4(), Uuid::new_v4());
|
||||||
|
let lease = lease_for(target_id, application, false);
|
||||||
|
let (mut hub, mut targets) = poll_fixture(&log, &lease, target_id);
|
||||||
|
hub.fail_progress = Some("heartbeat");
|
||||||
|
targets.get_mut(&target_id).unwrap().apply = Step::Slow(300);
|
||||||
|
let did = tokio::time::timeout(
|
||||||
|
Duration::from_secs(5),
|
||||||
|
poll(
|
||||||
|
&hub,
|
||||||
|
application,
|
||||||
|
None::<&FakeSource>,
|
||||||
|
&targets,
|
||||||
|
30,
|
||||||
|
Duration::from_millis(50),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect("poll finishes")
|
||||||
|
.unwrap();
|
||||||
|
assert!(did);
|
||||||
|
let log = log.lock().unwrap().clone();
|
||||||
|
let beats = log.iter().filter(|e| *e == "report:heartbeat").count();
|
||||||
|
assert!(beats >= 2, "heartbeats kept being attempted: {beats}");
|
||||||
|
assert_eq!(log.last().map(String::as_str), Some("report:applied"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// If the apply itself fails while heartbeats are failing, the failure is still reported.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn failed_apply_is_still_reported_when_heartbeats_fail() {
|
||||||
|
let log = log();
|
||||||
|
let (target_id, application) = (Uuid::new_v4(), Uuid::new_v4());
|
||||||
|
let lease = lease_for(target_id, application, false);
|
||||||
|
let (mut hub, mut targets) = poll_fixture(&log, &lease, target_id);
|
||||||
|
hub.fail_progress = Some("heartbeat");
|
||||||
|
targets.get_mut(&target_id).unwrap().apply = Step::Hang;
|
||||||
|
let err = tokio::time::timeout(
|
||||||
|
Duration::from_secs(5),
|
||||||
|
poll(
|
||||||
|
&hub,
|
||||||
|
application,
|
||||||
|
None::<&FakeSource>,
|
||||||
|
&targets,
|
||||||
|
1,
|
||||||
|
Duration::from_millis(50),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect("apply timeout ends the poll")
|
||||||
|
.unwrap();
|
||||||
|
assert!(err);
|
||||||
|
let log = log.lock().unwrap().clone();
|
||||||
|
assert!(log.iter().any(|e| e.starts_with("failed:apply_failed:")));
|
||||||
|
}
|
||||||
@@ -33,6 +33,9 @@ pub struct ImportArgs {
|
|||||||
/// Reconcile counts, times and sizes without downloading or writing snapshots.
|
/// Reconcile counts, times and sizes without downloading or writing snapshots.
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
inventory_only: bool,
|
inventory_only: bool,
|
||||||
|
/// The AWS CLI to run; a field only so tests can substitute a fake one.
|
||||||
|
#[arg(skip = PathBuf::from("aws"))]
|
||||||
|
program: PathBuf,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy, ValueEnum)]
|
#[derive(Clone, Copy, ValueEnum)]
|
||||||
@@ -96,6 +99,12 @@ struct Report {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn run(vault: &Vault, args: ImportArgs) -> Result<()> {
|
pub fn run(vault: &Vault, args: ImportArgs) -> Result<()> {
|
||||||
|
let report = reconcile(vault, args)?;
|
||||||
|
println!("{}", serde_json::to_string_pretty(&report)?);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reconcile(vault: &Vault, args: ImportArgs) -> Result<Report> {
|
||||||
ensure!(
|
ensure!(
|
||||||
!args.prefix.is_empty() && args.prefix.ends_with('/'),
|
!args.prefix.is_empty() && args.prefix.ends_with('/'),
|
||||||
"provide a per-application prefix ending in '/'"
|
"provide a per-application prefix ending in '/'"
|
||||||
@@ -173,7 +182,7 @@ pub fn run(vault: &Vault, args: ImportArgs) -> Result<()> {
|
|||||||
.map(|path| import_history(vault, path))
|
.map(|path| import_history(vault, path))
|
||||||
.transpose()?
|
.transpose()?
|
||||||
};
|
};
|
||||||
let report = Report {
|
Ok(Report {
|
||||||
application: args.application,
|
application: args.application,
|
||||||
bucket: args.bucket,
|
bucket: args.bucket,
|
||||||
prefix: args.prefix,
|
prefix: args.prefix,
|
||||||
@@ -181,13 +190,11 @@ pub fn run(vault: &Vault, args: ImportArgs) -> Result<()> {
|
|||||||
bytes,
|
bytes,
|
||||||
history_snapshot_id,
|
history_snapshot_id,
|
||||||
objects,
|
objects,
|
||||||
};
|
})
|
||||||
println!("{}", serde_json::to_string_pretty(&report)?);
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn aws(args: &ImportArgs, operation: &str) -> Command {
|
fn aws(args: &ImportArgs, operation: &str) -> Command {
|
||||||
let mut cmd = Command::new("aws");
|
let mut cmd = Command::new(&args.program);
|
||||||
cmd.args([
|
cmd.args([
|
||||||
"--no-cli-pager",
|
"--no-cli-pager",
|
||||||
"--no-cli-auto-prompt",
|
"--no-cli-auto-prompt",
|
||||||
@@ -285,3 +292,496 @@ fn import_history(vault: &Vault, path: &std::path::Path) -> Result<Uuid> {
|
|||||||
vault.import_legacy_payload(manifest, staged, taken_at)?;
|
vault.import_legacy_payload(manifest, staged, taken_at)?;
|
||||||
Ok(id)
|
Ok(id)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// These drive `reconcile` against a stand-in `aws` (a shell script that serves a local directory), so the
|
||||||
|
/// listing, conditional download, receipts and history paths all run for real; only S3 is faked.
|
||||||
|
#[cfg(all(test, unix))]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use serde_json::{json, Value};
|
||||||
|
use std::{fs, os::unix::fs::PermissionsExt, path::Path};
|
||||||
|
|
||||||
|
const ETAG: &str = "\"9b2cf535f27731c974343645a3985328\"";
|
||||||
|
const WHEN: &str = "2026-01-02T03:04:05+00:00";
|
||||||
|
|
||||||
|
struct Fixture {
|
||||||
|
dir: tempfile::TempDir,
|
||||||
|
vault: Vault,
|
||||||
|
listing: Vec<Value>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Fixture {
|
||||||
|
fn new() -> Self {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let vault = Vault::init(dir.path().join("vault"), "synthetic-passphrase").unwrap();
|
||||||
|
let fake = dir.path().join("fake");
|
||||||
|
fs::create_dir_all(fake.join("obj")).unwrap();
|
||||||
|
fs::create_dir_all(fake.join("meta")).unwrap();
|
||||||
|
let script = format!(
|
||||||
|
r#"#!/bin/sh
|
||||||
|
D='{}'
|
||||||
|
op="$6"
|
||||||
|
echo "$op" >> "$D/calls"
|
||||||
|
case "$op" in
|
||||||
|
list-objects-v2)
|
||||||
|
[ -f "$D/list.fail" ] && exit 1
|
||||||
|
cat "$D/list.json" ;;
|
||||||
|
get-object)
|
||||||
|
for a in "$@"; do
|
||||||
|
last="$a"
|
||||||
|
case "$a" in --key=*) key="${{a#--key=}}" ;; esac
|
||||||
|
done
|
||||||
|
name=$(basename "$key")
|
||||||
|
[ -f "$D/get.fail.$name" ] && exit 1
|
||||||
|
cp "$D/obj/$name" "$last"
|
||||||
|
cat "$D/meta/$name.json" ;;
|
||||||
|
esac
|
||||||
|
"#,
|
||||||
|
fake.display()
|
||||||
|
);
|
||||||
|
let program = dir.path().join("aws");
|
||||||
|
fs::write(&program, script).unwrap();
|
||||||
|
fs::set_permissions(&program, fs::Permissions::from_mode(0o755)).unwrap();
|
||||||
|
let fixture = Self {
|
||||||
|
dir,
|
||||||
|
vault,
|
||||||
|
listing: vec![],
|
||||||
|
};
|
||||||
|
fixture.publish();
|
||||||
|
fixture
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fake(&self) -> std::path::PathBuf {
|
||||||
|
self.dir.path().join("fake")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn publish(&self) {
|
||||||
|
fs::write(
|
||||||
|
self.fake().join("list.json"),
|
||||||
|
json!({ "Contents": self.listing }).to_string(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Put an object in the listing and on the fake bucket, with matching download metadata.
|
||||||
|
fn add(&mut self, key: &str, body: &[u8]) {
|
||||||
|
self.add_listed(key, body, body.len() as u64, ETAG);
|
||||||
|
let name = key.rsplit('/').next().unwrap();
|
||||||
|
fs::write(self.fake().join("obj").join(name), body).unwrap();
|
||||||
|
self.meta(key, ETAG, body.len() as u64, WHEN);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Only the listing entry, for metadata the object itself would not match.
|
||||||
|
fn add_listed(&mut self, key: &str, _body: &[u8], size: u64, etag: &str) {
|
||||||
|
self.listing.push(json!({
|
||||||
|
"Key": key, "ETag": etag, "Size": size, "LastModified": WHEN
|
||||||
|
}));
|
||||||
|
self.publish();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn meta(&self, key: &str, etag: &str, length: u64, modified: &str) {
|
||||||
|
let name = key.rsplit('/').next().unwrap();
|
||||||
|
fs::write(
|
||||||
|
self.fake().join("meta").join(format!("{name}.json")),
|
||||||
|
json!({"ETag": etag, "ContentLength": length, "LastModified": modified})
|
||||||
|
.to_string(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn calls(&self) -> Vec<String> {
|
||||||
|
fs::read_to_string(self.fake().join("calls"))
|
||||||
|
.unwrap_or_default()
|
||||||
|
.lines()
|
||||||
|
.map(str::to_owned)
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn args(&self) -> ImportArgs {
|
||||||
|
ImportArgs {
|
||||||
|
bucket: "legacy-bucket".into(),
|
||||||
|
prefix: "backups/shop/".into(),
|
||||||
|
endpoint: None,
|
||||||
|
orbit_id: Uuid::from_u128(7),
|
||||||
|
application: "shop".into(),
|
||||||
|
engine: Engine::Postgres,
|
||||||
|
history: None,
|
||||||
|
inventory_only: false,
|
||||||
|
program: self.dir.path().join("aws"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run(&self, args: ImportArgs) -> Result<Report> {
|
||||||
|
reconcile(&self.vault, args)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn snapshots(&self) -> usize {
|
||||||
|
self.vault.list_snapshots().unwrap().len()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn receipts(&self) -> usize {
|
||||||
|
fs::read_dir(self.vault.root().join("keys/legacy-imports"))
|
||||||
|
.map(|entries| entries.count())
|
||||||
|
.unwrap_or(0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn gzip_header(rest: &[u8]) -> Vec<u8> {
|
||||||
|
[&[0x1f, 0x8b][..], rest].concat()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn statuses(report: &Report) -> Vec<&'static str> {
|
||||||
|
report.objects.iter().map(|o| o.status).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- arguments are validated before anything is listed ----
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bad_arguments_are_refused_before_aws_is_run() {
|
||||||
|
let fx = Fixture::new();
|
||||||
|
type Tweak = fn(&mut ImportArgs);
|
||||||
|
let cases: [(&str, Tweak); 11] = [
|
||||||
|
("empty prefix", |a| a.prefix = String::new()),
|
||||||
|
("prefix without a trailing slash", |a| {
|
||||||
|
a.prefix = "backups/shop".into()
|
||||||
|
}),
|
||||||
|
("blank application", |a| a.application = " ".into()),
|
||||||
|
("long application", |a| a.application = "a".repeat(129)),
|
||||||
|
("control in application", |a| {
|
||||||
|
a.application = "sh\nop".into()
|
||||||
|
}),
|
||||||
|
("plain http endpoint", |a| {
|
||||||
|
a.endpoint = Some("http://s3.example.com".into())
|
||||||
|
}),
|
||||||
|
("http on another loopback port form", |a| {
|
||||||
|
a.endpoint = Some("http://localhost:9000".into())
|
||||||
|
}),
|
||||||
|
("credentials in the endpoint", |a| {
|
||||||
|
a.endpoint = Some("https://user:pw@s3.example.com".into())
|
||||||
|
}),
|
||||||
|
("query in the endpoint", |a| {
|
||||||
|
a.endpoint = Some("https://s3.example.com/?x=1".into())
|
||||||
|
}),
|
||||||
|
("fragment in the endpoint", |a| {
|
||||||
|
a.endpoint = Some("https://s3.example.com/#x".into())
|
||||||
|
}),
|
||||||
|
("newline in the endpoint", |a| {
|
||||||
|
a.endpoint = Some("https://s3.example.com/\nx".into())
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
for (what, tweak) in cases {
|
||||||
|
let mut args = fx.args();
|
||||||
|
tweak(&mut args);
|
||||||
|
assert!(fx.run(args).is_err(), "{what} must be refused");
|
||||||
|
}
|
||||||
|
assert!(fx.calls().is_empty(), "aws was never run");
|
||||||
|
let mut ok = fx.args();
|
||||||
|
ok.endpoint = Some("http://127.0.0.1:9000".into());
|
||||||
|
assert!(fx.run(ok).is_ok(), "a local test endpoint is allowed");
|
||||||
|
let mut ok = fx.args();
|
||||||
|
ok.endpoint = Some("https://s3.example.com".into());
|
||||||
|
assert!(fx.run(ok).is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- inventory ----
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn inventory_counts_only_sql_archives_under_the_prefix_and_writes_nothing() {
|
||||||
|
let mut fx = Fixture::new();
|
||||||
|
fx.add("backups/shop/a.sql", b"select 1;");
|
||||||
|
fx.add("backups/shop/b.sql.gz", &gzip_header(b"zz"));
|
||||||
|
fx.add("backups/shop/readme.txt", b"not a dump");
|
||||||
|
fx.add("backups/shop/nested/c.sql", b"select 3;");
|
||||||
|
fx.add("backups/shop/d.sql.bak", b"select 4;");
|
||||||
|
fx.add("backups/other/e.sql", b"another application");
|
||||||
|
fx.add("backups/shopping/f.sql", b"prefix lookalike");
|
||||||
|
let mut args = fx.args();
|
||||||
|
args.inventory_only = true;
|
||||||
|
let report = fx.run(args).unwrap();
|
||||||
|
assert_eq!(report.count, 3, "a, b and nested/c");
|
||||||
|
assert_eq!(report.bytes, 9 + 4 + 9);
|
||||||
|
assert_eq!(statuses(&report), ["inventoried"; 3]);
|
||||||
|
assert!(report.history_snapshot_id.is_none());
|
||||||
|
assert_eq!(fx.snapshots(), 0);
|
||||||
|
assert_eq!(fx.receipts(), 0);
|
||||||
|
assert_eq!(fx.calls(), ["list-objects-v2"], "no object was downloaded");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn inventory_only_ignores_a_history_export() {
|
||||||
|
let fx = Fixture::new();
|
||||||
|
let history = fx.dir.path().join("history.sqlite");
|
||||||
|
fs::write(&history, b"SQLite format 3\0 rows").unwrap();
|
||||||
|
let mut args = fx.args();
|
||||||
|
args.inventory_only = true;
|
||||||
|
args.history = Some(history);
|
||||||
|
let report = fx.run(args).unwrap();
|
||||||
|
assert!(report.history_snapshot_id.is_none());
|
||||||
|
assert_eq!(fx.snapshots(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_empty_or_missing_listing_is_a_clean_zero() {
|
||||||
|
let fx = Fixture::new();
|
||||||
|
let report = fx.run(fx.args()).unwrap();
|
||||||
|
assert_eq!((report.count, report.bytes), (0, 0));
|
||||||
|
fs::write(fx.fake().join("list.json"), "{}").unwrap();
|
||||||
|
assert_eq!(fx.run(fx.args()).unwrap().count, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn listing_failures_stop_the_run() {
|
||||||
|
let fx = Fixture::new();
|
||||||
|
fs::write(fx.fake().join("list.fail"), "").unwrap();
|
||||||
|
let err = fx.run(fx.args()).err().unwrap();
|
||||||
|
assert!(format!("{err:#}").contains("could not list"), "{err:#}");
|
||||||
|
fs::remove_file(fx.fake().join("list.fail")).unwrap();
|
||||||
|
for broken in [
|
||||||
|
"",
|
||||||
|
"not json",
|
||||||
|
r#"{"Contents":[{"Key":"x"}]}"#,
|
||||||
|
r#"{"Contents":"x"}"#,
|
||||||
|
] {
|
||||||
|
fs::write(fx.fake().join("list.json"), broken).unwrap();
|
||||||
|
assert!(fx.run(fx.args()).is_err(), "listing {broken:?}");
|
||||||
|
}
|
||||||
|
let missing = ImportArgs {
|
||||||
|
program: fx.dir.path().join("no-such-aws"),
|
||||||
|
..fx.args()
|
||||||
|
};
|
||||||
|
assert!(fx.run(missing).is_err(), "no aws binary is an error");
|
||||||
|
assert_eq!(fx.snapshots(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn untrustworthy_inventory_metadata_is_refused() {
|
||||||
|
for (size, etag) in [(0, ETAG), (5, ""), (5, "*")] {
|
||||||
|
let mut fx = Fixture::new();
|
||||||
|
fx.add_listed("backups/shop/a.sql", b"", size, etag);
|
||||||
|
let err = fx.run(fx.args()).err().unwrap();
|
||||||
|
assert!(
|
||||||
|
format!("{err:#}").contains("invalid legacy archive metadata"),
|
||||||
|
"size {size} etag {etag:?}: {err:#}"
|
||||||
|
);
|
||||||
|
assert_eq!(fx.snapshots(), 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_inventory_whose_sizes_overflow_is_refused() {
|
||||||
|
let mut fx = Fixture::new();
|
||||||
|
fx.add_listed("backups/shop/a.sql", b"", u64::MAX, ETAG);
|
||||||
|
fx.add_listed("backups/shop/b.sql", b"", 2, "\"other\"");
|
||||||
|
let mut args = fx.args();
|
||||||
|
args.inventory_only = true;
|
||||||
|
let err = fx.run(args).err().unwrap();
|
||||||
|
assert!(format!("{err:#}").contains("overflow"), "{err:#}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- import ----
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn importing_stores_each_archive_once_and_a_rerun_changes_nothing() {
|
||||||
|
let mut fx = Fixture::new();
|
||||||
|
fx.add("backups/shop/a.sql", b"create table a();");
|
||||||
|
fx.add("backups/shop/b.sql.gz", &gzip_header(b"compressed"));
|
||||||
|
let first = fx.run(fx.args()).unwrap();
|
||||||
|
assert_eq!(statuses(&first), ["imported", "imported"]);
|
||||||
|
assert_eq!((fx.snapshots(), fx.receipts()), (2, 2));
|
||||||
|
let stored = fx
|
||||||
|
.vault
|
||||||
|
.get_snapshot(first.objects[0].snapshot_id)
|
||||||
|
.unwrap()
|
||||||
|
.expect("stored under the reported id");
|
||||||
|
assert_eq!(stored.manifest.orbit_id, Uuid::from_u128(7));
|
||||||
|
assert_eq!(stored.manifest.orbit_name, "shop");
|
||||||
|
assert_eq!(stored.manifest.provider, "postgres");
|
||||||
|
assert_eq!(stored.manifest.labels, ["legacy-import"]);
|
||||||
|
assert_eq!(stored.manifest.restore_hints["format"], "plain");
|
||||||
|
assert_eq!(stored.manifest.restore_hints["legacy"]["etag"], ETAG);
|
||||||
|
let gz = fx
|
||||||
|
.vault
|
||||||
|
.get_snapshot(first.objects[1].snapshot_id)
|
||||||
|
.unwrap()
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(gz.manifest.restore_hints["format"], "sql_gzip");
|
||||||
|
assert_eq!(
|
||||||
|
stored.taken_at,
|
||||||
|
"2026-01-02T03:04:05Z".parse::<DateTime<Utc>>().unwrap(),
|
||||||
|
"the snapshot keeps the original time, not the import time"
|
||||||
|
);
|
||||||
|
let calls_before = fx.calls().len();
|
||||||
|
let second = fx.run(fx.args()).unwrap();
|
||||||
|
assert_eq!(statuses(&second), ["already_imported", "already_imported"]);
|
||||||
|
assert_eq!(
|
||||||
|
fx.calls().len(),
|
||||||
|
calls_before + 1,
|
||||||
|
"the rerun listed but downloaded nothing"
|
||||||
|
);
|
||||||
|
assert_eq!((fx.snapshots(), fx.receipts()), (2, 2));
|
||||||
|
assert_eq!(
|
||||||
|
first.objects[0].snapshot_id, second.objects[0].snapshot_id,
|
||||||
|
"ids are derived, so a rerun finds its own work"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_engine_orbit_and_endpoint_decide_the_mysql_manifest_and_the_snapshot_id() {
|
||||||
|
let mut fx = Fixture::new();
|
||||||
|
fx.add("backups/shop/a.sql", b"create table a();");
|
||||||
|
let mut mysql = fx.args();
|
||||||
|
mysql.engine = Engine::Mysql;
|
||||||
|
let first = fx.run(mysql).unwrap();
|
||||||
|
let stored = fx
|
||||||
|
.vault
|
||||||
|
.get_snapshot(first.objects[0].snapshot_id)
|
||||||
|
.unwrap()
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(stored.manifest.provider, "mysql");
|
||||||
|
// another orbit is a different import of the same bytes, not a duplicate
|
||||||
|
let mut other = fx.args();
|
||||||
|
other.orbit_id = Uuid::from_u128(8);
|
||||||
|
let second = fx.run(other).unwrap();
|
||||||
|
assert_ne!(first.objects[0].snapshot_id, second.objects[0].snapshot_id);
|
||||||
|
assert_eq!(statuses(&second), ["imported"]);
|
||||||
|
// so is another endpoint
|
||||||
|
let mut elsewhere = fx.args();
|
||||||
|
elsewhere.endpoint = Some("https://s3.example.com".into());
|
||||||
|
let third = fx.run(elsewhere).unwrap();
|
||||||
|
assert_ne!(first.objects[0].snapshot_id, third.objects[0].snapshot_id);
|
||||||
|
assert_eq!(fx.snapshots(), 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_object_that_changed_since_the_inventory_is_not_imported() {
|
||||||
|
for (what, etag, length, modified) in [
|
||||||
|
("etag", "\"changed\"", 17, WHEN),
|
||||||
|
("length", ETAG, 18, WHEN),
|
||||||
|
("time", ETAG, 17, "2026-01-02T03:04:06+00:00"),
|
||||||
|
] {
|
||||||
|
let mut fx = Fixture::new();
|
||||||
|
fx.add("backups/shop/a.sql", b"create table a();");
|
||||||
|
fx.meta("backups/shop/a.sql", etag, length, modified);
|
||||||
|
let err = fx.run(fx.args()).err().unwrap();
|
||||||
|
assert!(
|
||||||
|
format!("{err:#}").contains("changed since inventory"),
|
||||||
|
"{what}: {err:#}"
|
||||||
|
);
|
||||||
|
assert_eq!((fx.snapshots(), fx.receipts()), (0, 0), "{what}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_downloaded_file_of_the_wrong_size_is_not_imported() {
|
||||||
|
let mut fx = Fixture::new();
|
||||||
|
fx.add("backups/shop/a.sql", b"create table a();");
|
||||||
|
// the metadata agrees with the listing but fewer bytes arrived
|
||||||
|
fs::write(fx.fake().join("obj/a.sql"), b"create").unwrap();
|
||||||
|
let err = fx.run(fx.args()).err().unwrap();
|
||||||
|
assert!(format!("{err:#}").contains("changed since inventory"));
|
||||||
|
assert_eq!(fx.snapshots(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_gzip_named_archive_must_start_with_the_gzip_signature() {
|
||||||
|
let mut fx = Fixture::new();
|
||||||
|
fx.add("backups/shop/b.sql.gz", b"plainly not gzip");
|
||||||
|
let err = fx.run(fx.args()).err().unwrap();
|
||||||
|
assert!(format!("{err:#}").contains("gzip header"), "{err:#}");
|
||||||
|
assert_eq!((fx.snapshots(), fx.receipts()), (0, 0));
|
||||||
|
// a one-byte file cannot even hold the signature
|
||||||
|
let mut tiny = Fixture::new();
|
||||||
|
tiny.add("backups/shop/t.sql.gz", &[0x1f]);
|
||||||
|
assert!(tiny.run(tiny.args()).is_err());
|
||||||
|
assert_eq!(tiny.snapshots(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_plain_sql_archive_is_not_inspected_for_a_signature() {
|
||||||
|
let mut fx = Fixture::new();
|
||||||
|
fx.add("backups/shop/a.sql", &gzip_header(b"gz bytes in a .sql"));
|
||||||
|
let report = fx.run(fx.args()).unwrap();
|
||||||
|
assert_eq!(statuses(&report), ["imported"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_failed_download_stops_the_run_and_a_retry_resumes_where_it_left_off() {
|
||||||
|
let mut fx = Fixture::new();
|
||||||
|
fx.add("backups/shop/a.sql", b"create table a();");
|
||||||
|
fx.add("backups/shop/b.sql", b"create table b();");
|
||||||
|
fs::write(fx.fake().join("get.fail.b.sql"), "").unwrap();
|
||||||
|
let err = fx.run(fx.args()).err().unwrap();
|
||||||
|
assert!(format!("{err:#}").contains("download failed"), "{err:#}");
|
||||||
|
assert_eq!((fx.snapshots(), fx.receipts()), (1, 1), "a was kept");
|
||||||
|
fs::remove_file(fx.fake().join("get.fail.b.sql")).unwrap();
|
||||||
|
let retry = fx.run(fx.args()).unwrap();
|
||||||
|
assert_eq!(statuses(&retry), ["already_imported", "imported"]);
|
||||||
|
assert_eq!((fx.snapshots(), fx.receipts()), (2, 2));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_receipt_keeps_an_archive_from_returning_after_its_snapshot_is_forgotten() {
|
||||||
|
let mut fx = Fixture::new();
|
||||||
|
fx.add("backups/shop/a.sql", b"create table a();");
|
||||||
|
let first = fx.run(fx.args()).unwrap();
|
||||||
|
let id = first.objects[0].snapshot_id;
|
||||||
|
assert!(fx.vault.legacy_import_exists(id).unwrap());
|
||||||
|
fx.vault.forget(&[id]).unwrap();
|
||||||
|
assert_eq!(fx.snapshots(), 0);
|
||||||
|
let again = fx.run(fx.args()).unwrap();
|
||||||
|
assert_eq!(statuses(&again), ["already_imported"]);
|
||||||
|
assert_eq!(fx.snapshots(), 0, "retention's decision is not undone");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- the operator-history export ----
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_history_export_must_be_a_sqlite_file() {
|
||||||
|
let fx = Fixture::new();
|
||||||
|
let write = |name: &str, bytes: &[u8]| {
|
||||||
|
let path = fx.dir.path().join(name);
|
||||||
|
fs::write(&path, bytes).unwrap();
|
||||||
|
path
|
||||||
|
};
|
||||||
|
for (name, bytes) in [
|
||||||
|
("empty", &b""[..]),
|
||||||
|
("short", b"SQLite"),
|
||||||
|
("text", b"just a text file, long enough to read"),
|
||||||
|
("near", b"SQLite format 3 not-nul-terminated"),
|
||||||
|
("wal", b"SQLite format 4\0 later version"),
|
||||||
|
] {
|
||||||
|
let mut args = fx.args();
|
||||||
|
args.history = Some(write(name, bytes));
|
||||||
|
assert!(fx.run(args).is_err(), "{name} must be refused");
|
||||||
|
}
|
||||||
|
let mut missing = fx.args();
|
||||||
|
missing.history = Some(Path::new("/definitely/not/here.sqlite").into());
|
||||||
|
assert!(fx.run(missing).is_err());
|
||||||
|
assert_eq!(fx.snapshots(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_history_export_is_stored_once_and_identified_by_its_content() {
|
||||||
|
let fx = Fixture::new();
|
||||||
|
let path = fx.dir.path().join("history.sqlite");
|
||||||
|
fs::write(&path, b"SQLite format 3\0 first export").unwrap();
|
||||||
|
let mut args = fx.args();
|
||||||
|
args.history = Some(path.clone());
|
||||||
|
let first = fx.run(args.clone()).unwrap();
|
||||||
|
let id = first.history_snapshot_id.expect("history imported");
|
||||||
|
assert_eq!(fx.snapshots(), 1);
|
||||||
|
let stored = fx.vault.get_snapshot(id).unwrap().unwrap();
|
||||||
|
assert_eq!(stored.manifest.provider, "legacy-history");
|
||||||
|
assert_eq!(stored.manifest.orbit_id, Uuid::nil());
|
||||||
|
assert_eq!(stored.manifest.restore_hints["format"], "sqlite");
|
||||||
|
// same bytes: same snapshot, nothing new stored
|
||||||
|
let second = fx.run(args.clone()).unwrap();
|
||||||
|
assert_eq!(second.history_snapshot_id, Some(id));
|
||||||
|
assert_eq!(fx.snapshots(), 1);
|
||||||
|
// different bytes: a different snapshot
|
||||||
|
fs::write(&path, b"SQLite format 3\0 second export").unwrap();
|
||||||
|
let third = fx.run(args).unwrap();
|
||||||
|
assert_ne!(third.history_snapshot_id, Some(id));
|
||||||
|
assert_eq!(fx.snapshots(), 2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -441,4 +441,398 @@ mod tests {
|
|||||||
assert!(manifest.is_restore_safety());
|
assert!(manifest.is_restore_safety());
|
||||||
assert_eq!(manifest.safety_target().as_deref(), Some("t"));
|
assert_eq!(manifest.safety_target().as_deref(), Some("t"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- boundaries ----
|
||||||
|
|
||||||
|
fn at(y: i32, mo: u32, d: u32, h: u32, mi: u32, sec: u32) -> DateTime<Utc> {
|
||||||
|
Utc.with_ymd_and_hms(y, mo, d, h, mi, sec).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn snap(taken_at: DateTime<Utc>) -> SnapshotRef {
|
||||||
|
SnapshotRef {
|
||||||
|
id: Uuid::new_v4(),
|
||||||
|
taken_at,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn capture_age_boundary_is_a_whole_number_of_days() {
|
||||||
|
let now = at(2026, 11, 20, 12, 0, 0);
|
||||||
|
let newest = snap(now);
|
||||||
|
let exactly = snap(now - Duration::days(14));
|
||||||
|
let just_under = snap(now - Duration::days(14) + Duration::seconds(1));
|
||||||
|
let policy = CaptureRetention::Age { days: 14 };
|
||||||
|
let forgotten = evaluate_capture_retention(
|
||||||
|
policy,
|
||||||
|
vec![just_under.clone(), exactly.clone(), newest.clone()],
|
||||||
|
now,
|
||||||
|
);
|
||||||
|
assert_eq!(forgotten, [exactly.id], "14 days old to the second goes");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn capture_retention_never_forgets_the_newest_even_when_ancient_or_in_the_future() {
|
||||||
|
let now = at(2026, 11, 20, 12, 0, 0);
|
||||||
|
for policy in [
|
||||||
|
CaptureRetention::Age { days: 1 },
|
||||||
|
CaptureRetention::Count { keep: 1 },
|
||||||
|
] {
|
||||||
|
let only = snap(now - Duration::days(4000));
|
||||||
|
assert!(evaluate_capture_retention(policy, vec![only], now).is_empty());
|
||||||
|
// a snapshot stamped in the future (clock skew) has negative age and is never expired
|
||||||
|
let future = snap(now + Duration::days(3));
|
||||||
|
let old = snap(now - Duration::days(30));
|
||||||
|
assert_eq!(
|
||||||
|
evaluate_capture_retention(policy, vec![old.clone(), future], now),
|
||||||
|
[old.id]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert!(evaluate_capture_retention(CaptureRetention::default(), vec![], now).is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn capture_count_boundaries() {
|
||||||
|
let now = at(2026, 11, 20, 12, 0, 0);
|
||||||
|
let snaps: Vec<_> = (0..4).map(|i| snap(now - Duration::hours(i))).collect();
|
||||||
|
let count = |keep| {
|
||||||
|
evaluate_capture_retention(CaptureRetention::Count { keep }, snaps.clone(), now).len()
|
||||||
|
};
|
||||||
|
assert_eq!(count(1), 3);
|
||||||
|
assert_eq!(count(3), 1);
|
||||||
|
assert_eq!(count(4), 0, "keeping exactly as many as exist forgets none");
|
||||||
|
assert_eq!(count(u16::MAX), 0);
|
||||||
|
// keep 0 is rejected by validation, but must still not forget the newest if it slips through
|
||||||
|
assert!(!CaptureRetention::Count { keep: 0 }.is_valid());
|
||||||
|
assert!(!CaptureRetention::Age { days: 0 }.is_valid());
|
||||||
|
let forgotten =
|
||||||
|
evaluate_capture_retention(CaptureRetention::Count { keep: 0 }, snaps.clone(), now);
|
||||||
|
assert!(!forgotten.contains(&snaps[0].id));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn equal_timestamps_are_ordered_by_id_so_the_outcome_is_deterministic() {
|
||||||
|
let now = at(2026, 11, 20, 12, 0, 0);
|
||||||
|
let mut twins = vec![snap(now), snap(now), snap(now)];
|
||||||
|
let keep_one = CaptureRetention::Count { keep: 1 };
|
||||||
|
let first = evaluate_capture_retention(keep_one, twins.clone(), now);
|
||||||
|
twins.reverse();
|
||||||
|
let second = evaluate_capture_retention(keep_one, twins, now);
|
||||||
|
assert_eq!(set(&first), set(&second));
|
||||||
|
assert_eq!(first.len(), 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn safety_age_boundary_is_seven_whole_days() {
|
||||||
|
let now = at(2026, 11, 30, 12, 0, 0);
|
||||||
|
let copy = |age: Duration| SafetyRef {
|
||||||
|
id: Uuid::new_v4(),
|
||||||
|
taken_at: now - age,
|
||||||
|
target: "t".into(),
|
||||||
|
};
|
||||||
|
// three fresh copies fill the per-target quota, so age alone decides for the next two
|
||||||
|
let pad: Vec<_> = (1..=3).map(|i| copy(Duration::hours(i))).collect();
|
||||||
|
let exactly_seven = copy(Duration::days(7));
|
||||||
|
let just_under = copy(Duration::days(7) - Duration::seconds(1));
|
||||||
|
let forgotten = evaluate_safety_retention(
|
||||||
|
pad.into_iter()
|
||||||
|
.chain([exactly_seven.clone(), just_under.clone()])
|
||||||
|
.collect(),
|
||||||
|
now,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
forgotten,
|
||||||
|
[exactly_seven.id],
|
||||||
|
"exactly 7 days old is no longer recent; one second less still is"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn safety_retention_handles_empty_and_a_lone_ancient_copy() {
|
||||||
|
let now = at(2030, 1, 1, 0, 0, 0);
|
||||||
|
assert!(evaluate_safety_retention(vec![], now).is_empty());
|
||||||
|
assert!(evaluate_safety_retention(vec![safety(1, "only")], now).is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn gfs_period_boundaries_are_utc_midnight_iso_weeks_and_calendar_years() {
|
||||||
|
let daily = RetentionPolicy {
|
||||||
|
keep_daily: 2,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let last_second = snap(at(2025, 12, 31, 23, 59, 59));
|
||||||
|
let first_second = snap(at(2026, 1, 1, 0, 0, 0));
|
||||||
|
let earlier = snap(at(2025, 12, 31, 0, 0, 0));
|
||||||
|
// 23:59:59 and 00:00:00 straddle a day, so both days count and each keeps its newest
|
||||||
|
assert_eq!(
|
||||||
|
evaluate_gfs(
|
||||||
|
&daily,
|
||||||
|
vec![earlier.clone(), last_second.clone(), first_second.clone()]
|
||||||
|
),
|
||||||
|
[earlier.id]
|
||||||
|
);
|
||||||
|
// ISO weeks: Sun 2024-12-29 is week 52; Mon 2024-12-30 and Wed 2025-01-01 are week 1 of 2025
|
||||||
|
let weekly = RetentionPolicy {
|
||||||
|
keep_weekly: 2,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let sunday = snap(at(2024, 12, 29, 12, 0, 0));
|
||||||
|
let monday = snap(at(2024, 12, 30, 0, 0, 0));
|
||||||
|
let wednesday = snap(at(2025, 1, 1, 12, 0, 0));
|
||||||
|
assert_eq!(
|
||||||
|
evaluate_gfs(&weekly, vec![sunday, monday.clone(), wednesday]),
|
||||||
|
[monday.id]
|
||||||
|
);
|
||||||
|
// ISO week 53 of 2020 spans the new year
|
||||||
|
let a = snap(at(2020, 12, 31, 1, 0, 0));
|
||||||
|
let b = snap(at(2021, 1, 1, 1, 0, 0));
|
||||||
|
let one_week = RetentionPolicy {
|
||||||
|
keep_weekly: 1,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
assert_eq!(evaluate_gfs(&one_week, vec![a.clone(), b]), [a.id]);
|
||||||
|
let yearly = RetentionPolicy {
|
||||||
|
keep_yearly: 1,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
evaluate_gfs(&yearly, vec![first_second.clone(), last_second.clone()]),
|
||||||
|
[last_second.id]
|
||||||
|
);
|
||||||
|
// the same month number in another year is a different month
|
||||||
|
let monthly = RetentionPolicy {
|
||||||
|
keep_monthly: 2,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let jan25 = snap(at(2025, 1, 15, 0, 0, 0));
|
||||||
|
let jan26 = snap(at(2026, 1, 15, 0, 0, 0));
|
||||||
|
let jan26_early = snap(at(2026, 1, 2, 0, 0, 0));
|
||||||
|
assert_eq!(
|
||||||
|
evaluate_gfs(&monthly, vec![jan25, jan26, jan26_early.clone()]),
|
||||||
|
[jan26_early.id]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn gfs_edge_inputs() {
|
||||||
|
let all_tiers = RetentionPolicy {
|
||||||
|
keep_daily: 3,
|
||||||
|
keep_weekly: 3,
|
||||||
|
keep_monthly: 3,
|
||||||
|
keep_yearly: 3,
|
||||||
|
};
|
||||||
|
assert!(evaluate_gfs(&all_tiers, vec![]).is_empty());
|
||||||
|
assert!(evaluate_gfs(&all_tiers, vec![snap(at(2020, 2, 29, 0, 0, 0))]).is_empty());
|
||||||
|
// all tiers zero means no policy, which keeps everything rather than forgetting everything
|
||||||
|
let many: Vec<_> = (1..=5).map(|d| snap(at(2026, 1, d, 0, 0, 0))).collect();
|
||||||
|
assert!(evaluate_gfs(&RetentionPolicy::default(), many.clone()).is_empty());
|
||||||
|
let huge = RetentionPolicy {
|
||||||
|
keep_daily: u32::MAX,
|
||||||
|
keep_weekly: u32::MAX,
|
||||||
|
keep_monthly: u32::MAX,
|
||||||
|
keep_yearly: u32::MAX,
|
||||||
|
};
|
||||||
|
assert!(evaluate_gfs(&huge, many).is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- properties, over seeded pseudo-random histories (no extra dependency) ----
|
||||||
|
|
||||||
|
struct Rng(u64);
|
||||||
|
|
||||||
|
impl Rng {
|
||||||
|
fn next(&mut self) -> u64 {
|
||||||
|
self.0 ^= self.0 << 13;
|
||||||
|
self.0 ^= self.0 >> 7;
|
||||||
|
self.0 ^= self.0 << 17;
|
||||||
|
self.0
|
||||||
|
}
|
||||||
|
|
||||||
|
fn below(&mut self, n: u64) -> u64 {
|
||||||
|
self.next() % n
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn history(rng: &mut Rng, now: DateTime<Utc>) -> Vec<SnapshotRef> {
|
||||||
|
let n = rng.below(60);
|
||||||
|
(0..n)
|
||||||
|
.map(|_| {
|
||||||
|
// about three years at second resolution, with some collisions on whole hours
|
||||||
|
let secs = rng.below(3 * 365 * 86_400) as i64;
|
||||||
|
let secs = if rng.below(4) == 0 {
|
||||||
|
secs - secs % 3600
|
||||||
|
} else {
|
||||||
|
secs
|
||||||
|
};
|
||||||
|
snap(now - Duration::seconds(secs))
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn random_policy(rng: &mut Rng) -> RetentionPolicy {
|
||||||
|
RetentionPolicy {
|
||||||
|
keep_daily: rng.below(10) as u32,
|
||||||
|
keep_weekly: rng.below(10) as u32,
|
||||||
|
keep_monthly: rng.below(14) as u32,
|
||||||
|
keep_yearly: rng.below(5) as u32,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn survivors(all: &[SnapshotRef], forgotten: &[Uuid]) -> Vec<SnapshotRef> {
|
||||||
|
all.iter()
|
||||||
|
.filter(|s| !forgotten.contains(&s.id))
|
||||||
|
.cloned()
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn shuffled(rng: &mut Rng, mut v: Vec<SnapshotRef>) -> Vec<SnapshotRef> {
|
||||||
|
for i in (1..v.len()).rev() {
|
||||||
|
v.swap(i, rng.below(i as u64 + 1) as usize);
|
||||||
|
}
|
||||||
|
v
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set(ids: &[Uuid]) -> HashSet<Uuid> {
|
||||||
|
ids.iter().copied().collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn newest(all: &[SnapshotRef]) -> Option<&SnapshotRef> {
|
||||||
|
all.iter().max_by_key(|s| (s.taken_at, s.id))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn gfs_properties_hold_for_random_histories() {
|
||||||
|
let now = at(2026, 11, 20, 12, 0, 0);
|
||||||
|
let mut rng = Rng(0x9E37_79B9_7F4A_7C15);
|
||||||
|
for _ in 0..400 {
|
||||||
|
let all = history(&mut rng, now);
|
||||||
|
let policy = random_policy(&mut rng);
|
||||||
|
let forgotten = evaluate_gfs(&policy, all.clone());
|
||||||
|
let ids: Vec<_> = all.iter().map(|s| s.id).collect();
|
||||||
|
// only names snapshots it was given, each at most once
|
||||||
|
assert!(set(&forgotten).is_subset(&set(&ids)));
|
||||||
|
assert_eq!(set(&forgotten).len(), forgotten.len());
|
||||||
|
// the newest survives whenever any tier is switched on
|
||||||
|
if policy.has_tiers() {
|
||||||
|
if let Some(newest) = newest(&all) {
|
||||||
|
assert!(!forgotten.contains(&newest.id), "{policy:?}");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
assert!(forgotten.is_empty());
|
||||||
|
}
|
||||||
|
// input order is irrelevant
|
||||||
|
let again = evaluate_gfs(&policy, shuffled(&mut rng, all.clone()));
|
||||||
|
assert_eq!(set(&forgotten), set(&again));
|
||||||
|
// applying the policy to what is left forgets nothing more
|
||||||
|
let left = survivors(&all, &forgotten);
|
||||||
|
assert!(evaluate_gfs(&policy, left).is_empty(), "{policy:?}");
|
||||||
|
// keeping more of any tier never forgets more
|
||||||
|
let wider = RetentionPolicy {
|
||||||
|
keep_daily: policy.keep_daily + rng.below(3) as u32,
|
||||||
|
keep_weekly: policy.keep_weekly + rng.below(3) as u32,
|
||||||
|
keep_monthly: policy.keep_monthly + rng.below(3) as u32,
|
||||||
|
keep_yearly: policy.keep_yearly + rng.below(3) as u32,
|
||||||
|
};
|
||||||
|
assert!(set(&evaluate_gfs(&wider, all)).is_subset(&set(&forgotten)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn capture_retention_properties_hold_for_random_histories() {
|
||||||
|
let now = at(2026, 11, 20, 12, 0, 0);
|
||||||
|
let mut rng = Rng(0xD1B5_4A32_D192_ED03);
|
||||||
|
for _ in 0..400 {
|
||||||
|
let all = history(&mut rng, now);
|
||||||
|
let policy = if rng.below(2) == 0 {
|
||||||
|
CaptureRetention::Age {
|
||||||
|
days: 1 + rng.below(400) as u16,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
CaptureRetention::Count {
|
||||||
|
keep: 1 + rng.below(20) as u16,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let forgotten = evaluate_capture_retention(policy, all.clone(), now);
|
||||||
|
assert_eq!(set(&forgotten).len(), forgotten.len());
|
||||||
|
if let Some(newest) = newest(&all) {
|
||||||
|
assert!(!forgotten.contains(&newest.id));
|
||||||
|
}
|
||||||
|
let left = survivors(&all, &forgotten);
|
||||||
|
assert!(evaluate_capture_retention(policy, left, now).is_empty());
|
||||||
|
let again = evaluate_capture_retention(policy, shuffled(&mut rng, all.clone()), now);
|
||||||
|
assert_eq!(set(&forgotten), set(&again));
|
||||||
|
if let CaptureRetention::Count { keep } = policy {
|
||||||
|
assert_eq!(
|
||||||
|
all.len() - forgotten.len(),
|
||||||
|
all.len().min(usize::from(keep))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn safety_retention_properties_hold_for_random_histories() {
|
||||||
|
let now = at(2026, 11, 30, 12, 0, 0);
|
||||||
|
let mut rng = Rng(0x2545_F491_4F6C_DD1D);
|
||||||
|
for _ in 0..400 {
|
||||||
|
let all: Vec<SafetyRef> = (0..rng.below(30))
|
||||||
|
.map(|_| SafetyRef {
|
||||||
|
id: Uuid::new_v4(),
|
||||||
|
taken_at: now - Duration::seconds(rng.below(60 * 86_400) as i64),
|
||||||
|
target: format!("t{}", rng.below(3)),
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let forgotten = evaluate_safety_retention(all.clone(), now);
|
||||||
|
assert_eq!(set(&forgotten).len(), forgotten.len());
|
||||||
|
for copy in all.iter().filter(|c| forgotten.contains(&c.id)) {
|
||||||
|
// forgotten means old AND outside its target's newest three
|
||||||
|
assert!(now.signed_duration_since(copy.taken_at).num_days() >= SAFETY_KEEP_DAYS);
|
||||||
|
let newer = all
|
||||||
|
.iter()
|
||||||
|
.filter(|o| {
|
||||||
|
o.target == copy.target && (o.taken_at, o.id) > (copy.taken_at, copy.id)
|
||||||
|
})
|
||||||
|
.count();
|
||||||
|
assert!(newer >= SAFETY_KEEP_PER_TARGET);
|
||||||
|
}
|
||||||
|
for target in ["t0", "t1", "t2"] {
|
||||||
|
let newest = all
|
||||||
|
.iter()
|
||||||
|
.filter(|c| c.target == target)
|
||||||
|
.max_by_key(|c| (c.taken_at, c.id));
|
||||||
|
if let Some(newest) = newest {
|
||||||
|
assert!(!forgotten.contains(&newest.id));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let left: Vec<_> = all
|
||||||
|
.iter()
|
||||||
|
.filter(|c| !forgotten.contains(&c.id))
|
||||||
|
.cloned()
|
||||||
|
.collect();
|
||||||
|
assert!(evaluate_safety_retention(left, now).is_empty());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn legacy_decay_properties_hold_for_random_histories() {
|
||||||
|
let now = at(2026, 11, 20, 12, 0, 0);
|
||||||
|
let mut rng = Rng(0xA076_1D64_78BD_642F);
|
||||||
|
for _ in 0..400 {
|
||||||
|
let all = history(&mut rng, now);
|
||||||
|
let policy = DecayPolicy {
|
||||||
|
keep_daily: rng.below(10) as usize,
|
||||||
|
keep_weekly: rng.below(8) as usize,
|
||||||
|
keep_monthly: rng.below(14) as usize,
|
||||||
|
};
|
||||||
|
let forgotten = evaluate_decay(&policy, all.clone());
|
||||||
|
assert_eq!(set(&forgotten).len(), forgotten.len());
|
||||||
|
let ids: Vec<_> = all.iter().map(|s| s.id).collect();
|
||||||
|
assert!(set(&forgotten).is_subset(&set(&ids)));
|
||||||
|
if policy.keep_daily + policy.keep_weekly + policy.keep_monthly > 0 {
|
||||||
|
if let Some(newest) = newest(&all) {
|
||||||
|
assert!(!forgotten.contains(&newest.id));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let left = survivors(&all, &forgotten);
|
||||||
|
assert!(evaluate_decay(&policy, left).is_empty());
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -582,3 +582,275 @@ async fn sso_endpoints_are_rate_limited_per_source() {
|
|||||||
);
|
);
|
||||||
assert!(h.state.limits.oidc_login_allowed(other));
|
assert!(h.state.limits.oidc_login_allowed(other));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- pairing, the ways it must say no ----
|
||||||
|
|
||||||
|
const START: &str = "/api/v1/wormhole/pairing";
|
||||||
|
const CLAIM: &str = "/api/v1/wormhole/claim";
|
||||||
|
|
||||||
|
/// A different source address each time, so the per-source claim limit does not interfere.
|
||||||
|
fn fresh_peer() -> String {
|
||||||
|
static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(1);
|
||||||
|
let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||||
|
format!("192.0.{}.{}", (n >> 8) & 255, n & 255)
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Harness {
|
||||||
|
async fn start_code(&self) -> String {
|
||||||
|
let start = self
|
||||||
|
.call(request("POST", START, "127.0.0.1", Some(ADMIN), None))
|
||||||
|
.await;
|
||||||
|
assert_eq!(start.status(), StatusCode::OK);
|
||||||
|
json_of(start).await["code"].as_str().unwrap().to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn claim(&self, _peer: &str, body: Value) -> Response<Body> {
|
||||||
|
self.call(request("POST", CLAIM, &fresh_peer(), None, Some(body)))
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
fn outposts(&self) -> i64 {
|
||||||
|
self.scalar("SELECT COUNT(*) FROM outposts")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn credentials(&self) -> i64 {
|
||||||
|
self.scalar("SELECT COUNT(*) FROM outpost_credentials")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn only_an_admin_can_start_a_pairing() {
|
||||||
|
let h = harness().await;
|
||||||
|
for auth in [None, Some("wrong-token"), Some("")] {
|
||||||
|
let status = h
|
||||||
|
.status(request("POST", START, "127.0.0.1", auth, None))
|
||||||
|
.await;
|
||||||
|
assert!(
|
||||||
|
status == StatusCode::UNAUTHORIZED || status == StatusCode::FORBIDDEN,
|
||||||
|
"{auth:?} must not start a pairing, got {status}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// a paired agent's upload token is not an operator credential either
|
||||||
|
let (_, token) = h.pair("agent").await;
|
||||||
|
let status = h
|
||||||
|
.status(as_outpost(
|
||||||
|
request("POST", START, "198.51.100.20", None, None),
|
||||||
|
&token,
|
||||||
|
))
|
||||||
|
.await;
|
||||||
|
assert!(
|
||||||
|
status == StatusCode::UNAUTHORIZED || status == StatusCode::FORBIDDEN,
|
||||||
|
"an outpost token must not start a pairing, got {status}"
|
||||||
|
);
|
||||||
|
let codes: i64 = h.scalar("SELECT COUNT(*) FROM pairing_codes WHERE consumed_at IS NULL");
|
||||||
|
assert_eq!(codes, 0, "a refused request leaves no code behind");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_started_code_is_twelve_unambiguous_characters_valid_for_about_ten_minutes() {
|
||||||
|
let h = harness().await;
|
||||||
|
let start = h
|
||||||
|
.call(request("POST", START, "127.0.0.1", Some(ADMIN), None))
|
||||||
|
.await;
|
||||||
|
let body = json_of(start).await;
|
||||||
|
let code = body["code"].as_str().unwrap();
|
||||||
|
assert_eq!(code.len(), 12);
|
||||||
|
assert!(
|
||||||
|
code.chars()
|
||||||
|
.all(|c| "23456789ABCDEFGHJKLMNPQRSTUVWXYZ".contains(c)),
|
||||||
|
"no 0/O/1/I lookalikes: {code}"
|
||||||
|
);
|
||||||
|
let expires = chrono::DateTime::parse_from_rfc3339(body["expires_at"].as_str().unwrap())
|
||||||
|
.unwrap()
|
||||||
|
.timestamp();
|
||||||
|
let in_secs = expires - chrono::Utc::now().timestamp();
|
||||||
|
assert!((595..=600).contains(&in_secs), "expires in {in_secs}s");
|
||||||
|
assert_ne!(code, h.start_code().await, "codes are not repeated");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_claim_that_is_refused_creates_no_outpost_and_no_credential() {
|
||||||
|
let h = harness().await;
|
||||||
|
let code = h.start_code().await;
|
||||||
|
let lower = code.to_lowercase();
|
||||||
|
let spaced = format!(" {code} ");
|
||||||
|
let truncated = code[..11].to_string();
|
||||||
|
for wrong in [
|
||||||
|
lower.as_str(),
|
||||||
|
spaced.as_str(),
|
||||||
|
truncated.as_str(),
|
||||||
|
"",
|
||||||
|
"AAAAAAAAAAAA",
|
||||||
|
"'; DROP TABLE pairing_codes;--",
|
||||||
|
] {
|
||||||
|
let response = h
|
||||||
|
.claim("198.51.100.20", json!({"code": wrong, "outpost_name": "x"}))
|
||||||
|
.await;
|
||||||
|
assert_eq!(response.status(), StatusCode::GONE, "code {wrong:?}");
|
||||||
|
}
|
||||||
|
assert_eq!((h.outposts(), h.credentials()), (0, 0));
|
||||||
|
let failed: i64 = h.scalar(
|
||||||
|
"SELECT COUNT(*) FROM audit_events WHERE action='outpost.pair' AND outcome='failed'",
|
||||||
|
);
|
||||||
|
assert_eq!(failed, 6, "every refusal is audited");
|
||||||
|
let leaked: i64 = h.scalar(&format!(
|
||||||
|
"SELECT COUNT(*) FROM audit_events WHERE actor_id||action||coalesce(resource_id,'') LIKE '%{code}%'"
|
||||||
|
));
|
||||||
|
assert_eq!(leaked, 0, "the code is never written to the audit log");
|
||||||
|
// the real code still works afterwards: wrong guesses do not burn it
|
||||||
|
let ok = h
|
||||||
|
.claim(
|
||||||
|
"198.51.100.20",
|
||||||
|
json!({"code": code, "outpost_name": "real"}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(ok.status(), StatusCode::OK);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_claim_with_a_bad_name_is_refused_before_the_code_is_spent() {
|
||||||
|
let h = harness().await;
|
||||||
|
let code = h.start_code().await;
|
||||||
|
let too_long = "n".repeat(129);
|
||||||
|
for name in [
|
||||||
|
"",
|
||||||
|
" ",
|
||||||
|
"\t\n",
|
||||||
|
"tab\there",
|
||||||
|
"nul\u{0}byte",
|
||||||
|
too_long.as_str(),
|
||||||
|
] {
|
||||||
|
let response = h
|
||||||
|
.claim("198.51.100.20", json!({"code": code, "outpost_name": name}))
|
||||||
|
.await;
|
||||||
|
assert_eq!(response.status(), StatusCode::BAD_REQUEST, "name {name:?}");
|
||||||
|
}
|
||||||
|
assert_eq!(h.outposts(), 0);
|
||||||
|
let longest = "n".repeat(128);
|
||||||
|
let ok = h
|
||||||
|
.claim(
|
||||||
|
"198.51.100.20",
|
||||||
|
json!({"code": code, "outpost_name": longest}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(ok.status(), StatusCode::OK, "128 characters is allowed");
|
||||||
|
assert_eq!(h.outposts(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn malformed_claims_are_client_errors_and_never_touch_a_code() {
|
||||||
|
let h = harness().await;
|
||||||
|
let code = h.start_code().await;
|
||||||
|
for body in [
|
||||||
|
json!({}),
|
||||||
|
json!({"code": code}),
|
||||||
|
json!({"outpost_name": "x"}),
|
||||||
|
json!({"code": 12345, "outpost_name": "x"}),
|
||||||
|
json!({"code": null, "outpost_name": "x"}),
|
||||||
|
json!({"code": ["a"], "outpost_name": "x"}),
|
||||||
|
] {
|
||||||
|
let status = h.claim("198.51.100.20", body.clone()).await.status();
|
||||||
|
assert!(
|
||||||
|
status.is_client_error() && status != StatusCode::GONE,
|
||||||
|
"{body} gave {status}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let good = format!(r#"{{"code":"{code}","outpost_name":"x"}}"#);
|
||||||
|
let raw = |content_type: Option<&str>, body: &str| {
|
||||||
|
let mut builder = Request::builder()
|
||||||
|
.method("POST")
|
||||||
|
.uri(CLAIM)
|
||||||
|
.extension(ConnectInfo(
|
||||||
|
format!("{}:4000", fresh_peer())
|
||||||
|
.parse::<SocketAddr>()
|
||||||
|
.unwrap(),
|
||||||
|
));
|
||||||
|
if let Some(content_type) = content_type {
|
||||||
|
builder = builder.header(header::CONTENT_TYPE, content_type);
|
||||||
|
}
|
||||||
|
builder.body(Body::from(body.to_string())).unwrap()
|
||||||
|
};
|
||||||
|
for request in [
|
||||||
|
raw(Some("application/json"), "{not json"),
|
||||||
|
raw(None, &good),
|
||||||
|
raw(Some("text/plain"), &good),
|
||||||
|
] {
|
||||||
|
let status = h.status(request).await;
|
||||||
|
assert!(status.is_client_error(), "got {status}");
|
||||||
|
}
|
||||||
|
assert_eq!((h.outposts(), h.credentials()), (0, 0));
|
||||||
|
let ok = h
|
||||||
|
.claim("198.51.100.20", json!({"code": code, "outpost_name": "x"}))
|
||||||
|
.await;
|
||||||
|
assert_eq!(
|
||||||
|
ok.status(),
|
||||||
|
StatusCode::OK,
|
||||||
|
"the code survived every bad request"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn an_enormous_code_is_refused_without_trouble() {
|
||||||
|
let h = harness().await;
|
||||||
|
let huge = "A".repeat(1 << 20);
|
||||||
|
let status = h
|
||||||
|
.claim("198.51.100.20", json!({"code": huge, "outpost_name": "x"}))
|
||||||
|
.await
|
||||||
|
.status();
|
||||||
|
assert!(
|
||||||
|
status == StatusCode::GONE || status == StatusCode::PAYLOAD_TOO_LARGE,
|
||||||
|
"got {status}"
|
||||||
|
);
|
||||||
|
assert_eq!((h.outposts(), h.credentials()), (0, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_claimed_code_cannot_be_replayed_and_the_replay_is_audited() {
|
||||||
|
let h = harness().await;
|
||||||
|
let code = h.start_code().await;
|
||||||
|
let first = h
|
||||||
|
.claim(
|
||||||
|
"198.51.100.20",
|
||||||
|
json!({"code": code, "outpost_name": "first"}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(first.status(), StatusCode::OK);
|
||||||
|
let second = h
|
||||||
|
.claim(
|
||||||
|
"198.51.100.21",
|
||||||
|
json!({"code": code, "outpost_name": "second"}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(second.status(), StatusCode::GONE);
|
||||||
|
assert_eq!((h.outposts(), h.credentials()), (1, 1), "no second outpost");
|
||||||
|
let failed: i64 = h.scalar(
|
||||||
|
"SELECT COUNT(*) FROM audit_events WHERE action='outpost.pair' AND outcome='failed'",
|
||||||
|
);
|
||||||
|
assert_eq!(failed, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn an_expired_code_is_refused_and_old_ones_are_swept_by_the_next_pairing() {
|
||||||
|
let h = harness().await;
|
||||||
|
let now = chrono::Utc::now().timestamp();
|
||||||
|
h.state
|
||||||
|
.db
|
||||||
|
.insert_pairing("old-outpost", "STALECODE234", now - 1)
|
||||||
|
.unwrap();
|
||||||
|
h.state
|
||||||
|
.db
|
||||||
|
.insert_pairing("ancient-outpost", "ANCIENTCODE2", now - 200_000)
|
||||||
|
.unwrap();
|
||||||
|
let response = h
|
||||||
|
.claim(
|
||||||
|
"198.51.100.20",
|
||||||
|
json!({"code": "STALECODE234", "outpost_name": "late"}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(response.status(), StatusCode::GONE);
|
||||||
|
assert_eq!((h.outposts(), h.credentials()), (0, 0));
|
||||||
|
h.start_code().await;
|
||||||
|
// a code that expired a moment ago lingers (the claim still refuses it); one a day old is deleted
|
||||||
|
let rows: i64 = h.scalar("SELECT COUNT(*) FROM pairing_codes");
|
||||||
|
assert_eq!(rows, 2, "the recent stale code and the fresh one remain");
|
||||||
|
}
|
||||||
|
|||||||
@@ -10,7 +10,10 @@ use axum::body::Bytes;
|
|||||||
use futures_core::Stream;
|
use futures_core::Stream;
|
||||||
use std::io;
|
use std::io;
|
||||||
use std::pin::Pin;
|
use std::pin::Pin;
|
||||||
use std::sync::Arc;
|
use std::sync::{
|
||||||
|
atomic::{AtomicU64, Ordering},
|
||||||
|
Arc,
|
||||||
|
};
|
||||||
use std::task::{Context, Poll};
|
use std::task::{Context, Poll};
|
||||||
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
|
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
@@ -170,6 +173,26 @@ pub struct ExportGate {
|
|||||||
permits: Arc<Semaphore>,
|
permits: Arc<Semaphore>,
|
||||||
/// Free space that must remain after the export has been written.
|
/// Free space that must remain after the export has been written.
|
||||||
min_free: u64,
|
min_free: u64,
|
||||||
|
/// Bytes promised to exports that are admitted and not finished yet. Free space alone cannot say
|
||||||
|
/// that, because an export that has only just started has barely written anything.
|
||||||
|
reserved: Arc<AtomicU64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The most one export may reserve: 64 of them (the concurrency ceiling) still fit in a `u64`.
|
||||||
|
const MAX_RESERVATION: u64 = 1 << 57;
|
||||||
|
|
||||||
|
/// An admitted export: its place among the running ones and the disk it was promised. Both are given
|
||||||
|
/// back when this is dropped.
|
||||||
|
pub struct Admission {
|
||||||
|
_permit: OwnedSemaphorePermit,
|
||||||
|
reserved: Arc<AtomicU64>,
|
||||||
|
size: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for Admission {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.reserved.fetch_sub(self.size, Ordering::SeqCst);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub enum Refused {
|
pub enum Refused {
|
||||||
@@ -184,6 +207,7 @@ impl ExportGate {
|
|||||||
Self {
|
Self {
|
||||||
permits: Arc::new(Semaphore::new(concurrency)),
|
permits: Arc::new(Semaphore::new(concurrency)),
|
||||||
min_free,
|
min_free,
|
||||||
|
reserved: Arc::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -200,17 +224,31 @@ impl ExportGate {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Admit one export of about `size` bytes into `dir`. The permit lives as long as the response body.
|
/// Admit one export of about `size` bytes into `dir`. The slot and the bytes are held for as long as the
|
||||||
pub fn admit(&self, dir: &std::path::Path, size: u64) -> Result<OwnedSemaphorePermit, Refused> {
|
/// response body, so exports admitted together cannot each count on the same free space.
|
||||||
|
pub fn admit(&self, dir: &std::path::Path, size: u64) -> Result<Admission, Refused> {
|
||||||
let permit = self
|
let permit = self
|
||||||
.permits
|
.permits
|
||||||
.clone()
|
.clone()
|
||||||
.try_acquire_owned()
|
.try_acquire_owned()
|
||||||
.map_err(|_| Refused::Busy)?;
|
.map_err(|_| Refused::Busy)?;
|
||||||
|
// No disk is that large, and the cap keeps the running total from overflowing.
|
||||||
|
let size = size.min(MAX_RESERVATION);
|
||||||
|
// Reserve first, then check: concurrent callers can only over-refuse, never over-admit.
|
||||||
|
let earlier = self.reserved.fetch_add(size, Ordering::SeqCst);
|
||||||
|
let admission = Admission {
|
||||||
|
_permit: permit,
|
||||||
|
reserved: self.reserved.clone(),
|
||||||
|
size,
|
||||||
|
};
|
||||||
match free_bytes(dir) {
|
match free_bytes(dir) {
|
||||||
// `size` is the snapshot's recorded size; when a producer did not record one it is 0 and the margin alone applies.
|
// `size` is the snapshot's recorded size; when a producer did not record one it is 0 and the margin alone applies.
|
||||||
Some(free) if free < size.saturating_add(self.min_free) => Err(Refused::NoSpace),
|
// Bytes already written by running exports are no longer free and are counted again in `earlier`; being
|
||||||
_ => Ok(permit),
|
// that cautious is deliberate.
|
||||||
|
Some(free) if free < earlier.saturating_add(size).saturating_add(self.min_free) => {
|
||||||
|
Err(Refused::NoSpace)
|
||||||
|
}
|
||||||
|
_ => Ok(admission),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -248,7 +286,7 @@ pub fn sweep_stale(data_dir: &std::path::Path) -> usize {
|
|||||||
/// the client went away, or the response was discarded) releases the permit and deletes the export.
|
/// the client went away, or the response was discarded) releases the permit and deletes the export.
|
||||||
pub struct Guarded<S> {
|
pub struct Guarded<S> {
|
||||||
inner: Pin<Box<S>>,
|
inner: Pin<Box<S>>,
|
||||||
_permit: OwnedSemaphorePermit,
|
_permit: Admission,
|
||||||
_dir: tempfile::TempDir,
|
_dir: tempfile::TempDir,
|
||||||
db: Db,
|
db: Db,
|
||||||
principal: Principal,
|
principal: Principal,
|
||||||
@@ -261,7 +299,7 @@ pub struct Guarded<S> {
|
|||||||
impl<S> Guarded<S> {
|
impl<S> Guarded<S> {
|
||||||
pub fn new(
|
pub fn new(
|
||||||
inner: S,
|
inner: S,
|
||||||
permit: OwnedSemaphorePermit,
|
permit: Admission,
|
||||||
dir: tempfile::TempDir,
|
dir: tempfile::TempDir,
|
||||||
db: Db,
|
db: Db,
|
||||||
principal: Principal,
|
principal: Principal,
|
||||||
@@ -596,4 +634,45 @@ mod tests {
|
|||||||
"a snapshot bigger than the disk"
|
"a snapshot bigger than the disk"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn concurrent_exports_cannot_each_count_on_the_same_free_space() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let free = free_bytes(dir.path()).expect("statvfs works on the temp dir");
|
||||||
|
// each export needs a bit over a third of what is free, so two fit on paper but not together
|
||||||
|
// (the disk may move under us a little, which is why the margin is generous)
|
||||||
|
let size = free / 3 + free / 20;
|
||||||
|
let gate = ExportGate::new(8, 0);
|
||||||
|
let first = gate.admit(dir.path(), size).ok().expect("one fits");
|
||||||
|
let second = gate.admit(dir.path(), size).ok().expect("two fit");
|
||||||
|
assert!(
|
||||||
|
matches!(gate.admit(dir.path(), size), Err(Refused::NoSpace)),
|
||||||
|
"the third would need more than the disk has once the first two are counted"
|
||||||
|
);
|
||||||
|
drop(first);
|
||||||
|
assert!(
|
||||||
|
gate.admit(dir.path(), size).is_ok(),
|
||||||
|
"a finished export gives its bytes back"
|
||||||
|
);
|
||||||
|
drop(second);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_refused_export_leaves_nothing_reserved() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let gate = ExportGate::new(2, 0);
|
||||||
|
for _ in 0..3 {
|
||||||
|
assert!(matches!(
|
||||||
|
gate.admit(dir.path(), u64::MAX),
|
||||||
|
Err(Refused::NoSpace)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
assert_eq!(gate.reserved.load(Ordering::SeqCst), 0);
|
||||||
|
let busy = ExportGate::new(1, 0);
|
||||||
|
let held = busy.admit(dir.path(), 5).ok().unwrap();
|
||||||
|
assert!(matches!(busy.admit(dir.path(), 7), Err(Refused::Busy)));
|
||||||
|
assert_eq!(busy.reserved.load(Ordering::SeqCst), 5);
|
||||||
|
drop(held);
|
||||||
|
assert_eq!(busy.reserved.load(Ordering::SeqCst), 0);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user