use bytes::Bytes;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
use tokio::sync::Mutex;
use tokio::sync::Notify;
use tokio::time::{sleep, Instant};
use tracing::{info, warn};
use crate::config::Config;
use crate::error::Result;
use crate::metrics::Metrics;
use crate::replication::manifest::{Manifest, MANIFEST_KEY};
use crate::storage::BucketStore;
use crate::wal::WalFile;
pub struct SnapshotManager {
config: Config,
bucket: Arc<dyn BucketStore>,
manifest: Arc<Mutex<Manifest>>,
last_snapshot_time: Arc<Mutex<Instant>>,
trigger: Arc<Notify>,
snapshot_version: Arc<AtomicU64>,
force_next: Arc<AtomicBool>,
metrics: Arc<dyn Metrics>,
shutdown: Arc<Notify>,
conn: Arc<Mutex<rusqlite::Connection>>,
}
impl SnapshotManager {
#[allow(clippy::too_many_arguments)]
pub fn new(
config: Config,
bucket: Arc<dyn BucketStore>,
manifest: Arc<Mutex<Manifest>>,
trigger: Arc<Notify>,
snapshot_version: Arc<AtomicU64>,
force_next: Arc<AtomicBool>,
metrics: Arc<dyn Metrics>,
conn: Arc<Mutex<rusqlite::Connection>>,
) -> Self {
SnapshotManager {
config,
bucket,
manifest,
last_snapshot_time: Arc::new(Mutex::new(Instant::now())),
trigger,
snapshot_version,
force_next,
metrics,
shutdown: Arc::new(Notify::new()),
conn,
}
}
pub fn trigger(&self) -> Arc<Notify> {
self.trigger.clone()
}
pub fn force_next(&self) -> Arc<AtomicBool> {
self.force_next.clone()
}
pub fn shutdown_notify(&self) -> Arc<Notify> {
self.shutdown.clone()
}
pub fn bucket(&self) -> Arc<dyn BucketStore> {
self.bucket.clone()
}
pub async fn run(&self) {
loop {
if let Err(e) = crate::connection::verify_writer_id(
&self.bucket,
self.bucket.prefix(),
self.bucket.writer_id(),
)
.await
{
if e.is_wrong_writer() {
tracing::error!("WRITER IDENTITY LOST: {e} — stopping snapshot manager");
return;
}
warn!("Writer verification failed (will retry): {e}");
}
if let Err(e) = self.maybe_take_snapshot().await {
warn!("Snapshot check failed: {e}");
}
tokio::select! {
_ = sleep(self.config.snapshot_check_interval()) => {},
_ = self.trigger.notified() => {},
_ = self.shutdown.notified() => {
info!("SnapshotManager shutting down");
return;
},
}
}
}
pub async fn maybe_take_snapshot(&self) -> Result<()> {
let forced = self.force_next.swap(false, Ordering::Relaxed);
if !forced {
let wal_exists = match tokio::fs::try_exists(self.config.wal_path()).await {
Ok(exists) => exists,
Err(e) => {
warn!("Failed to check WAL existence for snapshot: {e}");
false
}
};
if !wal_exists {
return Ok(());
}
let wal_len = match tokio::fs::metadata(self.config.wal_path()).await {
Ok(m) => m.len(),
Err(e) => {
warn!("Failed to read WAL metadata for snapshot check: {e}");
return Ok(());
}
};
let elapsed = self.last_snapshot_time.lock().await.elapsed();
let should_snapshot = wal_len >= self.config.snapshot_threshold_bytes()
|| elapsed >= self.config.snapshot_interval();
if !should_snapshot {
return Ok(());
}
info!(
"Taking snapshot: WAL size {wal_size}MB, elapsed {elapsed_sec}s",
wal_size = wal_len / 1024 / 1024,
elapsed_sec = elapsed.as_secs(),
);
} else {
info!("Taking forced snapshot (salt-change trigger)");
}
self.take_snapshot().await?;
Ok(())
}
pub async fn take_snapshot(&self) -> Result<()> {
let snapshot_path = format!(
"snapshots/{}.db",
chrono::Utc::now().format("%Y%m%d-%H%M%S%.6f")
);
let db_path = self.config.db_path().clone();
let temp_db_path = db_path
.parent()
.unwrap_or_else(|| std::path::Path::new("."))
.join(".snapshot-temp.db");
let temp_db_path_for_cleanup = temp_db_path.clone();
let result = self
.take_snapshot_inner(&snapshot_path, &db_path, &temp_db_path)
.await;
if result.is_err() {
tokio::fs::remove_file(&temp_db_path_for_cleanup).await.ok();
}
result
}
async fn take_snapshot_inner(
&self,
snapshot_path: &str,
db_path: &std::path::Path,
temp_db_path: &std::path::Path,
) -> Result<()> {
let db_path_owned = db_path.to_path_buf();
let temp_db_path_owned = temp_db_path.to_path_buf();
let snapshot_path_owned = snapshot_path.to_string();
let main_size_after = {
let guard = self.conn.lock().await;
guard
.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)")
.map_err(|e| crate::error::Error::Snapshot(format!("checkpoint: {e}")))?;
let db_path_clone = db_path_owned.clone();
let main_size_after = tokio::task::spawn_blocking(move || {
std::fs::metadata(&db_path_clone)
.map(|m| m.len())
.unwrap_or(0)
})
.await
.unwrap_or(0);
drop(guard);
main_size_after
};
tracing::debug!(
"snapshot: main db size after checkpoint={}",
main_size_after
);
tokio::fs::copy(&db_path_owned, &temp_db_path_owned).await?;
let (page_size, db_size) = {
let temp_path = temp_db_path_owned.clone();
tokio::task::spawn_blocking(move || {
let conn = rusqlite::Connection::open(&temp_path)?;
conn.execute_batch("PRAGMA journal_mode = WAL")?;
conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)")?;
drop(conn);
let mut header = [0u8; 20];
let mut file = std::fs::File::open(&temp_path)?;
std::io::Read::read_exact(&mut file, &mut header)?;
let ps = crate::restore::read_page_size_from_db(&header)?;
let size = std::fs::metadata(&temp_path)?.len();
Ok::<_, crate::error::Error>((ps, size))
})
.await??
};
let checksum = {
let temp_path = temp_db_path_owned.clone();
tokio::task::spawn_blocking(move || {
let bytes = std::fs::read(&temp_path)?;
Ok::<_, std::io::Error>(crate::util::compute_sha256(&bytes))
})
.await?
.map_err(|e| crate::error::Error::Snapshot(format!("checksum failed: {e}")))?
};
self.bucket
.put_file(&snapshot_path_owned, &temp_db_path_owned)
.await?;
tokio::fs::remove_file(&temp_db_path_owned).await.ok();
let wal_len = tokio::fs::metadata(self.config.wal_path())
.await
.map(|m| m.len())
.unwrap_or(0);
self.metrics.snapshot_taken(db_size, wal_len);
let wal = {
let wal_path = self.config.wal_path().clone();
tokio::task::spawn_blocking(move || WalFile::open(&wal_path).ok())
.await
.unwrap_or(None)
};
let wal = wal.unwrap_or_else(|| {
warn!("WAL file not found or unreadable during snapshot, using synthetic header");
let header = crate::wal::WalHeader::synthetic(page_size, 0, 0);
crate::wal::WalFile::with_synthetic_header(header, page_size)
});
let mut manifest = self.manifest.lock().await;
let old_salt_prefix = if manifest.current_salt_1 != 0 || manifest.current_salt_2 != 0 {
if manifest.current_salt_1 != wal.header().salt_1
|| manifest.current_salt_2 != wal.header().salt_2
{
Some(manifest.segment_prefix())
} else {
None
}
} else {
None
};
manifest.update_snapshot(
snapshot_path.to_string(),
checksum.clone(),
wal.header().salt_1,
wal.header().salt_2,
page_size,
db_size,
);
let manifest_bytes = manifest.serialize()?;
let etag = manifest.etag.clone();
if let Err(e) = async {
if let Some(ref etag) = etag {
self.bucket
.put_if_match(MANIFEST_KEY, Bytes::from(manifest_bytes), etag)
.await
} else {
self.bucket
.put(MANIFEST_KEY, Bytes::from(manifest_bytes))
.await
}
}
.await
{
if matches!(e, crate::error::Error::PreconditionFailed { .. }) {
warn!("Manifest precondition failed during snapshot — another writer updated it. Re-reading and retrying.");
if let Ok(Some((remote_data, remote_etag))) =
self.bucket.get_with_etag(MANIFEST_KEY).await
{
if let Ok(mut remote) = Manifest::deserialize(&remote_data) {
remote.snapshot = Some(snapshot_path.to_string());
remote.snapshot_checksum = Some(checksum.clone());
remote.current_salt_1 = wal.header().salt_1;
remote.current_salt_2 = wal.header().salt_2;
remote.page_size = page_size;
remote.db_size = db_size;
remote.etag = Some(remote_etag);
let updated_bytes = remote.serialize()?;
if let Err(e2) = self
.bucket
.put_if_match(
MANIFEST_KEY,
Bytes::from(updated_bytes),
remote.etag.as_deref().unwrap_or(""),
)
.await
{
warn!("Retry manifest write also failed: {e2}. Snapshot {snapshot_path} is uploaded but manifest not updated.");
return Err(e2);
}
info!("Successfully updated manifest on retry after precondition failure.");
} else {
return Err(e);
}
} else {
return Err(e);
}
} else {
return Err(e);
}
}
drop(manifest);
if let Some(old_prefix) = old_salt_prefix {
match self.bucket.list(&old_prefix).await {
Ok(keys) => {
for key in keys {
if key.ends_with(".segment") || key.ends_with(".l1") {
if let Err(e) = self.bucket.delete(&key).await {
warn!("Failed to delete old segment {}: {e}", key);
} else {
self.metrics.segment_deleted(&key);
info!("Deleted old salt segment: {key}");
}
}
}
}
Err(e) => {
warn!("Failed to list old salt segments for cleanup: {e}");
}
}
}
*self.last_snapshot_time.lock().await = Instant::now();
self.snapshot_version.fetch_add(1, Ordering::Release);
info!("Snapshot complete: {} ({} bytes)", snapshot_path, db_size);
Ok(())
}
}