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 flate2::read::GzDecoder;
use flate2::write::GzEncoder;
use flate2::Compression;
use std::path::PathBuf;
use std::sync::Arc;

use crate::error::Result;
use crate::storage::BucketStore;

const MAX_DECOMPRESSED_SIZE: usize = 2 * 1024 * 1024 * 1024;

pub struct CompressedBucketStore {
    inner: Arc<dyn BucketStore>,
    level: u32,
    max_decompressed_size: usize,
}

impl CompressedBucketStore {
    pub fn new(inner: Arc<dyn BucketStore>, level: u32) -> Self {
        CompressedBucketStore {
            inner,
            level,
            max_decompressed_size: MAX_DECOMPRESSED_SIZE,
        }
    }

    pub fn with_max_decompressed_size(mut self, limit: usize) -> Self {
        self.max_decompressed_size = limit;
        self
    }

    fn compress(&self, data: &[u8]) -> Result<Vec<u8>> {
        let mut encoder = GzEncoder::new(Vec::new(), Compression::new(self.level));
        std::io::Write::write_all(&mut encoder, data)
            .map_err(|e| crate::error::Error::Other(format!("gzip compress: {e}")))?;
        encoder
            .finish()
            .map_err(|e| crate::error::Error::Other(format!("gzip finish: {e}")))
    }

    fn decompress(&self, data: &[u8]) -> Result<Vec<u8>> {
        let mut decoder = GzDecoder::new(data);
        let mut buf = Vec::new();
        let mut chunk = [0u8; 8192];
        use std::io::Read;
        loop {
            let n = decoder
                .read(&mut chunk)
                .map_err(|e| crate::error::Error::Other(format!("gzip decompress: {e}")))?;
            if n == 0 {
                break;
            }
            if buf.len() + n > self.max_decompressed_size {
                return Err(crate::error::Error::Other(format!(
                    "decompressed data exceeds {} byte limit (possible zip bomb)",
                    self.max_decompressed_size
                )));
            }
            buf.extend_from_slice(&chunk[..n]);
        }
        Ok(buf)
    }
}

#[async_trait]
impl BucketStore for CompressedBucketStore {
    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<()> {
        let compressed = self.compress(&data)?;
        self.inner.put(key, Bytes::from(compressed)).await
    }

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

    async fn get_with_etag(&self, key: &str) -> Result<Option<(Bytes, String)>> {
        // Delegate to inner's get_with_etag to get the real ETag.
        // The ETag refers to the compressed data on S3, which is correct for
        // put_if_match (which compresses first, then sends the compressed
        // data with the ETag to the inner store).
        match self.inner.get_with_etag(key).await? {
            Some((data, etag)) => {
                let decompressed = self.decompress(&data)?;
                Ok(Some((Bytes::from(decompressed), etag)))
            }
            None => Ok(None),
        }
    }

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

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

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

    async fn put_file(&self, key: &str, path: &std::path::Path) -> Result<()> {
        // Compress to a temp file (random suffix via NamedTempFile), then upload
        // via inner's streaming put_file. This avoids holding both the full
        // plaintext and compressed data in memory simultaneously.
        let level = self.level;

        // Create NamedTempFile with random name — no predictable path for symlink attacks
        let tmp_file = tempfile::NamedTempFile::new()
            .map_err(|e| crate::error::Error::Other(format!("create temp file: {e}")))?;

        // Read source file, compress, write to NamedTempFile
        tokio::task::spawn_blocking({
            let tmp_path = tmp_file.path().to_path_buf();
            let path = path.to_path_buf();
            move || -> Result<()> {
                let data = std::fs::read(&path).map_err(|e| {
                    crate::error::Error::Other(format!("failed to read file for compression: {e}"))
                })?;
                let mut encoder = GzEncoder::new(Vec::new(), Compression::new(level));
                std::io::Write::write_all(&mut encoder, &data)
                    .map_err(|e| crate::error::Error::Other(format!("gzip compress: {e}")))?;
                // Drop plaintext before finishing compression
                drop(data);
                let compressed = encoder
                    .finish()
                    .map_err(|e| crate::error::Error::Other(format!("gzip finish: {e}")))?;
                std::fs::write(&tmp_path, &compressed).map_err(|e| {
                    crate::error::Error::Other(format!("failed to write compressed temp file: {e}"))
                })?;
                Ok(())
            }
        })
        .await??;

        // Upload the compressed temp file via the inner store's streaming put_file.
        // NamedTempFile auto-deletes the temp file when it goes out of scope (RAII).
        let tmp_path = tmp_file.path().to_path_buf();
        let result = self.inner.put_file(key, &tmp_path).await;
        // Explicit drop to clean up temp file immediately (not waiting for scope exit)
        drop(tmp_file);
        result
    }

    async fn get_file(&self, key: &str, dest: &std::path::Path) -> Result<PathBuf> {
        // Stream compressed blob from inner to a temp file, then decompress
        // file-to-file in spawn_blocking. This avoids loading the full
        // compressed object into memory (only the decompress buffer is in memory).
        let compressed_tmp = dest.with_extension("compressed-tmp");
        self.inner.get_file(key, &compressed_tmp).await?;

        let tmp_path = dest.with_extension("tmp");
        let tmp_path_owned = tmp_path.clone();
        let dest_owned = dest.to_path_buf();
        let compressed_tmp_owned = compressed_tmp.clone();
        let max_size = self.max_decompressed_size;

        let result = tokio::task::spawn_blocking(move || -> Result<PathBuf> {
            use std::io::{Read, Write};
            let compressed_file = std::fs::File::open(&compressed_tmp_owned)?;
            let mut decoder = GzDecoder::new(compressed_file);
            let mut file = std::fs::File::create(&tmp_path_owned)?;
            let mut chunk = [0u8; 8192];
            let mut written: usize = 0;
            loop {
                let n = decoder
                    .read(&mut chunk)
                    .map_err(|e| crate::error::Error::Other(format!("gzip decompress: {e}")))?;
                if n == 0 {
                    break;
                }
                if written + n > max_size {
                    return Err(crate::error::Error::Other(format!(
                        "decompressed data exceeds {} byte limit (possible zip bomb)",
                        max_size
                    )));
                }
                Write::write_all(&mut file, &chunk[..n])?;
                written += n;
            }
            Write::flush(&mut file)?;
            file.sync_all()?;
            std::fs::rename(&tmp_path_owned, &dest_owned)?;
            Ok(dest_owned)
        })
        .await?;

        // Clean up the compressed temp file
        let _ = tokio::fs::remove_file(&compressed_tmp).await;
        result
    }

    async fn put_if_match(&self, key: &str, data: Bytes, etag: &str) -> Result<()> {
        // Compress first, then delegate conditional put to inner
        let compressed = self.compress(&data)?;
        self.inner
            .put_if_match(key, Bytes::from(compressed), etag)
            .await
    }

    async fn put_if_not_exists(&self, key: &str, data: Bytes) -> Result<()> {
        let compressed = self.compress(&data)?;
        self.inner
            .put_if_not_exists(key, Bytes::from(compressed))
            .await
    }
}