Skip to main content

wal_backup/
connection.rs

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
49/// The core type — manages a SQLite database with automatic S3 backup.
50///
51/// `DurabilityLayer` wraps a [`rusqlite::Connection`] and continuously ships
52/// WAL frames to an S3-compatible bucket in the background. On startup it
53/// restores the local DB from the bucket if needed.
54///
55/// # Lifecycle
56///
57/// 1. [`DurabilityLayer::open()`] — acquire locks, restore if needed, start background tasks
58/// 2. `layer.with_conn()` — run SQL statements
59/// 3. `layer.shutdown()` — checkpoint WAL, final sync, release locks
60///
61/// # Multi-writer protection
62///
63/// `open()` acquires three guards:
64/// - **flock** on `.db.lock` — prevents two processes on the same machine
65/// - **lock.json** in bucket — prevents two processes anywhere (with heartbeat)
66/// - **writer.json** in bucket — permanent ownership record
67///
68/// If any guard fails, `open()` returns an error.
69pub 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    /// File descriptor holding the flock. Kept alive for the lifetime of
85    /// the DurabilityLayer. Released on Drop, preventing two processes
86    /// from opening the same database file.
87    _db_lock_file: std::fs::File,
88    /// Heartbeat task for the bucket replica lock. None if replica lock is disabled.
89    _replica_lock_heartbeat: Option<JoinHandle<()>>,
90}
91
92/// Acquire an exclusive file lock on a lock file adjacent to the database.
93/// Uses a `.db.lock` file (not the DB itself) to avoid interfering with SQLite's
94/// own file locking. The lock is released when the File is dropped (shutdown/drop).
95fn 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    // LOCK_EX = 2, LOCK_NB = 4
108    let result = unsafe { libc::flock(fd, 2 | 4) };
109    if result == 0 {
110        // Write our PID for informational purposes
111        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
124/// Try to read the PID from a sidecar lock file (best-effort, informational only).
125/// The real lock is the flock, not this file.
126fn 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/// Replica lock data stored in lock.json in the bucket.
134#[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    /// Check if the lock is stale (heartbeat older than REPLICA_LOCK_STALE_SECS).
164    fn is_stale(&self) -> bool {
165        let Ok(heartbeat) = self.last_heartbeat.parse::<chrono::DateTime<chrono::Utc>>() else {
166            // Can't parse timestamp — treat as stale to be safe
167            return true;
168        };
169        let age = chrono::Utc::now() - heartbeat;
170        age > chrono::Duration::seconds(REPLICA_LOCK_STALE_SECS as i64)
171    }
172}
173
174/// Verify that this process is the authorized writer for this bucket prefix.
175/// Reads `writer.json` from the bucket — if it exists, our writer_id must match.
176/// If it doesn't exist, we create it atomically (we're the first writer).
177///
178/// This prevents the most dangerous scenario: two different servers accidentally
179/// configured with the same bucket prefix, silently overwriting each other's data.
180pub(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            // writer.json exists — parse it and compare
188            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            // No writer.json yet — we're the first writer. Create it atomically.
205            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                    // Race: another process created writer.json between our get and put.
213                    // Re-read and verify.
214                    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(()) // Another instance of the same writer
221                    } 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                    // Can't write to bucket — writer verification is safety-critical,
231                    // so we must fail rather than silently bypass the check.
232                    tracing::error!(
233                        "Cannot write writer.json to bucket: {e} — refusing to start"
234                    );
235                    Err(e)
236                }
237            }
238        }
239        Err(e) => {
240            // Can't read from bucket — writer verification is safety-critical.
241            tracing::error!(
242                "Cannot read writer.json from bucket: {e} — refusing to start"
243            );
244            Err(e)
245        }
246    }
247}
248
249/// Acquire the bucket replica lock atomically. Returns (ReplicaLock, lock_etag) on success.
250/// Uses `put_if_not_exists` for the initial creation (atomic), and `put_if_match` for
251/// stale lock acquisition (atomic with etag check). This ensures no two processes can
252/// ever acquire the same lock simultaneously.
253async 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    // Step 1: Try atomic create-if-not-exists
261    match bucket
262        .put_if_not_exists(REPLICA_LOCK_KEY, lock_bytes.clone().into())
263        .await
264    {
265        Ok(()) => {
266            // We atomically created the lock — we own it
267            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            // Lock already exists — check if it's stale
276            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                        // Fresh lock from another holder — REFUSE
285                        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                    // Stale lock — force-acquire atomically via etag check
299                    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                    // Can't parse existing lock — treat as stale, force-acquire atomically
314                    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            // Can't write lock — bucket lock is safety-critical, refuse to start.
328            tracing::error!(
329                "Cannot write replica lock to bucket: {e} — refusing to start"
330            );
331            Err(e)
332        }
333    }
334}
335
336impl DurabilityLayer {
337    /// Open a DurabilityLayer — the main entry point.
338    ///
339    /// This acquires the local file lock, verifies writer identity,
340    /// acquires the bucket replica lock, restores from S3 if needed,
341    /// validates bucket integrity, and starts background replication tasks.
342    ///
343    /// # Errors
344    ///
345    /// Returns [`Error::DatabaseLocked`] if another process holds the local DB lock.
346    /// Returns [`Error::ReplicaLocked`] if another process holds the bucket lock.
347    /// Returns [`Error::WrongWriter`] if another server owns this bucket prefix.
348    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        // Acquire exclusive file lock on the database to prevent two processes
362        // from opening the same DB. This is kernel-enforced and released on process death.
363        let db_lock_file = acquire_db_lock(config.db_path())?;
364
365        // Verify writer identity — make sure THIS process is the authorized
366        // writer for this bucket prefix. writer.json is permanent (survives shutdown).
367        verify_writer_id(&bucket, bucket.prefix(), bucket.writer_id()).await?;
368
369        // Acquire bucket replica lock to prevent two processes anywhere from
370        // replicating to the same bucket prefix.
371        let _replica_lock_guard = if config.replica_lock_enabled() {
372            let (replica_lock, replica_lock_etag) = acquire_replica_lock(&bucket).await?;
373
374            // Start heartbeat task for the replica lock
375            // Uses put_if_match with our etag — if another process force-acquired
376            // our lock, our heartbeat fails safely instead of overwriting theirs.
377            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(), &current_etag)
395                        .await
396                    {
397                        Ok(()) => {
398                            // Update our etag for next heartbeat
399                            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                            // Another process acquired our lock — stop heartbeating
407                            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        // Validate bucket integrity after restore — check that all referenced
425        // objects exist and checksums match. Log warnings for inconsistencies.
426        {
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    /// Wait for all pending WAL frames to be shipped to the bucket.
540    ///
541    /// Returns once the shipper has caught up, or times out after `sync_timeout`
542    /// (default 5s). On timeout, returns an error — the WAL frames remain locally
543    /// and will be retried on the next sync.
544    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            // Wait for the shipper to signal completion, with a fallback poll.
582            // sync_notify fires when the shipper completes a sync cycle.
583            let remaining = deadline.saturating_duration_since(Instant::now());
584            tokio::select! {
585                _ = self.sync_notify.notified() => {
586                    // Shipper completed a sync — check again on next iteration
587                }
588                _ = tokio::time::sleep(remaining.min(std::time::Duration::from_millis(50))) => {
589                    // Timeout or poll interval — check shipped_frames again
590                }
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    /// Run a closure with exclusive access to the [`rusqlite::Connection`].
630    ///
631    /// This is the preferred way to execute SQL. The connection is held under
632    /// a Tokio mutex, so the closure should be short-lived.
633    ///
634    /// # Example
635    ///
636    /// ```ignore
637    /// layer.with_conn(|conn| {
638    ///     conn.execute("INSERT INTO users (name) VALUES (?)", ["Alice"])
639    /// })?;
640    /// ```
641    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    /// Force an immediate snapshot upload to the bucket.
654    ///
655    /// Triggers `VACUUM INTO` and uploads the resulting DB file.
656    /// Normally snapshots happen automatically based on WAL size and time
657    /// intervals, but this is useful for ensuring data is durably in S3
658    /// before shutdown or during testing.
659    pub async fn force_snapshot(&self) -> Result<()> {
660        // Take the snapshot directly. We clear force_next afterward so the
661        // snapshot manager's run() loop doesn't also take a duplicate snapshot
662        // when it wakes up from the trigger notification.
663        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    /// Graceful shutdown — checkpoint WAL, final sync, release locks.
672    ///
673    /// This should always be called before dropping the DurabilityLayer.
674    /// If the layer is dropped without calling `shutdown()`, a warning is
675    /// logged and the WAL may not be checkpointed.
676    pub async fn shutdown(&self) -> Result<()> {
677        info!("DurabilityLayer shutting down");
678
679        // Ship all pending WAL frames before shutting down.
680        // This ensures the bucket is up-to-date before we checkpoint.
681        // Ignore timeout errors — best effort, the checkpoint will still happen.
682        if let Err(e) = self.sync_now().await {
683            warn!("Final sync on shutdown failed (data still in local WAL): {e}");
684        }
685
686        // Signal the snapshot manager to stop its loop
687        self.snapshot_mgr.shutdown_notify().notify_one();
688
689        // Now abort background tasks — the shipper has already shipped everything
690        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        // Release the bucket replica lock
700        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        // Write the current manifest generation to the sidecar file.
707        // This ensures the next open knows this DB was synced up to this
708        // generation, preventing unnecessary re-download from the bucket.
709        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    /// Logs a warning if shutdown() wasn't called.
728    /// Calling `shutdown()` explicitly is the recommended cleanup path — it
729    /// safely checkpoints the WAL on the Tokio runtime thread.
730    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
746/// Validate manifest against bucket contents after restore.
747/// Checks that all referenced objects exist and checksums are consistent.
748/// Logs warnings for inconsistencies but does NOT fail — the restore already succeeded
749/// and the DB is usable. Warnings indicate potential data integrity concerns.
750pub(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    // 1. Snapshot must exist if referenced
758    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        // A non-fresh manifest should have a snapshot
776        tracing::warn!(
777            "Bucket validation: manifest generation {} has no snapshot",
778            manifest.generation
779        );
780        warnings += 1;
781    }
782
783    // 2. L1 segments must exist
784    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    // 3. L0 segments with checksums — verify they exist
807    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    // Summary
826    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}