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 std::sync::Arc;
use std::time::Duration;
use wal_backup::{connection::HealthReport, Config, DurabilityLayer};

#[test]
fn test_health_report_display_format() {
    let report = HealthReport {
        healthy: true,
        replicator_alive: true,
        snapshot_alive: true,
        watcher_alive: true,
        last_sync_ago: Duration::from_secs(5),
        health_timeout: Duration::from_secs(30),
    };
    let s = report.to_string();
    assert!(s.contains("healthy=true"), "should show healthy=true: {s}");
    assert!(
        s.contains("replicator=true"),
        "should show replicator=true: {s}"
    );
    assert!(
        s.contains("snapshot=true"),
        "should show snapshot=true: {s}"
    );
    assert!(s.contains("watcher=true"), "should show watcher=true: {s}");
    assert!(
        s.contains("last_sync_ago=5s"),
        "should show last_sync_ago: {s}"
    );
}

#[test]
fn test_health_report_display_unhealthy() {
    let report = HealthReport {
        healthy: false,
        replicator_alive: true,
        snapshot_alive: false,
        watcher_alive: true,
        last_sync_ago: Duration::from_secs(60),
        health_timeout: Duration::from_secs(30),
    };
    let s = report.to_string();
    assert!(
        s.contains("healthy=false"),
        "should show healthy=false: {s}"
    );
    assert!(
        s.contains("snapshot=false"),
        "should show snapshot=false: {s}"
    );
}

#[test]
fn test_health_report_display_fields_present() {
    let report = HealthReport {
        healthy: true,
        replicator_alive: false,
        snapshot_alive: true,
        watcher_alive: false,
        last_sync_ago: Duration::from_millis(1234),
        health_timeout: Duration::from_secs(15),
    };
    let s = report.to_string();
    assert!(
        s.contains("replicator=false"),
        "should show replicator=false: {s}"
    );
    assert!(
        s.contains("watcher=false"),
        "should show watcher=false: {s}"
    );
    assert!(s.contains("timeout=15s"), "should show timeout: {s}");
}

#[test]
fn test_health_report_debug_impl() {
    let report = HealthReport {
        healthy: true,
        replicator_alive: true,
        snapshot_alive: true,
        watcher_alive: true,
        last_sync_ago: Duration::ZERO,
        health_timeout: Duration::from_secs(30),
    };
    let debug = format!("{:?}", report);
    assert!(
        debug.contains("HealthReport"),
        "Debug format should contain HealthReport: {debug}"
    );
}

#[test]
fn test_health_report_zero_duration() {
    let report = HealthReport {
        healthy: true,
        replicator_alive: true,
        snapshot_alive: true,
        watcher_alive: true,
        last_sync_ago: Duration::ZERO,
        health_timeout: Duration::ZERO,
    };
    let s = report.to_string();
    assert!(
        s.contains("last_sync_ago=0ns"),
        "zero duration should display: {s}"
    );
}

#[test]
fn test_health_report_very_large_duration() {
    let report = HealthReport {
        healthy: false,
        replicator_alive: false,
        snapshot_alive: false,
        watcher_alive: false,
        last_sync_ago: Duration::from_secs(10 * 365 * 24 * 3600),
        health_timeout: Duration::MAX,
    };
    let s = report.to_string();
    assert!(s.contains("healthy=false"), "should show unhealthy: {s}");
}

#[test]
fn test_health_report_watcher_alive_true_when_none() {
    let report = HealthReport {
        healthy: true,
        replicator_alive: true,
        snapshot_alive: true,
        watcher_alive: true,
        last_sync_ago: Duration::from_secs(1),
        health_timeout: Duration::from_secs(30),
    };
    assert!(
        report.watcher_alive,
        "Lazy mode: watcher_alive should default to true"
    );
    let s = report.to_string();
    assert!(
        s.contains("watcher=true"),
        "should show watcher=true in Lazy mode: {s}"
    );
}

#[tokio::test]
async fn test_open_with_metrics_invalid_config_returns_err() {
    use wal_backup::connection::DurabilityLayer;
    use wal_backup::storage::BucketStore;

    let tmp = tempfile::tempdir().unwrap();
    let bucket_dir = tmp.path().join("bucket");
    std::fs::create_dir_all(&bucket_dir).unwrap();
    let inner =
        Arc::new(object_store::local::LocalFileSystem::new_with_prefix(&bucket_dir).unwrap());
    let bucket: Arc<dyn BucketStore> =
        Arc::new(wal_backup::ObjectStoreBucket::new(inner, "test".to_string()).unwrap());

    let config = Config::new("/tmp/test.db").with_sync_timeout(Duration::ZERO);

    let result =
        DurabilityLayer::open_with_metrics(config, bucket, wal_backup::noop_metrics()).await;

    match result {
        Err(e) => {
            assert!(
                e.to_string().contains("invalid config"),
                "should mention invalid config, got: {e}"
            );
        }
        Ok(_) => panic!("invalid config should return Err"),
    }
}

#[tokio::test]
async fn test_sync_now_timeout_returns_replication_error() {
    use wal_backup::connection::DurabilityLayer;

    let tmp = tempfile::tempdir().unwrap();
    let db_path = tmp.path().join("timeout_test.db");
    let bucket_dir = tmp.path().join("bucket");
    std::fs::create_dir_all(&bucket_dir).unwrap();

    let store =
        Arc::new(object_store::local::LocalFileSystem::new_with_prefix(&bucket_dir).unwrap());
    let bucket =
        Arc::new(wal_backup::ObjectStoreBucket::new(store, "timeout_test".to_string()).unwrap());

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

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

    {
        let conn = layer.conn().await;
        conn.execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY)")
            .unwrap();
    }

    let result = layer.sync_now().await;
    match result {
        Err(ref e) => {
            assert!(
                e.to_string().contains("sync timeout"),
                "timeout should say 'sync timeout', got: {e}"
            );
        }
        Ok(()) => panic!("sync_now with 1ms timeout should return Err, got Ok"),
    }

    let _ = layer.shutdown().await;
}

#[tokio::test]
async fn test_lazy_mode_health_report_no_watcher() {
    use wal_backup::connection::DurabilityLayer;
    use wal_backup::SyncMode;

    let tmp = tempfile::tempdir().unwrap();
    let db_path = tmp.path().join("lazy_health.db");
    let bucket_dir = tmp.path().join("bucket");
    std::fs::create_dir_all(&bucket_dir).unwrap();

    let store =
        Arc::new(object_store::local::LocalFileSystem::new_with_prefix(&bucket_dir).unwrap());
    let bucket =
        Arc::new(wal_backup::ObjectStoreBucket::new(store, "lazy_health".to_string()).unwrap());

    let config = wal_backup::Config::new(&db_path)
        .with_sync_mode(SyncMode::Lazy)
        .with_poll_interval(Duration::from_millis(100))
        .with_snapshot_threshold(1024 * 1024 * 1024)
        .with_snapshot_interval(Duration::from_secs(86400))
        .with_replica_lock_enabled(false);

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

    let report = layer.health_report().await;
    assert!(
        report.watcher_alive,
        "Lazy mode should report watcher_alive=true (None => true)"
    );
    assert!(report.replicator_alive, "replicator should be alive");
    assert!(report.snapshot_alive, "snapshot should be alive");

    drop(layer);
}

#[tokio::test]
async fn test_database_locked_prevents_second_opener() {
    use object_store::local::LocalFileSystem;
    use wal_backup::{DurabilityLayer, ObjectStoreBucket, SyncMode};

    let tmp = tempfile::tempdir().expect("temp dir");
    let db_path = tmp.path().join("locked.db");
    let bucket_dir = tmp.path().join("bucket");
    std::fs::create_dir_all(&bucket_dir).expect("bucket dir");

    let store = Arc::new(LocalFileSystem::new_with_prefix(&bucket_dir).expect("store"));
    let bucket = Arc::new(ObjectStoreBucket::new(store, "lock-test".to_string()).expect("bucket"));

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

    // First open should succeed
    let layer1 = DurabilityLayer::open(config.clone(), bucket.clone())
        .await
        .expect("first open should succeed");

    // Second open on the same DB path should fail with DatabaseLocked
    let result = DurabilityLayer::open(config.clone(), bucket.clone()).await;
    match result {
        Err(e) => {
            let err_str = format!("{e}");
            assert!(
                err_str.contains("locked"),
                "expected 'locked' in error, got: {err_str}"
            );
        }
        Ok(_) => panic!("second open should have failed with DatabaseLocked"),
    }

    // After dropping the first layer, the lock should be released
    drop(layer1);

    // Third open should now succeed (lock released)
    let _layer3 = DurabilityLayer::open(config, bucket)
        .await
        .expect("open after drop should succeed");
}

#[tokio::test]
async fn test_wrong_writer_rejected() {
    let dir = tempfile::tempdir().expect("tempdir");
    let db_path = dir.path().join("test.db");
    let bucket_dir = dir.path().join("bucket");
    std::fs::create_dir_all(&bucket_dir).expect("mkdir");

    let store = Arc::new(
        object_store::local::LocalFileSystem::new_with_prefix(&bucket_dir)
            .expect("create local filesystem store"),
    );
    let bucket_a = Arc::new(
        wal_backup::ObjectStoreBucket::new(store.clone(), "test-prefix".to_string())
            .expect("create bucket")
            .with_writer_id("server-A"),
    );

    // First open: registers "server-A" as writer
    let config1 = Config::new(&db_path).with_replica_lock_enabled(false);
    let layer1 = DurabilityLayer::open(config1, bucket_a.clone())
        .await
        .expect("first open");
    layer1.shutdown().await.expect("shutdown");

    // Second open with different writer_id: should be REJECTED
    let bucket_b = Arc::new(
        wal_backup::ObjectStoreBucket::new(store, "test-prefix".to_string())
            .expect("create bucket")
            .with_writer_id("server-B"),
    );
    let db_path2 = dir.path().join("test2.db");
    let config2 = Config::new(&db_path2).with_replica_lock_enabled(false);
    match DurabilityLayer::open(config2, bucket_b).await {
        Err(e) if e.is_wrong_writer() => {
            // Expected! server-B cannot write to server-A's prefix
        }
        Err(e) => panic!("expected WrongWriter, got: {e}"),
        Ok(_) => panic!("server-B should be rejected from server-A's prefix"),
    }
}

#[tokio::test]
async fn test_same_writer_accepted_after_restart() {
    let dir = tempfile::tempdir().expect("tempdir");
    let db_path = dir.path().join("test.db");
    let bucket_dir = dir.path().join("bucket");
    std::fs::create_dir_all(&bucket_dir).expect("mkdir");

    let store = Arc::new(
        object_store::local::LocalFileSystem::new_with_prefix(&bucket_dir)
            .expect("create local filesystem store"),
    );
    let bucket = Arc::new(
        wal_backup::ObjectStoreBucket::new(store, "test-prefix".to_string())
            .expect("create bucket")
            .with_writer_id("my-server"),
    );

    // First open: registers "my-server" as writer
    let config1 = Config::new(&db_path).with_replica_lock_enabled(false);
    let layer1 = DurabilityLayer::open(config1, bucket.clone())
        .await
        .expect("first open");
    layer1.shutdown().await.expect("shutdown");

    // Second open with SAME writer_id: should be ACCEPTED
    let db_path2 = dir.path().join("test2.db");
    let config2 = Config::new(&db_path2).with_replica_lock_enabled(false);
    let layer2 = DurabilityLayer::open(config2, bucket)
        .await
        .expect("same writer should be accepted");
    layer2.shutdown().await.expect("shutdown");
}