1use bytes::Bytes;
2use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
3use std::sync::Arc;
4use std::time::Instant;
5use tokio::sync::Mutex;
6use tokio::sync::Notify;
7use tokio::task::JoinHandle;
8use tracing::{info, warn};
9
10use crate::config::{Config, SyncMode};
11use crate::error::{Error, Result};
12use crate::metrics::{noop_metrics, Metrics};
13use crate::replication::manifest::{Manifest, MANIFEST_KEY};
14use crate::replication::{FrameShipper, SnapshotManager};
15use crate::restore::{self, RestoreEngine};
16use crate::storage::BucketStore;
17use crate::wal::WalFile;
18
19const REPLICA_LOCK_KEY: &str = "lock.json";
20const WRITER_KEY: &str = "writer.json";
21const REPLICA_LOCK_STALE_SECS: u64 = 30;
22const REPLICA_LOCK_HEARTBEAT_SECS: u64 = 10;
23
24#[derive(Debug, Clone)]
25pub struct HealthReport {
26 pub healthy: bool,
27 pub replicator_alive: bool,
28 pub snapshot_alive: bool,
29 pub watcher_alive: bool,
30 pub last_sync_ago: std::time::Duration,
31 pub health_timeout: std::time::Duration,
32}
33
34impl std::fmt::Display for HealthReport {
35 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36 write!(
37 f,
38 "healthy={} replicator={} snapshot={} watcher={} last_sync_ago={:?} timeout={:?}",
39 self.healthy,
40 self.replicator_alive,
41 self.snapshot_alive,
42 self.watcher_alive,
43 self.last_sync_ago,
44 self.health_timeout,
45 )
46 }
47}
48
49pub struct DurabilityLayer {
70 conn: Arc<Mutex<rusqlite::Connection>>,
71 last_sync: Arc<Mutex<Instant>>,
72 replicator_handle: JoinHandle<()>,
73 snapshot_handle: JoinHandle<()>,
74 snapshot_trigger: Arc<Notify>,
75 sync_notify: Arc<Notify>,
76 wal_notify: Arc<Notify>,
77 snapshot_mgr: Arc<SnapshotManager>,
78 _watcher_handle: Option<JoinHandle<()>>,
79 shipped_frames: Arc<AtomicU32>,
80 health_timeout: std::time::Duration,
81 sync_timeout: std::time::Duration,
82 wal_path: std::path::PathBuf,
83 db_path: std::path::PathBuf,
84 _db_lock_file: std::fs::File,
88 _replica_lock_heartbeat: Option<JoinHandle<()>>,
90}
91
92fn acquire_db_lock(db_path: &std::path::Path) -> crate::error::Result<std::fs::File> {
96 let lock_path = db_path.with_extension("db.lock");
97 let file = std::fs::OpenOptions::new()
98 .read(true)
99 .write(true)
100 .create(true)
101 .truncate(false)
102 .open(&lock_path)
103 .map_err(crate::error::Error::Io)?;
104
105 use std::os::unix::io::AsRawFd;
106 let fd = file.as_raw_fd();
107 let result = unsafe { libc::flock(fd, 2 | 4) };
109 if result == 0 {
110 use std::io::Write;
112 let mut f = std::fs::File::create(&lock_path).map_err(crate::error::Error::Io)?;
113 write!(f, "{}", std::process::id()).ok();
114 Ok(file)
115 } else {
116 let holder_pid = read_lock_pid(db_path).unwrap_or(0);
117 Err(crate::error::Error::DatabaseLocked {
118 path: db_path.to_path_buf(),
119 holder_pid,
120 })
121 }
122}
123
124fn read_lock_pid(db_path: &std::path::Path) -> Option<u32> {
127 let lock_path = db_path.with_extension("db.lock");
128 std::fs::read_to_string(lock_path)
129 .ok()
130 .and_then(|s| s.trim().parse::<u32>().ok())
131}
132
133#[derive(serde::Serialize, serde::Deserialize, Clone)]
135struct ReplicaLock {
136 pid: u32,
137 hostname: String,
138 started_at: String,
139 last_heartbeat: String,
140}
141
142impl ReplicaLock {
143 fn new() -> Self {
144 let now = chrono::Utc::now().to_rfc3339();
145 let hostname = std::env::var("HOSTNAME")
146 .or_else(|_| std::env::var("HOST"))
147 .unwrap_or_else(|_| "unknown".to_string());
148 ReplicaLock {
149 pid: std::process::id(),
150 hostname,
151 started_at: now.clone(),
152 last_heartbeat: now,
153 }
154 }
155
156 fn with_updated_heartbeat(&self) -> Self {
157 ReplicaLock {
158 last_heartbeat: chrono::Utc::now().to_rfc3339(),
159 ..self.clone()
160 }
161 }
162
163 fn is_stale(&self) -> bool {
165 let Ok(heartbeat) = self.last_heartbeat.parse::<chrono::DateTime<chrono::Utc>>() else {
166 return true;
168 };
169 let age = chrono::Utc::now() - heartbeat;
170 age > chrono::Duration::seconds(REPLICA_LOCK_STALE_SECS as i64)
171 }
172}
173
174pub(crate) async fn verify_writer_id(
181 bucket: &Arc<dyn BucketStore>,
182 prefix: &str,
183 our_writer_id: &str,
184) -> crate::error::Result<()> {
185 match bucket.get(WRITER_KEY).await {
186 Ok(Some(existing_data)) => {
187 let stored_writer_id = String::from_utf8_lossy(&existing_data).trim().to_string();
189 if stored_writer_id == our_writer_id {
190 tracing::trace!("Writer identity verified: {our_writer_id}");
191 Ok(())
192 } else {
193 tracing::error!(
194 "WRITER MISMATCH: this process is '{our_writer_id}' but bucket prefix '{prefix}' is owned by '{stored_writer_id}'"
195 );
196 Err(Error::WrongWriter {
197 prefix: prefix.to_string(),
198 expected_writer: stored_writer_id,
199 actual_writer: our_writer_id.to_string(),
200 })
201 }
202 }
203 Ok(None) => {
204 let bytes = Bytes::from(our_writer_id.as_bytes().to_vec());
206 match bucket.put_if_not_exists(WRITER_KEY, bytes).await {
207 Ok(()) => {
208 tracing::info!("Registered as writer for prefix '{prefix}': {our_writer_id}");
209 Ok(())
210 }
211 Err(Error::PreconditionFailed { .. }) => {
212 let data = bucket
215 .get(WRITER_KEY)
216 .await?
217 .ok_or_else(|| Error::Other("writer.json disappeared".to_string()))?;
218 let stored = String::from_utf8_lossy(&data).trim().to_string();
219 if stored == our_writer_id {
220 Ok(()) } else {
222 Err(Error::WrongWriter {
223 prefix: prefix.to_string(),
224 expected_writer: stored,
225 actual_writer: our_writer_id.to_string(),
226 })
227 }
228 }
229 Err(e) => {
230 tracing::error!(
233 "Cannot write writer.json to bucket: {e} — refusing to start"
234 );
235 Err(e)
236 }
237 }
238 }
239 Err(e) => {
240 tracing::error!(
242 "Cannot read writer.json from bucket: {e} — refusing to start"
243 );
244 Err(e)
245 }
246 }
247}
248
249async fn acquire_replica_lock(
254 bucket: &Arc<dyn BucketStore>,
255) -> crate::error::Result<(ReplicaLock, String)> {
256 let lock = ReplicaLock::new();
257 let lock_bytes = serde_json::to_vec(&lock)
258 .map_err(|e| Error::Other(format!("serialize replica lock: {e}")))?;
259
260 match bucket
262 .put_if_not_exists(REPLICA_LOCK_KEY, lock_bytes.clone().into())
263 .await
264 {
265 Ok(()) => {
266 tracing::debug!("Acquired replica lock (new creation)");
268 if let Some((_, our_etag)) = bucket.get_with_etag(REPLICA_LOCK_KEY).await? {
269 Ok((lock, our_etag))
270 } else {
271 Ok((lock, String::new()))
272 }
273 }
274 Err(Error::PreconditionFailed { .. }) => {
275 let (existing_data, existing_etag) = bucket
277 .get_with_etag(REPLICA_LOCK_KEY)
278 .await?
279 .ok_or_else(|| Error::Other("Lock exists but can't be read".to_string()))?;
280
281 match serde_json::from_slice::<ReplicaLock>(&existing_data) {
282 Ok(existing_lock) => {
283 if !existing_lock.is_stale() {
284 tracing::warn!(
286 "Replica lock held by PID {} on {} (heartbeat {})",
287 existing_lock.pid,
288 existing_lock.hostname,
289 existing_lock.last_heartbeat
290 );
291 return Err(Error::ReplicaLocked {
292 prefix: REPLICA_LOCK_KEY.to_string(),
293 holder_pid: existing_lock.pid,
294 holder_hostname: existing_lock.hostname,
295 last_heartbeat: existing_lock.last_heartbeat,
296 });
297 }
298 tracing::info!(
300 "Stale replica lock detected (holder PID {} on {}, last heartbeat {}), force-acquiring",
301 existing_lock.pid, existing_lock.hostname, existing_lock.last_heartbeat
302 );
303 bucket
304 .put_if_match(REPLICA_LOCK_KEY, lock_bytes.into(), &existing_etag)
305 .await?;
306 if let Some((_, our_etag)) = bucket.get_with_etag(REPLICA_LOCK_KEY).await? {
307 Ok((lock, our_etag))
308 } else {
309 Ok((lock, String::new()))
310 }
311 }
312 Err(_) => {
313 tracing::warn!("Cannot parse existing replica lock, force-acquiring");
315 bucket
316 .put_if_match(REPLICA_LOCK_KEY, lock_bytes.into(), &existing_etag)
317 .await?;
318 if let Some((_, our_etag)) = bucket.get_with_etag(REPLICA_LOCK_KEY).await? {
319 Ok((lock, our_etag))
320 } else {
321 Ok((lock, String::new()))
322 }
323 }
324 }
325 }
326 Err(e) => {
327 tracing::error!(
329 "Cannot write replica lock to bucket: {e} — refusing to start"
330 );
331 Err(e)
332 }
333 }
334}
335
336impl DurabilityLayer {
337 pub async fn open(config: Config, bucket: Arc<dyn BucketStore>) -> Result<Self> {
349 Self::open_with_metrics(config, bucket, noop_metrics()).await
350 }
351
352 pub async fn open_with_metrics(
353 config: Config,
354 bucket: Arc<dyn BucketStore>,
355 metrics: Arc<dyn Metrics>,
356 ) -> Result<Self> {
357 config
358 .validate()
359 .map_err(|e| crate::error::Error::Config(format!("invalid config: {e}")))?;
360
361 let db_lock_file = acquire_db_lock(config.db_path())?;
364
365 verify_writer_id(&bucket, bucket.prefix(), bucket.writer_id()).await?;
368
369 let _replica_lock_guard = if config.replica_lock_enabled() {
372 let (replica_lock, replica_lock_etag) = acquire_replica_lock(&bucket).await?;
373
374 let heartbeat_bucket = bucket.clone();
378 let heartbeat_lock = replica_lock.clone();
379 let heartbeat_etag = replica_lock_etag.clone();
380 let heartbeat_handle = tokio::spawn(async move {
381 let mut current_etag = heartbeat_etag;
382 loop {
383 tokio::time::sleep(std::time::Duration::from_secs(REPLICA_LOCK_HEARTBEAT_SECS))
384 .await;
385 let updated = heartbeat_lock.with_updated_heartbeat();
386 let bytes = match serde_json::to_vec(&updated) {
387 Ok(b) => b,
388 Err(e) => {
389 tracing::error!("Failed to serialize replica lock heartbeat: {e}");
390 continue;
391 }
392 };
393 match heartbeat_bucket
394 .put_if_match(REPLICA_LOCK_KEY, bytes.into(), ¤t_etag)
395 .await
396 {
397 Ok(()) => {
398 if let Ok(Some((_, new_etag))) =
400 heartbeat_bucket.get_with_etag(REPLICA_LOCK_KEY).await
401 {
402 current_etag = new_etag;
403 }
404 }
405 Err(e) if e.is_precondition_failed() => {
406 tracing::error!("Replica lock was acquired by another process — stopping heartbeat. THIS SHOULD NOT HAPPEN in normal operation.");
408 return;
409 }
410 Err(e) => {
411 tracing::warn!("Failed to update replica lock heartbeat: {e}");
412 }
413 }
414 }
415 });
416 Some(heartbeat_handle)
417 } else {
418 None
419 };
420
421 let restore = RestoreEngine::new(config.clone(), bucket.clone());
422 let manifest = restore.with_metrics(metrics.clone()).restore().await?;
423
424 {
427 let m = manifest.lock().await;
428 validate_manifest_against_bucket(&m, &bucket).await;
429 }
430
431 let conn = rusqlite::Connection::open(config.db_path())?;
432
433 conn.execute_batch("PRAGMA journal_mode = WAL")?;
434 conn.execute_batch("PRAGMA wal_autocheckpoint = 0")?;
435 conn.execute_batch("PRAGMA synchronous = NORMAL")?;
436
437 let conn = Arc::new(Mutex::new(conn));
438
439 let snapshot_trigger = Arc::new(Notify::new());
440 let sync_notify = Arc::new(Notify::new());
441 let wal_notify = Arc::new(Notify::new());
442 let snapshot_version = Arc::new(AtomicU64::new(0));
443 let shipped_frames = Arc::new(AtomicU32::new(0));
444 let force_next = Arc::new(AtomicBool::new(false));
445
446 let wal_notify_clone = wal_notify.clone();
447 let wal_path = config.wal_path().clone();
448 let immediate_poll_interval = config.immediate_poll_interval();
449 let watcher_handle = if config.sync_mode() == &SyncMode::Immediate {
450 let handle = tokio::spawn(async move {
451 let mut last_size: u64 = 0;
452 loop {
453 tokio::time::sleep(immediate_poll_interval).await;
454 if let Ok(meta) = tokio::fs::metadata(&wal_path).await {
455 let new_size = meta.len();
456 if new_size != last_size {
457 last_size = new_size;
458 wal_notify_clone.notify_one();
459 }
460 }
461 }
462 });
463 Some(handle)
464 } else {
465 None
466 };
467
468 let shipper = FrameShipper::new(
469 config.clone(),
470 bucket.clone(),
471 manifest.clone(),
472 snapshot_trigger.clone(),
473 sync_notify.clone(),
474 wal_notify.clone(),
475 snapshot_version.clone(),
476 force_next.clone(),
477 shipped_frames.clone(),
478 metrics.clone(),
479 );
480 let last_sync = shipper.last_sync();
481
482 let snap_mgr = Arc::new(SnapshotManager::new(
483 config.clone(),
484 bucket.clone(),
485 manifest.clone(),
486 snapshot_trigger.clone(),
487 snapshot_version.clone(),
488 force_next.clone(),
489 metrics.clone(),
490 conn.clone(),
491 ));
492
493 let health_timeout = config.health_timeout();
494 let sync_timeout = config.sync_timeout();
495
496 let replicator_handle = tokio::spawn({
497 let shipper = shipper;
498 async move {
499 shipper.run().await;
500 }
501 });
502
503 let snapshot_handle = tokio::spawn({
504 let snap_mgr = snap_mgr.clone();
505 async move {
506 snap_mgr.run().await;
507 }
508 });
509
510 info!("DurabilityLayer initialized");
511 info!(" DB path: {}", config.db_path().display());
512 info!(" Poll interval: {:?}", config.poll_interval());
513 info!(" Sync mode: {:?}", config.sync_mode());
514 info!(
515 " Snapshot threshold: {}MB",
516 config.snapshot_threshold_bytes() / 1024 / 1024
517 );
518
519 Ok(DurabilityLayer {
520 conn,
521 last_sync,
522 replicator_handle,
523 snapshot_handle,
524 snapshot_trigger,
525 sync_notify,
526 wal_notify,
527 snapshot_mgr: snap_mgr,
528 _watcher_handle: watcher_handle,
529 shipped_frames,
530 health_timeout,
531 sync_timeout,
532 wal_path: config.wal_path().clone(),
533 db_path: config.db_path().clone(),
534 _db_lock_file: db_lock_file,
535 _replica_lock_heartbeat: _replica_lock_guard,
536 })
537 }
538
539 pub async fn sync_now(&self) -> Result<()> {
545 {
546 let guard = self.conn.lock().await;
547 guard.execute_batch("BEGIN")?;
548 guard.execute_batch("COMMIT")?;
549 }
550
551 self.wal_notify.notify_one();
552
553 let deadline = Instant::now() + self.sync_timeout;
554 let mut iteration = 0u32;
555 loop {
556 iteration += 1;
557
558 if iteration == 1 || iteration % 10 == 0 {
559 let current = self.shipped_frames.load(Ordering::Acquire);
560 let wal_path = self.wal_path.clone();
561 let has_pending =
562 tokio::task::spawn_blocking(move || match WalFile::open(&wal_path) {
563 Ok(w) => w.total_frames() > current,
564 Err(_) => false,
565 })
566 .await
567 .unwrap_or(false);
568
569 if !has_pending {
570 *self.last_sync.lock().await = Instant::now();
571 return Ok(());
572 }
573 }
574
575 if Instant::now() > deadline {
576 return Err(crate::error::Error::Replication(format!(
577 "sync timeout: WAL frames not shipped within {:?}",
578 self.sync_timeout
579 )));
580 }
581 let remaining = deadline.saturating_duration_since(Instant::now());
584 tokio::select! {
585 _ = self.sync_notify.notified() => {
586 }
588 _ = tokio::time::sleep(remaining.min(std::time::Duration::from_millis(50))) => {
589 }
591 }
592 }
593 }
594
595 pub async fn last_sync(&self) -> Instant {
596 *self.last_sync.lock().await
597 }
598
599 pub async fn is_healthy(&self) -> bool {
600 self.health_report().await.healthy
601 }
602
603 pub async fn health_report(&self) -> HealthReport {
604 let replicator_alive = !self.replicator_handle.is_finished();
605 let snapshot_alive = !self.snapshot_handle.is_finished();
606 let watcher_alive = match &self._watcher_handle {
607 Some(h) => !h.is_finished(),
608 None => true,
609 };
610 let last_sync_ago = self.last_sync.lock().await.elapsed();
611 let healthy = replicator_alive
612 && snapshot_alive
613 && watcher_alive
614 && last_sync_ago < self.health_timeout;
615 HealthReport {
616 healthy,
617 replicator_alive,
618 snapshot_alive,
619 watcher_alive,
620 last_sync_ago,
621 health_timeout: self.health_timeout,
622 }
623 }
624
625 pub async fn conn(&self) -> tokio::sync::MutexGuard<'_, rusqlite::Connection> {
626 self.conn.lock().await
627 }
628
629 pub async fn with_conn<F, T>(&self, f: F) -> Result<T>
642 where
643 F: FnOnce(&rusqlite::Connection) -> rusqlite::Result<T>,
644 {
645 let guard = self.conn.lock().await;
646 f(&guard).map_err(crate::error::Error::from)
647 }
648
649 pub fn sync_notify(&self) -> Arc<Notify> {
650 self.sync_notify.clone()
651 }
652
653 pub async fn force_snapshot(&self) -> Result<()> {
660 let result = self.snapshot_mgr.take_snapshot().await;
664 self.snapshot_mgr
665 .force_next()
666 .store(false, Ordering::Relaxed);
667 self.snapshot_trigger.notify_one();
668 result
669 }
670
671 pub async fn shutdown(&self) -> Result<()> {
677 info!("DurabilityLayer shutting down");
678
679 if let Err(e) = self.sync_now().await {
683 warn!("Final sync on shutdown failed (data still in local WAL): {e}");
684 }
685
686 self.snapshot_mgr.shutdown_notify().notify_one();
688
689 self.replicator_handle.abort();
691 self.snapshot_handle.abort();
692 if let Some(h) = self._replica_lock_heartbeat.as_ref() {
693 h.abort();
694 }
695 if let Some(handle) = &self._watcher_handle {
696 handle.abort();
697 }
698
699 if let Err(e) = self.snapshot_mgr.bucket().delete(REPLICA_LOCK_KEY).await {
701 tracing::warn!("Failed to delete replica lock on shutdown: {e}");
702 } else {
703 tracing::info!("Replica lock released on shutdown");
704 }
705
706 if let Ok(Some(data)) = self.snapshot_mgr.bucket().get(MANIFEST_KEY).await {
710 if let Ok(manifest) = Manifest::deserialize(&data) {
711 if let Err(e) = restore::write_generation(&self.db_path, manifest.generation).await
712 {
713 tracing::warn!("Failed to write generation file on shutdown: {e}");
714 }
715 }
716 }
717
718 let guard = self.conn.lock().await;
719 guard.execute_batch("PRAGMA wal_checkpoint(FULL)")?;
720 drop(guard);
721
722 Ok(())
723 }
724}
725
726impl Drop for DurabilityLayer {
727 fn drop(&mut self) {
731 self.replicator_handle.abort();
732 self.snapshot_handle.abort();
733 if let Some(handle) = &self._watcher_handle {
734 handle.abort();
735 }
736 if let Some(handle) = &self._replica_lock_heartbeat {
737 handle.abort();
738 }
739 tracing::warn!(concat!(
740 "DurabilityLayer dropped without calling shutdown() — ",
741 "WAL may not be checkpointed. Call shutdown() explicitly for clean shutdown."
742 ));
743 }
744}
745
746pub(crate) async fn validate_manifest_against_bucket(
751 manifest: &crate::replication::Manifest,
752 bucket: &Arc<dyn BucketStore>,
753) {
754 let mut warnings = 0u32;
755 let mut errors = 0u32;
756
757 if let Some(ref snap_key) = manifest.snapshot {
759 match bucket.exists(snap_key).await {
760 Ok(true) => {
761 tracing::debug!("Bucket validation: snapshot '{snap_key}' exists");
762 }
763 Ok(false) => {
764 tracing::error!(
765 "Bucket validation: snapshot '{snap_key}' referenced in manifest but MISSING from bucket!"
766 );
767 errors += 1;
768 }
769 Err(e) => {
770 tracing::warn!("Bucket validation: cannot verify snapshot '{snap_key}': {e}");
771 warnings += 1;
772 }
773 }
774 } else if manifest.generation > 0 {
775 tracing::warn!(
777 "Bucket validation: manifest generation {} has no snapshot",
778 manifest.generation
779 );
780 warnings += 1;
781 }
782
783 for seg in &manifest.l1_files {
785 match bucket.exists(&seg.key).await {
786 Ok(true) => {
787 tracing::debug!("Bucket validation: L1 segment '{}' exists", seg.key);
788 }
789 Ok(false) => {
790 tracing::error!(
791 "Bucket validation: L1 segment '{}' referenced in manifest but MISSING from bucket!",
792 seg.key
793 );
794 errors += 1;
795 }
796 Err(e) => {
797 tracing::warn!(
798 "Bucket validation: cannot verify L1 segment '{}': {e}",
799 seg.key
800 );
801 warnings += 1;
802 }
803 }
804 }
805
806 for key in manifest.segment_checksums.keys() {
808 match bucket.exists(key).await {
809 Ok(true) => {
810 tracing::debug!("Bucket validation: L0 segment '{key}' exists");
811 }
812 Ok(false) => {
813 tracing::error!(
814 "Bucket validation: L0 segment '{key}' referenced in manifest but MISSING from bucket!"
815 );
816 errors += 1;
817 }
818 Err(e) => {
819 tracing::warn!("Bucket validation: cannot verify L0 segment '{key}': {e}");
820 warnings += 1;
821 }
822 }
823 }
824
825 if errors > 0 || warnings > 0 {
827 tracing::warn!(
828 "Bucket validation complete: {errors} errors, {warnings} warnings. \
829 The restored DB is usable but may have missing segments.",
830 );
831 } else {
832 tracing::debug!("Bucket validation: all referenced objects present");
833 }
834}