wal-backup 0.8.11

Embedded SQLite WAL replication to S3-compatible object storage. Not a sidecar — a library. Like Litestream, but embedded.
Documentation
use object_store::aws::AmazonS3Builder;
use std::sync::Arc;
use std::time::Duration;
use wal_backup::replication::manifest::MANIFEST_KEY;
use wal_backup::{BucketStore, Config, DurabilityLayer, ObjectStoreBucket, RestoreBehavior};

fn require_env(name: &str) -> String {
    std::env::var(name).unwrap_or_else(|_| {
        panic!(
            "E2E test requires env var {name}. Source .env.e2e before running: \
             source .env.e2e && cargo test --test e2e_tests -- --ignored"
        )
    })
}

fn build_ovh_bucket(prefix: &str) -> Arc<dyn BucketStore> {
    let endpoint = require_env("AWS_ENDPOINT_URL");
    let region = require_env("AWS_REGION");
    let access_key = require_env("AWS_ACCESS_KEY_ID");
    let secret_key = require_env("AWS_SECRET_ACCESS_KEY");
    let bucket_name = require_env("E2E_BUCKET_NAME");

    let store = AmazonS3Builder::new()
        .with_endpoint(&endpoint)
        .with_region(&region)
        .with_access_key_id(&access_key)
        .with_secret_access_key(&secret_key)
        .with_bucket_name(&bucket_name)
        .build()
        .unwrap_or_else(|e| panic!("failed to build S3 store for {endpoint}: {e}"));

    let bucket = ObjectStoreBucket::new(Arc::new(store), prefix.to_string())
        .expect("create ObjectStoreBucket");
    Arc::new(bucket)
}

async fn cleanup_bucket(bucket: &Arc<dyn BucketStore>, prefix: &str) {
    let all_keys = match bucket.list("").await {
        Ok(k) => k,
        Err(e) => {
            eprintln!("cleanup: list failed: {e}");
            return;
        }
    };
    let mut deleted = 0;
    for key in &all_keys {
        if key.starts_with(prefix) || key == MANIFEST_KEY {
            if let Err(e) = bucket.delete(key).await {
                eprintln!("cleanup: delete {key} failed: {e}");
            } else {
                deleted += 1;
            }
        }
    }
    if deleted > 0 {
        eprintln!("cleanup: deleted {deleted} objects");
    }
}

fn unique_prefix() -> String {
    static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    let ts = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_nanos();
    let pid = std::process::id();
    let seq = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    format!("e2e-test-{pid}-{ts}-{seq}")
}

async fn wait_for_sync(layer: &DurabilityLayer, timeout: Duration) {
    let deadline = std::time::Instant::now() + timeout;
    loop {
        if layer.is_healthy().await {
            return;
        }
        if std::time::Instant::now() > deadline {
            panic!("wait_for_sync timed out after {:?}", timeout);
        }
        tokio::time::sleep(Duration::from_millis(100)).await;
    }
}

async fn wait_for_manifest_snapshot(bucket: &Arc<dyn BucketStore>, timeout: Duration) -> String {
    let deadline = std::time::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 let Some(snap) = v.get("snapshot").and_then(|s| s.as_str()) {
                    return snap.to_string();
                }
            }
        }
        if std::time::Instant::now() > deadline {
            panic!("manifest snapshot not found within {:?}", timeout);
        }
        tokio::time::sleep(Duration::from_millis(200)).await;
    }
}

fn count_rows(conn: &rusqlite::Connection, table: &str) -> i64 {
    let safe_table = table.replace('"', "\"\"");
    conn.query_row(
        &format!("SELECT COUNT(*) FROM \"{safe_table}\""),
        [],
        |row| row.get(0),
    )
    .expect("count rows")
}

#[tokio::test]
#[ignore]
async fn e2e_ovh_write_sync_snapshot_restore() {
    let prefix = unique_prefix();
    let bucket = build_ovh_bucket(&prefix);

    let tmp = tempfile::tempdir().expect("create temp dir");
    let db_path = tmp.path().join("e2e.db");

    let config = Config::new(&db_path)
        .with_poll_interval(Duration::from_millis(100))
        .with_restore_behavior(RestoreBehavior::UploadLocalIfNewer)
        .with_snapshot_threshold(1024 * 1024 * 1024)
        .with_snapshot_interval(Duration::from_secs(86400))
        .with_replica_lock_enabled(false);

    let layer = DurabilityLayer::open(config, bucket.clone())
        .await
        .expect("open durability layer");

    {
        let conn = layer.conn().await;
        conn.execute_batch("CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT, value REAL)")
            .expect("create table");
        for i in 1..=100 {
            conn.execute(
                "INSERT INTO items (name, value) VALUES (?1, ?2)",
                rusqlite::params![format!("item-{i}"), i as f64 * 1.1],
            )
            .expect("insert row");
        }
    }

    layer.sync_now().await.expect("sync_now");
    wait_for_sync(&layer, Duration::from_secs(15)).await;
    tokio::time::sleep(Duration::from_millis(500)).await;

    layer.force_snapshot().await.expect("force_snapshot");
    tokio::time::sleep(Duration::from_secs(2)).await;

    wait_for_manifest_snapshot(&bucket, Duration::from_secs(30)).await;
    tokio::time::sleep(Duration::from_secs(1)).await;

    let manifest_data = bucket
        .get(MANIFEST_KEY)
        .await
        .expect("get manifest")
        .expect("manifest should exist");
    let manifest_json: serde_json::Value =
        serde_json::from_slice(&manifest_data).expect("parse manifest");
    assert!(
        manifest_json.get("snapshot").is_some(),
        "manifest should have a snapshot"
    );

    layer.shutdown().await.expect("shutdown");
    drop(layer);

    std::fs::remove_file(&db_path).expect("remove db");
    let wal_path = db_path.with_extension("db-wal");
    let _ = std::fs::remove_file(&wal_path);
    let shm_path = db_path.with_extension("db-shm");
    let _ = std::fs::remove_file(&shm_path);

    let config2 = Config::new(&db_path)
        .with_poll_interval(Duration::from_millis(100))
        .with_restore_behavior(RestoreBehavior::AlwaysRestoreFromBucket)
        .with_snapshot_threshold(1024 * 1024 * 1024)
        .with_snapshot_interval(Duration::from_secs(86400))
        .with_replica_lock_enabled(false);

    let layer2 = DurabilityLayer::open(config2, bucket.clone())
        .await
        .expect("open restored durability layer");

    {
        let conn = layer2.conn().await;
        let count = count_rows(&conn, "items");
        assert_eq!(count, 100, "restored DB should have all 100 rows");

        let sum: f64 = conn
            .query_row("SELECT SUM(value) FROM items", [], |r| r.get(0))
            .expect("sum");
        let expected_sum: f64 = (1..=100).map(|i| i as f64 * 1.1).sum();
        assert!(
            (sum - expected_sum).abs() < 0.01,
            "sum mismatch: got {sum}, expected {expected_sum}"
        );

        let sample: String = conn
            .query_row("SELECT name FROM items WHERE id = 42", [], |r| r.get(0))
            .expect("sample query");
        assert_eq!(sample, "item-42", "restored data should match");
    }

    layer2.shutdown().await.expect("shutdown layer2");

    cleanup_bucket(&bucket, &prefix).await;
}

#[tokio::test]
#[ignore]
async fn e2e_ovh_empty_db_restore() {
    let prefix = unique_prefix();
    let bucket = build_ovh_bucket(&prefix);

    let tmp = tempfile::tempdir().expect("create temp dir");
    let db_path = tmp.path().join("empty_e2e.db");

    let config = Config::new(&db_path)
        .with_poll_interval(Duration::from_millis(100))
        .with_restore_behavior(RestoreBehavior::UploadLocalIfNewer)
        .with_snapshot_threshold(1024 * 1024 * 1024)
        .with_snapshot_interval(Duration::from_secs(86400))
        .with_replica_lock_enabled(false);

    let layer = DurabilityLayer::open(config, bucket.clone())
        .await
        .expect("open empty layer");

    {
        let conn = layer.conn().await;
        conn.execute_batch("CREATE TABLE empty_test (id INTEGER PRIMARY KEY)")
            .expect("create table");
    }

    layer.sync_now().await.expect("sync");
    wait_for_sync(&layer, Duration::from_secs(15)).await;

    layer.force_snapshot().await.expect("force snapshot");
    tokio::time::sleep(Duration::from_secs(1)).await;

    wait_for_manifest_snapshot(&bucket, Duration::from_secs(15)).await;
    tokio::time::sleep(Duration::from_secs(1)).await;

    layer.shutdown().await.expect("shutdown");
    drop(layer);

    std::fs::remove_file(&db_path).expect("remove db");
    let _ = std::fs::remove_file(db_path.with_extension("db-wal"));
    let _ = std::fs::remove_file(db_path.with_extension("db-shm"));

    let config2 = Config::new(&db_path)
        .with_poll_interval(Duration::from_millis(100))
        .with_restore_behavior(RestoreBehavior::AlwaysRestoreFromBucket)
        .with_snapshot_threshold(1024 * 1024 * 1024)
        .with_snapshot_interval(Duration::from_secs(86400))
        .with_replica_lock_enabled(false);

    let layer2 = DurabilityLayer::open(config2, bucket.clone())
        .await
        .expect("restore empty db");

    {
        let conn = layer2.conn().await;
        let count = count_rows(&conn, "empty_test");
        assert_eq!(count, 0, "empty table should have 0 rows");
    }

    layer2.shutdown().await.expect("shutdown");

    cleanup_bucket(&bucket, &prefix).await;
}

#[tokio::test]
#[ignore]
async fn e2e_ovh_health_and_with_conn() {
    let prefix = unique_prefix();
    let bucket = build_ovh_bucket(&prefix);

    let tmp = tempfile::tempdir().expect("create temp dir");
    let db_path = tmp.path().join("health_e2e.db");

    let config = Config::new(&db_path)
        .with_poll_interval(Duration::from_millis(100))
        .with_restore_behavior(RestoreBehavior::UploadLocalIfNewer)
        .with_snapshot_threshold(1024 * 1024 * 1024)
        .with_snapshot_interval(Duration::from_secs(86400))
        .with_replica_lock_enabled(false);

    let layer = DurabilityLayer::open(config, bucket.clone())
        .await
        .expect("open layer");

    layer
        .with_conn(|c| {
            c.execute_batch("CREATE TABLE hc (id INTEGER PRIMARY KEY, v TEXT)")?;
            c.execute("INSERT INTO hc (v) VALUES ('health-check')", [])
        })
        .await
        .expect("with_conn create+insert");

    layer.sync_now().await.expect("sync");
    wait_for_sync(&layer, Duration::from_secs(15)).await;

    let report = layer.health_report().await;
    assert!(report.healthy, "layer should be healthy: {report}");
    assert!(report.replicator_alive, "replicator should be alive");
    assert!(report.snapshot_alive, "snapshot should be alive");

    let count: i64 = layer
        .with_conn(|c| c.query_row("SELECT COUNT(*) FROM hc", [], |r| r.get(0)))
        .await
        .expect("with_conn query");
    assert_eq!(count, 1, "with_conn should read back data");

    layer.shutdown().await.expect("shutdown");

    cleanup_bucket(&bucket, &prefix).await;
}