#[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};
static DEFAULT_WRITER_ID: OnceLock<String> = OnceLock::new();
#[async_trait]
pub trait BucketStore: Send + Sync {
fn prefix(&self) -> &str;
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>;
async fn put_file(&self, key: &str, path: &std::path::Path) -> Result<()>;
async fn get_file(&self, key: &str, dest: &std::path::Path) -> Result<PathBuf>;
async fn put_if_match(&self, key: &str, data: Bytes, etag: &str) -> Result<()>;
async fn put_if_not_exists(&self, key: &str, data: Bytes) -> Result<()>;
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
)));
}
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,
})
}
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)
}
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?
}
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, file,
);
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);
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)?;
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(),
})
}
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(),
})
}
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()),
}
}
}