wal-backup 0.8.11

Embedded SQLite WAL replication to S3-compatible object storage. Not a sidecar — a library. Like Litestream, but embedded.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
#[cfg(feature = "compression")]
pub mod compressed;
#[cfg(feature = "encryption")]
pub mod encrypted;
pub mod object_store_util;

use crate::error::Result;
use async_trait::async_trait;
use bytes::Bytes;
use futures::StreamExt;
use object_store::path::Path;
use object_store::ObjectStore;
use std::path::PathBuf;
use std::sync::{Arc, OnceLock};

/// Process-wide default writer_id generated once on first use.
/// Ensures that multiple `ObjectStoreBucket` instances in the same
/// process share the same fallback writer_id, while different
/// processes (pods, containers) never collide.
static DEFAULT_WRITER_ID: OnceLock<String> = OnceLock::new();

/// Bucket-based object storage backend for wal-backup.
///
/// # Architecture: one prefix, one owner
///
/// Each bucket prefix (e.g. `s3://my-bucket/prod-app`) belongs to exactly ONE server.
/// That ownership is recorded in `writer.json` in the bucket, and verified:
///
/// 1. At `DurabilityLayer::open()` — the gate
/// 2. Every shipper loop iteration — continuous guard
/// 3. Every snapshot loop iteration — continuous guard
///
/// If another server tries to open the same prefix, it gets `Error::WrongWriter`.
///
/// **The bucket is NOT a replication bus.** It's a backup. The pattern is:
///
/// ```text
/// Server A → writes to s3://bucket/server-a-prefix   (A's backup)
/// Server B → writes to s3://bucket/server-b-prefix   (B's backup)
/// ```
///
/// If you need data from another server's prefix, use `wal-backup restore`
/// to a separate location. Don't share prefixes between servers.
#[async_trait]
/// Trait for S3-compatible object storage backends.
///
/// Each `BucketStore` is scoped to a single prefix (e.g. `"my-app"`).
/// One prefix = one server. The bucket is NOT a replication bus.
///
/// Implementations: [`ObjectStoreBucket`], `CompressedBucketStore` (feature),
/// `EncryptedBucketStore` (feature), `InMemoryStore` (tests only).
pub trait BucketStore: Send + Sync {
    /// The bucket prefix this store is scoped to (e.g. "my-app/db1").
    /// Each prefix has exactly one owner — see module docs.
    fn prefix(&self) -> &str;

    /// Identity of this writer. Stored in writer.json in the bucket.
    /// Verified on open and every background loop iteration.
    /// If another server tries to use this prefix, they get Error::WrongWriter.
    fn writer_id(&self) -> &str;

    async fn put(&self, key: &str, data: Bytes) -> Result<()>;
    async fn get(&self, key: &str) -> Result<Option<Bytes>>;
    async fn list(&self, prefix: &str) -> Result<Vec<String>>;
    async fn delete(&self, key: &str) -> Result<()>;
    async fn exists(&self, key: &str) -> Result<bool>;

    /// Stream a local file to object storage. Avoids loading the entire file
    /// into memory, making it safe for large database snapshots.
    async fn put_file(&self, key: &str, path: &std::path::Path) -> Result<()>;

    /// Stream from object storage directly to a local file. Avoids loading
    /// the entire object into memory. Returns the file path on success.
    async fn get_file(&self, key: &str, dest: &std::path::Path) -> Result<PathBuf>;

    /// Put data with an ETag precondition. Fails with `PreconditionFailed` if the
    /// object's current ETag does not match `etag`. This enables optimistic
    /// concurrency control for manifest writes.
    async fn put_if_match(&self, key: &str, data: Bytes, etag: &str) -> Result<()>;

    /// Atomically create an object only if it does not already exist.
    /// Returns `Ok(())` if created, `Err(Error::PreconditionFailed)` if already exists.
    /// This is the key primitive for acquiring distributed locks.
    async fn put_if_not_exists(&self, key: &str, data: Bytes) -> Result<()>;

    /// Internal: get object data and its ETag. Used to populate manifest.etag
    /// after reading the manifest from bucket.
    ///
    /// Note: this loads the full object into memory via `bytes().await`.
    /// This is acceptable because it's only used for the manifest (small JSON),
    /// not for large snapshots (which use `get_file()` for streaming).
    async fn get_with_etag(&self, key: &str) -> Result<Option<(Bytes, String)>>;
}

pub struct ObjectStoreBucket {
    inner: Arc<dyn ObjectStore>,
    prefix: String,
    writer_id: String,
}

impl ObjectStoreBucket {
    pub fn new(store: Arc<dyn ObjectStore>, prefix: String) -> Result<Self> {
        let prefix = prefix.trim_end_matches('/').to_string();
        if prefix.contains("..") || prefix.contains('\0') || prefix.starts_with('/') {
            return Err(crate::error::Error::Config(format!(
                "ObjectStoreBucket prefix must not contain path traversal, null bytes, or be absolute: {}",
                prefix
            )));
        }
        // Default writer_id from hostname — stable across restarts.
        // If hostname is unavailable (common in containers), generate a
        // nanosecond-timestamp fallback so two pods never share "unknown".
        let writer_id = std::env::var("HOSTNAME")
            .or_else(|_| std::env::var("HOST"))
            .unwrap_or_else(|_| {
                DEFAULT_WRITER_ID
                    .get_or_init(|| {
                        let ts = std::time::SystemTime::now()
                            .duration_since(std::time::UNIX_EPOCH)
                            .unwrap_or_default()
                            .as_nanos();
                        format!("unknown-{ts}")
                    })
                    .clone()
            });
        Ok(ObjectStoreBucket {
            inner: store,
            prefix,
            writer_id,
        })
    }

    /// Set the writer identity for this bucket connection. Stored in writer.json
    /// in the bucket to prevent a wrong server from writing to this prefix.
    ///
    /// This is the "who am I" check. Set it to something that uniquely identifies
    /// this deployment — e.g. "web-server-1", "prod-us-east".
    ///
    /// If another server tries to open the same bucket prefix with a different
    /// writer_id, it gets `Error::WrongWriter`.
    ///
    /// If not set, defaults to the machine's hostname.
    pub fn with_writer_id(mut self, id: impl Into<String>) -> Self {
        self.writer_id = id.into();
        self
    }

    fn full_path(&self, key: &str) -> Result<Path> {
        if key.contains("..") || key.contains('\0') || key.starts_with('/') {
            return Err(crate::error::Error::Config(format!(
                "object key must not contain path traversal, null bytes, or be absolute: {key}"
            )));
        }
        let path = if self.prefix.is_empty() {
            Path::from(key)
        } else {
            Path::from(format!("{}/{}", self.prefix, key))
        };
        Ok(path)
    }

    /// Small file upload: read entire file into memory, single PUT.
    /// For files under the multipart threshold (64MB).
    async fn put_file_single(&self, full_path: &Path, path: &std::path::Path) -> Result<()> {
        let path = path.to_path_buf();
        let inner = self.inner.clone();
        let full_path = full_path.clone();

        tokio::task::spawn_blocking(move || {
            let runtime = tokio::runtime::Handle::current();
            runtime.block_on(async {
                let data = tokio::fs::read(&path)
                    .await
                    .map_err(crate::error::Error::Io)?;
                inner
                    .put(&full_path, data.into())
                    .await
                    .map_err(crate::error::Error::ObjectStore)?;
                Ok(())
            })
        })
        .await?
    }

    /// Large file upload: stream file contents through multipart upload.
    /// Memory usage is bounded by the part size (~5MB), not the file size.
    async fn put_file_streaming(&self, full_path: &Path, path: &std::path::Path) -> Result<()> {
        use object_store::MultipartUpload;

        let mut upload = self
            .inner
            .put_multipart(full_path)
            .await
            .map_err(crate::error::Error::ObjectStore)?;

        let file = tokio::fs::File::open(path).await?;
        let mut reader = tokio::io::BufReader::with_capacity(
            5 * 1024 * 1024, // 5MB read buffer matches part size
            file,
        );

        // Stream file contents in 5MB parts (required by most object stores)
        let mut buf = vec![0u8; 5 * 1024 * 1024];
        loop {
            let n = tokio::io::AsyncReadExt::read(&mut reader, &mut buf).await?;
            if n == 0 {
                break;
            }
            let part_data = bytes::Bytes::copy_from_slice(&buf[..n]);
            upload
                .put_part(part_data.into())
                .await
                .map_err(|e| crate::error::Error::Other(format!("multipart put_part: {e}")))?;
        }

        upload
            .complete()
            .await
            .map_err(|e| crate::error::Error::Other(format!("multipart complete: {e}")))?;

        Ok(())
    }
}

#[async_trait]
impl BucketStore for ObjectStoreBucket {
    fn prefix(&self) -> &str {
        &self.prefix
    }
    fn writer_id(&self) -> &str {
        &self.writer_id
    }

    async fn put(&self, key: &str, data: Bytes) -> Result<()> {
        let path = self.full_path(key)?;
        self.inner.put(&path, data.into()).await?;
        Ok(())
    }

    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)>> {
        use object_store::Error as ObjError;
        let path = self.full_path(key)?;
        match self.inner.get(&path).await {
            Ok(result) => {
                let etag = result
                    .meta
                    .e_tag
                    .clone()
                    .unwrap_or_else(|| "unknown".to_string());
                let bytes = result.bytes().await?;
                Ok(Some((bytes, etag)))
            }
            Err(ObjError::NotFound { .. }) => Ok(None),
            Err(e) => Err(e.into()),
        }
    }

    async fn list(&self, prefix: &str) -> Result<Vec<String>> {
        let path = self.full_path(prefix)?;
        let mut results = Vec::new();
        let mut stream = self.inner.list(Some(&path));
        let prefix_path = Path::from(self.prefix.as_str());

        while let Some(meta) = stream.next().await {
            let meta = meta?;
            let stripped = match meta.location.prefix_match(&prefix_path) {
                Some(parts) => parts
                    .map(|p| p.as_ref().to_string())
                    .collect::<Vec<_>>()
                    .join("/"),
                None => {
                    tracing::warn!(
                        "list result {} does not match bucket prefix {}, returning full path",
                        meta.location,
                        self.prefix
                    );
                    meta.location.to_string()
                }
            };
            results.push(stripped);
        }

        Ok(results)
    }

    async fn delete(&self, key: &str) -> Result<()> {
        let path = self.full_path(key)?;
        self.inner.delete(&path).await?;
        Ok(())
    }

    async fn exists(&self, key: &str) -> Result<bool> {
        use object_store::Error as ObjError;
        let path = self.full_path(key)?;
        match self.inner.head(&path).await {
            Ok(_) => Ok(true),
            Err(ObjError::NotFound { .. }) => Ok(false),
            Err(e) => Err(e.into()),
        }
    }

    async fn put_file(&self, key: &str, path: &std::path::Path) -> Result<()> {
        let full_path = self.full_path(key)?;
        let file_size = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);

        // For files larger than 64MB, use streaming multipart upload to avoid
        // loading the entire file into memory. For smaller files, use the
        // simpler single-put path.
        const MULTIPART_THRESHOLD: u64 = 64 * 1024 * 1024;

        if file_size >= MULTIPART_THRESHOLD {
            self.put_file_streaming(&full_path, path).await
        } else {
            self.put_file_single(&full_path, path).await
        }
    }

    async fn get_file(&self, key: &str, dest: &std::path::Path) -> Result<PathBuf> {
        use object_store::Error as ObjError;
        use tokio::io::AsyncWriteExt;
        let path = self.full_path(key)?;
        // Stream directly from object storage to disk — no full blob in memory.
        // Use async I/O so no spawn_blocking needed for the write.
        let result = match self.inner.get(&path).await {
            Ok(r) => r,
            Err(ObjError::NotFound { .. }) => {
                return Err(crate::error::Error::Other(format!(
                    "Snapshot not found: {key}"
                )))
            }
            Err(e) => return Err(e.into()),
        };

        let tmp_path = dest.with_extension("tmp");
        let mut file = tokio::fs::File::create(&tmp_path).await?;
        let stream = result.into_stream();
        futures::pin_mut!(stream);
        while let Some(chunk) = stream.next().await {
            let chunk = chunk.map_err(std::io::Error::other)?;
            file.write_all(&chunk).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<()> {
        use object_store::{ObjectStore, PutMode, PutOptions, UpdateVersion};
        let path = self.full_path(key)?;
        let opts = PutOptions {
            mode: PutMode::Update(UpdateVersion {
                e_tag: Some(etag.to_string()),
                version: None,
            }),
            ..Default::default()
        };
        match self.inner.put_opts(&path, data.clone().into(), opts).await {
            Ok(_) => Ok(()),
            Err(object_store::Error::Precondition { .. }) => {
                Err(crate::error::Error::PreconditionFailed {
                    key: key.to_string(),
                    expected: etag.to_string(),
                })
            }
            // Fall back to unconditional put if the store doesn't support conditional writes
            // (e.g., local filesystem). Note: this loses atomicity — only use for testing.
            Err(object_store::Error::NotImplemented) => {
                tracing::warn!(
                    "object store does not support conditional put — falling back to unconditional put for {}. \
                     This loses atomicity: only safe for single-writer deployments (e.g. local filesystem).",
                    key
                );
                self.inner.put(&path, data.into()).await?;
                Ok(())
            }
            Err(e) => Err(e.into()),
        }
    }

    async fn put_if_not_exists(&self, key: &str, data: Bytes) -> Result<()> {
        use object_store::{ObjectStore, PutMode, PutOptions};
        let path = self.full_path(key)?;
        let opts = PutOptions {
            mode: PutMode::Create,
            ..Default::default()
        };
        match self.inner.put_opts(&path, data.clone().into(), opts).await {
            Ok(_) => Ok(()),
            Err(object_store::Error::Precondition { .. }) => {
                Err(crate::error::Error::PreconditionFailed {
                    key: key.to_string(),
                    expected: "<not exists>".to_string(),
                })
            }
            // Fall back to get-then-put for stores that don't support Create mode
            Err(object_store::Error::NotImplemented) => {
                tracing::warn!(
                    "object store does not support Create-mode put — falling back to get-then-put for {}. \
                     This is a TOCTOU race: only safe for single-writer deployments.",
                    key
                );
                if self.inner.head(&path).await.is_ok() {
                    return Err(crate::error::Error::PreconditionFailed {
                        key: key.to_string(),
                        expected: "<not exists>".to_string(),
                    });
                }
                self.inner.put(&path, data.into()).await?;
                Ok(())
            }
            Err(e) => Err(e.into()),
        }
    }
}