Skip to main content

wal_backup/storage/
mod.rs

1#[cfg(feature = "compression")]
2pub mod compressed;
3#[cfg(feature = "encryption")]
4pub mod encrypted;
5pub mod object_store_util;
6
7use crate::error::Result;
8use async_trait::async_trait;
9use bytes::Bytes;
10use futures::StreamExt;
11use object_store::path::Path;
12use object_store::ObjectStore;
13use std::path::PathBuf;
14use std::sync::{Arc, OnceLock};
15
16/// Process-wide default writer_id generated once on first use.
17/// Ensures that multiple `ObjectStoreBucket` instances in the same
18/// process share the same fallback writer_id, while different
19/// processes (pods, containers) never collide.
20static DEFAULT_WRITER_ID: OnceLock<String> = OnceLock::new();
21
22/// Bucket-based object storage backend for wal-backup.
23///
24/// # Architecture: one prefix, one owner
25///
26/// Each bucket prefix (e.g. `s3://my-bucket/prod-app`) belongs to exactly ONE server.
27/// That ownership is recorded in `writer.json` in the bucket, and verified:
28///
29/// 1. At `DurabilityLayer::open()` — the gate
30/// 2. Every shipper loop iteration — continuous guard
31/// 3. Every snapshot loop iteration — continuous guard
32///
33/// If another server tries to open the same prefix, it gets `Error::WrongWriter`.
34///
35/// **The bucket is NOT a replication bus.** It's a backup. The pattern is:
36///
37/// ```text
38/// Server A → writes to s3://bucket/server-a-prefix   (A's backup)
39/// Server B → writes to s3://bucket/server-b-prefix   (B's backup)
40/// ```
41///
42/// If you need data from another server's prefix, use `wal-backup restore`
43/// to a separate location. Don't share prefixes between servers.
44#[async_trait]
45/// Trait for S3-compatible object storage backends.
46///
47/// Each `BucketStore` is scoped to a single prefix (e.g. `"my-app"`).
48/// One prefix = one server. The bucket is NOT a replication bus.
49///
50/// Implementations: [`ObjectStoreBucket`], `CompressedBucketStore` (feature),
51/// `EncryptedBucketStore` (feature), `InMemoryStore` (tests only).
52pub trait BucketStore: Send + Sync {
53    /// The bucket prefix this store is scoped to (e.g. "my-app/db1").
54    /// Each prefix has exactly one owner — see module docs.
55    fn prefix(&self) -> &str;
56
57    /// Identity of this writer. Stored in writer.json in the bucket.
58    /// Verified on open and every background loop iteration.
59    /// If another server tries to use this prefix, they get Error::WrongWriter.
60    fn writer_id(&self) -> &str;
61
62    async fn put(&self, key: &str, data: Bytes) -> Result<()>;
63    async fn get(&self, key: &str) -> Result<Option<Bytes>>;
64    async fn list(&self, prefix: &str) -> Result<Vec<String>>;
65    async fn delete(&self, key: &str) -> Result<()>;
66    async fn exists(&self, key: &str) -> Result<bool>;
67
68    /// Stream a local file to object storage. Avoids loading the entire file
69    /// into memory, making it safe for large database snapshots.
70    async fn put_file(&self, key: &str, path: &std::path::Path) -> Result<()>;
71
72    /// Stream from object storage directly to a local file. Avoids loading
73    /// the entire object into memory. Returns the file path on success.
74    async fn get_file(&self, key: &str, dest: &std::path::Path) -> Result<PathBuf>;
75
76    /// Put data with an ETag precondition. Fails with `PreconditionFailed` if the
77    /// object's current ETag does not match `etag`. This enables optimistic
78    /// concurrency control for manifest writes.
79    async fn put_if_match(&self, key: &str, data: Bytes, etag: &str) -> Result<()>;
80
81    /// Atomically create an object only if it does not already exist.
82    /// Returns `Ok(())` if created, `Err(Error::PreconditionFailed)` if already exists.
83    /// This is the key primitive for acquiring distributed locks.
84    async fn put_if_not_exists(&self, key: &str, data: Bytes) -> Result<()>;
85
86    /// Internal: get object data and its ETag. Used to populate manifest.etag
87    /// after reading the manifest from bucket.
88    ///
89    /// Note: this loads the full object into memory via `bytes().await`.
90    /// This is acceptable because it's only used for the manifest (small JSON),
91    /// not for large snapshots (which use `get_file()` for streaming).
92    async fn get_with_etag(&self, key: &str) -> Result<Option<(Bytes, String)>>;
93}
94
95pub struct ObjectStoreBucket {
96    inner: Arc<dyn ObjectStore>,
97    prefix: String,
98    writer_id: String,
99}
100
101impl ObjectStoreBucket {
102    pub fn new(store: Arc<dyn ObjectStore>, prefix: String) -> Result<Self> {
103        let prefix = prefix.trim_end_matches('/').to_string();
104        if prefix.contains("..") || prefix.contains('\0') || prefix.starts_with('/') {
105            return Err(crate::error::Error::Config(format!(
106                "ObjectStoreBucket prefix must not contain path traversal, null bytes, or be absolute: {}",
107                prefix
108            )));
109        }
110        // Default writer_id from hostname — stable across restarts.
111        // If hostname is unavailable (common in containers), generate a
112        // nanosecond-timestamp fallback so two pods never share "unknown".
113        let writer_id = std::env::var("HOSTNAME")
114            .or_else(|_| std::env::var("HOST"))
115            .unwrap_or_else(|_| {
116                DEFAULT_WRITER_ID
117                    .get_or_init(|| {
118                        let ts = std::time::SystemTime::now()
119                            .duration_since(std::time::UNIX_EPOCH)
120                            .unwrap_or_default()
121                            .as_nanos();
122                        format!("unknown-{ts}")
123                    })
124                    .clone()
125            });
126        Ok(ObjectStoreBucket {
127            inner: store,
128            prefix,
129            writer_id,
130        })
131    }
132
133    /// Set the writer identity for this bucket connection. Stored in writer.json
134    /// in the bucket to prevent a wrong server from writing to this prefix.
135    ///
136    /// This is the "who am I" check. Set it to something that uniquely identifies
137    /// this deployment — e.g. "web-server-1", "prod-us-east".
138    ///
139    /// If another server tries to open the same bucket prefix with a different
140    /// writer_id, it gets `Error::WrongWriter`.
141    ///
142    /// If not set, defaults to the machine's hostname.
143    pub fn with_writer_id(mut self, id: impl Into<String>) -> Self {
144        self.writer_id = id.into();
145        self
146    }
147
148    fn full_path(&self, key: &str) -> Result<Path> {
149        if key.contains("..") || key.contains('\0') || key.starts_with('/') {
150            return Err(crate::error::Error::Config(format!(
151                "object key must not contain path traversal, null bytes, or be absolute: {key}"
152            )));
153        }
154        let path = if self.prefix.is_empty() {
155            Path::from(key)
156        } else {
157            Path::from(format!("{}/{}", self.prefix, key))
158        };
159        Ok(path)
160    }
161
162    /// Small file upload: read entire file into memory, single PUT.
163    /// For files under the multipart threshold (64MB).
164    async fn put_file_single(&self, full_path: &Path, path: &std::path::Path) -> Result<()> {
165        let path = path.to_path_buf();
166        let inner = self.inner.clone();
167        let full_path = full_path.clone();
168
169        tokio::task::spawn_blocking(move || {
170            let runtime = tokio::runtime::Handle::current();
171            runtime.block_on(async {
172                let data = tokio::fs::read(&path)
173                    .await
174                    .map_err(crate::error::Error::Io)?;
175                inner
176                    .put(&full_path, data.into())
177                    .await
178                    .map_err(crate::error::Error::ObjectStore)?;
179                Ok(())
180            })
181        })
182        .await?
183    }
184
185    /// Large file upload: stream file contents through multipart upload.
186    /// Memory usage is bounded by the part size (~5MB), not the file size.
187    async fn put_file_streaming(&self, full_path: &Path, path: &std::path::Path) -> Result<()> {
188        use object_store::MultipartUpload;
189
190        let mut upload = self
191            .inner
192            .put_multipart(full_path)
193            .await
194            .map_err(crate::error::Error::ObjectStore)?;
195
196        let file = tokio::fs::File::open(path).await?;
197        let mut reader = tokio::io::BufReader::with_capacity(
198            5 * 1024 * 1024, // 5MB read buffer matches part size
199            file,
200        );
201
202        // Stream file contents in 5MB parts (required by most object stores)
203        let mut buf = vec![0u8; 5 * 1024 * 1024];
204        loop {
205            let n = tokio::io::AsyncReadExt::read(&mut reader, &mut buf).await?;
206            if n == 0 {
207                break;
208            }
209            let part_data = bytes::Bytes::copy_from_slice(&buf[..n]);
210            upload
211                .put_part(part_data.into())
212                .await
213                .map_err(|e| crate::error::Error::Other(format!("multipart put_part: {e}")))?;
214        }
215
216        upload
217            .complete()
218            .await
219            .map_err(|e| crate::error::Error::Other(format!("multipart complete: {e}")))?;
220
221        Ok(())
222    }
223}
224
225#[async_trait]
226impl BucketStore for ObjectStoreBucket {
227    fn prefix(&self) -> &str {
228        &self.prefix
229    }
230    fn writer_id(&self) -> &str {
231        &self.writer_id
232    }
233
234    async fn put(&self, key: &str, data: Bytes) -> Result<()> {
235        let path = self.full_path(key)?;
236        self.inner.put(&path, data.into()).await?;
237        Ok(())
238    }
239
240    async fn get(&self, key: &str) -> Result<Option<Bytes>> {
241        self.get_with_etag(key).await.map(|opt| opt.map(|(b, _)| b))
242    }
243
244    async fn get_with_etag(&self, key: &str) -> Result<Option<(Bytes, String)>> {
245        use object_store::Error as ObjError;
246        let path = self.full_path(key)?;
247        match self.inner.get(&path).await {
248            Ok(result) => {
249                let etag = result
250                    .meta
251                    .e_tag
252                    .clone()
253                    .unwrap_or_else(|| "unknown".to_string());
254                let bytes = result.bytes().await?;
255                Ok(Some((bytes, etag)))
256            }
257            Err(ObjError::NotFound { .. }) => Ok(None),
258            Err(e) => Err(e.into()),
259        }
260    }
261
262    async fn list(&self, prefix: &str) -> Result<Vec<String>> {
263        let path = self.full_path(prefix)?;
264        let mut results = Vec::new();
265        let mut stream = self.inner.list(Some(&path));
266        let prefix_path = Path::from(self.prefix.as_str());
267
268        while let Some(meta) = stream.next().await {
269            let meta = meta?;
270            let stripped = match meta.location.prefix_match(&prefix_path) {
271                Some(parts) => parts
272                    .map(|p| p.as_ref().to_string())
273                    .collect::<Vec<_>>()
274                    .join("/"),
275                None => {
276                    tracing::warn!(
277                        "list result {} does not match bucket prefix {}, returning full path",
278                        meta.location,
279                        self.prefix
280                    );
281                    meta.location.to_string()
282                }
283            };
284            results.push(stripped);
285        }
286
287        Ok(results)
288    }
289
290    async fn delete(&self, key: &str) -> Result<()> {
291        let path = self.full_path(key)?;
292        self.inner.delete(&path).await?;
293        Ok(())
294    }
295
296    async fn exists(&self, key: &str) -> Result<bool> {
297        use object_store::Error as ObjError;
298        let path = self.full_path(key)?;
299        match self.inner.head(&path).await {
300            Ok(_) => Ok(true),
301            Err(ObjError::NotFound { .. }) => Ok(false),
302            Err(e) => Err(e.into()),
303        }
304    }
305
306    async fn put_file(&self, key: &str, path: &std::path::Path) -> Result<()> {
307        let full_path = self.full_path(key)?;
308        let file_size = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);
309
310        // For files larger than 64MB, use streaming multipart upload to avoid
311        // loading the entire file into memory. For smaller files, use the
312        // simpler single-put path.
313        const MULTIPART_THRESHOLD: u64 = 64 * 1024 * 1024;
314
315        if file_size >= MULTIPART_THRESHOLD {
316            self.put_file_streaming(&full_path, path).await
317        } else {
318            self.put_file_single(&full_path, path).await
319        }
320    }
321
322    async fn get_file(&self, key: &str, dest: &std::path::Path) -> Result<PathBuf> {
323        use object_store::Error as ObjError;
324        use tokio::io::AsyncWriteExt;
325        let path = self.full_path(key)?;
326        // Stream directly from object storage to disk — no full blob in memory.
327        // Use async I/O so no spawn_blocking needed for the write.
328        let result = match self.inner.get(&path).await {
329            Ok(r) => r,
330            Err(ObjError::NotFound { .. }) => {
331                return Err(crate::error::Error::Other(format!(
332                    "Snapshot not found: {key}"
333                )))
334            }
335            Err(e) => return Err(e.into()),
336        };
337
338        let tmp_path = dest.with_extension("tmp");
339        let mut file = tokio::fs::File::create(&tmp_path).await?;
340        let stream = result.into_stream();
341        futures::pin_mut!(stream);
342        while let Some(chunk) = stream.next().await {
343            let chunk = chunk.map_err(std::io::Error::other)?;
344            file.write_all(&chunk).await?;
345        }
346        file.flush().await?;
347        file.sync_all().await?;
348        tokio::fs::rename(&tmp_path, dest).await?;
349        Ok(dest.to_path_buf())
350    }
351
352    async fn put_if_match(&self, key: &str, data: Bytes, etag: &str) -> Result<()> {
353        use object_store::{ObjectStore, PutMode, PutOptions, UpdateVersion};
354        let path = self.full_path(key)?;
355        let opts = PutOptions {
356            mode: PutMode::Update(UpdateVersion {
357                e_tag: Some(etag.to_string()),
358                version: None,
359            }),
360            ..Default::default()
361        };
362        match self.inner.put_opts(&path, data.clone().into(), opts).await {
363            Ok(_) => Ok(()),
364            Err(object_store::Error::Precondition { .. }) => {
365                Err(crate::error::Error::PreconditionFailed {
366                    key: key.to_string(),
367                    expected: etag.to_string(),
368                })
369            }
370            // Fall back to unconditional put if the store doesn't support conditional writes
371            // (e.g., local filesystem). Note: this loses atomicity — only use for testing.
372            Err(object_store::Error::NotImplemented) => {
373                tracing::warn!(
374                    "object store does not support conditional put — falling back to unconditional put for {}. \
375                     This loses atomicity: only safe for single-writer deployments (e.g. local filesystem).",
376                    key
377                );
378                self.inner.put(&path, data.into()).await?;
379                Ok(())
380            }
381            Err(e) => Err(e.into()),
382        }
383    }
384
385    async fn put_if_not_exists(&self, key: &str, data: Bytes) -> Result<()> {
386        use object_store::{ObjectStore, PutMode, PutOptions};
387        let path = self.full_path(key)?;
388        let opts = PutOptions {
389            mode: PutMode::Create,
390            ..Default::default()
391        };
392        match self.inner.put_opts(&path, data.clone().into(), opts).await {
393            Ok(_) => Ok(()),
394            Err(object_store::Error::Precondition { .. }) => {
395                Err(crate::error::Error::PreconditionFailed {
396                    key: key.to_string(),
397                    expected: "<not exists>".to_string(),
398                })
399            }
400            // Fall back to get-then-put for stores that don't support Create mode
401            Err(object_store::Error::NotImplemented) => {
402                tracing::warn!(
403                    "object store does not support Create-mode put — falling back to get-then-put for {}. \
404                     This is a TOCTOU race: only safe for single-writer deployments.",
405                    key
406                );
407                if self.inner.head(&path).await.is_ok() {
408                    return Err(crate::error::Error::PreconditionFailed {
409                        key: key.to_string(),
410                        expected: "<not exists>".to_string(),
411                    });
412                }
413                self.inner.put(&path, data.into()).await?;
414                Ok(())
415            }
416            Err(e) => Err(e.into()),
417        }
418    }
419}