use bytes::Bytes;
use std::sync::Arc;
use tokio::sync::Mutex;
use crate::config::Config;
use crate::error::{Error, Result};
use crate::metrics::Metrics;
use crate::replication::manifest::{Manifest, MANIFEST_KEY};
use crate::storage::BucketStore;
use crate::wal::{WalFile, WalHeader};
pub struct RestoreEngine {
config: Config,
bucket: Arc<dyn BucketStore>,
metrics: Option<Arc<dyn Metrics>>,
}
fn generation_path(db_path: &std::path::Path) -> std::path::PathBuf {
db_path.with_extension("generation")
}
pub(crate) async fn write_generation(
db_path: &std::path::Path,
generation: u64,
) -> crate::error::Result<()> {
let path = generation_path(db_path);
tokio::fs::write(&path, generation.to_string())
.await
.map_err(|e| crate::error::Error::Other(format!("failed to write generation file: {e}")))
}
async fn read_generation(db_path: &std::path::Path) -> Result<Option<u64>> {
let path = generation_path(db_path);
match tokio::fs::read_to_string(&path).await {
Ok(content) => {
match content.trim().parse::<u64>() {
Ok(gen) => Ok(Some(gen)),
Err(e) => {
tracing::warn!(
"Corrupted generation file at {} — cannot parse '{}': {}. \
Treating as missing generation.",
path.display(), content.trim(), e
);
Ok(None)
}
}
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
Ok(None)
}
Err(e) => {
tracing::warn!(
"Cannot read generation file at {}: {}",
path.display(), e
);
Ok(None)
}
}
}
impl RestoreEngine {
pub fn new(config: Config, bucket: Arc<dyn BucketStore>) -> Self {
RestoreEngine {
config,
bucket,
metrics: None,
}
}
pub fn with_metrics(self, metrics: Arc<dyn Metrics>) -> Self {
Self {
metrics: Some(metrics),
..self
}
}
async fn detect_local_salts(&self) -> (u32, u32, u32) {
let db_exists = tokio::fs::try_exists(self.config.db_path())
.await
.unwrap_or(false);
let wal_exists = tokio::fs::try_exists(self.config.wal_path())
.await
.unwrap_or(false);
if !db_exists && !wal_exists {
return (0, 0, 4096);
}
if wal_exists {
let wal_path = self.config.wal_path().clone();
let wal_result = tokio::task::spawn_blocking(move || WalFile::open(&wal_path))
.await
.ok()
.and_then(|r| r.ok());
if let Some(w) = wal_result {
let ps = if db_exists {
read_page_size_from_db_async(self.config.db_path())
.await
.unwrap_or_else(|_| {
tracing::warn!("failed to read page size from DB, using WAL page size");
w.page_size()
})
} else {
w.page_size()
};
return (w.header().salt_1, w.header().salt_2, ps);
}
}
if db_exists {
let db_page_size = read_page_size_from_db_async(self.config.db_path())
.await
.unwrap_or_else(|e| {
tracing::warn!("failed to read page size from DB: {e}");
0
});
let ps = if db_page_size > 0 { db_page_size } else { 4096 };
tracing::warn!("WAL file not found, using zero salts with page size {ps}");
return (0, 0, ps);
}
(0, 0, 4096)
}
pub async fn restore(&self) -> Result<Arc<Mutex<Manifest>>> {
let start = std::time::Instant::now();
let manifest_with_etag = self.bucket.get_with_etag(MANIFEST_KEY).await?;
let (mut manifest, from_bucket) = match manifest_with_etag {
Some((data, etag)) => {
let mut m = Manifest::deserialize(&data)?;
m.etag = Some(etag);
(m, true)
}
None => {
let (salt_1, salt_2, page_size) = self.detect_local_salts().await;
(Manifest::new(salt_1, salt_2, page_size), false)
}
};
if from_bucket {
let local_exists = match tokio::fs::try_exists(self.config.db_path()).await {
Ok(exists) => exists,
Err(e) => {
tracing::warn!("failed to check DB existence for restore: {e}");
false
}
};
let local_newer = local_exists && self.local_is_newer_than_manifest(&manifest).await;
let local_newer = if local_newer && (manifest.snapshot.is_some() || manifest.shipped_frames > 0) {
match self.is_db_empty().await {
Ok(true) => {
tracing::warn!(
"Local DB is empty but generation file says it was synced (gen {}). \
Restoring from bucket instead — the generation file may be stale.",
manifest.generation
);
false
}
Ok(false) => true,
Err(e) => {
tracing::warn!(
"Failed to check if local DB is empty: {e} — assuming not empty"
);
true
}
}
} else {
local_newer
};
match self.config.restore_behavior() {
crate::config::RestoreBehavior::UploadLocalIfNewer => {
if local_newer {
self.upload_local_as_snapshot(&mut manifest).await?;
} else {
self.download_and_reconstruct(&manifest).await?;
}
}
crate::config::RestoreBehavior::AlwaysRestoreFromBucket
| crate::config::RestoreBehavior::Recoverable => {
self.download_and_reconstruct(&manifest).await?;
}
crate::config::RestoreBehavior::ErrorIfConflict => {
if local_exists && local_newer {
return Err(Error::Restore(
"Local database is newer than bucket manifest. \
Set restore_behavior to UploadLocalIfNewer or AlwaysRestoreFromBucket \
to resolve."
.to_string(),
));
}
self.download_and_reconstruct(&manifest).await?;
}
}
}
if from_bucket {
let elapsed = start.elapsed();
if let Some(ref metrics) = self.metrics {
metrics.restore_completed(elapsed.as_millis() as u64);
}
write_generation(self.config.db_path(), manifest.generation).await?;
}
Ok(Arc::new(Mutex::new(manifest)))
}
pub async fn local_is_newer_than_manifest(&self, manifest: &Manifest) -> bool {
if manifest.generation == 0 && manifest.snapshot.is_none() {
return true;
}
let local_exists = match tokio::fs::try_exists(self.config.db_path()).await {
Ok(exists) => exists,
Err(e) => {
tracing::warn!("failed to check DB existence for local_is_newer: {e}");
false
}
};
if !local_exists {
return false;
}
let local_gen = read_generation(self.config.db_path()).await.unwrap_or(None);
match local_gen {
Some(gen) => gen > manifest.generation,
None => {
let has_snapshot = manifest.snapshot.is_some();
if has_snapshot {
tracing::warn!(
"No generation file found but bucket has snapshot (gen {}) — assuming bucket is authoritative. \
Use `--force-takeover` or delete bucket data to upload local instead.",
manifest.generation
);
false
} else {
tracing::debug!(
"No generation file and no snapshot — assuming local DB is newer"
);
true
}
}
}
}
pub async fn is_db_empty(&self) -> Result<bool> {
let db_path = self.config.db_path().to_path_buf();
let is_empty = tokio::task::spawn_blocking(move || {
let conn = rusqlite::Connection::open_with_flags(
&db_path,
rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
)?;
let count: i64 = conn.query_row(
"SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'",
[],
|row| row.get(0),
)?;
Ok::<bool, crate::error::Error>(count == 0)
})
.await
.map_err(|e| crate::error::Error::Other(format!("is_db_empty join: {e}")))??;
Ok(is_empty)
}
async fn upload_local_as_snapshot(&self, manifest: &mut Manifest) -> Result<()> {
let snapshot_path = format!(
"snapshots/{}.db",
chrono::Utc::now().format("%Y%m%d-%H%M%S%.6f")
);
let (local_bytes, page_size, salt_1, salt_2) = {
let db_path = self.config.db_path().clone();
let wal_path = self.config.wal_path().clone();
tokio::task::spawn_blocking(move || {
let (s1, s2) = match WalFile::open(&wal_path) {
Ok(w) => (w.header().salt_1, w.header().salt_2),
Err(_) => {
tracing::warn!(
"Cannot read WAL file for snapshot upload — using zero salts. \
The WAL may have been truncated by a concurrent checkpoint."
);
(0u32, 0u32)
}
};
let conn = rusqlite::Connection::open(&db_path)?;
conn.execute_batch("PRAGMA journal_mode = WAL")?;
conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)")?;
drop(conn);
let bytes = std::fs::read(&db_path)?;
let ps = read_page_size_from_db(&bytes)?;
Ok::<_, crate::error::Error>((bytes, ps, s1, s2))
})
.await??
};
let checksum = crate::util::compute_sha256(&local_bytes);
self.bucket
.put(&snapshot_path, Bytes::from(local_bytes))
.await?;
let db_size = tokio::fs::metadata(self.config.db_path())
.await
.map(|m| m.len())
.unwrap_or(0);
manifest.update_snapshot(snapshot_path, checksum, salt_1, salt_2, page_size, db_size);
let manifest_bytes = manifest.serialize()?;
match manifest.etag.clone() {
Some(etag) => {
self.bucket
.put_if_match(MANIFEST_KEY, Bytes::from(manifest_bytes), &etag)
.await?;
}
None => {
self.bucket
.put_if_not_exists(MANIFEST_KEY, Bytes::from(manifest_bytes))
.await?;
}
}
write_generation(self.config.db_path(), manifest.generation).await?;
Ok(())
}
async fn download_and_reconstruct(&self, manifest: &Manifest) -> Result<()> {
let db_path = self.config.db_path();
let marker_path = db_path.with_extension("db.restore-in-progress");
if tokio::fs::try_exists(&marker_path).await.unwrap_or(false) {
tracing::warn!(
"Found stale restore marker — previous restore may have crashed mid-rename. \
Cleaning up."
);
let wal_tmp = db_path.with_extension("wal.restore-tmp");
let db_tmp = db_path.with_extension("db.restore-tmp");
tokio::fs::remove_file(&wal_tmp).await.ok();
tokio::fs::remove_file(&db_tmp).await.ok();
tokio::fs::remove_file(&marker_path).await.ok();
}
if let Some(ref snapshot_key) = manifest.snapshot {
let tmp_path = self.config.db_path().with_extension("db.restore-tmp");
let tmp_path_for_cleanup = tmp_path.clone();
let result = self
.download_and_reconstruct_inner(manifest, snapshot_key, &tmp_path)
.await;
if result.is_err() {
tokio::fs::remove_file(&tmp_path_for_cleanup).await.ok();
let wal_tmp = self.config.wal_path().with_extension("wal.restore-tmp");
tokio::fs::remove_file(&wal_tmp).await.ok();
}
result
} else {
Err(Error::Restore(
"No snapshot found in bucket. Cannot restore without a base database.".to_string(),
))
}
}
async fn download_and_reconstruct_inner(
&self,
manifest: &Manifest,
snapshot_key: &str,
tmp_path: &std::path::Path,
) -> Result<()> {
let tmp_path_owned = tmp_path.to_path_buf();
self.bucket.get_file(snapshot_key, &tmp_path_owned).await?;
let (snapshot_page_size, checksum) = tokio::task::spawn_blocking({
let tmp_path = tmp_path_owned.clone();
move || {
let mut file = std::fs::File::open(&tmp_path)?;
let mut header = [0u8; 20];
std::io::Read::read_exact(&mut file, &mut header)?;
let page_size = read_page_size_from_db(&header)?;
drop(file);
let checksum = crate::util::compute_sha256_file(&tmp_path)?;
Ok::<_, crate::error::Error>((page_size, checksum))
}
})
.await??;
if let Some(ref expected_checksum) = manifest.snapshot_checksum {
if &checksum != expected_checksum {
let detail = format!(
"Snapshot checksum mismatch: expected {}, got {}",
expected_checksum, checksum
);
match self.config.restore_behavior {
crate::config::RestoreBehavior::Recoverable => {
tracing::warn!("{} — proceeding anyway (Recoverable mode)", detail);
if let Some(m) = self.metrics.as_ref() {
m.checksum_warning(&detail)
}
}
_ => {
return Err(Error::Restore(detail));
}
}
}
}
let page_size = snapshot_page_size;
let wal_tmp_path = self.config.wal_path().with_extension("wal.restore-tmp");
if manifest.shipped_frames > 0 {
self.download_wal_segments_to(manifest, page_size, &wal_tmp_path)
.await?;
} else {
use tokio::io::AsyncWriteExt;
let mut f = tokio::fs::File::create(&wal_tmp_path).await?;
f.flush().await?;
f.sync_all().await?;
}
let db_path = self.config.db_path();
let wal_path = self.config.wal_path();
let marker_path = db_path.with_extension("db.restore-in-progress");
let marker_body = format!("wal:{}", wal_tmp_path.display());
tokio::fs::write(&marker_path, &marker_body).await?;
tokio::fs::rename(&tmp_path_owned, db_path).await?;
tokio::fs::rename(&wal_tmp_path, wal_path).await?;
tokio::fs::remove_file(&marker_path).await?;
Ok(())
}
async fn download_wal_segments_to(
&self,
manifest: &Manifest,
page_size: u32,
tmp_wal_path: &std::path::Path,
) -> Result<()> {
let prefix = manifest.segment_prefix();
let all_keys = self.bucket.list(&prefix).await?;
let mut l1_keys: Vec<String> = all_keys
.iter()
.filter(|k| k.ends_with(".l1"))
.cloned()
.collect();
let mut l0_keys: Vec<String> = all_keys
.iter()
.filter(|k| k.ends_with(".segment"))
.cloned()
.collect();
l1_keys.sort();
l0_keys.sort();
let l1_max = manifest.l1_max_frame_value();
let uncovered_l0_keys: Vec<String> = l0_keys
.into_iter()
.filter(|k| {
match extract_start_frame_from_key(k) {
Some(start) => start >= l1_max,
None => true, }
})
.collect();
if l1_keys.is_empty() && uncovered_l0_keys.is_empty() {
let wal_header =
WalHeader::synthetic(page_size, manifest.current_salt_1, manifest.current_salt_2);
let wal_header_data = serialize_header(&wal_header);
use tokio::io::AsyncWriteExt;
let mut file = tokio::fs::File::create(tmp_wal_path).await?;
file.write_all(&wal_header_data).await?;
file.flush().await?;
file.sync_all().await?;
return Ok(());
}
let wal_header_data = match self.read_wal_header_if_exists().await {
Some(header) => serialize_header(&header),
None => {
let header = WalHeader::synthetic(
page_size,
manifest.current_salt_1,
manifest.current_salt_2,
);
serialize_header(&header)
}
};
let mut file = tokio::fs::File::create(tmp_wal_path).await?;
use tokio::io::AsyncWriteExt;
file.write_all(&wal_header_data).await?;
for key in &l1_keys {
let data = self
.bucket
.get(key)
.await?
.ok_or_else(|| Error::Restore(format!("L1 file not found: {key}")))?;
if let Some(l1) = manifest.l1_files.iter().find(|l| &l.key == key) {
if let Some(ref expected) = l1.checksum {
let actual = crate::util::compute_sha256(&data);
if &actual != expected {
return Err(Error::Restore(format!(
"L1 file {key} checksum mismatch: expected {expected}, got {actual}"
)));
}
}
}
file.write_all(&data).await?;
}
for key in &uncovered_l0_keys {
let segment_data = self
.bucket
.get(key)
.await?
.ok_or_else(|| Error::Restore(format!("Segment not found: {key}")))?;
if let Some(expected) = manifest.segment_checksums.get(key) {
let actual = crate::util::compute_sha256(&segment_data);
if &actual != expected {
return Err(Error::Restore(format!(
"Segment {key} checksum mismatch: expected {expected}, got {actual}"
)));
}
} else {
tracing::debug!(
"No checksum in manifest for segment {key} — skipping verification"
);
}
file.write_all(&segment_data).await?;
}
file.flush().await?;
file.sync_all().await?; drop(file);
Ok(())
}
async fn read_wal_header_if_exists(&self) -> Option<crate::wal::WalHeader> {
let path = self.config.wal_path().clone();
tokio::task::spawn_blocking(move || {
if !path.exists() {
return None;
}
match crate::wal::WalFile::open(&path) {
Ok(w) => Some(w.header().clone()),
Err(_) => None,
}
})
.await
.ok()
.flatten()
}
}
fn serialize_header(header: &WalHeader) -> Vec<u8> {
let mut buf = Vec::with_capacity(32);
buf.extend_from_slice(&header.magic.to_be_bytes());
buf.extend_from_slice(&header.file_format.to_be_bytes());
buf.extend_from_slice(&header.page_size.to_be_bytes());
buf.extend_from_slice(&header.checkpoint_seq.to_be_bytes());
buf.extend_from_slice(&header.salt_1.to_be_bytes());
buf.extend_from_slice(&header.salt_2.to_be_bytes());
buf.extend_from_slice(&header.checksum_1.to_be_bytes());
buf.extend_from_slice(&header.checksum_2.to_be_bytes());
buf
}
pub fn read_page_size_from_db(data: &[u8]) -> Result<u32> {
if data.len() < 20 {
return Err(Error::Restore(
"snapshot too small to read page size".to_string(),
));
}
let page_size = u16::from_be_bytes([data[16], data[17]]);
let page_size = if page_size == 1 {
65536
} else {
page_size as u32
};
Ok(page_size)
}
pub async fn read_page_size_from_db_async(path: &std::path::Path) -> Result<u32> {
let mut file = tokio::fs::File::open(path).await?;
let mut buf = [0u8; 20];
tokio::io::AsyncReadExt::read_exact(&mut file, &mut buf).await?;
drop(file);
read_page_size_from_db(&buf)
}
fn extract_start_frame_from_key(key: &str) -> Option<u32> {
let segments: Vec<&str> = key.rsplitn(2, '/').collect();
if segments.len() < 2 {
return None;
}
let filename = segments[0];
filename.split('-').next().and_then(|s| {
s.strip_suffix(".segment")
.or_else(|| s.strip_suffix(".l1"))
.unwrap_or(s)
.parse::<u32>()
.ok()
})
}