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 async_trait::async_trait;
use bytes::Bytes;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;

use wal_backup::error::Error;
use wal_backup::storage::BucketStore;

#[allow(dead_code)]
pub struct InMemoryStore {
    data: std::sync::Mutex<HashMap<String, (Vec<u8>, u64)>>,
    counter: std::sync::Mutex<u64>,
    prefix: String,
    writer_id: String,
}

#[allow(dead_code)]
impl InMemoryStore {
    pub fn new() -> Self {
        Self {
            data: std::sync::Mutex::new(HashMap::new()),
            counter: std::sync::Mutex::new(0),
            prefix: "test".to_string(),
            writer_id: "test-writer".to_string(),
        }
    }

    pub fn with_data(initial: HashMap<String, Vec<u8>>) -> Self {
        Self {
            data: std::sync::Mutex::new(initial.into_iter().map(|(k, v)| (k, (v, 0))).collect()),
            counter: std::sync::Mutex::new(0),
            prefix: "test".to_string(),
            writer_id: "test-writer".to_string(),
        }
    }

    pub fn arc() -> Arc<Self> {
        Arc::new(Self::new())
    }

    #[allow(dead_code)]
    pub fn arc_with_data(initial: HashMap<String, Vec<u8>>) -> Arc<Self> {
        Arc::new(Self::with_data(initial))
    }

    #[allow(dead_code)]
    pub fn get_raw(&self, key: &str) -> Option<Vec<u8>> {
        self.data.lock().unwrap().get(key).map(|(v, _)| v.clone())
    }
}

#[async_trait]
impl BucketStore for InMemoryStore {
    fn prefix(&self) -> &str {
        &self.prefix
    }
    fn writer_id(&self) -> &str {
        &self.writer_id
    }
    async fn put(&self, key: &str, data: Bytes) -> Result<(), Error> {
        let mut counter = self.counter.lock().unwrap();
        *counter += 1;
        let _etag = format!("etag-{}", *counter);
        self.data
            .lock()
            .unwrap()
            .insert(key.to_string(), (data.to_vec(), *counter));
        Ok(())
    }

    async fn get(&self, key: &str) -> Result<Option<Bytes>, Error> {
        self.get_with_etag(key).await.map(|opt| opt.map(|(b, _)| b))
    }

    async fn get_with_etag(&self, key: &str) -> Result<Option<(Bytes, String)>, Error> {
        Ok(self
            .data
            .lock()
            .unwrap()
            .get(key)
            .map(|(v, c)| (Bytes::from(v.clone()), format!("etag-{}", c))))
    }

    async fn list(&self, prefix: &str) -> Result<Vec<String>, Error> {
        Ok(self
            .data
            .lock()
            .unwrap()
            .keys()
            .filter(|k| k.starts_with(prefix))
            .cloned()
            .collect())
    }

    async fn delete(&self, key: &str) -> Result<(), Error> {
        self.data.lock().unwrap().remove(key);
        Ok(())
    }

    async fn exists(&self, key: &str) -> Result<bool, Error> {
        Ok(self.data.lock().unwrap().contains_key(key))
    }

    async fn put_file(&self, key: &str, path: &std::path::Path) -> Result<(), Error> {
        let data = tokio::fs::read(path)
            .await
            .map_err(|e| Error::Other(format!("failed to read file: {e}")))?;
        let mut counter = self.counter.lock().unwrap();
        *counter += 1;
        self.data
            .lock()
            .unwrap()
            .insert(key.to_string(), (data, *counter));
        Ok(())
    }

    async fn get_file(&self, key: &str, dest: &std::path::Path) -> Result<PathBuf, Error> {
        use tokio::io::AsyncWriteExt;
        let data = self
            .data
            .lock()
            .unwrap()
            .get(key)
            .cloned()
            .ok_or_else(|| Error::Other(format!("Snapshot not found: {key}")))?
            .0;
        let tmp_path = dest.with_extension("tmp");
        let mut file = tokio::fs::File::create(&tmp_path).await?;
        file.write_all(&data).await?;
        file.flush().await?;
        file.sync_all().await?;
        tokio::fs::rename(&tmp_path, dest).await?;
        Ok(dest.to_path_buf())
    }

    async fn put_if_match(&self, key: &str, data: Bytes, etag: &str) -> Result<(), Error> {
        // Check precondition while holding the lock, then release before calling put
        let etag_ok = {
            let guard = self.data.lock().unwrap();
            match guard.get(key) {
                Some((_, counter)) => {
                    let current_etag = format!("etag-{}", counter);
                    current_etag == etag
                }
                None => false,
            }
        };
        if !etag_ok {
            return Err(Error::PreconditionFailed {
                key: key.to_string(),
                expected: etag.to_string(),
            });
        }
        self.put(key, data).await
    }

    async fn put_if_not_exists(&self, key: &str, data: Bytes) -> Result<(), Error> {
        {
            let guard = self.data.lock().unwrap();
            if guard.contains_key(key) {
                return Err(Error::PreconditionFailed {
                    key: key.to_string(),
                    expected: "<not exists>".to_string(),
                });
            }
        } // guard dropped here before .await
        self.put(key, data).await
    }
}
pub struct FailOnManifestStore {
    inner: InMemoryStore,
    fail_manifest: std::sync::atomic::AtomicBool,
    fail_precondition: std::sync::atomic::AtomicBool,
}

#[allow(dead_code)]
impl FailOnManifestStore {
    pub fn new() -> Self {
        Self {
            inner: InMemoryStore::new(),
            fail_manifest: std::sync::atomic::AtomicBool::new(true),
            fail_precondition: std::sync::atomic::AtomicBool::new(false),
        }
    }

    pub fn arc() -> Arc<Self> {
        Arc::new(Self::new())
    }

    #[allow(dead_code)]
    pub fn stop_failing(&self) {
        self.fail_manifest
            .store(false, std::sync::atomic::Ordering::Relaxed);
    }

    #[allow(dead_code)]
    pub fn set_precondition_failure(&self, enabled: bool) {
        self.fail_precondition
            .store(enabled, std::sync::atomic::Ordering::Relaxed);
    }
}

#[async_trait]
impl BucketStore for FailOnManifestStore {
    fn prefix(&self) -> &str {
        self.inner.prefix()
    }
    fn writer_id(&self) -> &str {
        self.inner.writer_id()
    }
    async fn put(&self, key: &str, data: Bytes) -> Result<(), Error> {
        if key == "manifest.json"
            && self
                .fail_manifest
                .load(std::sync::atomic::Ordering::Relaxed)
        {
            return Err(Error::Other("simulated manifest write failure".into()));
        }
        self.inner.put(key, data).await
    }

    async fn get(&self, key: &str) -> Result<Option<Bytes>, Error> {
        self.inner.get(key).await
    }

    async fn get_with_etag(&self, key: &str) -> Result<Option<(Bytes, String)>, Error> {
        self.inner.get_with_etag(key).await
    }

    async fn list(&self, prefix: &str) -> Result<Vec<String>, Error> {
        self.inner.list(prefix).await
    }

    async fn delete(&self, key: &str) -> Result<(), Error> {
        self.inner.delete(key).await
    }

    async fn exists(&self, key: &str) -> Result<bool, Error> {
        self.inner.exists(key).await
    }

    async fn put_file(&self, key: &str, path: &std::path::Path) -> Result<(), Error> {
        if key == "manifest.json"
            && self
                .fail_manifest
                .load(std::sync::atomic::Ordering::Relaxed)
        {
            return Err(Error::Other("simulated manifest write failure".into()));
        }
        self.inner.put_file(key, path).await
    }

    async fn get_file(&self, key: &str, dest: &std::path::Path) -> Result<PathBuf, Error> {
        self.inner.get_file(key, dest).await
    }

    async fn put_if_match(&self, key: &str, data: Bytes, etag: &str) -> Result<(), Error> {
        if key == "manifest.json"
            && self
                .fail_manifest
                .load(std::sync::atomic::Ordering::Relaxed)
        {
            return Err(Error::Other("simulated manifest write failure".into()));
        }
        if key == "manifest.json"
            && self
                .fail_precondition
                .load(std::sync::atomic::Ordering::Relaxed)
        {
            return Err(Error::PreconditionFailed {
                key: key.to_string(),
                expected: etag.to_string(),
            });
        }
        self.inner.put_if_match(key, data, etag).await
    }

    async fn put_if_not_exists(&self, key: &str, data: Bytes) -> Result<(), Error> {
        self.inner.put_if_not_exists(key, data).await
    }
}