mod common;
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64};
use std::sync::Arc;
use std::time::Duration;
use common::InMemoryStore;
use tokio::sync::{Mutex as TokioMutex, Notify};
use wal_backup::config::{Config, SyncMode};
use wal_backup::error::Error;
use wal_backup::metrics::noop_metrics;
use wal_backup::replication::manifest::Manifest;
use wal_backup::replication::shipper::FrameShipper;
use wal_backup::storage::BucketStore;
use wal_backup::wal::checksum::wal_checksum_pair;
fn setup_test_db(tmp: &tempfile::TempDir, name: &str) -> std::path::PathBuf {
let db_path = tmp.path().join(format!("{}.db", name));
std::fs::write(&db_path, vec![0u8; 4096]).unwrap();
db_path
}
fn build_shipper(
db_path: &std::path::Path,
store: Arc<dyn BucketStore>,
manifest: Arc<TokioMutex<Manifest>>,
) -> FrameShipper {
let config = Config::new(db_path)
.with_sync_mode(SyncMode::Immediate)
.with_poll_interval(Duration::from_millis(50));
let snapshot_trigger = Arc::new(Notify::new());
let sync_notify = Arc::new(Notify::new());
let wal_notify = Arc::new(Notify::new());
let snapshot_version: Arc<AtomicU64> = AtomicU64::new(0).into();
let force_snapshot: Arc<AtomicBool> = AtomicBool::new(false).into();
let shipped_frames: Arc<AtomicU32> = AtomicU32::new(0).into();
FrameShipper::new(
config,
store,
manifest,
snapshot_trigger,
sync_notify,
wal_notify,
snapshot_version,
force_snapshot,
shipped_frames,
noop_metrics(),
)
}
fn build_shipper_with_config(
config: Config,
store: Arc<dyn BucketStore>,
manifest: Arc<TokioMutex<Manifest>>,
) -> FrameShipper {
let snapshot_trigger = Arc::new(Notify::new());
let sync_notify = Arc::new(Notify::new());
let wal_notify = Arc::new(Notify::new());
let snapshot_version: Arc<AtomicU64> = AtomicU64::new(0).into();
let force_snapshot: Arc<AtomicBool> = AtomicBool::new(false).into();
let shipped_frames: Arc<AtomicU32> = AtomicU32::new(0).into();
FrameShipper::new(
config,
store,
manifest,
snapshot_trigger,
sync_notify,
wal_notify,
snapshot_version,
force_snapshot,
shipped_frames,
noop_metrics(),
)
}
fn create_valid_wal_with_frames(
page_size: u32,
num_frames: u32,
salt_1: u32,
salt_2: u32,
) -> Vec<u8> {
let magic: u32 = 0x377f0682;
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 mut buf = Vec::with_capacity(32 + (num_frames as usize) * (24 + page_size as usize));
buf.extend_from_slice(&magic.to_be_bytes());
buf.extend_from_slice(&file_format.to_be_bytes());
buf.extend_from_slice(&page_size.to_be_bytes());
buf.extend_from_slice(&checkpoint_seq.to_be_bytes());
buf.extend_from_slice(&salt_1.to_be_bytes());
buf.extend_from_slice(&salt_2.to_be_bytes());
buf.extend_from_slice(&ck1.to_be_bytes());
buf.extend_from_slice(&ck2.to_be_bytes());
let mut prev_ck1 = ck1;
let mut prev_ck2 = ck2;
for i in 0..num_frames {
let page_number: u32 = i + 1;
let db_size_after: u32 = if i == num_frames - 1 { 1 } else { 0 };
let frame_data = vec![0xAAu8; 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_data);
let (fc1, fc2) = wal_checksum_pair(prev_ck1, prev_ck2, &checksum_input, false);
buf.extend_from_slice(&page_number.to_be_bytes());
buf.extend_from_slice(&db_size_after.to_be_bytes());
buf.extend_from_slice(&salt_1.to_be_bytes());
buf.extend_from_slice(&salt_2.to_be_bytes());
buf.extend_from_slice(&fc1.to_be_bytes());
buf.extend_from_slice(&fc2.to_be_bytes());
buf.extend_from_slice(&frame_data);
prev_ck1 = fc1;
prev_ck2 = fc2;
}
buf
}
fn create_valid_wal_header_only(page_size: u32, salt_1: u32, salt_2: u32) -> Vec<u8> {
create_valid_wal_with_frames(page_size, 0, salt_1, salt_2)
}
#[test]
fn test_shipper_new_creates_shipper() {
let tmp = tempfile::tempdir().unwrap();
let db_path = setup_test_db(&tmp, "shipper_new");
let store = InMemoryStore::arc();
let manifest = Arc::new(TokioMutex::new(Manifest::new(0, 0, 4096)));
let shipper = build_shipper(&db_path, store, manifest.clone());
let last_sync = shipper.last_sync();
let _guard = last_sync.blocking_lock();
}
#[test]
fn test_shipper_sync_notify_returns_notify() {
let tmp = tempfile::tempdir().unwrap();
let db_path = setup_test_db(&tmp, "shipper_notify");
let store = InMemoryStore::arc();
let manifest = Arc::new(TokioMutex::new(Manifest::new(0, 0, 4096)));
let shipper = build_shipper(&db_path, store, manifest.clone());
let sync_notify = shipper.sync_notify();
drop(sync_notify);
}
#[test]
fn test_shipper_public_api_accessible() {
let tmp = tempfile::tempdir().unwrap();
let db_path = setup_test_db(&tmp, "public_api");
let store = InMemoryStore::arc();
let manifest = Arc::new(TokioMutex::new(Manifest::new(0x1111, 0x2222, 4096)));
let shipper = build_shipper(&db_path, store, manifest.clone());
let _ = shipper.last_sync();
let _ = shipper.sync_notify();
}
#[test]
fn test_shipper_no_panic_on_drop() {
let tmp = tempfile::tempdir().unwrap();
let db_path = setup_test_db(&tmp, "drop_test");
let store = InMemoryStore::arc();
let manifest = Arc::new(TokioMutex::new(Manifest::new(0, 0, 4096)));
let shipper = build_shipper(&db_path, store, manifest.clone());
drop(shipper);
}
#[tokio::test]
async fn test_sync_once_no_wal_returns_ok_false() {
let tmp = tempfile::tempdir().unwrap();
let db_path = setup_test_db(&tmp, "no_wal");
let store = InMemoryStore::arc();
let manifest = Arc::new(TokioMutex::new(Manifest::new(0, 0, 4096)));
let shipper = build_shipper(&db_path, store, manifest.clone());
let result = shipper.sync_once().await;
assert!(result.is_ok());
assert!(!result.unwrap());
}
#[tokio::test]
async fn test_sync_once_empty_wal_returns_ok_false() {
let tmp = tempfile::tempdir().unwrap();
let db_path = setup_test_db(&tmp, "empty_wal");
let wal_path = db_path.with_extension("db-wal");
let wal_data = create_valid_wal_header_only(4096, 0xAAAA, 0xBBBB);
std::fs::write(&wal_path, &wal_data).unwrap();
let store = InMemoryStore::arc();
let manifest = Arc::new(TokioMutex::new(Manifest::new(0xAAAA, 0xBBBB, 4096)));
let shipper = build_shipper(&db_path, store, manifest.clone());
let result = shipper.sync_once().await;
assert!(result.is_ok());
assert!(!result.unwrap(), "0 frames → should return false");
let m = manifest.lock().await;
assert_eq!(m.shipped_frames, 0);
}
#[tokio::test]
async fn test_sync_once_corrupt_wal_returns_err() {
let tmp = tempfile::tempdir().unwrap();
let db_path = setup_test_db(&tmp, "corrupt_wal");
let wal_path = db_path.with_extension("db-wal");
let mut corrupt = create_valid_wal_header_only(4096, 0xAAAA, 0xBBBB);
corrupt[0] = 0xDE;
corrupt[1] = 0xAD;
std::fs::write(&wal_path, &corrupt).unwrap();
let store = InMemoryStore::arc();
let manifest = Arc::new(TokioMutex::new(Manifest::new(0xAAAA, 0xBBBB, 4096)));
let shipper = build_shipper(&db_path, store, manifest.clone());
let result = shipper.sync_once().await;
assert!(result.is_err(), "corrupt WAL (bad magic) should return Err");
}
#[tokio::test]
async fn test_sync_once_ships_frames_and_updates_manifest() {
let tmp = tempfile::tempdir().unwrap();
let db_path = setup_test_db(&tmp, "ship_frames");
let salt_1: u32 = 0xDEAD;
let salt_2: u32 = 0xBEEF;
let wal_path = db_path.with_extension("db-wal");
let wal_data = create_valid_wal_with_frames(4096, 3, salt_1, salt_2);
std::fs::write(&wal_path, &wal_data).unwrap();
let store = InMemoryStore::arc();
let manifest = Arc::new(TokioMutex::new(Manifest::new(salt_1, salt_2, 4096)));
let shipper = build_shipper(&db_path, store.clone(), manifest.clone());
let result = shipper.sync_once().await;
assert!(result.is_ok());
assert!(result.unwrap(), "3 frames should ship successfully");
let m = manifest.lock().await;
assert_eq!(
m.shipped_frames, 3,
"shipped_frames should be 3 after shipping 3 frames"
);
assert!(
m.generation > 0,
"generation should increment after shipping"
);
}
#[tokio::test]
async fn test_sync_once_max_frames_per_segment_truncates() {
let tmp = tempfile::tempdir().unwrap();
let db_path = setup_test_db(&tmp, "max_frames");
let salt_1: u32 = 0x1111;
let salt_2: u32 = 0x2222;
let wal_path = db_path.with_extension("db-wal");
let wal_data = create_valid_wal_with_frames(4096, 10, salt_1, salt_2);
std::fs::write(&wal_path, &wal_data).unwrap();
let store = InMemoryStore::arc();
let manifest = Arc::new(TokioMutex::new(Manifest::new(salt_1, salt_2, 4096)));
let config = Config::new(&db_path)
.with_sync_mode(SyncMode::Immediate)
.with_poll_interval(Duration::from_millis(50))
.with_max_frames_per_segment(3);
let shipper = build_shipper_with_config(config, store, manifest.clone());
let result = shipper.sync_once().await;
assert!(result.is_ok());
assert!(result.unwrap(), "should ship at least some frames");
let m = manifest.lock().await;
assert_eq!(
m.shipped_frames, 3,
"max_frames_per_segment=3 should limit to 3 frames out of 10"
);
}
#[tokio::test]
async fn test_sync_once_manifest_conflict_returns_err() {
let tmp = tempfile::tempdir().unwrap();
let db_path = setup_test_db(&tmp, "conflict");
let salt_1: u32 = 0xAAAA;
let salt_2: u32 = 0xBBBB;
let wal_path = db_path.with_extension("db-wal");
let wal_data = create_valid_wal_with_frames(4096, 1, salt_1, salt_2);
std::fs::write(&wal_path, &wal_data).unwrap();
let store = InMemoryStore::arc();
let mut remote_manifest = Manifest::new(salt_1, salt_2, 4096);
remote_manifest.generation = 100;
remote_manifest.update_shipped_frames(1);
let remote_data = remote_manifest.serialize().unwrap();
store
.put("manifest.json", remote_data.into())
.await
.unwrap();
let mut local_manifest = Manifest::new(salt_1, salt_2, 4096);
local_manifest.generation = 1;
let manifest = Arc::new(TokioMutex::new(local_manifest));
let shipper = build_shipper(&db_path, store, manifest.clone());
let result = shipper.sync_once().await;
assert!(result.is_err());
let err = result.unwrap_err();
assert!(
matches!(err, Error::ManifestConflict { .. }),
"remote ahead should cause ManifestConflict, got: {err}"
);
}
#[tokio::test]
async fn test_sync_once_fresh_manifest_adopts_wal_salts() {
let tmp = tempfile::tempdir().unwrap();
let db_path = setup_test_db(&tmp, "fresh_salt");
let salt_1: u32 = 0xCCCC;
let salt_2: u32 = 0xDDDD;
let wal_path = db_path.with_extension("db-wal");
let wal_data = create_valid_wal_with_frames(4096, 1, salt_1, salt_2);
std::fs::write(&wal_path, &wal_data).unwrap();
let store = InMemoryStore::arc();
let manifest = Arc::new(TokioMutex::new(Manifest::new(0, 0, 4096)));
let shipper = build_shipper(&db_path, store, manifest.clone());
let result = shipper.sync_once().await;
assert!(result.is_ok());
let m = manifest.lock().await;
assert_eq!(
m.current_salt_1, salt_1,
"fresh manifest should adopt WAL salt_1"
);
assert_eq!(
m.current_salt_2, salt_2,
"fresh manifest should adopt WAL salt_2"
);
}
#[tokio::test]
async fn test_sync_once_salt_change_triggers_snapshot() {
let tmp = tempfile::tempdir().unwrap();
let db_path = setup_test_db(&tmp, "salt_change");
let old_salt_1: u32 = 0x1111;
let old_salt_2: u32 = 0x2222;
let new_salt_1: u32 = 0x3333;
let new_salt_2: u32 = 0x4444;
let wal_path = db_path.with_extension("db-wal");
let wal_data = create_valid_wal_with_frames(4096, 1, new_salt_1, new_salt_2);
std::fs::write(&wal_path, &wal_data).unwrap();
let store = InMemoryStore::arc();
let mut m = Manifest::new(old_salt_1, old_salt_2, 4096);
m.generation = 5;
let manifest = Arc::new(TokioMutex::new(m));
let config = Config::new(&db_path)
.with_sync_mode(SyncMode::Immediate)
.with_poll_interval(Duration::from_millis(50));
let snapshot_trigger = Arc::new(Notify::new());
let sync_notify = Arc::new(Notify::new());
let wal_notify = Arc::new(Notify::new());
let snapshot_version: Arc<AtomicU64> = AtomicU64::new(0).into();
let force_snapshot: Arc<AtomicBool> = AtomicBool::new(false).into();
let shipped_frames: Arc<AtomicU32> = AtomicU32::new(0).into();
let force_ref = force_snapshot.clone();
let version_ref = snapshot_version.clone();
let shipper = FrameShipper::new(
config,
store,
manifest.clone(),
snapshot_trigger,
sync_notify,
wal_notify,
snapshot_version,
force_snapshot,
shipped_frames,
noop_metrics(),
);
let handle = tokio::spawn(async move { shipper.sync_once().await });
tokio::time::sleep(Duration::from_millis(200)).await;
assert!(
force_ref.load(std::sync::atomic::Ordering::Relaxed),
"force_snapshot should be set to true on salt change"
);
version_ref.fetch_add(1, std::sync::atomic::Ordering::Release);
let result = handle.await.unwrap();
assert!(result.is_ok());
assert!(
!result.unwrap(),
"salt change should defer shipping, returning false"
);
}
#[tokio::test]
async fn test_run_exits_on_manifest_conflict() {
let tmp = tempfile::tempdir().unwrap();
let db_path = setup_test_db(&tmp, "run_conflict");
let salt_1: u32 = 0xAAAA;
let salt_2: u32 = 0xBBBB;
let wal_path = db_path.with_extension("db-wal");
let wal_data = create_valid_wal_with_frames(4096, 1, salt_1, salt_2);
std::fs::write(&wal_path, &wal_data).unwrap();
let store = InMemoryStore::arc();
let mut remote_manifest = Manifest::new(salt_1, salt_2, 4096);
remote_manifest.generation = 100;
remote_manifest.update_shipped_frames(1);
let remote_data = remote_manifest.serialize().unwrap();
store
.put("manifest.json", remote_data.into())
.await
.unwrap();
let mut local_manifest = Manifest::new(salt_1, salt_2, 4096);
local_manifest.generation = 1;
let manifest = Arc::new(TokioMutex::new(local_manifest));
let shipper = build_shipper(&db_path, store, manifest.clone());
let start = tokio::time::Instant::now();
shipper.run().await;
let elapsed = start.elapsed();
assert!(
elapsed < Duration::from_secs(5),
"run() should exit quickly on ManifestConflict, took {:?}",
elapsed
);
}
#[tokio::test]
async fn test_sync_once_local_ahead_proceeds() {
let tmp = tempfile::tempdir().unwrap();
let db_path = setup_test_db(&tmp, "local_ahead");
let salt_1: u32 = 0xAAAA;
let salt_2: u32 = 0xBBBB;
let wal_path = db_path.with_extension("db-wal");
let wal_data = create_valid_wal_with_frames(4096, 1, salt_1, salt_2);
std::fs::write(&wal_path, &wal_data).unwrap();
let store = InMemoryStore::arc();
let mut remote_manifest = Manifest::new(salt_1, salt_2, 4096);
remote_manifest.generation = 1;
remote_manifest.last_updated = "2024-01-01T00:00:00Z".to_string();
let remote_data = remote_manifest.serialize().unwrap();
store
.put("manifest.json", remote_data.into())
.await
.unwrap();
let mut local_manifest = Manifest::new(salt_1, salt_2, 4096);
local_manifest.generation = 10;
let manifest = Arc::new(TokioMutex::new(local_manifest));
let shipper = build_shipper(&db_path, store.clone(), manifest.clone());
let result = shipper.sync_once().await;
assert!(
result.is_ok(),
"LocalAhead conflict should not cause error, got: {:?}",
result
);
assert!(
result.unwrap(),
"should still ship frames when local is ahead"
);
let m = manifest.lock().await;
assert!(
m.generation > 10,
"generation should have incremented past 10"
);
}
#[tokio::test]
async fn test_sync_once_no_new_frames_returns_false() {
let tmp = tempfile::tempdir().unwrap();
let db_path = setup_test_db(&tmp, "no_new");
let salt_1: u32 = 0xAAAA;
let salt_2: u32 = 0xBBBB;
let wal_path = db_path.with_extension("db-wal");
let wal_data = create_valid_wal_with_frames(4096, 2, salt_1, salt_2);
std::fs::write(&wal_path, &wal_data).unwrap();
let store = InMemoryStore::arc();
let mut m = Manifest::new(salt_1, salt_2, 4096);
m.shipped_frames = 2;
let manifest = Arc::new(TokioMutex::new(m));
let shipper = build_shipper(&db_path, store, manifest.clone());
let result = shipper.sync_once().await;
assert!(result.is_ok());
assert!(!result.unwrap(), "no new frames should return false");
}
#[tokio::test]
async fn test_sync_once_checksum_error_returns_err() {
let tmp = tempfile::tempdir().unwrap();
let db_path = setup_test_db(&tmp, "checksum_err");
let salt_1: u32 = 0xAAAA;
let salt_2: u32 = 0xBBBB;
let wal_path = db_path.with_extension("db-wal");
let magic: u32 = 0x377f0682;
let file_format: u32 = 3007000;
let page_size: u32 = 4096;
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 mut buf = Vec::new();
buf.extend_from_slice(&magic.to_be_bytes());
buf.extend_from_slice(&file_format.to_be_bytes());
buf.extend_from_slice(&page_size.to_be_bytes());
buf.extend_from_slice(&checkpoint_seq.to_be_bytes());
buf.extend_from_slice(&salt_1.to_be_bytes());
buf.extend_from_slice(&salt_2.to_be_bytes());
buf.extend_from_slice(&ck1.to_be_bytes());
buf.extend_from_slice(&ck2.to_be_bytes());
let page_number: u32 = 1;
let db_size_after: u32 = 1;
let frame_data = vec![0xAAu8; 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_data);
let (mut fc1, fc2) = wal_checksum_pair(ck1, ck2, &checksum_input, false);
fc1 = !fc1;
buf.extend_from_slice(&page_number.to_be_bytes());
buf.extend_from_slice(&db_size_after.to_be_bytes());
buf.extend_from_slice(&salt_1.to_be_bytes());
buf.extend_from_slice(&salt_2.to_be_bytes());
buf.extend_from_slice(&fc1.to_be_bytes());
buf.extend_from_slice(&fc2.to_be_bytes());
buf.extend_from_slice(&frame_data);
std::fs::write(&wal_path, &buf).unwrap();
let store = InMemoryStore::arc();
let manifest = Arc::new(TokioMutex::new(Manifest::new(salt_1, salt_2, 4096)));
let shipper = build_shipper(&db_path, store, manifest);
let result = shipper.sync_once().await;
assert!(result.is_err(), "WAL checksum error should return Err");
assert!(
matches!(result.unwrap_err(), Error::WalChecksum { .. }),
"should be WalChecksum error"
);
}
#[tokio::test]
async fn test_sync_once_wal_truncated_triggers_snapshot_wait() {
let tmp = tempfile::tempdir().unwrap();
let db_path = setup_test_db(&tmp, "wal_truncated");
let old_salt_1: u32 = 0x1111;
let old_salt_2: u32 = 0x2222;
let new_salt_1: u32 = 0x3333;
let new_salt_2: u32 = 0x4444;
let wal_path = db_path.with_extension("db-wal");
let wal_data = create_valid_wal_with_frames(4096, 1, new_salt_1, new_salt_2);
std::fs::write(&wal_path, &wal_data).unwrap();
let store = InMemoryStore::arc();
let mut m = Manifest::new(old_salt_1, old_salt_2, 4096);
m.shipped_frames = 5;
let manifest = Arc::new(TokioMutex::new(m));
let config = Config::new(&db_path)
.with_sync_mode(SyncMode::Immediate)
.with_poll_interval(Duration::from_millis(50));
let snapshot_trigger = Arc::new(Notify::new());
let sync_notify = Arc::new(Notify::new());
let wal_notify = Arc::new(Notify::new());
let snapshot_version: Arc<AtomicU64> = AtomicU64::new(0).into();
let force_snapshot: Arc<AtomicBool> = AtomicBool::new(false).into();
let shipped_frames: Arc<AtomicU32> = AtomicU32::new(5).into();
let force_ref = force_snapshot.clone();
let version_ref = snapshot_version.clone();
let shipper = FrameShipper::new(
config,
store,
manifest.clone(),
snapshot_trigger,
sync_notify,
wal_notify,
snapshot_version,
force_snapshot,
shipped_frames,
noop_metrics(),
);
let handle = tokio::spawn(async move { shipper.sync_once().await });
tokio::time::sleep(Duration::from_millis(200)).await;
assert!(
force_ref.load(std::sync::atomic::Ordering::Relaxed),
"force_snapshot should be set to true on WAL truncation"
);
version_ref.fetch_add(1, std::sync::atomic::Ordering::Release);
let result = handle.await.unwrap();
assert!(result.is_ok());
assert!(
!result.unwrap(),
"WAL truncation should defer shipping, returning false"
);
}
#[tokio::test]
async fn test_shipper_rollback_manifest_on_upload_failure() {
let tmp = tempfile::tempdir().unwrap();
let db_path = tmp.path().join("rollback.db");
let wal_path = db_path.with_extension("db-wal");
let salt_1: u32 = 0xCAFE;
let salt_2: u32 = 0xBEEF;
let page_size: u32 = 4096;
std::fs::write(&db_path, vec![0u8; page_size as usize]).unwrap();
let wal_data = create_valid_wal_with_frames(page_size, 2, salt_1, salt_2);
std::fs::write(&wal_path, &wal_data).unwrap();
let store = common::FailOnManifestStore::arc();
let manifest = Arc::new(TokioMutex::new(Manifest::new(salt_1, salt_2, page_size)));
let config = Config::new(&db_path)
.with_sync_mode(SyncMode::Immediate)
.with_poll_interval(Duration::from_millis(50));
let snapshot_trigger = Arc::new(Notify::new());
let sync_notify = Arc::new(Notify::new());
let wal_notify = Arc::new(Notify::new());
let snapshot_version: Arc<AtomicU64> = AtomicU64::new(0).into();
let force_snapshot: Arc<AtomicBool> = AtomicBool::new(false).into();
let shipped_frames: Arc<AtomicU32> = AtomicU32::new(0).into();
let shipper = FrameShipper::new(
config,
store,
manifest.clone(),
snapshot_trigger,
sync_notify,
wal_notify,
snapshot_version,
force_snapshot,
shipped_frames,
noop_metrics(),
);
let original_shipped = manifest.lock().await.shipped_frames;
let result = shipper.sync_once().await;
assert!(
result.is_err(),
"sync_once should fail when manifest write fails, got: {:?}",
result
);
let after_shipped = manifest.lock().await.shipped_frames;
assert_eq!(
after_shipped, original_shipped,
"manifest.shipped_frames should be rolled back on manifest write failure, got {} (expected {})",
after_shipped, original_shipped
);
}
#[tokio::test]
async fn test_shipper_sync_once_handles_missing_wal_gracefully() {
let tmp = tempfile::tempdir().unwrap();
let db_path = tmp.path().join("no_wal.db");
std::fs::write(&db_path, vec![0u8; 4096]).unwrap();
let store = InMemoryStore::arc();
let manifest = Arc::new(TokioMutex::new(Manifest::new(0, 0, 4096)));
let config = Config::new(&db_path)
.with_sync_mode(SyncMode::Immediate)
.with_poll_interval(Duration::from_millis(50));
let shipper = build_shipper_with_config(config, store, manifest);
let result = shipper.sync_once().await;
assert!(
result.is_ok(),
"sync_once should not error when WAL file is missing: {:?}",
result
);
assert!(
!result.unwrap(),
"sync_once should return false when no WAL frames to ship"
);
}
#[tokio::test]
async fn test_gc_deletes_orphaned_segments() {
let tmp = tempfile::tempdir().unwrap();
let db_path = tmp.path().join("test.db");
std::fs::write(&db_path, vec![0u8; 4096]).unwrap();
let store = InMemoryStore::arc();
let manifest = Arc::new(TokioMutex::new(Manifest::new(100, 200, 4096)));
manifest.lock().await.shipped_frames = 50;
let shipper = build_shipper_with_config(Config::new(&db_path), store.clone(), manifest);
store
.put(
"wal/100-200/00000000-00000049.segment",
vec![1u8; 100].into(),
)
.await
.unwrap();
store
.put(
"wal/100-200/00000050-00000099.segment",
vec![2u8; 100].into(),
)
.await
.unwrap();
store
.put(
"wal/100-200/00000100-00000149.segment",
vec![3u8; 100].into(),
)
.await
.unwrap();
let deleted = shipper.gc().await.unwrap();
assert_eq!(deleted, 1, "Should delete 1 orphaned segment");
assert!(store
.get("wal/100-200/00000050-00000099.segment")
.await
.unwrap()
.is_some());
assert!(store
.get("wal/100-200/00000100-00000149.segment")
.await
.unwrap()
.is_some());
}
#[tokio::test]
async fn test_gc_keeps_active_segments() {
let tmp = tempfile::tempdir().unwrap();
let db_path = tmp.path().join("test.db");
std::fs::write(&db_path, vec![0u8; 4096]).unwrap();
let store = InMemoryStore::arc();
let manifest = Arc::new(TokioMutex::new(Manifest::new(100, 200, 4096)));
manifest.lock().await.shipped_frames = 100;
let shipper = build_shipper_with_config(Config::new(&db_path), store.clone(), manifest);
store
.put(
"wal/100-200/00000100-00000199.segment",
vec![1u8; 100].into(),
)
.await
.unwrap();
store
.put(
"wal/100-200/00000200-00000299.segment",
vec![2u8; 100].into(),
)
.await
.unwrap();
let deleted = shipper.gc().await.unwrap();
assert_eq!(deleted, 0, "Should delete 0 active segments");
assert!(store
.get("wal/100-200/00000100-00000199.segment")
.await
.unwrap()
.is_some());
assert!(store
.get("wal/100-200/00000200-00000299.segment")
.await
.unwrap()
.is_some());
}
#[tokio::test]
async fn test_gc_ignores_different_salt_prefix() {
let tmp = tempfile::tempdir().unwrap();
let db_path = tmp.path().join("test.db");
std::fs::write(&db_path, vec![0u8; 4096]).unwrap();
let store = InMemoryStore::arc();
let manifest = Arc::new(TokioMutex::new(Manifest::new(100, 200, 4096)));
manifest.lock().await.shipped_frames = 10;
let shipper = build_shipper_with_config(Config::new(&db_path), store.clone(), manifest);
store
.put(
"wal/300-400/00000000-00000049.segment",
vec![1u8; 100].into(),
)
.await
.unwrap();
let deleted = shipper.gc().await.unwrap();
assert_eq!(deleted, 0, "Should not delete segments with different salt");
assert!(store
.get("wal/300-400/00000000-00000049.segment")
.await
.unwrap()
.is_some());
}
#[tokio::test]
async fn test_gc_empty_when_no_shipped_frames() {
let tmp = tempfile::tempdir().unwrap();
let db_path = tmp.path().join("test.db");
std::fs::write(&db_path, vec![0u8; 4096]).unwrap();
let store = InMemoryStore::arc();
let manifest = Arc::new(TokioMutex::new(Manifest::new(100, 200, 4096)));
manifest.lock().await.shipped_frames = 0;
let shipper = build_shipper_with_config(Config::new(&db_path), store.clone(), manifest);
store
.put(
"wal/100-200/00000000-00000049.segment",
vec![1u8; 100].into(),
)
.await
.unwrap();
let deleted = shipper.gc().await.unwrap();
assert_eq!(deleted, 0, "Should not delete when shipped_frames=0");
assert!(store
.get("wal/100-200/00000000-00000049.segment")
.await
.unwrap()
.is_some());
}
#[tokio::test]
async fn test_wal_size_backpressure_pauses_shipping() {
let tmp = tempfile::tempdir().unwrap();
let db_path = tmp.path().join("test.db");
std::fs::write(&db_path, vec![0u8; 4096]).unwrap();
let store = InMemoryStore::arc();
let manifest = Arc::new(TokioMutex::new(Manifest::new(100, 200, 4096)));
manifest.lock().await.shipped_frames = 0;
let config = Config::new(&db_path)
.with_sync_mode(SyncMode::Immediate)
.with_poll_interval(Duration::from_millis(50))
.with_max_wal_size_bytes(10);
let shipper = build_shipper_with_config(config, store, manifest);
let result = shipper.sync_once().await.unwrap();
assert!(
!result,
"sync_once should return false when WAL exceeds max size"
);
}
#[tokio::test]
async fn test_wal_size_zero_disables_backpressure() {
let tmp = tempfile::tempdir().unwrap();
let db_path = tmp.path().join("test.db");
std::fs::write(&db_path, vec![0u8; 4096]).unwrap();
let store = InMemoryStore::arc();
let manifest = Arc::new(TokioMutex::new(Manifest::new(100, 200, 4096)));
manifest.lock().await.shipped_frames = 0;
let config = Config::new(&db_path)
.with_sync_mode(SyncMode::Immediate)
.with_poll_interval(Duration::from_millis(50))
.with_max_wal_size_bytes(0);
let shipper = build_shipper_with_config(config, store, manifest);
let result = shipper.sync_once().await.unwrap();
assert!(
!result,
"sync_once should return false when no frames to ship (not due to backpressure)"
);
}
#[tokio::test]
async fn test_compact_merges_l0_segments_into_l1() {
let tmp = tempfile::tempdir().unwrap();
let db_path = tmp.path().join("test.db");
std::fs::write(&db_path, vec![0u8; 4096]).unwrap();
let store = InMemoryStore::arc();
let manifest = Arc::new(TokioMutex::new(Manifest::new(100, 200, 4096)));
manifest.lock().await.shipped_frames = 200;
let config = Config::new(&db_path).with_compaction_min_segments(3);
let shipper = build_shipper_with_config(config, store.clone(), manifest.clone());
store
.put(
"wal/100-200/00000000-00000099.segment",
vec![1u8; 100].into(),
)
.await
.unwrap();
store
.put(
"wal/100-200/00000100-00000149.segment",
vec![2u8; 100].into(),
)
.await
.unwrap();
store
.put(
"wal/100-200/00000150-00000199.segment",
vec![3u8; 100].into(),
)
.await
.unwrap();
store
.put(
"wal/100-200/00000200-00000249.segment",
vec![4u8; 100].into(),
)
.await
.unwrap();
store
.put(
"wal/100-200/00000250-00000299.segment",
vec![5u8; 100].into(),
)
.await
.unwrap();
let compacted = shipper.compact().await.unwrap();
assert_eq!(compacted, 5, "Should compact all 5 L0 segments");
assert!(
store
.get("wal/100-200/00000000-00000299.l1")
.await
.unwrap()
.is_some(),
"L1 file should be uploaded"
);
let m = manifest.lock().await;
assert_eq!(m.l1_files.len(), 1, "Manifest should have 1 L1 file");
assert_eq!(m.l1_files[0].start_frame, 0);
assert_eq!(m.l1_files[0].end_frame, 299);
assert_eq!(m.l1_files[0].source_count, 5);
assert_eq!(m.l1_max_frame, Some(299));
}
#[tokio::test]
async fn test_compact_skips_when_fewer_than_min_segments() {
let tmp = tempfile::tempdir().unwrap();
let db_path = tmp.path().join("test.db");
std::fs::write(&db_path, vec![0u8; 4096]).unwrap();
let store = InMemoryStore::arc();
let manifest = Arc::new(TokioMutex::new(Manifest::new(100, 200, 4096)));
manifest.lock().await.shipped_frames = 100;
let config = Config::new(&db_path).with_compaction_min_segments(10);
let shipper = build_shipper_with_config(config, store.clone(), manifest);
store
.put(
"wal/100-200/00000000-00000049.segment",
vec![1u8; 100].into(),
)
.await
.unwrap();
store
.put(
"wal/100-200/00000050-00000099.segment",
vec![2u8; 100].into(),
)
.await
.unwrap();
let compacted = shipper.compact().await.unwrap();
assert_eq!(
compacted, 0,
"Should not compact when fewer than min_segments"
);
let keys = store.list("wal/100-200/").await.unwrap();
assert!(
keys.iter().all(|k| !k.ends_with(".l1")),
"No L1 files should exist"
);
}
#[tokio::test]
async fn test_compact_skips_already_covered_segments() {
let tmp = tempfile::tempdir().unwrap();
let db_path = tmp.path().join("test.db");
std::fs::write(&db_path, vec![0u8; 4096]).unwrap();
let store = InMemoryStore::arc();
let manifest = Arc::new(TokioMutex::new(Manifest::new(100, 200, 4096)));
manifest.lock().await.shipped_frames = 300;
manifest.lock().await.l1_max_frame = Some(199); manifest
.lock()
.await
.l1_files
.push(wal_backup::replication::manifest::L1File {
key: "wal/100-200/00000000-00000199.l1".to_string(),
start_frame: 0,
end_frame: 199,
source_count: 4,
checksum: None,
});
let config = Config::new(&db_path).with_compaction_min_segments(2);
let shipper = build_shipper_with_config(config, store.clone(), manifest.clone());
store
.put(
"wal/100-200/00000000-00000099.segment",
vec![1u8; 100].into(),
)
.await
.unwrap(); store
.put(
"wal/100-200/00000100-00000199.segment",
vec![2u8; 100].into(),
)
.await
.unwrap(); store
.put(
"wal/100-200/00000200-00000249.segment",
vec![3u8; 100].into(),
)
.await
.unwrap(); store
.put(
"wal/100-200/00000250-00000299.segment",
vec![4u8; 100].into(),
)
.await
.unwrap();
let compacted = shipper.compact().await.unwrap();
assert_eq!(compacted, 2, "Should compact only uncovered segments");
let m = manifest.lock().await;
assert_eq!(m.l1_files.len(), 2, "Should have 2 L1 files (old + new)");
assert_eq!(m.l1_max_frame, Some(299));
}
#[tokio::test]
async fn test_compact_no_segments_returns_zero() {
let tmp = tempfile::tempdir().unwrap();
let db_path = tmp.path().join("test.db");
std::fs::write(&db_path, vec![0u8; 4096]).unwrap();
let store = InMemoryStore::arc();
let manifest = Arc::new(TokioMutex::new(Manifest::new(100, 200, 4096)));
let config = Config::new(&db_path);
let shipper = build_shipper_with_config(config, store, manifest);
let compacted = shipper.compact().await.unwrap();
assert_eq!(compacted, 0, "Should return 0 when no segments exist");
}
#[tokio::test]
async fn test_gc_deletes_compacted_l0_segments() {
let tmp = tempfile::tempdir().unwrap();
let db_path = tmp.path().join("test.db");
std::fs::write(&db_path, vec![0u8; 4096]).unwrap();
let store = InMemoryStore::arc();
let manifest = Arc::new(TokioMutex::new(Manifest::new(100, 200, 4096)));
manifest.lock().await.shipped_frames = 200; manifest.lock().await.l1_max_frame = Some(199);
let shipper = build_shipper_with_config(Config::new(&db_path), store.clone(), manifest);
store
.put(
"wal/100-200/00000000-00000099.segment",
vec![1u8; 100].into(),
)
.await
.unwrap(); store
.put(
"wal/100-200/00000100-00000199.segment",
vec![2u8; 100].into(),
)
.await
.unwrap(); store
.put(
"wal/100-200/00000200-00000299.segment",
vec![3u8; 100].into(),
)
.await
.unwrap();
let deleted = shipper.gc().await.unwrap();
assert_eq!(deleted, 2, "Should delete 2 compacted L0 segments");
assert!(store
.get("wal/100-200/00000200-00000299.segment")
.await
.unwrap()
.is_some());
assert!(store
.get("wal/100-200/00000000-00000099.segment")
.await
.unwrap()
.is_none());
assert!(store
.get("wal/100-200/00000100-00000199.segment")
.await
.unwrap()
.is_none());
}
#[tokio::test]
async fn test_snapshot_clears_l1_files() {
let mut manifest = Manifest::new(100, 200, 4096);
manifest.shipped_frames = 100;
manifest
.l1_files
.push(wal_backup::replication::manifest::L1File {
key: "wal/100-200/00000000-00000099.l1".to_string(),
start_frame: 0,
end_frame: 99,
source_count: 3,
checksum: None,
});
manifest.l1_max_frame = Some(99);
manifest.update_snapshot(
"snapshots/test.db".to_string(),
"checksum".to_string(),
100,
200,
4096,
4096,
);
assert!(
manifest.l1_files.is_empty(),
"L1 files should be cleared after snapshot"
);
assert_eq!(
manifest.l1_max_frame, None,
"l1_max_frame should be None after snapshot"
);
assert_eq!(
manifest.shipped_frames, 0,
"shipped_frames should be 0 after snapshot"
);
}