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 thiserror::Error;

#[derive(Error, Debug)]
#[non_exhaustive]
pub enum Error {
    #[error("SQLite error: {0}")]
    Sqlite(#[from] rusqlite::Error),

    #[error("Object store error: {0}")]
    ObjectStore(#[from] object_store::Error),

    #[error("WAL parse error at offset {offset}: {detail}")]
    WalParse { offset: u64, detail: String },

    #[error("WAL checksum mismatch at frame {frame}: ck1 stored {stored_1:#x}, computed {computed_1:#x}; ck2 stored {stored_2:#x}, computed {computed_2:#x}")]
    WalChecksum {
        frame: u32,
        stored_1: u32,
        computed_1: u32,
        stored_2: u32,
        computed_2: u32,
    },

    #[error("Restore error: {0}")]
    Restore(String),

    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    #[error("Replication error: {0}")]
    Replication(String),

    #[error("Manifest conflict: remote is ahead (gen {remote_gen} vs local {local_gen}). Re-restore required.")]
    ManifestConflict { local_gen: u64, remote_gen: u64 },

    #[error("Snapshot error: {0}")]
    Snapshot(String),

    #[error("Configuration error: {0}")]
    Config(String),

    #[error("Serialization error: {0}")]
    Serialization(#[from] serde_json::Error),

    #[error("Task join error: {0}")]
    Join(#[from] tokio::task::JoinError),

    #[error("{0}")]
    Other(String),

    #[error(
        "Precondition failed for key '{key}': expected etag '{expected}', object was modified"
    )]
    PreconditionFailed { key: String, expected: String },

    #[error("Compaction error: {0}")]
    Compaction(String),

    #[error("Database locked by another process: {path} (PID {holder_pid})")]
    DatabaseLocked {
        path: std::path::PathBuf,
        holder_pid: u32,
    },

    #[error("Replica locked by another process: prefix '{prefix}' held by PID {holder_pid} on {holder_hostname} (last heartbeat {last_heartbeat})")]
    ReplicaLocked {
        prefix: String,
        holder_pid: u32,
        holder_hostname: String,
        last_heartbeat: String,
    },
    /// This bucket prefix belongs to another server. Your writer_id does not
    /// match writer.json in the bucket. This means you should NOT open this prefix
    /// at all — not for writing, not for reading, not for anything.
    ///
    /// Each bucket prefix has exactly ONE owner. If you need data from this prefix,
    /// use the CLI `wal-backup restore` to a separate location, or give this
    /// server its own prefix.
    #[error("THIS PREFIX BELONGS TO ANOTHER SERVER: prefix '{prefix}' is owned by '{expected_writer}', you are '{actual_writer}'. Do NOT share bucket prefixes between servers. Each server gets its own prefix.")]
    WrongWriter {
        prefix: String,
        expected_writer: String,
        actual_writer: String,
    },
}

impl Error {
    pub fn is_not_found(&self) -> bool {
        match self {
            Error::ObjectStore(e) => matches!(e, object_store::Error::NotFound { .. }),
            _ => false,
        }
    }

    pub fn is_io_not_found(&self) -> bool {
        match self {
            Error::Io(e) => e.kind() == std::io::ErrorKind::NotFound,
            _ => false,
        }
    }

    /// Returns true if the error is transient and the operation should be retried.
    /// Fatal errors (precondition failures, manifest conflicts) return false.
    pub fn is_retryable(&self) -> bool {
        match self {
            Error::ObjectStore(e) => !matches!(e, object_store::Error::NotFound { .. }),
            Error::Io(e) => matches!(
                e.kind(),
                std::io::ErrorKind::Interrupted
                    | std::io::ErrorKind::WouldBlock
                    | std::io::ErrorKind::ConnectionRefused
                    | std::io::ErrorKind::ConnectionReset
                    | std::io::ErrorKind::ConnectionAborted
                    | std::io::ErrorKind::TimedOut
                    | std::io::ErrorKind::NotConnected
            ),
            Error::PreconditionFailed { .. } => false,
            Error::ManifestConflict { .. } => false,
            Error::Config(_) => false,
            Error::WalParse { .. } => false,
            Error::WalChecksum { .. } => false,
            Error::DatabaseLocked { .. } => false,
            Error::ReplicaLocked { .. } => false,
            Error::WrongWriter { .. } => false,
            // Sqlite locking/IO errors are transient; syntax/constraint are not.
            // Be conservative: assume retryable since most errors in the
            // replication loop are IO/lock related.
            Error::Sqlite(_) => true,
            // Restore failures (missing snapshot, corrupt data) are permanent.
            Error::Restore(_) => false,
            // Replication errors (network, timeout) are transient.
            Error::Replication(_) => true,
            // Snapshot errors (disk full, temp file) may be transient.
            Error::Snapshot(_) => true,
            // Serialization errors (corrupt data) are permanent.
            Error::Serialization(_) => false,
            // Join errors (task panicked or cancelled) are permanent.
            Error::Join(_) => false,
            // Generic errors — unknown, assume permanent.
            Error::Other(_) => false,
            // Compaction errors (disk, IO) may be transient.
            Error::Compaction(_) => true,
        }
    }

    /// Returns true if this error is because another process holds the local DB lock.
    pub fn is_database_locked(&self) -> bool {
        matches!(self, Error::DatabaseLocked { .. })
    }

    /// Returns true if this error is because another process holds the bucket replica lock.
    pub fn is_replica_locked(&self) -> bool {
        matches!(self, Error::ReplicaLocked { .. })
    }

    pub fn is_wrong_writer(&self) -> bool {
        matches!(self, Error::WrongWriter { .. })
    }

    /// Returns true if this error is a precondition failure (CAS/conditional write conflict).
    pub fn is_precondition_failed(&self) -> bool {
        matches!(self, Error::PreconditionFailed { .. })
    }
}

pub type Result<T> = std::result::Result<T, Error>;