wal-backup 0.8.11

Embedded SQLite WAL replication to S3-compatible object storage. Not a sidecar — a library. Like Litestream, but embedded.
Documentation
use chrono::Utc;
use serde::{Deserialize, Serialize};

/// A compacted L1 file that merges multiple L0 segments into one.
/// L1 files cover a contiguous range of WAL frames and are used
/// during restore to reduce the number of GET requests.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct L1File {
    /// Object key in the bucket (e.g. "wal/salt/00000001-00005000.l1")
    pub key: String,
    /// First frame in the L1 range (inclusive)
    pub start_frame: u32,
    /// Last frame in the L1 range (inclusive)
    pub end_frame: u32,
    /// Number of L0 segments that were merged to create this L1
    pub source_count: u32,
    /// SHA256 checksum of the L1 file content ("sha256:...")
    /// None for backward compatibility with existing manifests.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub checksum: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Manifest {
    pub version: u32,
    pub generation: u64,
    pub snapshot: Option<String>,
    pub snapshot_checksum: Option<String>,
    pub current_salt_1: u32,
    pub current_salt_2: u32,
    pub page_size: u32,
    pub shipped_frames: u32,
    pub db_size: u64,
    pub last_updated: String,
    /// ETag of the manifest object in the bucket. Used for conditional writes.
    /// None means the manifest doesn't exist yet (fresh start) or we don't know the etag.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub etag: Option<String>,
    /// Compacted L1 files. These merge multiple L0 segments into fewer,
    /// larger files for efficient restore. L0 segments covered by an L1
    /// file can be safely deleted by GC.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub l1_files: Vec<L1File>,
    /// The highest frame covered by any L1 file. L0 segments with
    /// end_frame <= this value are candidates for GC after compaction.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub l1_max_frame: Option<u32>,
    /// SHA256 checksums of L0 segment files, keyed by object key.
    /// Used during restore to verify segment integrity before replay.
    /// Empty for backward compatibility with existing manifests.
    #[serde(default, skip_serializing_if = "std::collections::HashMap::is_empty")]
    pub segment_checksums: std::collections::HashMap<String, String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConflictLevel {
    None,
    LocalAhead,
    RemoteAhead,
}

impl Manifest {
    pub fn new(salt_1: u32, salt_2: u32, page_size: u32) -> Self {
        Manifest {
            version: 1,
            generation: 0,
            snapshot: None,
            snapshot_checksum: None,
            current_salt_1: salt_1,
            current_salt_2: salt_2,
            page_size,
            shipped_frames: 0,
            db_size: 0,
            last_updated: Utc::now().to_rfc3339(),
            etag: None,
            l1_files: Vec::new(),
            l1_max_frame: None,
            segment_checksums: std::collections::HashMap::new(),
        }
    }

    pub fn update_snapshot(
        &mut self,
        snapshot_path: String,
        checksum: String,
        salt_1: u32,
        salt_2: u32,
        page_size: u32,
        db_size: u64,
    ) {
        self.snapshot = Some(snapshot_path);
        self.snapshot_checksum = Some(checksum);
        self.current_salt_1 = salt_1;
        self.current_salt_2 = salt_2;
        self.page_size = page_size;
        self.shipped_frames = 0;
        self.db_size = db_size;
        self.last_updated = Utc::now().to_rfc3339();
        // After a snapshot, all L1 files are stale (they reference the old salt).
        // The snapshot resets shipped_frames to 0, so L1 files covering
        // the old frame range are no longer needed for restore.
        self.l1_files.clear();
        self.l1_max_frame = None;
        // Prune segment checksums for the old salt prefix since those segments
        // belong to the previous generation and will never be restored.
        // Keep checksums for the new salt so new segments can still be verified.
        let old_salt_prefix = format!("wal/{:08x}{:08x}/", salt_1, salt_2);
        self.segment_checksums
            .retain(|key, _| !key.starts_with(&old_salt_prefix));
    }

    pub fn update_shipped_frames(&mut self, frames: u32) {
        self.shipped_frames = frames;
        self.generation = self.generation.saturating_add(1);
        self.last_updated = Utc::now().to_rfc3339();
    }

    pub fn conflict_level(&self, remote: &Manifest) -> ConflictLevel {
        if remote.generation > self.generation {
            ConflictLevel::RemoteAhead
        } else if self.generation > remote.generation {
            ConflictLevel::LocalAhead
        } else {
            // Equal generation means both manifests are at the same point.
            // No conflict — both are consistent.
            ConflictLevel::None
        }
    }

    pub fn check_conflict(&self, remote: &Manifest) -> bool {
        self.conflict_level(remote) != ConflictLevel::None
    }

    pub fn salt_string(&self) -> String {
        format!("{}-{}", self.current_salt_1, self.current_salt_2)
    }

    pub fn is_different_salt(&self, salt_1: u32, salt_2: u32) -> bool {
        self.current_salt_1 != salt_1 || self.current_salt_2 != salt_2
    }

    pub fn segment_prefix(&self) -> String {
        format!("wal/{}/", self.salt_string())
    }

    /// Returns the highest frame covered by any L1 file, or 0 if no L1 files exist.
    /// L0 segments with end_frame <= this value are fully covered by compaction
    /// and can be safely deleted by GC.
    pub fn l1_max_frame_value(&self) -> u32 {
        self.l1_max_frame.unwrap_or(0)
    }

    /// Add an L1 file to the manifest and update l1_max_frame.
    pub fn add_l1_file(&mut self, l1: L1File) {
        let end = l1.end_frame;
        self.l1_files.push(l1);
        self.l1_max_frame = Some(end.max(self.l1_max_frame.unwrap_or(0)));
        self.last_updated = Utc::now().to_rfc3339();
    }

    /// Update the ETag after reading it from the bucket (e.g. from GET response headers).
    pub fn set_etag(&mut self, etag: String) {
        self.etag = Some(etag);
    }

    /// Set last_updated from an RFC3339 string. For test use.
    /// Panics if the string is not valid RFC3339.
    pub fn set_last_updated_str(&mut self, ts: &str) {
        self.last_updated = ts
            .parse()
            .expect("set_last_updated_str: invalid RFC3339 timestamp");
    }

    /// Create a manifest with a specific last_updated timestamp. For test use.
    /// Panics if the string is not valid RFC3339.
    pub fn with_last_updated(salt_1: u32, salt_2: u32, page_size: u32, ts: &str) -> Self {
        let mut m = Self::new(salt_1, salt_2, page_size);
        m.last_updated = ts
            .parse()
            .expect("with_last_updated: invalid RFC3339 timestamp");
        m
    }

    pub fn serialize(&self) -> crate::error::Result<Vec<u8>> {
        serde_json::to_vec(self).map_err(crate::error::Error::Serialization)
    }

    pub fn deserialize(data: &[u8]) -> crate::error::Result<Self> {
        // First parse into a raw JSON value so we can inspect the version field
        // before committing to the full deserialization. This lets us return a
        // clear error for unsupported manifest versions rather than silently
        // producing wrong data.
        let raw: serde_json::Value =
            serde_json::from_slice(data).map_err(crate::error::Error::Serialization)?;
        if let Some(v) = raw.get("version").and_then(|v| v.as_u64()) {
            if v != 1 {
                return Err(crate::error::Error::Other(format!(
                    "unsupported manifest version {} (only version 1 is supported)",
                    v
                )));
            }
        }
        serde_json::from_slice(data).map_err(crate::error::Error::Serialization)
    }
}

pub const MANIFEST_KEY: &str = "manifest.json";