mod common;
use bytes::Bytes;
use object_store::local::LocalFileSystem;
use std::sync::Arc;
use std::time::Duration;
use wal_backup::replication::manifest::MANIFEST_KEY;
use wal_backup::{BucketStore, Config, DurabilityLayer, Metrics, ObjectStoreBucket, SyncMode};
fn setup_tmp_dir(test_name: &str) -> (tempfile::TempDir, std::path::PathBuf) {
let tmp = tempfile::tempdir().expect("create temp dir");
let db_path = tmp.path().join(format!("{}.db", test_name));
let bucket_dir = tmp.path().join("bucket");
std::fs::create_dir_all(&bucket_dir).expect("create bucket dir");
(tmp, db_path)
}
async fn create_layer(
db_path: &std::path::Path,
bucket_prefix: &str,
bucket_dir: &std::path::Path,
poll_ms: u64,
) -> DurabilityLayer {
let store = Arc::new(
LocalFileSystem::new_with_prefix(bucket_dir).expect("create local filesystem store"),
);
let bucket =
Arc::new(ObjectStoreBucket::new(store, bucket_prefix.to_string()).expect("create bucket"));
let config = Config::new(db_path)
.with_poll_interval(Duration::from_millis(poll_ms))
.with_restore_behavior(wal_backup::RestoreBehavior::UploadLocalIfNewer)
.with_snapshot_threshold(1024 * 1024 * 1024)
.with_snapshot_interval(Duration::from_secs(86400))
.with_replica_lock_enabled(false);
DurabilityLayer::open(config, bucket)
.await
.expect("open durability layer")
}
async fn create_layer_with_sync_mode(
db_path: &std::path::Path,
bucket_prefix: &str,
bucket_dir: &std::path::Path,
poll_ms: u64,
sync_mode: SyncMode,
immediate_poll_ms: u64,
) -> DurabilityLayer {
let store = Arc::new(
LocalFileSystem::new_with_prefix(bucket_dir).expect("create local filesystem store"),
);
let bucket =
Arc::new(ObjectStoreBucket::new(store, bucket_prefix.to_string()).expect("create bucket"));
let config = Config::new(db_path)
.with_poll_interval(Duration::from_millis(poll_ms))
.with_sync_mode(sync_mode)
.with_immediate_poll_interval(Duration::from_millis(immediate_poll_ms))
.with_restore_behavior(wal_backup::RestoreBehavior::UploadLocalIfNewer)
.with_snapshot_threshold(1024 * 1024 * 1024)
.with_snapshot_interval(Duration::from_secs(86400))
.with_replica_lock_enabled(false);
DurabilityLayer::open(config, bucket)
.await
.expect("open durability layer")
}
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")
}
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(50)).await;
}
}
#[tokio::test]
async fn test_basic_write_and_restore() {
let (_tmp, db_path) = setup_tmp_dir("basic_write_restore");
let bucket_dir = db_path.parent().unwrap().join("bucket");
let layer = create_layer(&db_path, "test1", &bucket_dir, 50).await;
{
let conn = layer.conn().await;
conn.execute_batch("CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)")
.expect("create table");
conn.execute(
"INSERT INTO test (value) VALUES (?1)",
rusqlite::params!["hello"],
)
.expect("insert row");
conn.execute(
"INSERT INTO test (value) VALUES (?1)",
rusqlite::params!["world"],
)
.expect("insert row");
}
layer.sync_now().await.expect("sync");
wait_for_sync(&layer, Duration::from_secs(5)).await;
drop(layer);
let layer2 = create_layer(&db_path, "test1", &bucket_dir, 50).await;
{
let conn = layer2.conn().await;
let mut stmt = conn
.prepare("SELECT value FROM test ORDER BY id")
.expect("prepare select");
let rows: Vec<String> = stmt
.query_map([], |row| row.get(0))
.expect("query")
.filter_map(|r| r.ok())
.collect();
assert_eq!(rows, vec!["hello".to_string(), "world".to_string()]);
}
}
#[tokio::test]
async fn test_write_then_sync_then_verify() {
let (_tmp, db_path) = setup_tmp_dir("sync_verify");
let bucket_dir = db_path.parent().unwrap().join("bucket");
let layer = create_layer(&db_path, "sync_test", &bucket_dir, 50).await;
{
let conn = layer.conn().await;
conn.execute_batch("CREATE TABLE data (k TEXT PRIMARY KEY, v INTEGER)")
.expect("create table");
for i in 0..10 {
conn.execute(
"INSERT INTO data (k, v) VALUES (?1, ?2)",
rusqlite::params![format!("key_{}", i), i],
)
.expect("insert row");
}
}
layer.sync_now().await.expect("sync");
wait_for_sync(&layer, Duration::from_secs(5)).await;
assert!(layer.is_healthy().await);
assert!(layer.last_sync().await.elapsed() < Duration::from_secs(5));
}
#[tokio::test]
async fn test_crash_recovery_snapshot_and_segments() {
let (_tmp, db_path) = setup_tmp_dir("crash_snap_seg");
let bucket_dir = db_path.parent().unwrap().join("bucket");
let layer = create_layer(&db_path, "crash1", &bucket_dir, 50).await;
{
let conn = layer.conn().await;
conn.execute_batch("CREATE TABLE items (id INTEGER PRIMARY KEY, val TEXT)")
.expect("create table");
for i in 0..100 {
conn.execute(
"INSERT INTO items (val) VALUES (?1)",
rusqlite::params![format!("pre_snap_{}", i)],
)
.expect("insert");
}
}
{
let conn = layer.conn().await;
assert_eq!(count_rows(&conn, "items"), 100);
}
layer.force_snapshot().await.expect("force snapshot");
wait_for_sync(&layer, Duration::from_secs(5)).await;
{
let conn = layer.conn().await;
for i in 0..50 {
conn.execute(
"INSERT INTO items (val) VALUES (?1)",
rusqlite::params![format!("post_snap_{}", i)],
)
.expect("insert");
}
}
layer.sync_now().await.expect("sync");
wait_for_sync(&layer, Duration::from_secs(5)).await;
layer.shutdown().await.expect("shutdown");
{
let conn = layer.conn().await;
assert_eq!(count_rows(&conn, "items"), 150);
}
layer.shutdown().await.expect("shutdown");
drop(layer);
let layer2 = create_layer(&db_path, "crash1", &bucket_dir, 50).await;
{
let conn = layer2.conn().await;
assert_eq!(count_rows(&conn, "items"), 150);
}
{
let conn = layer2.conn().await;
let mut stmt = conn
.prepare("SELECT val FROM items WHERE val LIKE 'post_snap_%' ORDER BY val")
.expect("prepare");
let rows: Vec<String> = stmt
.query_map([], |row| row.get(0))
.expect("query")
.filter_map(|r| r.ok())
.collect();
assert_eq!(rows.len(), 50, "post-snapshot data must survive crash");
}
}
#[tokio::test]
async fn test_crash_recovery_no_data_loss() {
let (_tmp, db_path) = setup_tmp_dir("crash_noloss");
let bucket_dir = db_path.parent().unwrap().join("bucket");
let layer = create_layer(&db_path, "crash2", &bucket_dir, 50).await;
{
let conn = layer.conn().await;
conn.execute_batch("CREATE TABLE sensor (ts INTEGER PRIMARY KEY, reading REAL)")
.expect("create table");
for ts in 0..1000 {
conn.execute(
"INSERT INTO sensor (ts, reading) VALUES (?1, ?2)",
rusqlite::params![ts, (ts as f64) * 0.5],
)
.expect("insert");
}
}
layer.sync_now().await.expect("sync");
wait_for_sync(&layer, Duration::from_secs(5)).await;
layer.force_snapshot().await.expect("force snapshot");
wait_for_sync(&layer, Duration::from_secs(5)).await;
tokio::time::sleep(Duration::from_millis(200)).await;
layer.shutdown().await.expect("shutdown");
drop(layer);
let layer2 = create_layer(&db_path, "crash2", &bucket_dir, 50).await;
{
let conn = layer2.conn().await;
assert_eq!(count_rows(&conn, "sensor"), 1000);
}
drop(layer2);
let layer3 = create_layer(&db_path, "crash2", &bucket_dir, 50).await;
{
let conn = layer3.conn().await;
assert_eq!(count_rows(&conn, "sensor"), 1000);
}
}
#[tokio::test]
async fn test_immediate_sync_mode_ships_frames() {
let (_tmp, db_path) = setup_tmp_dir("immediate_sync");
let bucket_dir = db_path.parent().unwrap().join("bucket");
let layer = create_layer_with_sync_mode(
&db_path,
"immediate_test",
&bucket_dir,
1000,
SyncMode::Immediate,
20,
)
.await;
{
let conn = layer.conn().await;
conn.execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT)")
.expect("create table");
conn.execute("INSERT INTO t (v) VALUES (?1)", rusqlite::params!["data"])
.expect("insert");
}
layer.sync_now().await.expect("sync");
wait_for_sync(&layer, Duration::from_secs(5)).await;
assert!(layer.is_healthy().await);
assert!(layer.last_sync().await.elapsed() < Duration::from_secs(5));
drop(layer);
let layer2 = create_layer(&db_path, "immediate_test", &bucket_dir, 1000).await;
let conn = layer2.conn().await;
let mut stmt = conn.prepare("SELECT v FROM t").expect("prepare select");
let rows: Vec<String> = stmt
.query_map([], |row| row.get(0))
.expect("query")
.filter_map(|r| r.ok())
.collect();
assert_eq!(rows, vec!["data"]);
}
#[tokio::test]
async fn test_lazy_sync_mode_batches_uploads() {
let (_tmp, db_path) = setup_tmp_dir("lazy_sync");
let bucket_dir = db_path.parent().unwrap().join("bucket");
let layer =
create_layer_with_sync_mode(&db_path, "lazy_test", &bucket_dir, 200, SyncMode::Lazy, 20)
.await;
{
let conn = layer.conn().await;
conn.execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT)")
.expect("create table");
for i in 0..100 {
conn.execute(
"INSERT INTO t (v) VALUES (?1)",
rusqlite::params![format!("row_{}", i)],
)
.expect("insert");
}
}
tokio::time::sleep(Duration::from_millis(50)).await;
let last_sync_before = layer.last_sync().await;
tokio::time::sleep(Duration::from_millis(450)).await;
let last_sync_after = layer.last_sync().await;
drop(layer);
assert!(
last_sync_after > last_sync_before,
"Lazy sync should update last_sync after poll_interval elapsed"
);
}
#[tokio::test]
async fn test_is_healthy_checks_watcher_in_immediate_mode() {
let (_tmp, db_path) = setup_tmp_dir("health_check");
let bucket_dir = db_path.parent().unwrap().join("bucket");
let layer = create_layer_with_sync_mode(
&db_path,
"health_test",
&bucket_dir,
1000,
SyncMode::Immediate,
20,
)
.await;
assert!(layer.is_healthy().await, "Fresh layer should be healthy");
drop(layer);
}
#[tokio::test]
async fn test_bucket_restore_after_local_delete() {
let (_tmp, db_path) = setup_tmp_dir("bucket_restore");
let bucket_dir = db_path.parent().unwrap().join("bucket");
let store = Arc::new(
object_store::local::LocalFileSystem::new_with_prefix(&bucket_dir).expect("store"),
);
let bucket =
Arc::new(ObjectStoreBucket::new(store, "bucket_restore_test".to_string()).expect("bucket"));
let layer = create_layer(&db_path, "bucket_restore_test", &bucket_dir, 50).await;
{
let conn = layer.conn().await;
conn.execute_batch("CREATE TABLE data (k TEXT PRIMARY KEY, v INTEGER)")
.expect("create table");
for i in 0..100 {
conn.execute(
"INSERT INTO data (k, v) VALUES (?1, ?2)",
rusqlite::params![format!("key_{}", i), i],
)
.expect("insert row");
}
}
layer.sync_now().await.expect("sync");
wait_for_sync(&layer, Duration::from_secs(5)).await;
layer.force_snapshot().await.expect("force snapshot");
wait_for_sync(&layer, Duration::from_secs(5)).await;
tokio::time::sleep(Duration::from_millis(200)).await;
layer.shutdown().await.expect("shutdown");
drop(layer);
let manifest_data = bucket
.get(MANIFEST_KEY)
.await
.expect("get manifest")
.expect("manifest must exist after snapshot");
let manifest: serde_json::Value =
serde_json::from_slice(&manifest_data).expect("valid manifest json");
assert!(
manifest.get("snapshot").and_then(|v| v.as_str()).is_some(),
"manifest must have a snapshot after force_snapshot: {:?}",
manifest
);
std::fs::remove_file(&db_path).expect("delete local DB");
let wal_path = db_path.with_extension("db-wal");
std::fs::remove_file(&wal_path).ok();
let wal_shm_path = db_path.with_extension("db-wal-shm");
std::fs::remove_file(&wal_shm_path).ok();
let layer2 = create_layer(&db_path, "bucket_restore_test", &bucket_dir, 50).await;
{
let conn = layer2.conn().await;
assert_eq!(
count_rows(&conn, "data"),
100,
"Data must be restored from bucket after local delete"
);
}
}
#[tokio::test]
async fn test_concurrent_writes_multiple_connections() {
let (_tmp, db_path) = setup_tmp_dir("concurrent_writes");
let bucket_dir = db_path.parent().unwrap().join("bucket");
let layer = create_layer(&db_path, "concurrent_test", &bucket_dir, 50).await;
{
let conn = layer.conn().await;
conn.execute_batch(
"CREATE TABLE IF NOT EXISTS concurrent_test (id INTEGER PRIMARY KEY, value TEXT)",
)
.expect("create table");
}
let layer = Arc::new(layer);
let handles: Vec<_> = (0..4)
.map(|thread_id| {
let layer = layer.clone();
tokio::spawn(async move {
let conn = layer.conn().await;
for i in 0..25 {
conn.execute(
"INSERT INTO concurrent_test (value) VALUES (?1)",
rusqlite::params![format!("thread_{}_row_{}", thread_id, i)],
)
.expect("insert");
}
})
})
.collect();
for handle in handles {
handle.await.expect("thread panic");
}
layer.sync_now().await.expect("sync");
wait_for_sync(&layer, Duration::from_secs(5)).await;
{
let conn = layer.conn().await;
let count = count_rows(&conn, "concurrent_test");
assert_eq!(count, 100, "All 100 rows from 4 threads should be present");
}
}
#[tokio::test]
async fn test_salt_change_triggers_snapshot_and_cleans_old_segments() {
let (_tmp, db_path) = setup_tmp_dir("salt_change_cleanup");
let bucket_dir = db_path.parent().unwrap().join("bucket");
let layer = create_layer(&db_path, "salt_test", &bucket_dir, 50).await;
{
let conn = layer.conn().await;
conn.execute_batch("CREATE TABLE data (id INTEGER PRIMARY KEY, v TEXT)")
.expect("create table");
for i in 0..50 {
conn.execute(
"INSERT INTO data (v) VALUES (?1)",
rusqlite::params![format!("row_{}", i)],
)
.expect("insert");
}
}
layer.sync_now().await.expect("sync first batch");
wait_for_sync(&layer, Duration::from_secs(5)).await;
layer.force_snapshot().await.expect("force snapshot");
wait_for_sync(&layer, Duration::from_secs(5)).await;
let segments_before: Vec<String> = {
let store = Arc::new(
object_store::local::LocalFileSystem::new_with_prefix(&bucket_dir).expect("store"),
);
let bucket = Arc::new(
ObjectStoreBucket::new(store, "salt_test".to_string()).expect("create bucket"),
);
bucket
.list("wal/")
.await
.expect("list wal")
.into_iter()
.filter(|k| k.ends_with(".segment"))
.collect()
};
let _old_prefix_count = segments_before.len();
{
let conn = layer.conn().await;
conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)")
.expect("checkpoint to force salt change");
for i in 50..100 {
conn.execute(
"INSERT INTO data (v) VALUES (?1)",
rusqlite::params![format!("row_{}", i)],
)
.expect("insert");
}
}
layer.sync_now().await.expect("sync after salt change");
wait_for_sync(&layer, Duration::from_secs(5)).await;
layer
.force_snapshot()
.await
.expect("force snapshot after salt change");
wait_for_sync(&layer, Duration::from_secs(5)).await;
layer.sync_now().await.expect("sync after snapshot");
wait_for_sync(&layer, Duration::from_secs(5)).await;
drop(layer);
let layer2 = create_layer(&db_path, "salt_test", &bucket_dir, 50).await;
{
let conn = layer2.conn().await;
assert_eq!(
count_rows(&conn, "data"),
100,
"all rows survive salt change"
);
}
}
#[tokio::test]
async fn test_recoverable_behavior_proceeds_on_checksum_mismatch() {
use wal_backup::RestoreBehavior;
let (_tmp, db_path) = setup_tmp_dir("recoverable_test");
let bucket_dir = _tmp.path().join("bucket");
std::fs::create_dir_all(&bucket_dir).expect("create bucket dir");
let store = Arc::new(LocalFileSystem::new_with_prefix(&bucket_dir).expect("create store"));
let bucket =
Arc::new(ObjectStoreBucket::new(store, "recoverable".to_string()).expect("create bucket"));
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));
let layer = DurabilityLayer::open(config, bucket.clone())
.await
.expect("open layer");
{
let conn = layer.conn().await;
conn.execute_batch("CREATE TABLE data (id INTEGER PRIMARY KEY, v TEXT)")
.expect("create table");
for i in 0..10 {
conn.execute(
"INSERT INTO data (v) VALUES (?1)",
rusqlite::params![format!("row_{}", i)],
)
.expect("insert");
}
}
layer.sync_now().await.expect("sync");
wait_for_sync(&layer, Duration::from_secs(5)).await;
layer.force_snapshot().await.expect("force snapshot");
wait_for_sync(&layer, Duration::from_secs(5)).await;
tokio::time::sleep(Duration::from_millis(200)).await;
layer.shutdown().await.expect("shutdown");
drop(layer);
let manifest_bytes = bucket
.get(MANIFEST_KEY)
.await
.expect("get manifest")
.expect("manifest must exist after snapshot");
let mut manifest_json: serde_json::Value =
serde_json::from_slice(&manifest_bytes).expect("valid json");
let corrupted_checksum = manifest_json
.get("snapshot_checksum")
.and_then(|c| c.as_str())
.map(|checksum| {
let hash_part = checksum
.strip_prefix("sha256:")
.expect("checksum should have sha256: prefix");
let mut bytes = hex::decode(hash_part).expect("valid hex after prefix");
bytes[0] ^= 0xFF;
format!("sha256:{}", hex::encode(bytes))
})
.expect("snapshot_checksum must exist");
if let Some(obj) = manifest_json.as_object_mut() {
obj.insert(
"snapshot_checksum".to_string(),
serde_json::Value::String(corrupted_checksum),
);
}
bucket
.put(
MANIFEST_KEY,
Bytes::from(serde_json::to_vec(&manifest_json).expect("serialize")),
)
.await
.expect("write corrupted manifest");
std::fs::remove_file(&db_path).expect("remove local db to force restore from bucket");
let config2 = Config::new(&db_path)
.with_poll_interval(Duration::from_millis(100))
.with_restore_behavior(RestoreBehavior::Recoverable)
.with_snapshot_threshold(1024 * 1024 * 1024)
.with_snapshot_interval(Duration::from_secs(86400));
let layer2 = DurabilityLayer::open(config2, bucket.clone())
.await
.expect("open layer with Recoverable");
{
let conn = layer2.conn().await;
let count: i64 = conn
.query_row("SELECT COUNT(*) FROM data", [], |r| r.get(0))
.expect("count rows");
assert_eq!(
count, 10,
"data should be recovered despite corrupted manifest checksum"
);
}
}
#[tokio::test]
async fn test_shutdown_completes_cleanly() {
let (_tmp, db_path) = setup_tmp_dir("shutdown_test");
let bucket_dir = db_path.parent().unwrap().join("bucket");
let layer = create_layer(&db_path, "shutdown", &bucket_dir, 50).await;
{
let conn = layer.conn().await;
conn.execute_batch("CREATE TABLE data (id INTEGER PRIMARY KEY, v TEXT)")
.expect("create table");
conn.execute("INSERT INTO data (v) VALUES ('test')", [])
.expect("insert");
}
layer.sync_now().await.expect("sync before shutdown");
layer.shutdown().await.expect("shutdown");
}
#[tokio::test]
async fn test_is_healthy_after_sync() {
let (_tmp, db_path) = setup_tmp_dir("health_test");
let bucket_dir = db_path.parent().unwrap().join("bucket");
let layer = create_layer(&db_path, "health", &bucket_dir, 50).await;
{
let conn = layer.conn().await;
conn.execute_batch("CREATE TABLE data (id INTEGER PRIMARY KEY)")
.expect("create table");
}
layer.sync_now().await.expect("sync");
assert!(
layer.is_healthy().await,
"layer should be healthy after sync"
);
}
#[tokio::test]
async fn test_immediate_sync_mode_ships_wal() {
let (_tmp, db_path) = setup_tmp_dir("immediate_sync");
let bucket_dir = db_path.parent().unwrap().join("bucket");
let layer = create_layer_with_sync_mode(
&db_path,
"immediate",
&bucket_dir,
50,
SyncMode::Immediate,
50,
)
.await;
{
let conn = layer.conn().await;
conn.execute_batch("CREATE TABLE data (id INTEGER PRIMARY KEY, v TEXT)")
.expect("create table");
for i in 0..5 {
conn.execute(
"INSERT INTO data (v) VALUES (?1)",
rusqlite::params![format!("row_{}", i)],
)
.expect("insert");
}
}
layer.sync_now().await.expect("sync in immediate mode");
let store = Arc::new(LocalFileSystem::new_with_prefix(&bucket_dir).expect("create store"));
let bucket =
Arc::new(ObjectStoreBucket::new(store, "immediate".to_string()).expect("create bucket"));
let deadline = std::time::Instant::now() + Duration::from_secs(5);
let segments = loop {
let segs: Vec<String> = bucket
.list("wal/")
.await
.expect("list")
.into_iter()
.filter(|k| k.ends_with(".segment"))
.collect();
if !segs.is_empty() {
break segs;
}
if std::time::Instant::now() > deadline {
break segs;
}
tokio::time::sleep(Duration::from_millis(50)).await;
};
assert!(
!segments.is_empty(),
"immediate mode should ship WAL segments"
);
}
#[cfg(all(feature = "compression", feature = "encryption"))]
#[tokio::test]
async fn test_compression_encryption_stacking() {
use common::InMemoryStore;
use wal_backup::storage::compressed::CompressedBucketStore;
use wal_backup::storage::encrypted::EncryptedBucketStore;
let base = InMemoryStore::arc();
let encrypted = Arc::new(EncryptedBucketStore::new(base.clone(), &[0x42u8; 32]));
let compressed_encrypted = CompressedBucketStore::new(encrypted, 6);
let plaintext = b"compressible data for stacking test: AAAAAAABBBBBBB".repeat(100);
compressed_encrypted
.put("stacked", Bytes::copy_from_slice(&plaintext))
.await
.unwrap();
let raw = base.get_raw("stacked").unwrap();
assert!(
raw.starts_with(b"ENCR"),
"outermost layer should be encrypted"
);
assert!(
raw.len() < plaintext.len(),
"compressed+encrypted should be smaller than original ({} >= {})",
raw.len(),
plaintext.len()
);
let decrypted = compressed_encrypted.get("stacked").await.unwrap().unwrap();
assert_eq!(decrypted.as_ref(), plaintext.as_slice());
}
#[tokio::test]
async fn test_error_if_conflict_rejects_newer_local() {
use wal_backup::RestoreBehavior;
let (_tmp, db_path) = setup_tmp_dir("error_if_conflict");
let bucket_dir = _tmp.path().join("bucket");
std::fs::create_dir_all(&bucket_dir).expect("create bucket dir");
let store = Arc::new(LocalFileSystem::new_with_prefix(&bucket_dir).expect("store"));
let bucket =
Arc::new(ObjectStoreBucket::new(store, "error_conflict".to_string()).expect("bucket"));
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));
let layer = DurabilityLayer::open(config, bucket.clone())
.await
.expect("open layer");
{
let conn = layer.conn().await;
conn.execute_batch("CREATE TABLE data (id INTEGER PRIMARY KEY, v TEXT)")
.expect("create table");
for i in 0..10 {
conn.execute(
"INSERT INTO data (v) VALUES (?1)",
rusqlite::params![format!("row_{}", i)],
)
.expect("insert");
}
}
layer.sync_now().await.expect("sync");
wait_for_sync(&layer, Duration::from_secs(5)).await;
layer.force_snapshot().await.expect("force snapshot");
wait_for_sync(&layer, Duration::from_secs(5)).await;
tokio::time::sleep(Duration::from_millis(200)).await;
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 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));
let layer2 = DurabilityLayer::open(config2, bucket.clone())
.await
.expect("restore from bucket");
{
let conn = layer2.conn().await;
conn.execute("INSERT INTO data (v) VALUES ('new_row')", [])
.expect("insert");
}
layer2.sync_now().await.expect("sync2");
wait_for_sync(&layer2, Duration::from_secs(5)).await;
tokio::time::sleep(Duration::from_millis(200)).await;
layer2.shutdown().await.expect("shutdown2");
drop(layer2);
{
let conn = rusqlite::Connection::open(&db_path).expect("open raw");
conn.execute("INSERT INTO data (v) VALUES ('external_modification')", [])
.expect("external insert");
}
let gen_path = db_path.with_extension("generation");
std::fs::write(&gen_path, "99999").expect("write fake generation");
let config3 = Config::new(&db_path)
.with_poll_interval(Duration::from_millis(100))
.with_restore_behavior(RestoreBehavior::ErrorIfConflict)
.with_snapshot_threshold(1024 * 1024 * 1024)
.with_snapshot_interval(Duration::from_secs(86400));
let result = DurabilityLayer::open(config3, bucket).await;
assert!(
result.is_err(),
"ErrorIfConflict should reject when local generation is higher than bucket"
);
}
#[tokio::test]
async fn test_always_restore_from_bucket_overwrites_local() {
use wal_backup::RestoreBehavior;
let (_tmp, db_path) = setup_tmp_dir("always_restore");
let bucket_dir = _tmp.path().join("bucket");
std::fs::create_dir_all(&bucket_dir).expect("create bucket dir");
let store = Arc::new(LocalFileSystem::new_with_prefix(&bucket_dir).expect("store"));
let bucket =
Arc::new(ObjectStoreBucket::new(store, "always_restore".to_string()).expect("bucket"));
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));
let layer = DurabilityLayer::open(config, bucket.clone())
.await
.expect("open layer");
{
let conn = layer.conn().await;
conn.execute_batch("CREATE TABLE data (id INTEGER PRIMARY KEY, v TEXT)")
.expect("create table");
for i in 0..20 {
conn.execute(
"INSERT INTO data (v) VALUES (?1)",
rusqlite::params![format!("bucket_row_{}", i)],
)
.expect("insert");
}
}
layer.sync_now().await.expect("sync");
wait_for_sync(&layer, Duration::from_secs(5)).await;
layer.force_snapshot().await.expect("force snapshot");
wait_for_sync(&layer, Duration::from_secs(5)).await;
tokio::time::sleep(Duration::from_millis(200)).await;
layer.shutdown().await.expect("shutdown");
drop(layer);
{
let conn = rusqlite::Connection::open(&db_path).expect("open db directly");
conn.execute("INSERT INTO data (v) VALUES ('local_only_row')", [])
.expect("insert extra row");
drop(conn);
}
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));
let layer2 = DurabilityLayer::open(config2, bucket.clone())
.await
.expect("open with AlwaysRestoreFromBucket");
{
let conn = layer2.conn().await;
let count = count_rows(&conn, "data");
assert_eq!(
count, 20,
"AlwaysRestoreFromBucket should restore bucket data (not 21 with local-only row)"
);
}
}
#[tokio::test]
async fn test_empty_database_restore() {
let (_tmp, db_path) = setup_tmp_dir("empty_db_restore");
let bucket_dir = _tmp.path().join("bucket");
std::fs::create_dir_all(&bucket_dir).expect("create bucket dir");
let store = Arc::new(LocalFileSystem::new_with_prefix(&bucket_dir).expect("store"));
let bucket =
Arc::new(ObjectStoreBucket::new(store, "empty_restore".to_string()).expect("bucket"));
let config = Config::new(&db_path)
.with_poll_interval(Duration::from_millis(100))
.with_snapshot_threshold(1024 * 1024 * 1024)
.with_snapshot_interval(Duration::from_secs(86400));
let layer = DurabilityLayer::open(config, bucket.clone())
.await
.expect("open 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(5)).await;
layer.force_snapshot().await.expect("force snapshot");
wait_for_sync(&layer, Duration::from_secs(5)).await;
tokio::time::sleep(Duration::from_millis(200)).await;
layer.shutdown().await.expect("shutdown");
drop(layer);
std::fs::remove_file(&db_path).expect("remove local DB");
let wal_path = db_path.with_extension("db-wal");
let _ = std::fs::remove_file(&wal_path);
let config2 = Config::new(&db_path)
.with_poll_interval(Duration::from_millis(100))
.with_snapshot_threshold(1024 * 1024 * 1024)
.with_snapshot_interval(Duration::from_secs(86400));
let layer2 = DurabilityLayer::open(config2, bucket)
.await
.expect("restore from bucket");
{
let conn = layer2.conn().await;
let count = count_rows(&conn, "empty_test");
assert_eq!(count, 0, "empty table should have 0 rows after restore");
}
}
struct CountingMetrics {
snapshots: std::sync::atomic::AtomicU32,
}
impl CountingMetrics {
fn new() -> Self {
Self {
snapshots: std::sync::atomic::AtomicU32::new(0),
}
}
}
impl Metrics for CountingMetrics {
fn frames_shipped(&self, _count: u32) {}
fn snapshot_taken(&self, _db_size: u64, _wal_size: u64) {
self.snapshots
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
fn sync_completed(&self, _duration_ms: u64) {}
fn restore_completed(&self, _duration_ms: u64) {}
fn segment_uploaded(&self, _key: &str, _size: u64) {}
fn segment_deleted(&self, _key: &str) {}
fn shipper_error(&self, _detail: &str) {}
}
#[tokio::test]
async fn test_open_with_metrics() {
let (_tmp, db_path) = setup_tmp_dir("metrics_test");
let bucket_dir = _tmp.path().join("bucket");
std::fs::create_dir_all(&bucket_dir).expect("create bucket dir");
let store = Arc::new(LocalFileSystem::new_with_prefix(&bucket_dir).expect("store"));
let bucket =
Arc::new(ObjectStoreBucket::new(store, "metrics_test".to_string()).expect("bucket"));
let metrics = Arc::new(CountingMetrics::new());
let config = Config::new(&db_path)
.with_poll_interval(Duration::from_millis(100))
.with_snapshot_threshold(1024 * 1024 * 1024)
.with_snapshot_interval(Duration::from_secs(86400));
let layer = DurabilityLayer::open_with_metrics(config, bucket, metrics.clone())
.await
.expect("open with metrics");
{
let conn = layer.conn().await;
conn.execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY)")
.expect("create table");
}
layer.sync_now().await.expect("sync");
wait_for_sync(&layer, Duration::from_secs(5)).await;
layer.force_snapshot().await.expect("snapshot");
wait_for_sync(&layer, Duration::from_secs(5)).await;
tokio::time::sleep(Duration::from_millis(200)).await;
let snap_count = metrics.snapshots.load(std::sync::atomic::Ordering::Relaxed);
assert!(
snap_count >= 1,
"metrics should record snapshot (got {snap_count})"
);
layer.shutdown().await.expect("shutdown");
}
#[tokio::test]
async fn test_auto_snapshot_trigger_on_size_threshold() {
let (_tmp, db_path) = setup_tmp_dir("auto_snapshot");
let bucket_dir = _tmp.path().join("bucket");
std::fs::create_dir_all(&bucket_dir).expect("create bucket dir");
let store = Arc::new(LocalFileSystem::new_with_prefix(&bucket_dir).expect("store"));
let bucket = Arc::new(ObjectStoreBucket::new(store, "auto_snap".to_string()).expect("bucket"));
let config = Config::new(&db_path)
.with_poll_interval(Duration::from_millis(50))
.with_snapshot_threshold(1)
.with_snapshot_interval(Duration::from_secs(86400));
let layer = DurabilityLayer::open(config, bucket.clone())
.await
.expect("open layer");
{
let conn = layer.conn().await;
conn.execute_batch("CREATE TABLE data (id INTEGER PRIMARY KEY, v TEXT)")
.expect("create table");
conn.execute("INSERT INTO data (v) VALUES ('x')", [])
.expect("insert");
}
layer.sync_now().await.expect("sync");
wait_for_sync(&layer, Duration::from_secs(5)).await;
let deadline = std::time::Instant::now() + Duration::from_secs(10);
loop {
let manifest_data = bucket.get(MANIFEST_KEY).await.expect("get manifest");
if let Some(data) = manifest_data {
let v: serde_json::Value = serde_json::from_slice(&data).expect("json");
if v.get("snapshot").and_then(|v| v.as_str()).is_some() {
break;
}
}
if std::time::Instant::now() > deadline {
panic!("auto snapshot not triggered within timeout");
}
tokio::time::sleep(Duration::from_millis(200)).await;
}
drop(layer);
}
#[tokio::test]
async fn test_health_report_returns_diagnostics() {
let (_tmp, db_path) = setup_tmp_dir("health_report");
let bucket_dir = db_path.parent().unwrap().join("bucket");
let layer = create_layer(&db_path, "health_rpt", &bucket_dir, 50).await;
{
let conn = layer.conn().await;
conn.execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY)")
.expect("create table");
}
layer.sync_now().await.expect("sync");
let report = layer.health_report().await;
assert!(report.healthy);
assert!(report.replicator_alive);
assert!(report.snapshot_alive);
assert!(report.last_sync_ago < Duration::from_secs(5));
}
#[tokio::test]
async fn test_with_conn_scoped_closure() {
let (_tmp, db_path) = setup_tmp_dir("with_conn_test");
let bucket_dir = db_path.parent().unwrap().join("bucket");
let layer = create_layer(&db_path, "with_conn", &bucket_dir, 50).await;
{
let conn = layer.conn().await;
conn.execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT)")
.expect("create table");
}
layer
.with_conn(|c| c.execute("INSERT INTO t (v) VALUES ('via_with_conn')", []))
.await
.expect("with_conn insert");
let count: i64 = layer
.with_conn(|c| c.query_row("SELECT COUNT(*) FROM t", [], |r| r.get(0)))
.await
.expect("with_conn query");
assert_eq!(count, 1, "with_conn should execute queries through closure");
}
#[tokio::test]
async fn test_shutdown_ships_pending_frames() {
let (_tmp, db_path) = setup_tmp_dir("shutdown_ships_test");
let bucket_dir = db_path.parent().unwrap().join("bucket");
let layer = create_layer(&db_path, "shutdown_ships", &bucket_dir, 50).await;
{
let conn = layer.conn().await;
conn.execute_batch("CREATE TABLE data (id INTEGER PRIMARY KEY, v TEXT)")
.expect("create table");
for i in 0..100 {
conn.execute("INSERT INTO data (v) VALUES (?1)", [&format!("row-{i}")])
.expect("insert");
}
}
layer.shutdown().await.expect("shutdown");
let store = Arc::new(
LocalFileSystem::new_with_prefix(&bucket_dir).expect("create local filesystem store"),
);
let bucket = Arc::new(
ObjectStoreBucket::new(store, "shutdown_ships".to_string()).expect("create bucket"),
);
let manifest_data = bucket
.get(MANIFEST_KEY)
.await
.expect("get manifest")
.expect("manifest exists");
let manifest: wal_backup::replication::manifest::Manifest =
wal_backup::replication::manifest::Manifest::deserialize(&manifest_data)
.expect("parse manifest");
assert!(
manifest.shipped_frames > 0,
"shipped_frames should be > 0 after shutdown (frames were shipped), got {}",
manifest.shipped_frames
);
let conn = rusqlite::Connection::open(&db_path).expect("open db");
let count: i64 = conn
.query_row("SELECT COUNT(*) FROM data", [], |r| r.get(0))
.expect("count");
assert_eq!(count, 100, "all rows should be in the DB after shutdown");
}