mod common;
use object_store::local::LocalFileSystem;
use std::sync::Arc;
use wal_backup::config::{Config, RestoreBehavior};
use wal_backup::replication::manifest::Manifest;
use wal_backup::restore::{read_page_size_from_db, read_page_size_from_db_async, RestoreEngine};
use wal_backup::ObjectStoreBucket;
use common::InMemoryStore;
fn make_db_with_page_size(page_size: u16) -> Vec<u8> {
let mut data = vec![0u8; 100];
data[16..18].copy_from_slice(&page_size.to_be_bytes());
data
}
#[test]
fn test_read_page_size_from_db_async_too_short() {
let tmp = tempfile::tempdir().unwrap();
let db_path = tmp.path().join("tiny.db");
std::fs::write(&db_path, vec![0u8; 10]).unwrap();
let rt = tokio::runtime::Runtime::new().unwrap();
let result = rt.block_on(read_page_size_from_db_async(&db_path));
assert!(result.is_err());
}
#[test]
fn test_read_page_size_from_db_async_ok() {
let tmp = tempfile::tempdir().unwrap();
let db_path = tmp.path().join("test.db");
std::fs::write(&db_path, make_db_with_page_size(4096)).unwrap();
let rt = tokio::runtime::Runtime::new().unwrap();
let result = rt.block_on(read_page_size_from_db_async(&db_path)).unwrap();
assert_eq!(result, 4096);
}
#[test]
fn test_read_page_size_from_db_async_8192() {
let tmp = tempfile::tempdir().unwrap();
let db_path = tmp.path().join("test.db");
std::fs::write(&db_path, make_db_with_page_size(8192)).unwrap();
let rt = tokio::runtime::Runtime::new().unwrap();
let result = rt.block_on(read_page_size_from_db_async(&db_path)).unwrap();
assert_eq!(result, 8192);
}
#[test]
fn test_read_page_size_from_db_special_1_means_65536() {
let data = make_db_with_page_size(1);
let result = read_page_size_from_db(&data).unwrap();
assert_eq!(result, 65536);
}
#[test]
fn test_read_page_size_from_db_too_small() {
let data = vec![0u8; 10];
assert!(read_page_size_from_db(&data).is_err());
}
#[test]
fn test_local_is_newer_than_manifest_gen0_no_snapshot() {
use wal_backup::config::{Config, RestoreBehavior};
use wal_backup::replication::manifest::Manifest;
let tmp = tempfile::tempdir().unwrap();
let db_path = tmp.path().join("test.db");
std::fs::write(&db_path, make_db_with_page_size(4096)).unwrap();
let inner = InMemoryStore::arc();
let config = Config::new(&db_path).with_restore_behavior(RestoreBehavior::UploadLocalIfNewer);
let engine = RestoreEngine::new(config, inner.clone());
let manifest = Manifest::new(0x1234, 0x5678, 4096);
let rt = tokio::runtime::Runtime::new().unwrap();
let result = rt.block_on(engine.local_is_newer_than_manifest(&manifest));
assert!(
result,
"generation=0 with no snapshot should be treated as newer (fresh start)"
);
}
#[test]
fn test_local_is_newer_than_manifest_with_existing_snapshot() {
use wal_backup::config::{Config, RestoreBehavior};
use wal_backup::replication::manifest::Manifest;
let tmp = tempfile::tempdir().unwrap();
let db_path = tmp.path().join("test.db");
std::fs::write(&db_path, make_db_with_page_size(4096)).unwrap();
let inner = InMemoryStore::arc();
let config = Config::new(&db_path).with_restore_behavior(RestoreBehavior::UploadLocalIfNewer);
let engine = RestoreEngine::new(config, inner.clone());
let mut manifest = Manifest::new(0x1234, 0x5678, 4096);
manifest.generation = 5;
manifest.update_snapshot(
"snapshots/test.db".to_string(),
"sha256:abc".to_string(),
0x1234,
0x5678,
4096,
100,
);
manifest.last_updated = "2099-01-01T00:00:00Z".to_string();
let rt = tokio::runtime::Runtime::new().unwrap();
let result = rt.block_on(engine.local_is_newer_than_manifest(&manifest));
assert!(
!result,
"local DB with no generation file and bucket has snapshot should prefer bucket (anti-data-loss guard)"
);
}
#[test]
fn test_local_is_newer_than_manifest_with_generation_and_snapshot() {
use wal_backup::config::{Config, RestoreBehavior};
use wal_backup::replication::manifest::Manifest;
let tmp = tempfile::tempdir().unwrap();
let db_path = tmp.path().join("test.db");
std::fs::write(&db_path, make_db_with_page_size(4096)).unwrap();
let inner = InMemoryStore::arc();
let config = Config::new(&db_path).with_restore_behavior(RestoreBehavior::UploadLocalIfNewer);
let engine = RestoreEngine::new(config, inner.clone());
let mut manifest = Manifest::new(0x1234, 0x5678, 4096);
manifest.generation = 5;
manifest.update_snapshot(
"snapshots/test.db".to_string(),
"sha256:abc".to_string(),
0x1234,
0x5678,
4096,
100,
);
manifest.last_updated = "2099-01-01T00:00:00Z".to_string();
let gen_path = db_path.with_extension("generation");
std::fs::write(&gen_path, "5").unwrap();
let rt = tokio::runtime::Runtime::new().unwrap();
let result = rt.block_on(engine.local_is_newer_than_manifest(&manifest));
assert!(
!result,
"local DB with matching generation should NOT be newer than manifest"
);
std::fs::write(&gen_path, "10").unwrap();
let result2 = rt.block_on(engine.local_is_newer_than_manifest(&manifest));
assert!(
result2,
"local DB with higher generation should be newer than manifest"
);
}
#[test]
fn test_stale_generation_with_empty_db_restores_from_bucket() {
use common::InMemoryStore;
use wal_backup::config::{Config, RestoreBehavior};
use wal_backup::replication::manifest::Manifest;
use wal_backup::restore::RestoreEngine;
let tmp = tempfile::tempdir().unwrap();
let db_path = tmp.path().join("test.db");
let conn = rusqlite::Connection::open(&db_path).unwrap();
conn.execute_batch("CREATE TABLE data (id INTEGER PRIMARY KEY)")
.unwrap();
conn.execute_batch("DROP TABLE data").unwrap();
drop(conn);
let gen_path = db_path.with_extension("generation");
std::fs::write(&gen_path, "1000").unwrap();
let inner = InMemoryStore::arc();
let config = Config::new(&db_path).with_restore_behavior(RestoreBehavior::UploadLocalIfNewer);
let engine = RestoreEngine::new(config, inner.clone());
let mut manifest = Manifest::new(0x1234, 0x5678, 4096);
manifest.generation = 5;
manifest.update_snapshot(
"snapshots/test.db".to_string(),
"sha256:abc".to_string(),
0x1234,
0x5678,
4096,
100,
);
let rt = tokio::runtime::Runtime::new().unwrap();
let result = rt.block_on(engine.local_is_newer_than_manifest(&manifest));
assert!(
result,
"raw local_is_newer still returns true (gen 1000 > 5) — the guard is in restore()"
);
let is_empty = rt.block_on(engine.is_db_empty()).unwrap();
assert!(
is_empty,
"empty DB (no user tables) should be detected as empty"
);
let conn = rusqlite::Connection::open(&db_path).unwrap();
conn.execute_batch("CREATE TABLE events (id INTEGER PRIMARY KEY, kind TEXT)")
.unwrap();
conn.execute("INSERT INTO events (kind) VALUES ('test')", [])
.unwrap();
drop(conn);
let is_empty = rt.block_on(engine.is_db_empty()).unwrap();
assert!(
!is_empty,
"DB with user tables should NOT be detected as empty"
);
}
#[tokio::test]
async fn test_restore_fresh_start_no_manifest_no_local_db() {
use wal_backup::config::{Config, RestoreBehavior};
let tmp = tempfile::tempdir().unwrap();
let db_path = tmp.path().join("fresh.db");
let bucket_dir = tmp.path().join("bucket");
std::fs::create_dir_all(&bucket_dir).unwrap();
let inner = Arc::new(LocalFileSystem::new_with_prefix(&bucket_dir).unwrap());
let bucket = Arc::new(ObjectStoreBucket::new(inner, "fresh".to_string()).unwrap());
let config = Config::new(&db_path).with_restore_behavior(RestoreBehavior::UploadLocalIfNewer);
let engine = RestoreEngine::new(config, bucket);
let manifest_arc = engine.restore().await.unwrap();
let manifest = manifest_arc.lock().await;
assert_eq!(manifest.current_salt_1, 0);
assert_eq!(manifest.current_salt_2, 0);
assert_eq!(manifest.generation, 0);
}
#[tokio::test]
async fn test_restore_fresh_start_no_manifest_with_local_wal() {
use wal_backup::config::{Config, RestoreBehavior};
let tmp = tempfile::tempdir().unwrap();
let db_path = tmp.path().join("fresh.db");
let wal_path = tmp.path().join("fresh.db-wal");
let page_size = 4096u32;
let magic = 0x377f0682u32;
let file_format = 3007000u32;
let checkpoint_seq = 1u32;
let salt_1 = 0xDEADBEEFu32;
let salt_2 = 0xCAFEBABEu32;
let mut header_data = [0u8; 24];
header_data[0..4].copy_from_slice(&magic.to_be_bytes());
header_data[4..8].copy_from_slice(&file_format.to_be_bytes());
header_data[8..12].copy_from_slice(&page_size.to_be_bytes());
header_data[12..16].copy_from_slice(&checkpoint_seq.to_be_bytes());
header_data[16..20].copy_from_slice(&salt_1.to_be_bytes());
header_data[20..24].copy_from_slice(&salt_2.to_be_bytes());
let (ck1, ck2) = wal_backup::wal::checksum::wal_checksum_pair(0, 0, &header_data, false);
let mut wal_bytes = Vec::new();
wal_bytes.extend_from_slice(&magic.to_be_bytes());
wal_bytes.extend_from_slice(&file_format.to_be_bytes());
wal_bytes.extend_from_slice(&page_size.to_be_bytes());
wal_bytes.extend_from_slice(&checkpoint_seq.to_be_bytes());
wal_bytes.extend_from_slice(&salt_1.to_be_bytes());
wal_bytes.extend_from_slice(&salt_2.to_be_bytes());
wal_bytes.extend_from_slice(&ck1.to_be_bytes());
wal_bytes.extend_from_slice(&ck2.to_be_bytes());
std::fs::write(&wal_path, &wal_bytes).unwrap();
std::fs::write(&db_path, make_db_with_page_size(4096)).unwrap();
let bucket_dir = tmp.path().join("bucket2");
std::fs::create_dir_all(&bucket_dir).unwrap();
let inner = Arc::new(LocalFileSystem::new_with_prefix(&bucket_dir).unwrap());
let bucket = Arc::new(ObjectStoreBucket::new(inner, "wal_salt".to_string()).unwrap());
let config = Config::new(&db_path).with_restore_behavior(RestoreBehavior::UploadLocalIfNewer);
let engine = RestoreEngine::new(config, bucket);
let manifest_arc = engine.restore().await.unwrap();
let manifest = manifest_arc.lock().await;
assert_eq!(manifest.current_salt_1, salt_1);
assert_eq!(manifest.current_salt_2, salt_2);
assert_eq!(manifest.page_size, 4096);
}
#[tokio::test]
async fn test_restore_snapshot_checksum_mismatch_recoverable() {
use wal_backup::config::{Config, RestoreBehavior};
use wal_backup::replication::manifest::Manifest;
let tmp = tempfile::tempdir().unwrap();
let db_path = tmp.path().join("test.db");
let mut store_data = std::collections::HashMap::new();
let snapshot_bytes = make_db_with_page_size(4096);
let wrong_checksum = "sha256:0000000000000000000000000000000000000000000000000000000000000000";
store_data.insert("snapshots/test.db".to_string(), snapshot_bytes);
let mut manifest = Manifest::new(0x1111, 0x2222, 4096);
manifest.update_snapshot(
"snapshots/test.db".to_string(),
wrong_checksum.to_string(),
0x1111,
0x2222,
4096,
100,
);
let manifest_bytes = manifest.serialize().unwrap();
store_data.insert("manifest.json".to_string(), manifest_bytes);
let store = InMemoryStore::arc_with_data(store_data);
let config = Config::new(&db_path).with_restore_behavior(RestoreBehavior::Recoverable);
let engine = RestoreEngine::new(config, store);
let result = engine.restore().await;
assert!(
result.is_ok(),
"Recoverable mode should proceed despite checksum mismatch, got: {:?}",
result
);
}
#[tokio::test]
async fn test_restore_checksum_mismatch_non_recoverable_returns_error() {
use wal_backup::config::{Config, RestoreBehavior};
use wal_backup::replication::manifest::Manifest;
let tmp = tempfile::tempdir().unwrap();
let db_path = tmp.path().join("test.db");
let mut store_data = std::collections::HashMap::new();
let snapshot_bytes = make_db_with_page_size(4096);
let wrong_checksum = "sha256:0000000000000000000000000000000000000000000000000000000000000000";
store_data.insert("snapshots/test.db".to_string(), snapshot_bytes);
let mut manifest = Manifest::new(0x1111, 0x2222, 4096);
manifest.update_snapshot(
"snapshots/test.db".to_string(),
wrong_checksum.to_string(),
0x1111,
0x2222,
4096,
100,
);
let manifest_bytes = manifest.serialize().unwrap();
store_data.insert("manifest.json".to_string(), manifest_bytes);
let store = InMemoryStore::arc_with_data(store_data);
let config = Config::new(&db_path).with_restore_behavior(RestoreBehavior::UploadLocalIfNewer);
let engine = RestoreEngine::new(config, store);
let result = engine.restore().await;
assert!(
result.is_err(),
"UploadLocalIfNewer (non-Recoverable) should fail on checksum mismatch, got: {:?}",
result
);
let err = result.unwrap_err();
assert!(
err.to_string().contains("checksum mismatch"),
"error should mention checksum mismatch, got: {err}"
);
}
#[tokio::test]
async fn test_restore_no_snapshot_in_manifest_returns_error() {
use wal_backup::config::Config;
let tmp = tempfile::tempdir().unwrap();
let db_path = tmp.path().join("test.db");
let mut store_data = std::collections::HashMap::new();
let mut manifest = Manifest::new(0x1111, 0x2222, 4096);
manifest.generation = 5;
manifest.last_updated = "2024-01-01T00:00:00Z".to_string();
let manifest_bytes = manifest.serialize().unwrap();
store_data.insert("manifest.json".to_string(), manifest_bytes);
let store = InMemoryStore::arc_with_data(store_data);
let config = Config::new(&db_path)
.with_restore_behavior(wal_backup::RestoreBehavior::AlwaysRestoreFromBucket);
let engine = RestoreEngine::new(config, store);
let result = engine.restore().await;
assert!(
result.is_err(),
"manifest with no snapshot should error, got: {:?}",
result
);
let err = result.unwrap_err();
assert!(
err.to_string().contains("No snapshot found"),
"error should say 'No snapshot found', got: {err}"
);
}
#[tokio::test]
async fn test_restore_snapshot_not_found_in_bucket_returns_error() {
use wal_backup::config::{Config, RestoreBehavior};
let tmp = tempfile::tempdir().unwrap();
let db_path = tmp.path().join("test.db");
let mut store_data = std::collections::HashMap::new();
let mut manifest = Manifest::new(0x1111, 0x2222, 4096);
manifest.update_snapshot(
"snapshots/missing.db".to_string(),
"sha256:abc123".to_string(),
0x1111,
0x2222,
4096,
100,
);
let manifest_bytes = manifest.serialize().unwrap();
store_data.insert("manifest.json".to_string(), manifest_bytes);
let store = InMemoryStore::arc_with_data(store_data);
let config =
Config::new(&db_path).with_restore_behavior(RestoreBehavior::AlwaysRestoreFromBucket);
let engine = RestoreEngine::new(config, store);
let result = engine.restore().await;
assert!(result.is_err(), "missing snapshot file should error");
let err = result.unwrap_err();
assert!(
err.to_string().contains("Snapshot not found"),
"error should say 'Snapshot not found', got: {err}"
);
}
#[tokio::test]
async fn test_restore_no_segments_but_shipped_frames_creates_wal_with_header() {
use wal_backup::config::{Config, RestoreBehavior};
let tmp = tempfile::tempdir().unwrap();
let db_path = tmp.path().join("test.db");
let mut store_data = std::collections::HashMap::new();
let snapshot_bytes = make_db_with_page_size(4096);
store_data.insert("snapshots/test.db".to_string(), snapshot_bytes.clone());
let mut manifest = Manifest::new(0x1111, 0x2222, 4096);
manifest.update_snapshot(
"snapshots/test.db".to_string(),
compute_sha256(&snapshot_bytes),
0x1111,
0x2222,
4096,
100,
);
manifest.shipped_frames = 5;
let manifest_bytes = manifest.serialize().unwrap();
store_data.insert("manifest.json".to_string(), manifest_bytes);
let store = InMemoryStore::arc_with_data(store_data);
let config =
Config::new(&db_path).with_restore_behavior(RestoreBehavior::AlwaysRestoreFromBucket);
let engine = RestoreEngine::new(config, store);
let result = engine.restore().await;
assert!(
result.is_ok(),
"restore with shipped_frames but no segments should succeed (no WAL file created), got: {:?}",
result
);
let wal_path = db_path.with_extension("db-wal");
assert!(
wal_path.exists(),
"WAL file should be created with header even when there are no segments to download"
);
}
#[test]
fn test_local_is_newer_than_manifest_true_by_timestamp() {
use wal_backup::config::{Config, RestoreBehavior};
use wal_backup::replication::manifest::Manifest;
let tmp = tempfile::tempdir().unwrap();
let db_path = tmp.path().join("test.db");
std::fs::write(&db_path, make_db_with_page_size(4096)).unwrap();
let inner = InMemoryStore::arc();
let config = Config::new(&db_path).with_restore_behavior(RestoreBehavior::UploadLocalIfNewer);
let engine = RestoreEngine::new(config, inner.clone());
let mut manifest = Manifest::new(0x1234, 0x5678, 4096);
manifest.generation = 5;
manifest.update_snapshot(
"snapshots/test.db".to_string(),
"sha256:abc".to_string(),
0x1234,
0x5678,
4096,
100,
);
manifest.last_updated = "2020-01-01T00:00:00Z".to_string();
let rt = tokio::runtime::Runtime::new().unwrap();
let result = rt.block_on(engine.local_is_newer_than_manifest(&manifest));
assert!(
!result,
"local DB with no generation file and bucket has snapshot should prefer bucket (anti-data-loss guard)"
);
}
#[test]
fn test_local_is_newer_than_manifest_no_local_db_returns_false() {
use wal_backup::config::{Config, RestoreBehavior};
use wal_backup::replication::manifest::Manifest;
let tmp = tempfile::tempdir().unwrap();
let db_path = tmp.path().join("nonexistent.db");
let inner = InMemoryStore::arc();
let config = Config::new(&db_path).with_restore_behavior(RestoreBehavior::UploadLocalIfNewer);
let engine = RestoreEngine::new(config, inner.clone());
let mut manifest = Manifest::new(0x1234, 0x5678, 4096);
manifest.generation = 5;
manifest.update_snapshot(
"snapshots/test.db".to_string(),
"sha256:abc".to_string(),
0x1234,
0x5678,
4096,
100,
);
manifest.last_updated = "2020-01-01T00:00:00Z".to_string();
let rt = tokio::runtime::Runtime::new().unwrap();
let result = rt.block_on(engine.local_is_newer_than_manifest(&manifest));
assert!(
!result,
"no local DB file should not be newer than manifest"
);
}
use wal_backup::util::compute_sha256;
#[tokio::test]
async fn test_restore_with_segments_synthesizes_wal_header() {
use wal_backup::config::{Config, RestoreBehavior};
let tmp = tempfile::tempdir().unwrap();
let db_path = tmp.path().join("synth.db");
let snapshot_bytes = make_db_with_page_size(4096);
let salt_1: u32 = 0xDEAD;
let salt_2: u32 = 0xBEEF;
let mut manifest = Manifest::new(salt_1, salt_2, 4096);
manifest.update_snapshot(
"snapshots/synth.db".to_string(),
compute_sha256(&snapshot_bytes),
salt_1,
salt_2,
4096,
snapshot_bytes.len() as u64,
);
manifest.shipped_frames = 1;
let segment_prefix = manifest.segment_prefix();
let segment_key = format!("{}00000000-00000001.segment", segment_prefix);
let magic: u32 = 0x377f0682;
let page_size: u32 = 4096;
let file_format: u32 = 3007000;
let checkpoint_seq: u32 = 1;
let mut header_data = [0u8; 24];
header_data[0..4].copy_from_slice(&magic.to_be_bytes());
header_data[4..8].copy_from_slice(&file_format.to_be_bytes());
header_data[8..12].copy_from_slice(&page_size.to_be_bytes());
header_data[12..16].copy_from_slice(&checkpoint_seq.to_be_bytes());
header_data[16..20].copy_from_slice(&salt_1.to_be_bytes());
header_data[20..24].copy_from_slice(&salt_2.to_be_bytes());
let (ck1, ck2) = wal_backup::wal::checksum::wal_checksum_pair(0, 0, &header_data, false);
let page_number: u32 = 1;
let db_size_after: u32 = 1;
let frame_page_data = vec![0u8; page_size as usize];
let mut checksum_input = Vec::with_capacity(8 + page_size as usize);
checksum_input.extend_from_slice(&page_number.to_be_bytes());
checksum_input.extend_from_slice(&db_size_after.to_be_bytes());
checksum_input.extend_from_slice(&frame_page_data);
let (fc1, fc2) = wal_backup::wal::checksum::wal_checksum_pair(ck1, ck2, &checksum_input, false);
let mut segment = Vec::new();
segment.extend_from_slice(&page_number.to_be_bytes());
segment.extend_from_slice(&db_size_after.to_be_bytes());
segment.extend_from_slice(&salt_1.to_be_bytes());
segment.extend_from_slice(&salt_2.to_be_bytes());
segment.extend_from_slice(&fc1.to_be_bytes());
segment.extend_from_slice(&fc2.to_be_bytes());
segment.extend_from_slice(&frame_page_data);
let mut store_data = std::collections::HashMap::new();
store_data.insert("snapshots/synth.db".to_string(), snapshot_bytes);
store_data.insert("manifest.json".to_string(), manifest.serialize().unwrap());
store_data.insert(segment_key, segment);
let store = InMemoryStore::arc_with_data(store_data);
let config =
Config::new(&db_path).with_restore_behavior(RestoreBehavior::AlwaysRestoreFromBucket);
let engine = RestoreEngine::new(config, store);
let result = engine.restore().await;
assert!(
result.is_ok(),
"restore with segments should succeed even without existing WAL: {:?}",
result
);
let wal_path = db_path.with_extension("db-wal");
assert!(
wal_path.exists(),
"WAL file should be created after restore"
);
}
#[tokio::test]
async fn test_restore_checksum_mismatch_errorifconflict_returns_error() {
use wal_backup::config::{Config, RestoreBehavior};
let tmp = tempfile::tempdir().unwrap();
let db_path = tmp.path().join("errorconflict.db");
let mut store_data = std::collections::HashMap::new();
let snapshot_bytes = make_db_with_page_size(4096);
let wrong_checksum = "sha256:0000000000000000000000000000000000000000000000000000000000000000";
store_data.insert("snapshots/test.db".to_string(), snapshot_bytes);
let mut manifest = Manifest::new(0x1111, 0x2222, 4096);
manifest.update_snapshot(
"snapshots/test.db".to_string(),
wrong_checksum.to_string(),
0x1111,
0x2222,
4096,
100,
);
let manifest_bytes = manifest.serialize().unwrap();
store_data.insert("manifest.json".to_string(), manifest_bytes);
let store = InMemoryStore::arc_with_data(store_data);
let config = Config::new(&db_path).with_restore_behavior(RestoreBehavior::ErrorIfConflict);
let engine = RestoreEngine::new(config, store);
let result = engine.restore().await;
assert!(
result.is_err(),
"ErrorIfConflict should also fail on checksum mismatch (falls through to _ branch): {:?}",
result
);
}
#[tokio::test]
async fn test_restore_checksum_uses_streaming_hash() {
let tmp = tempfile::tempdir().unwrap();
let bucket_dir = tmp.path().join("bucket");
std::fs::create_dir_all(&bucket_dir).unwrap();
let db_path = tmp.path().join("streaming_hash.db");
let conn = rusqlite::Connection::open(&db_path).unwrap();
conn.execute_batch("PRAGMA journal_mode = WAL").unwrap();
conn.execute_batch("PRAGMA wal_autocheckpoint = 0").unwrap();
conn.execute_batch("CREATE TABLE IF NOT EXISTS t (id INTEGER PRIMARY KEY, val TEXT NOT NULL)")
.unwrap();
conn.execute("INSERT INTO t (val) VALUES ('x')", [])
.unwrap();
drop(conn);
let db_bytes = std::fs::read(&db_path).unwrap();
let expected_checksum = wal_backup::util::compute_sha256(&db_bytes);
let page_size = read_page_size_from_db(&db_bytes).unwrap();
let mut store_data = std::collections::HashMap::new();
store_data.insert("snapshots/test.db".to_string(), db_bytes);
let mut manifest = Manifest::new(0x1111, 0x2222, page_size);
manifest.update_snapshot(
"snapshots/test.db".to_string(),
expected_checksum.clone(),
0x1111,
0x2222,
page_size,
100,
);
let manifest_bytes = manifest.serialize().unwrap();
store_data.insert("manifest.json".to_string(), manifest_bytes);
let store = InMemoryStore::arc_with_data(store_data);
let restore_db_path = tmp.path().join("restored.db");
let config = Config::new(&restore_db_path)
.with_restore_behavior(RestoreBehavior::AlwaysRestoreFromBucket);
let engine = RestoreEngine::new(config, store);
let result = engine.restore().await;
assert!(
result.is_ok(),
"restore should succeed with matching checksum: {:?}",
result
);
assert!(restore_db_path.exists(), "restored DB should exist on disk");
}
#[tokio::test]
async fn test_upload_local_preserves_wal_salt_before_truncate() {
let tmp = tempfile::tempdir().unwrap();
let db_path = tmp.path().join("salt_test.db");
let conn = rusqlite::Connection::open(&db_path).unwrap();
conn.execute_batch("PRAGMA journal_mode = WAL").unwrap();
conn.execute_batch("PRAGMA wal_autocheckpoint = 0").unwrap();
conn.execute_batch("CREATE TABLE IF NOT EXISTS t (id INTEGER PRIMARY KEY)")
.unwrap();
conn.execute("INSERT INTO t DEFAULT VALUES", []).unwrap();
let wal_path = db_path.with_extension("db-wal");
let original_salt = {
let wal = wal_backup::WalFile::open(&wal_path).unwrap();
(wal.header().salt_1, wal.header().salt_2)
};
assert!(
original_salt.0 != 0 || original_salt.1 != 0,
"WAL should have non-zero salts after write"
);
let mut store_data = std::collections::HashMap::new();
let manifest = Manifest::new(0, 0, 4096);
let manifest_bytes = manifest.serialize().unwrap();
store_data.insert("manifest.json".to_string(), manifest_bytes);
let store = InMemoryStore::arc_with_data(store_data);
let config = Config::new(&db_path).with_restore_behavior(RestoreBehavior::UploadLocalIfNewer);
let engine = RestoreEngine::new(config, store);
let result = engine.restore().await;
assert!(result.is_ok(), "restore should succeed: {:?}", result);
let manifest_arc = result.unwrap();
let manifest_guard = manifest_arc.lock().await;
assert_eq!(
(manifest_guard.current_salt_1, manifest_guard.current_salt_2),
original_salt,
"manifest should preserve WAL salt values from before checkpoint truncation"
);
drop(conn);
}
fn compute_sha256_for_restore(data: &[u8]) -> String {
use sha2::Digest;
let mut hasher = sha2::Sha256::new();
hasher.update(data);
let result = sha2::Digest::finalize(hasher);
format!(
"sha256:{}",
result
.iter()
.map(|b| format!("{:02x}", b))
.collect::<String>()
)
}
#[tokio::test]
async fn test_restore_with_l1_and_uncovered_l0_segments() {
use wal_backup::config::{Config, RestoreBehavior};
use wal_backup::replication::manifest::{L1File, Manifest};
use wal_backup::wal::checksum::wal_checksum_pair;
let tmp = tempfile::tempdir().unwrap();
let db_path = tmp.path().join("l1_restore.db");
let snapshot_bytes = make_db_with_page_size(4096);
let snapshot_checksum = compute_sha256_for_restore(&snapshot_bytes);
let salt_1: u32 = 0xAAAA;
let salt_2: u32 = 0xBBBB;
let mut manifest = Manifest::new(salt_1, salt_2, 4096);
manifest.update_snapshot(
"snapshots/l1_restore.db".to_string(),
snapshot_checksum.clone(),
salt_1,
salt_2,
4096,
snapshot_bytes.len() as u64,
);
manifest.shipped_frames = 2;
manifest.l1_files.push(L1File {
key: format!("wal/{}-{}/{:08}-{:08}.l1", salt_1, salt_2, 0, 0),
start_frame: 0,
end_frame: 0,
source_count: 1,
checksum: None,
});
manifest.l1_max_frame = Some(0);
let magic: u32 = 0x377f0682;
let page_size: u32 = 4096;
let file_format: u32 = 3007000;
let checkpoint_seq: u32 = 1;
let mut header_data = [0u8; 24];
header_data[0..4].copy_from_slice(&magic.to_be_bytes());
header_data[4..8].copy_from_slice(&file_format.to_be_bytes());
header_data[8..12].copy_from_slice(&page_size.to_be_bytes());
header_data[12..16].copy_from_slice(&checkpoint_seq.to_be_bytes());
header_data[16..20].copy_from_slice(&salt_1.to_be_bytes());
header_data[20..24].copy_from_slice(&salt_2.to_be_bytes());
let (ck1, ck2) = wal_checksum_pair(0, 0, &header_data, false);
let page_number: u32 = 1;
let db_size_after: u32 = 1;
let frame_page_data = vec![0u8; page_size as usize];
let mut checksum_input = Vec::with_capacity(8 + page_size as usize);
checksum_input.extend_from_slice(&page_number.to_be_bytes());
checksum_input.extend_from_slice(&db_size_after.to_be_bytes());
checksum_input.extend_from_slice(&frame_page_data);
let (fc1, fc2) = wal_checksum_pair(ck1, ck2, &checksum_input, false);
let mut frame0_data = Vec::new();
frame0_data.extend_from_slice(&page_number.to_be_bytes());
frame0_data.extend_from_slice(&db_size_after.to_be_bytes());
frame0_data.extend_from_slice(&salt_1.to_be_bytes());
frame0_data.extend_from_slice(&salt_2.to_be_bytes());
frame0_data.extend_from_slice(&fc1.to_be_bytes());
frame0_data.extend_from_slice(&fc2.to_be_bytes());
frame0_data.extend_from_slice(&frame_page_data);
let page_number_1: u32 = 2;
let mut checksum_input2 = Vec::with_capacity(8 + page_size as usize);
checksum_input2.extend_from_slice(&page_number_1.to_be_bytes());
checksum_input2.extend_from_slice(&db_size_after.to_be_bytes());
checksum_input2.extend_from_slice(&frame_page_data);
let (fc1b, fc2b) = wal_checksum_pair(fc1, fc2, &checksum_input2, false);
let mut frame1_data = Vec::new();
frame1_data.extend_from_slice(&page_number_1.to_be_bytes());
frame1_data.extend_from_slice(&db_size_after.to_be_bytes());
frame1_data.extend_from_slice(&salt_1.to_be_bytes());
frame1_data.extend_from_slice(&salt_2.to_be_bytes());
frame1_data.extend_from_slice(&fc1b.to_be_bytes());
frame1_data.extend_from_slice(&fc2b.to_be_bytes());
frame1_data.extend_from_slice(&frame_page_data);
let l1_key = format!("wal/{}-{}/{:08}-{:08}.l1", salt_1, salt_2, 0, 0);
let l0_key = format!("wal/{}-{}/{:08}-{:08}.segment", salt_1, salt_2, 1, 2);
let mut store_data = std::collections::HashMap::new();
store_data.insert("snapshots/l1_restore.db".to_string(), snapshot_bytes);
store_data.insert("manifest.json".to_string(), manifest.serialize().unwrap());
store_data.insert(l1_key, frame0_data);
store_data.insert(l0_key, frame1_data);
let store = InMemoryStore::arc_with_data(store_data);
let config =
Config::new(&db_path).with_restore_behavior(RestoreBehavior::AlwaysRestoreFromBucket);
let engine = RestoreEngine::new(config, store);
let result = engine.restore().await;
assert!(
result.is_ok(),
"restore with L1 + L0 should succeed: {:?}",
result
);
let wal_path = db_path.with_extension("db-wal");
assert!(wal_path.exists(), "WAL file should exist after restore");
let wal_data = std::fs::read(&wal_path).unwrap();
let wal_frame_size = (24 + page_size) as usize;
let wal_data_size = wal_data.len() - 32;
assert_eq!(
wal_data_size / wal_frame_size,
2,
"WAL should have 2 frames (1 from L1, 1 from L0)"
);
}