use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::Duration;
use object_store::aws::AmazonS3Builder;
use tokio::time::Instant;
use tracing::{error, info, warn};
use wal_backup::replication::manifest::MANIFEST_KEY;
use wal_backup::{
BucketStore, CompressedBucketStore, Config, DurabilityLayer, EncryptedBucketStore,
ObjectStoreBucket, RestoreBehavior,
};
struct HarnessMetrics {
frames: AtomicU64,
snapshots: AtomicU64,
syncs: AtomicU64,
uploads: AtomicU64,
errors: AtomicU64,
}
impl HarnessMetrics {
fn new() -> Self {
Self {
frames: AtomicU64::new(0),
snapshots: AtomicU64::new(0),
syncs: AtomicU64::new(0),
uploads: AtomicU64::new(0),
errors: AtomicU64::new(0),
}
}
fn report(&self) -> String {
format!(
"frames={} snapshots={} syncs={} uploads={} errors={}",
self.frames.load(Ordering::Relaxed),
self.snapshots.load(Ordering::Relaxed),
self.syncs.load(Ordering::Relaxed),
self.uploads.load(Ordering::Relaxed),
self.errors.load(Ordering::Relaxed)
)
}
}
impl wal_backup::Metrics for HarnessMetrics {
fn frames_shipped(&self, count: u32) {
self.frames.fetch_add(count as u64, Ordering::Relaxed);
}
fn snapshot_taken(&self, _db_size: u64, _wal_size: u64) {
self.snapshots.fetch_add(1, Ordering::Relaxed);
}
fn sync_completed(&self, _duration_ms: u64) {
self.syncs.fetch_add(1, Ordering::Relaxed);
}
fn restore_completed(&self, _duration_ms: u64) {}
fn segment_uploaded(&self, _key: &str, _size: u64) {
self.uploads.fetch_add(1, Ordering::Relaxed);
}
fn segment_deleted(&self, _key: &str) {}
fn shipper_error(&self, detail: &str) {
self.errors.fetch_add(1, Ordering::Relaxed);
warn!("shipper error: {}", detail);
}
fn snapshot_error(&self, detail: &str) {
self.errors.fetch_add(1, Ordering::Relaxed);
warn!("snapshot error: {}", detail);
}
fn segment_compacted(&self, l0_count: u32, l1_key: &str) {
info!("compacted {} L0 → {}", l0_count, l1_key);
}
fn orphan_deleted(&self, key: &str) {
info!("gc deleted: {}", key);
}
}
fn require_env(name: &str) -> String {
std::env::var(name).unwrap_or_else(|_| panic!("E2E harness requires env var {}", name))
}
fn build_s3_bucket(prefix: &str) -> Arc<dyn BucketStore> {
let store = AmazonS3Builder::new()
.with_endpoint(require_env("AWS_ENDPOINT_URL"))
.with_region(require_env("AWS_REGION"))
.with_access_key_id(require_env("AWS_ACCESS_KEY_ID"))
.with_secret_access_key(require_env("AWS_SECRET_ACCESS_KEY"))
.with_bucket_name(require_env("E2E_BUCKET_NAME"))
.build()
.unwrap_or_else(|e| panic!("S3 store: {e}"));
Arc::new(ObjectStoreBucket::new(Arc::new(store), prefix.to_string()).expect("bucket"))
}
#[allow(dead_code)]
fn build_encrypted_compressed_bucket(prefix: &str) -> Arc<dyn BucketStore> {
let base = build_s3_bucket(prefix);
let encrypted = Arc::new(EncryptedBucketStore::new(base, &[0x42u8; 32]));
Arc::new(CompressedBucketStore::new(encrypted, 6))
}
fn unique_prefix(phase: &str) -> String {
let ts = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs();
format!("e2e-{phase}-{}-{ts}", std::process::id())
}
fn config(db_path: &PathBuf) -> Config {
Config::new(db_path)
.with_poll_interval(Duration::from_millis(50))
.with_restore_behavior(RestoreBehavior::UploadLocalIfNewer)
.with_snapshot_threshold(1024 * 1024 * 1024)
.with_snapshot_interval(Duration::from_secs(86400))
.with_sync_timeout(Duration::from_secs(30))
.with_health_timeout(Duration::from_secs(60))
}
fn config_with_compaction(db_path: &PathBuf) -> Config {
config(db_path)
.with_compaction_interval(Some(Duration::from_secs(2)))
.with_compaction_min_segments(3)
.with_gc_interval(Some(Duration::from_secs(3)))
}
async fn wait_healthy(layer: &DurabilityLayer, timeout: Duration) {
let deadline = Instant::now() + timeout;
loop {
if layer.is_healthy().await {
return;
}
if Instant::now() > deadline {
panic!("wait_healthy timed out after {:?}", timeout);
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
async fn wait_for_manifest_snapshot(bucket: &Arc<dyn BucketStore>, timeout: Duration) {
let deadline = Instant::now() + timeout;
loop {
if let Ok(Some(data)) = bucket.get(MANIFEST_KEY).await {
if let Ok(v) = serde_json::from_slice::<serde_json::Value>(&data) {
if v.get("snapshot").and_then(|s| s.as_str()).is_some() {
return;
}
}
}
if Instant::now() > deadline {
panic!("manifest snapshot not found within {:?}", timeout);
}
tokio::time::sleep(Duration::from_millis(200)).await;
}
}
async fn cleanup_bucket(bucket: &Arc<dyn BucketStore>) {
match bucket.list("").await {
Ok(keys) => {
let mut deleted = 0u32;
for key in &keys {
if let Err(e) = bucket.delete(key).await {
warn!("cleanup: {key}: {e}");
} else {
deleted += 1;
}
}
info!("cleanup: deleted {deleted} objects");
}
Err(e) => warn!("cleanup list: {e}"),
}
}
fn count_rows(conn: &rusqlite::Connection, table: &str) -> i64 {
let safe = table.replace('"', "\"\"");
conn.query_row(&format!("SELECT COUNT(*) FROM \"{safe}\""), [], |r| {
r.get(0)
})
.expect("count")
}
fn integrity_check(conn: &rusqlite::Connection) -> String {
conn.query_row("PRAGMA integrity_check", [], |r| r.get::<_, String>(0))
.expect("integrity")
}
fn temp_db(phase: &str) -> (tempfile::TempDir, PathBuf) {
let tmp = tempfile::tempdir().expect("temp dir");
let db = tmp.path().join(format!("{phase}.db"));
(tmp, db)
}
fn delete_local_db(db_path: &PathBuf) {
std::fs::remove_file(db_path).ok();
std::fs::remove_file(db_path.with_extension("db-wal")).ok();
std::fs::remove_file(db_path.with_extension("db-shm")).ok();
}
async fn phase_basic_write_sync_restore() -> Result<(), String> {
info!("\n╔════════════════════════════════════════════════════════════╗");
info!("║ PHASE 1: Basic Write → Sync → Snapshot → Restore ║");
info!("╚════════════════════════════════════════════════════════════╝");
let prefix = unique_prefix("basic");
let bucket = build_s3_bucket(&prefix);
let (_tmp, db_path) = temp_db("basic");
let metrics = Arc::new(HarnessMetrics::new());
let layer =
DurabilityLayer::open_with_metrics(config(&db_path), bucket.clone(), metrics.clone())
.await
.map_err(|e| format!("open: {e}"))?;
{
let conn = layer.conn().await;
conn.execute_batch("CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT, value REAL)")
.map_err(|e| format!("create: {e}"))?;
for i in 1..=100i32 {
conn.execute(
"INSERT INTO items (name, value) VALUES (?1, ?2)",
rusqlite::params![format!("item-{i}"), i as f64 * 1.1],
)
.map_err(|e| format!("insert {i}: {e}"))?;
}
}
layer.sync_now().await.map_err(|e| format!("sync: {e}"))?;
wait_healthy(&layer, Duration::from_secs(15)).await;
tokio::time::sleep(Duration::from_millis(500)).await;
layer
.force_snapshot()
.await
.map_err(|e| format!("snapshot: {e}"))?;
wait_for_manifest_snapshot(&bucket, Duration::from_secs(30)).await;
tokio::time::sleep(Duration::from_millis(500)).await;
info!("Metrics: {}", metrics.report());
layer.shutdown().await.ok();
drop(layer);
delete_local_db(&db_path);
let layer2 = DurabilityLayer::open(
config(&db_path).with_restore_behavior(RestoreBehavior::AlwaysRestoreFromBucket),
bucket.clone(),
)
.await
.map_err(|e| format!("restore: {e}"))?;
{
let conn = layer2.conn().await;
let count = count_rows(&conn, "items");
if count != 100 {
return Err(format!("Expected 100 rows, got {count}"));
}
let sum: f64 = conn
.query_row("SELECT SUM(value) FROM items", [], |r| r.get(0))
.map_err(|e| format!("sum: {e}"))?;
let expected: f64 = (1..=100).map(|i| i as f64 * 1.1).sum();
if (sum - expected).abs() > 0.01 {
return Err(format!("Sum mismatch: {sum} vs {expected}"));
}
let ic = integrity_check(&conn);
if ic != "ok" {
return Err(format!("Integrity: {ic}"));
}
}
layer2.shutdown().await.ok();
cleanup_bucket(&bucket).await;
info!("✅ Phase 1 PASSED");
Ok(())
}
async fn phase_crash_recovery() -> Result<(), String> {
info!("\n╔════════════════════════════════════════════════════════════╗");
info!("║ PHASE 2: Crash Recovery (simulate unclean shutdown) ║");
info!("╚════════════════════════════════════════════════════════════╝");
let prefix = unique_prefix("crash");
let bucket = build_s3_bucket(&prefix);
let (_tmp, db_path) = temp_db("crash");
let layer = DurabilityLayer::open(config(&db_path), bucket.clone())
.await
.map_err(|e| format!("open: {e}"))?;
{
let conn = layer.conn().await;
conn.execute_batch("CREATE TABLE crash_test (id INTEGER PRIMARY KEY, data TEXT)")
.map_err(|e| format!("create: {e}"))?;
for i in 1..=50i32 {
conn.execute(
"INSERT INTO crash_test (data) VALUES (?1)",
rusqlite::params![format!("pre-crash-{i}")],
)
.map_err(|e| format!("insert: {e}"))?;
}
}
layer.sync_now().await.map_err(|e| format!("sync: {e}"))?;
wait_healthy(&layer, Duration::from_secs(15)).await;
tokio::time::sleep(Duration::from_millis(500)).await;
layer
.force_snapshot()
.await
.map_err(|e| format!("snapshot: {e}"))?;
wait_for_manifest_snapshot(&bucket, Duration::from_secs(30)).await;
tokio::time::sleep(Duration::from_millis(500)).await;
{
let conn = layer.conn().await;
for i in 51..=100i32 {
conn.execute(
"INSERT INTO crash_test (data) VALUES (?1)",
rusqlite::params![format!("post-snap-{i}")],
)
.map_err(|e| format!("insert: {e}"))?;
}
}
layer.sync_now().await.map_err(|e| format!("sync2: {e}"))?;
wait_healthy(&layer, Duration::from_secs(15)).await;
info!("Simulating crash (dropping layer without clean shutdown)...");
layer.shutdown().await.ok();
drop(layer);
delete_local_db(&db_path);
let layer2 = DurabilityLayer::open(
config(&db_path).with_restore_behavior(RestoreBehavior::AlwaysRestoreFromBucket),
bucket.clone(),
)
.await
.map_err(|e| format!("restore: {e}"))?;
let restored_count = {
let conn = layer2.conn().await;
let count = count_rows(&conn, "crash_test");
info!("Restored {count} rows after crash");
if count < 50 {
return Err(format!("Too few rows: {count} (expected >= 50)"));
}
let ic = integrity_check(&conn);
if ic != "ok" {
return Err(format!("Integrity: {ic}"));
}
count
};
layer2.shutdown().await.ok();
cleanup_bucket(&bucket).await;
info!("✅ Phase 2 PASSED (restored {restored_count} rows)");
Ok(())
}
async fn phase_compaction() -> Result<(), String> {
info!("\n╔════════════════════════════════════════════════════════════╗");
info!("║ PHASE 3: Compaction (L0 → L1 merge) ║");
info!("╚════════════════════════════════════════════════════════════╝");
let prefix = unique_prefix("compact");
let bucket = build_s3_bucket(&prefix);
let (_tmp, db_path) = temp_db("compact");
let cfg = config_with_compaction(&db_path)
.with_max_frames_per_segment(5)
.with_poll_interval(Duration::from_millis(20));
let metrics = Arc::new(HarnessMetrics::new());
let layer = DurabilityLayer::open_with_metrics(cfg, bucket.clone(), metrics.clone())
.await
.map_err(|e| format!("open: {e}"))?;
{
let conn = layer.conn().await;
conn.execute_batch("CREATE TABLE compact_test (id INTEGER PRIMARY KEY, v INTEGER)")
.map_err(|e| format!("create: {e}"))?;
}
for batch in 0..10u32 {
{
let conn = layer.conn().await;
for i in 0..5u32 {
let row = batch * 5 + i;
conn.execute(
"INSERT INTO compact_test (v) VALUES (?1)",
rusqlite::params![row],
)
.map_err(|e| format!("insert {row}: {e}"))?;
}
}
layer
.sync_now()
.await
.map_err(|e| format!("sync batch {batch}: {e}"))?;
tokio::time::sleep(Duration::from_millis(200)).await;
}
info!("Waiting for compaction...");
tokio::time::sleep(Duration::from_secs(6)).await;
let all_keys = bucket
.list("wal/")
.await
.map_err(|e| format!("list: {e}"))?;
let l1_count = all_keys.iter().filter(|k| k.ends_with(".l1")).count();
let l0_count = all_keys.iter().filter(|k| k.ends_with(".segment")).count();
info!("Bucket: {l1_count} L1 files, {l0_count} L0 segments");
info!("Metrics: {}", metrics.report());
layer
.force_snapshot()
.await
.map_err(|e| format!("snapshot: {e}"))?;
wait_for_manifest_snapshot(&bucket, Duration::from_secs(30)).await;
tokio::time::sleep(Duration::from_millis(500)).await;
layer.shutdown().await.ok();
drop(layer);
delete_local_db(&db_path);
let layer2 = DurabilityLayer::open(
config(&db_path).with_restore_behavior(RestoreBehavior::AlwaysRestoreFromBucket),
bucket.clone(),
)
.await
.map_err(|e| format!("restore: {e}"))?;
{
let conn = layer2.conn().await;
let count = count_rows(&conn, "compact_test");
if count != 50 {
return Err(format!("Expected 50 rows, got {count}"));
}
let ic = integrity_check(&conn);
if ic != "ok" {
return Err(format!("Integrity: {ic}"));
}
}
layer2.shutdown().await.ok();
cleanup_bucket(&bucket).await;
info!("✅ Phase 3 PASSED (L1 files: {l1_count})");
Ok(())
}
async fn phase_high_volume() -> Result<(), String> {
info!("\n╔════════════════════════════════════════════════════════════╗");
info!("║ PHASE 4: High Volume (10,000 rows) ║");
info!("╚════════════════════════════════════════════════════════════╝");
let prefix = unique_prefix("volume");
let bucket = build_s3_bucket(&prefix);
let (_tmp, db_path) = temp_db("volume");
let metrics = Arc::new(HarnessMetrics::new());
let layer =
DurabilityLayer::open_with_metrics(config(&db_path), bucket.clone(), metrics.clone())
.await
.map_err(|e| format!("open: {e}"))?;
{
let conn = layer.conn().await;
conn.execute_batch("CREATE TABLE volume_test (id INTEGER PRIMARY KEY, data BLOB)")
.map_err(|e| format!("create: {e}"))?;
}
let start = Instant::now();
let total = 10_000u32;
let batch_size = 100u32;
for batch in 0..(total / batch_size) {
{
let conn = layer.conn().await;
for i in 0..batch_size {
let row = batch * batch_size + i;
let data = vec![(row % 256) as u8; 100];
conn.execute(
"INSERT INTO volume_test (data) VALUES (?1)",
rusqlite::params![data],
)
.map_err(|e| format!("insert {row}: {e}"))?;
}
}
if batch % 10 == 0 {
layer
.sync_now()
.await
.map_err(|e| format!("sync {batch}: {e}"))?;
}
}
layer
.sync_now()
.await
.map_err(|e| format!("final sync: {e}"))?;
wait_healthy(&layer, Duration::from_secs(30)).await;
let elapsed = start.elapsed();
info!(
"Inserted {total} rows in {:?} ({:.0} rows/sec)",
elapsed,
total as f64 / elapsed.as_secs_f64()
);
info!("Metrics: {}", metrics.report());
layer
.force_snapshot()
.await
.map_err(|e| format!("snapshot: {e}"))?;
wait_for_manifest_snapshot(&bucket, Duration::from_secs(30)).await;
tokio::time::sleep(Duration::from_millis(500)).await;
layer.shutdown().await.ok();
drop(layer);
delete_local_db(&db_path);
let layer2 = DurabilityLayer::open(
config(&db_path).with_restore_behavior(RestoreBehavior::AlwaysRestoreFromBucket),
bucket.clone(),
)
.await
.map_err(|e| format!("restore: {e}"))?;
{
let conn = layer2.conn().await;
let count = count_rows(&conn, "volume_test");
if count != total as i64 {
return Err(format!("Expected {total} rows, got {count}"));
}
let ic = integrity_check(&conn);
if ic != "ok" {
return Err(format!("Integrity: {ic}"));
}
}
layer2.shutdown().await.ok();
cleanup_bucket(&bucket).await;
info!("✅ Phase 4 PASSED");
Ok(())
}
#[cfg(all(feature = "compression", feature = "encryption"))]
async fn phase_encryption_compression() -> Result<(), String> {
info!("\n╔════════════════════════════════════════════════════════════╗");
info!("║ PHASE 5: Encryption + Compression stacking ║");
info!("╚════════════════════════════════════════════════════════════╝");
let prefix = unique_prefix("enccomp");
let bucket = build_encrypted_compressed_bucket(&prefix);
let (_tmp, db_path) = temp_db("enccomp");
let layer = DurabilityLayer::open(config(&db_path), bucket.clone())
.await
.map_err(|e| format!("open: {e}"))?;
{
let conn = layer.conn().await;
conn.execute_batch("CREATE TABLE enc_test (id INTEGER PRIMARY KEY, secret TEXT)")
.map_err(|e| format!("create: {e}"))?;
conn.execute(
"INSERT INTO enc_test (secret) VALUES (?1)",
rusqlite::params!["sensitive-data-12345"],
)
.map_err(|e| format!("insert: {e}"))?;
}
layer.sync_now().await.map_err(|e| format!("sync: {e}"))?;
wait_healthy(&layer, Duration::from_secs(15)).await;
tokio::time::sleep(Duration::from_millis(500)).await;
layer
.force_snapshot()
.await
.map_err(|e| format!("snapshot: {e}"))?;
wait_for_manifest_snapshot(&bucket, Duration::from_secs(30)).await;
tokio::time::sleep(Duration::from_millis(500)).await;
layer.shutdown().await.ok();
drop(layer);
delete_local_db(&db_path);
let layer2 = DurabilityLayer::open(
config(&db_path).with_restore_behavior(RestoreBehavior::AlwaysRestoreFromBucket),
bucket.clone(),
)
.await
.map_err(|e| format!("restore: {e}"))?;
{
let conn = layer2.conn().await;
let secret: String = conn
.query_row("SELECT secret FROM enc_test", [], |r| r.get(0))
.map_err(|e| format!("query: {e}"))?;
if secret != "sensitive-data-12345" {
return Err(format!("Data mismatch: '{secret}'"));
}
let ic = integrity_check(&conn);
if ic != "ok" {
return Err(format!("Integrity: {ic}"));
}
}
layer2.shutdown().await.ok();
cleanup_bucket(&bucket).await;
info!("✅ Phase 5 PASSED");
Ok(())
}
#[cfg(not(all(feature = "compression", feature = "encryption")))]
async fn phase_encryption_compression() -> Result<(), String> {
info!("⏭ Skipping Phase 5 (enable compression+encryption features)");
Ok(())
}
#[tokio::main]
async fn main() {
tracing_subscriber::fmt()
.with_max_level(tracing::Level::INFO)
.init();
info!("═══════════════════════════════════════════════════════════════");
info!(" wal-backup E2E Test Harness");
info!(
" Bucket: {} at {}",
std::env::var("E2E_BUCKET_NAME").unwrap_or_else(|_| "???".into()),
std::env::var("AWS_ENDPOINT_URL").unwrap_or_else(|_| "???".into()),
);
info!("═══════════════════════════════════════════════════════════════");
let mut passed = 0u32;
let mut failed = 0u32;
macro_rules! run {
($name:expr, $fut:expr) => {
match $fut.await {
Ok(()) => passed += 1,
Err(e) => {
error!("❌ {}: {}", $name, e);
failed += 1;
}
}
};
}
run!(
"Phase 1: Basic Write/Sync/Restore",
phase_basic_write_sync_restore()
);
run!("Phase 2: Crash Recovery", phase_crash_recovery());
run!("Phase 3: Compaction", phase_compaction());
run!("Phase 4: High Volume", phase_high_volume());
run!(
"Phase 5: Encryption+Compression",
phase_encryption_compression()
);
info!("\n═══════════════════════════════════════════════════════════════");
info!(" Results: {} passed, {} failed", passed, failed);
info!("═══════════════════════════════════════════════════════════════");
if failed > 0 {
std::process::exit(1);
}
}