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
16static DEFAULT_WRITER_ID: OnceLock<String> = OnceLock::new();
21
22#[async_trait]
45pub trait BucketStore: Send + Sync {
53 fn prefix(&self) -> &str;
56
57 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 async fn put_file(&self, key: &str, path: &std::path::Path) -> Result<()>;
71
72 async fn get_file(&self, key: &str, dest: &std::path::Path) -> Result<PathBuf>;
75
76 async fn put_if_match(&self, key: &str, data: Bytes, etag: &str) -> Result<()>;
80
81 async fn put_if_not_exists(&self, key: &str, data: Bytes) -> Result<()>;
85
86 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 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 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 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 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, file,
200 );
201
202 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 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 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 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 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}