use bytes::Bytes;
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
use std::sync::Arc;
use std::time::Instant;
use tokio::sync::Mutex;
use tokio::sync::Notify;
use tokio::task::JoinHandle;
use tracing::{info, warn};
use crate::config::{Config, SyncMode};
use crate::error::{Error, Result};
use crate::metrics::{noop_metrics, Metrics};
use crate::replication::manifest::{Manifest, MANIFEST_KEY};
use crate::replication::{FrameShipper, SnapshotManager};
use crate::restore::{self, RestoreEngine};
use crate::storage::BucketStore;
use crate::wal::WalFile;
const REPLICA_LOCK_KEY: &str = "lock.json";
const WRITER_KEY: &str = "writer.json";
const REPLICA_LOCK_STALE_SECS: u64 = 30;
const REPLICA_LOCK_HEARTBEAT_SECS: u64 = 10;
#[derive(Debug, Clone)]
pub struct HealthReport {
pub healthy: bool,
pub replicator_alive: bool,
pub snapshot_alive: bool,
pub watcher_alive: bool,
pub last_sync_ago: std::time::Duration,
pub health_timeout: std::time::Duration,
}
impl std::fmt::Display for HealthReport {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"healthy={} replicator={} snapshot={} watcher={} last_sync_ago={:?} timeout={:?}",
self.healthy,
self.replicator_alive,
self.snapshot_alive,
self.watcher_alive,
self.last_sync_ago,
self.health_timeout,
)
}
}
pub struct DurabilityLayer {
conn: Arc<Mutex<rusqlite::Connection>>,
last_sync: Arc<Mutex<Instant>>,
replicator_handle: JoinHandle<()>,
snapshot_handle: JoinHandle<()>,
snapshot_trigger: Arc<Notify>,
sync_notify: Arc<Notify>,
wal_notify: Arc<Notify>,
snapshot_mgr: Arc<SnapshotManager>,
_watcher_handle: Option<JoinHandle<()>>,
shipped_frames: Arc<AtomicU32>,
health_timeout: std::time::Duration,
sync_timeout: std::time::Duration,
wal_path: std::path::PathBuf,
db_path: std::path::PathBuf,
_db_lock_file: std::fs::File,
_replica_lock_heartbeat: Option<JoinHandle<()>>,
}
fn acquire_db_lock(db_path: &std::path::Path) -> crate::error::Result<std::fs::File> {
let lock_path = db_path.with_extension("db.lock");
let file = std::fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(&lock_path)
.map_err(crate::error::Error::Io)?;
use std::os::unix::io::AsRawFd;
let fd = file.as_raw_fd();
let result = unsafe { libc::flock(fd, 2 | 4) };
if result == 0 {
use std::io::Write;
let mut f = std::fs::File::create(&lock_path).map_err(crate::error::Error::Io)?;
write!(f, "{}", std::process::id()).ok();
Ok(file)
} else {
let holder_pid = read_lock_pid(db_path).unwrap_or(0);
Err(crate::error::Error::DatabaseLocked {
path: db_path.to_path_buf(),
holder_pid,
})
}
}
fn read_lock_pid(db_path: &std::path::Path) -> Option<u32> {
let lock_path = db_path.with_extension("db.lock");
std::fs::read_to_string(lock_path)
.ok()
.and_then(|s| s.trim().parse::<u32>().ok())
}
#[derive(serde::Serialize, serde::Deserialize, Clone)]
struct ReplicaLock {
pid: u32,
hostname: String,
started_at: String,
last_heartbeat: String,
}
impl ReplicaLock {
fn new() -> Self {
let now = chrono::Utc::now().to_rfc3339();
let hostname = std::env::var("HOSTNAME")
.or_else(|_| std::env::var("HOST"))
.unwrap_or_else(|_| "unknown".to_string());
ReplicaLock {
pid: std::process::id(),
hostname,
started_at: now.clone(),
last_heartbeat: now,
}
}
fn with_updated_heartbeat(&self) -> Self {
ReplicaLock {
last_heartbeat: chrono::Utc::now().to_rfc3339(),
..self.clone()
}
}
fn is_stale(&self) -> bool {
let Ok(heartbeat) = self.last_heartbeat.parse::<chrono::DateTime<chrono::Utc>>() else {
return true;
};
let age = chrono::Utc::now() - heartbeat;
age > chrono::Duration::seconds(REPLICA_LOCK_STALE_SECS as i64)
}
}
pub(crate) async fn verify_writer_id(
bucket: &Arc<dyn BucketStore>,
prefix: &str,
our_writer_id: &str,
) -> crate::error::Result<()> {
match bucket.get(WRITER_KEY).await {
Ok(Some(existing_data)) => {
let stored_writer_id = String::from_utf8_lossy(&existing_data).trim().to_string();
if stored_writer_id == our_writer_id {
tracing::trace!("Writer identity verified: {our_writer_id}");
Ok(())
} else {
tracing::error!(
"WRITER MISMATCH: this process is '{our_writer_id}' but bucket prefix '{prefix}' is owned by '{stored_writer_id}'"
);
Err(Error::WrongWriter {
prefix: prefix.to_string(),
expected_writer: stored_writer_id,
actual_writer: our_writer_id.to_string(),
})
}
}
Ok(None) => {
let bytes = Bytes::from(our_writer_id.as_bytes().to_vec());
match bucket.put_if_not_exists(WRITER_KEY, bytes).await {
Ok(()) => {
tracing::info!("Registered as writer for prefix '{prefix}': {our_writer_id}");
Ok(())
}
Err(Error::PreconditionFailed { .. }) => {
let data = bucket
.get(WRITER_KEY)
.await?
.ok_or_else(|| Error::Other("writer.json disappeared".to_string()))?;
let stored = String::from_utf8_lossy(&data).trim().to_string();
if stored == our_writer_id {
Ok(()) } else {
Err(Error::WrongWriter {
prefix: prefix.to_string(),
expected_writer: stored,
actual_writer: our_writer_id.to_string(),
})
}
}
Err(e) => {
tracing::error!(
"Cannot write writer.json to bucket: {e} — refusing to start"
);
Err(e)
}
}
}
Err(e) => {
tracing::error!(
"Cannot read writer.json from bucket: {e} — refusing to start"
);
Err(e)
}
}
}
async fn acquire_replica_lock(
bucket: &Arc<dyn BucketStore>,
) -> crate::error::Result<(ReplicaLock, String)> {
let lock = ReplicaLock::new();
let lock_bytes = serde_json::to_vec(&lock)
.map_err(|e| Error::Other(format!("serialize replica lock: {e}")))?;
match bucket
.put_if_not_exists(REPLICA_LOCK_KEY, lock_bytes.clone().into())
.await
{
Ok(()) => {
tracing::debug!("Acquired replica lock (new creation)");
if let Some((_, our_etag)) = bucket.get_with_etag(REPLICA_LOCK_KEY).await? {
Ok((lock, our_etag))
} else {
Ok((lock, String::new()))
}
}
Err(Error::PreconditionFailed { .. }) => {
let (existing_data, existing_etag) = bucket
.get_with_etag(REPLICA_LOCK_KEY)
.await?
.ok_or_else(|| Error::Other("Lock exists but can't be read".to_string()))?;
match serde_json::from_slice::<ReplicaLock>(&existing_data) {
Ok(existing_lock) => {
if !existing_lock.is_stale() {
tracing::warn!(
"Replica lock held by PID {} on {} (heartbeat {})",
existing_lock.pid,
existing_lock.hostname,
existing_lock.last_heartbeat
);
return Err(Error::ReplicaLocked {
prefix: REPLICA_LOCK_KEY.to_string(),
holder_pid: existing_lock.pid,
holder_hostname: existing_lock.hostname,
last_heartbeat: existing_lock.last_heartbeat,
});
}
tracing::info!(
"Stale replica lock detected (holder PID {} on {}, last heartbeat {}), force-acquiring",
existing_lock.pid, existing_lock.hostname, existing_lock.last_heartbeat
);
bucket
.put_if_match(REPLICA_LOCK_KEY, lock_bytes.into(), &existing_etag)
.await?;
if let Some((_, our_etag)) = bucket.get_with_etag(REPLICA_LOCK_KEY).await? {
Ok((lock, our_etag))
} else {
Ok((lock, String::new()))
}
}
Err(_) => {
tracing::warn!("Cannot parse existing replica lock, force-acquiring");
bucket
.put_if_match(REPLICA_LOCK_KEY, lock_bytes.into(), &existing_etag)
.await?;
if let Some((_, our_etag)) = bucket.get_with_etag(REPLICA_LOCK_KEY).await? {
Ok((lock, our_etag))
} else {
Ok((lock, String::new()))
}
}
}
}
Err(e) => {
tracing::error!(
"Cannot write replica lock to bucket: {e} — refusing to start"
);
Err(e)
}
}
}
impl DurabilityLayer {
pub async fn open(config: Config, bucket: Arc<dyn BucketStore>) -> Result<Self> {
Self::open_with_metrics(config, bucket, noop_metrics()).await
}
pub async fn open_with_metrics(
config: Config,
bucket: Arc<dyn BucketStore>,
metrics: Arc<dyn Metrics>,
) -> Result<Self> {
config
.validate()
.map_err(|e| crate::error::Error::Config(format!("invalid config: {e}")))?;
let db_lock_file = acquire_db_lock(config.db_path())?;
verify_writer_id(&bucket, bucket.prefix(), bucket.writer_id()).await?;
let _replica_lock_guard = if config.replica_lock_enabled() {
let (replica_lock, replica_lock_etag) = acquire_replica_lock(&bucket).await?;
let heartbeat_bucket = bucket.clone();
let heartbeat_lock = replica_lock.clone();
let heartbeat_etag = replica_lock_etag.clone();
let heartbeat_handle = tokio::spawn(async move {
let mut current_etag = heartbeat_etag;
loop {
tokio::time::sleep(std::time::Duration::from_secs(REPLICA_LOCK_HEARTBEAT_SECS))
.await;
let updated = heartbeat_lock.with_updated_heartbeat();
let bytes = match serde_json::to_vec(&updated) {
Ok(b) => b,
Err(e) => {
tracing::error!("Failed to serialize replica lock heartbeat: {e}");
continue;
}
};
match heartbeat_bucket
.put_if_match(REPLICA_LOCK_KEY, bytes.into(), ¤t_etag)
.await
{
Ok(()) => {
if let Ok(Some((_, new_etag))) =
heartbeat_bucket.get_with_etag(REPLICA_LOCK_KEY).await
{
current_etag = new_etag;
}
}
Err(e) if e.is_precondition_failed() => {
tracing::error!("Replica lock was acquired by another process — stopping heartbeat. THIS SHOULD NOT HAPPEN in normal operation.");
return;
}
Err(e) => {
tracing::warn!("Failed to update replica lock heartbeat: {e}");
}
}
}
});
Some(heartbeat_handle)
} else {
None
};
let restore = RestoreEngine::new(config.clone(), bucket.clone());
let manifest = restore.with_metrics(metrics.clone()).restore().await?;
{
let m = manifest.lock().await;
validate_manifest_against_bucket(&m, &bucket).await;
}
let conn = rusqlite::Connection::open(config.db_path())?;
conn.execute_batch("PRAGMA journal_mode = WAL")?;
conn.execute_batch("PRAGMA wal_autocheckpoint = 0")?;
conn.execute_batch("PRAGMA synchronous = NORMAL")?;
let conn = Arc::new(Mutex::new(conn));
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::new(AtomicU64::new(0));
let shipped_frames = Arc::new(AtomicU32::new(0));
let force_next = Arc::new(AtomicBool::new(false));
let wal_notify_clone = wal_notify.clone();
let wal_path = config.wal_path().clone();
let immediate_poll_interval = config.immediate_poll_interval();
let watcher_handle = if config.sync_mode() == &SyncMode::Immediate {
let handle = tokio::spawn(async move {
let mut last_size: u64 = 0;
loop {
tokio::time::sleep(immediate_poll_interval).await;
if let Ok(meta) = tokio::fs::metadata(&wal_path).await {
let new_size = meta.len();
if new_size != last_size {
last_size = new_size;
wal_notify_clone.notify_one();
}
}
}
});
Some(handle)
} else {
None
};
let shipper = FrameShipper::new(
config.clone(),
bucket.clone(),
manifest.clone(),
snapshot_trigger.clone(),
sync_notify.clone(),
wal_notify.clone(),
snapshot_version.clone(),
force_next.clone(),
shipped_frames.clone(),
metrics.clone(),
);
let last_sync = shipper.last_sync();
let snap_mgr = Arc::new(SnapshotManager::new(
config.clone(),
bucket.clone(),
manifest.clone(),
snapshot_trigger.clone(),
snapshot_version.clone(),
force_next.clone(),
metrics.clone(),
conn.clone(),
));
let health_timeout = config.health_timeout();
let sync_timeout = config.sync_timeout();
let replicator_handle = tokio::spawn({
let shipper = shipper;
async move {
shipper.run().await;
}
});
let snapshot_handle = tokio::spawn({
let snap_mgr = snap_mgr.clone();
async move {
snap_mgr.run().await;
}
});
info!("DurabilityLayer initialized");
info!(" DB path: {}", config.db_path().display());
info!(" Poll interval: {:?}", config.poll_interval());
info!(" Sync mode: {:?}", config.sync_mode());
info!(
" Snapshot threshold: {}MB",
config.snapshot_threshold_bytes() / 1024 / 1024
);
Ok(DurabilityLayer {
conn,
last_sync,
replicator_handle,
snapshot_handle,
snapshot_trigger,
sync_notify,
wal_notify,
snapshot_mgr: snap_mgr,
_watcher_handle: watcher_handle,
shipped_frames,
health_timeout,
sync_timeout,
wal_path: config.wal_path().clone(),
db_path: config.db_path().clone(),
_db_lock_file: db_lock_file,
_replica_lock_heartbeat: _replica_lock_guard,
})
}
pub async fn sync_now(&self) -> Result<()> {
{
let guard = self.conn.lock().await;
guard.execute_batch("BEGIN")?;
guard.execute_batch("COMMIT")?;
}
self.wal_notify.notify_one();
let deadline = Instant::now() + self.sync_timeout;
let mut iteration = 0u32;
loop {
iteration += 1;
if iteration == 1 || iteration % 10 == 0 {
let current = self.shipped_frames.load(Ordering::Acquire);
let wal_path = self.wal_path.clone();
let has_pending =
tokio::task::spawn_blocking(move || match WalFile::open(&wal_path) {
Ok(w) => w.total_frames() > current,
Err(_) => false,
})
.await
.unwrap_or(false);
if !has_pending {
*self.last_sync.lock().await = Instant::now();
return Ok(());
}
}
if Instant::now() > deadline {
return Err(crate::error::Error::Replication(format!(
"sync timeout: WAL frames not shipped within {:?}",
self.sync_timeout
)));
}
let remaining = deadline.saturating_duration_since(Instant::now());
tokio::select! {
_ = self.sync_notify.notified() => {
}
_ = tokio::time::sleep(remaining.min(std::time::Duration::from_millis(50))) => {
}
}
}
}
pub async fn last_sync(&self) -> Instant {
*self.last_sync.lock().await
}
pub async fn is_healthy(&self) -> bool {
self.health_report().await.healthy
}
pub async fn health_report(&self) -> HealthReport {
let replicator_alive = !self.replicator_handle.is_finished();
let snapshot_alive = !self.snapshot_handle.is_finished();
let watcher_alive = match &self._watcher_handle {
Some(h) => !h.is_finished(),
None => true,
};
let last_sync_ago = self.last_sync.lock().await.elapsed();
let healthy = replicator_alive
&& snapshot_alive
&& watcher_alive
&& last_sync_ago < self.health_timeout;
HealthReport {
healthy,
replicator_alive,
snapshot_alive,
watcher_alive,
last_sync_ago,
health_timeout: self.health_timeout,
}
}
pub async fn conn(&self) -> tokio::sync::MutexGuard<'_, rusqlite::Connection> {
self.conn.lock().await
}
pub async fn with_conn<F, T>(&self, f: F) -> Result<T>
where
F: FnOnce(&rusqlite::Connection) -> rusqlite::Result<T>,
{
let guard = self.conn.lock().await;
f(&guard).map_err(crate::error::Error::from)
}
pub fn sync_notify(&self) -> Arc<Notify> {
self.sync_notify.clone()
}
pub async fn force_snapshot(&self) -> Result<()> {
let result = self.snapshot_mgr.take_snapshot().await;
self.snapshot_mgr
.force_next()
.store(false, Ordering::Relaxed);
self.snapshot_trigger.notify_one();
result
}
pub async fn shutdown(&self) -> Result<()> {
info!("DurabilityLayer shutting down");
if let Err(e) = self.sync_now().await {
warn!("Final sync on shutdown failed (data still in local WAL): {e}");
}
self.snapshot_mgr.shutdown_notify().notify_one();
self.replicator_handle.abort();
self.snapshot_handle.abort();
if let Some(h) = self._replica_lock_heartbeat.as_ref() {
h.abort();
}
if let Some(handle) = &self._watcher_handle {
handle.abort();
}
if let Err(e) = self.snapshot_mgr.bucket().delete(REPLICA_LOCK_KEY).await {
tracing::warn!("Failed to delete replica lock on shutdown: {e}");
} else {
tracing::info!("Replica lock released on shutdown");
}
if let Ok(Some(data)) = self.snapshot_mgr.bucket().get(MANIFEST_KEY).await {
if let Ok(manifest) = Manifest::deserialize(&data) {
if let Err(e) = restore::write_generation(&self.db_path, manifest.generation).await
{
tracing::warn!("Failed to write generation file on shutdown: {e}");
}
}
}
let guard = self.conn.lock().await;
guard.execute_batch("PRAGMA wal_checkpoint(FULL)")?;
drop(guard);
Ok(())
}
}
impl Drop for DurabilityLayer {
fn drop(&mut self) {
self.replicator_handle.abort();
self.snapshot_handle.abort();
if let Some(handle) = &self._watcher_handle {
handle.abort();
}
if let Some(handle) = &self._replica_lock_heartbeat {
handle.abort();
}
tracing::warn!(concat!(
"DurabilityLayer dropped without calling shutdown() — ",
"WAL may not be checkpointed. Call shutdown() explicitly for clean shutdown."
));
}
}
pub(crate) async fn validate_manifest_against_bucket(
manifest: &crate::replication::Manifest,
bucket: &Arc<dyn BucketStore>,
) {
let mut warnings = 0u32;
let mut errors = 0u32;
if let Some(ref snap_key) = manifest.snapshot {
match bucket.exists(snap_key).await {
Ok(true) => {
tracing::debug!("Bucket validation: snapshot '{snap_key}' exists");
}
Ok(false) => {
tracing::error!(
"Bucket validation: snapshot '{snap_key}' referenced in manifest but MISSING from bucket!"
);
errors += 1;
}
Err(e) => {
tracing::warn!("Bucket validation: cannot verify snapshot '{snap_key}': {e}");
warnings += 1;
}
}
} else if manifest.generation > 0 {
tracing::warn!(
"Bucket validation: manifest generation {} has no snapshot",
manifest.generation
);
warnings += 1;
}
for seg in &manifest.l1_files {
match bucket.exists(&seg.key).await {
Ok(true) => {
tracing::debug!("Bucket validation: L1 segment '{}' exists", seg.key);
}
Ok(false) => {
tracing::error!(
"Bucket validation: L1 segment '{}' referenced in manifest but MISSING from bucket!",
seg.key
);
errors += 1;
}
Err(e) => {
tracing::warn!(
"Bucket validation: cannot verify L1 segment '{}': {e}",
seg.key
);
warnings += 1;
}
}
}
for key in manifest.segment_checksums.keys() {
match bucket.exists(key).await {
Ok(true) => {
tracing::debug!("Bucket validation: L0 segment '{key}' exists");
}
Ok(false) => {
tracing::error!(
"Bucket validation: L0 segment '{key}' referenced in manifest but MISSING from bucket!"
);
errors += 1;
}
Err(e) => {
tracing::warn!("Bucket validation: cannot verify L0 segment '{key}': {e}");
warnings += 1;
}
}
}
if errors > 0 || warnings > 0 {
tracing::warn!(
"Bucket validation complete: {errors} errors, {warnings} warnings. \
The restored DB is usable but may have missing segments.",
);
} else {
tracing::debug!("Bucket validation: all referenced objects present");
}
}