mirror of
https://github.com/block/buzz.git
synced 2026-11-27 11:41:21 +00:00
Signed-off-by: Will Pfleger <pfleger.will@gmail.com> Signed-off-by: Will Pfleger <wpfleger@block.xyz> Signed-off-by: Will Pfleger <wpfleger@squareup.com> Signed-off-by: Will Pfleger <wpfleger96@gmail.com> Co-authored-by: npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7 <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@sprout-oss.stage.blox.sqprod.co> Co-authored-by: npub1fgdl5qqnh3k3f2xkqrvt7cujalhm623x4s7fdjdj5yrtp5fzjl9qrjpucw <4a1bfa0013bc6d14a8d600d8bf6392efefbd2a26ac3c96c9b2a106b0d12297ca@sprout-oss.stage.blox.sqprod.co> Co-authored-by: npub16v54tttfqacx9ycvc3k0ut0npj564ahcuajzy6qjvh57ntmsf4uq4806j2 <d32955ad69077062930cc46cfe2df30ca9aaf6f8e76422681265e9e9af704d78@sprout-oss.stage.blox.sqprod.co> Co-authored-by: Will Pfleger <wpfleger96@gmail.com>
192 lines
7.0 KiB
Rust
192 lines
7.0 KiB
Rust
//! S3/MinIO storage client.
|
|
|
|
use std::path::Path;
|
|
use std::pin::Pin;
|
|
|
|
use crate::config::MediaConfig;
|
|
use crate::error::MediaError;
|
|
use bytes::Bytes;
|
|
use s3::creds::Credentials;
|
|
use s3::{Bucket, Region};
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
/// A stream of byte chunks from S3, usable with `axum::body::Body::from_stream()`.
|
|
pub type ByteStream = Pin<Box<dyn futures_core::Stream<Item = Result<Bytes, MediaError>> + Send>>;
|
|
|
|
/// S3-compatible object storage client.
|
|
pub struct MediaStorage {
|
|
bucket: Box<Bucket>,
|
|
}
|
|
|
|
impl MediaStorage {
|
|
/// Create a new storage client from config.
|
|
pub fn new(config: &MediaConfig) -> Result<Self, MediaError> {
|
|
let region = Region::Custom {
|
|
region: "us-east-1".into(),
|
|
endpoint: config.s3_endpoint.clone(),
|
|
};
|
|
let creds = Credentials::new(
|
|
Some(&config.s3_access_key),
|
|
Some(&config.s3_secret_key),
|
|
None,
|
|
None,
|
|
None,
|
|
)
|
|
.map_err(|e| MediaError::StorageError(e.to_string()))?;
|
|
let bucket = Bucket::new(&config.s3_bucket, region, creds)
|
|
.map_err(|e| MediaError::StorageError(e.to_string()))?
|
|
.with_path_style();
|
|
Ok(Self { bucket })
|
|
}
|
|
|
|
/// Store an object from a byte slice.
|
|
///
|
|
/// Used for images, sidecars, and thumbnails. For large video files use
|
|
/// [`put_file`] to avoid loading the entire blob into RAM.
|
|
pub async fn put(&self, key: &str, bytes: &[u8], content_type: &str) -> Result<(), MediaError> {
|
|
self.bucket
|
|
.put_object_with_content_type(key, bytes, content_type)
|
|
.await?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Stream a file from disk into S3 without loading it into RAM.
|
|
///
|
|
/// Uses rust-s3's `put_object_stream_with_content_type` which reads from
|
|
/// the file incrementally via an 8 MiB `BufReader`. The full file is never
|
|
/// held in memory simultaneously. Intended for video blobs (up to 500 MB).
|
|
pub async fn put_file(
|
|
&self,
|
|
key: &str,
|
|
path: &Path,
|
|
content_type: &str,
|
|
) -> Result<(), MediaError> {
|
|
const BUF: usize = 8 * 1024 * 1024; // 8 MiB read buffer
|
|
|
|
let file = tokio::fs::File::open(path)
|
|
.await
|
|
.map_err(|e| MediaError::Io(e.to_string()))?;
|
|
let mut reader = tokio::io::BufReader::with_capacity(BUF, file);
|
|
|
|
self.bucket
|
|
.put_object_stream_with_content_type(&mut reader, key, content_type)
|
|
.await?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Retrieve an object's bytes.
|
|
pub async fn get(&self, key: &str) -> Result<Vec<u8>, MediaError> {
|
|
match self.bucket.get_object(key).await {
|
|
Ok(response) => Ok(response.to_vec()),
|
|
Err(s3::error::S3Error::HttpFailWithBody(404, _)) => Err(MediaError::NotFound),
|
|
Err(e) => Err(MediaError::StorageError(e.to_string())),
|
|
}
|
|
}
|
|
|
|
/// Retrieve a byte range from an object via S3-native `Range` GET.
|
|
///
|
|
/// `start` and `end` are inclusive byte offsets. Only the requested slice
|
|
/// is transferred from S3 — the full object is never loaded into RAM.
|
|
/// Intended for HTTP 206 range responses on large video blobs.
|
|
pub async fn get_range(&self, key: &str, start: u64, end: u64) -> Result<Vec<u8>, MediaError> {
|
|
match self.bucket.get_object_range(key, start, Some(end)).await {
|
|
Ok(response) => Ok(response.to_vec()),
|
|
Err(s3::error::S3Error::HttpFailWithBody(404, _)) => Err(MediaError::NotFound),
|
|
Err(e) => Err(MediaError::StorageError(e.to_string())),
|
|
}
|
|
}
|
|
|
|
/// Stream an object's bytes from S3 without loading into RAM.
|
|
///
|
|
/// Returns a pinned stream of `Result<Bytes, MediaError>` chunks.
|
|
/// The full object is never buffered — intended for streaming large
|
|
/// blobs (video) directly into HTTP responses via `Body::from_stream()`.
|
|
pub async fn get_stream(&self, key: &str) -> Result<ByteStream, MediaError> {
|
|
let response = self
|
|
.bucket
|
|
.get_object_stream(key)
|
|
.await
|
|
.map_err(|e| MediaError::StorageError(e.to_string()))?;
|
|
|
|
if response.status_code == 404 {
|
|
return Err(MediaError::NotFound);
|
|
}
|
|
|
|
let stream = futures_util::StreamExt::map(response.bytes, |chunk| {
|
|
chunk.map_err(|e| MediaError::StorageError(e.to_string()))
|
|
});
|
|
Ok(Box::pin(stream))
|
|
}
|
|
|
|
/// Check if an object exists. Returns false on 404.
|
|
pub async fn head(&self, key: &str) -> Result<bool, MediaError> {
|
|
match self.bucket.head_object(key).await {
|
|
Ok(_) => Ok(true),
|
|
Err(s3::error::S3Error::HttpFailWithBody(404, _)) => Ok(false),
|
|
Err(e) => Err(MediaError::StorageError(e.to_string())),
|
|
}
|
|
}
|
|
|
|
/// Delete an object. Returns an error on failure — callers decide whether to propagate.
|
|
pub async fn delete(&self, key: &str) -> Result<(), MediaError> {
|
|
self.bucket
|
|
.delete_object(key)
|
|
.await
|
|
.map_err(|e| MediaError::StorageError(e.to_string()))?;
|
|
Ok(())
|
|
}
|
|
|
|
/// HEAD with metadata — returns Content-Length (size).
|
|
pub async fn head_with_metadata(&self, key: &str) -> Result<Option<BlobHeadMeta>, MediaError> {
|
|
match self.bucket.head_object(key).await {
|
|
Ok((result, _)) => Ok(Some(BlobHeadMeta {
|
|
size: result.content_length.unwrap_or(0) as u64,
|
|
})),
|
|
Err(s3::error::S3Error::HttpFailWithBody(404, _)) => Ok(None),
|
|
Err(e) => Err(MediaError::StorageError(e.to_string())),
|
|
}
|
|
}
|
|
|
|
/// Read sidecar JSON for a given sha256 (bare hash, no extension).
|
|
pub async fn get_sidecar(&self, sha256: &str) -> Result<BlobMeta, MediaError> {
|
|
let key = format!("_meta/{sha256}.json");
|
|
let resp = self.bucket.get_object(&key).await?;
|
|
let meta: BlobMeta = serde_json::from_slice(&resp.to_vec())?;
|
|
Ok(meta)
|
|
}
|
|
|
|
/// Convenience: read just the MIME type from the sidecar.
|
|
pub async fn read_sidecar_mime(&self, sha256_ext: &str) -> Option<String> {
|
|
let sha256 = sha256_ext.split('.').next().unwrap_or(sha256_ext);
|
|
self.get_sidecar(sha256).await.ok().map(|m| m.mime_type)
|
|
}
|
|
}
|
|
|
|
/// Metadata returned by HEAD — just enough for BUD-01 response headers.
|
|
pub struct BlobHeadMeta {
|
|
pub size: u64,
|
|
}
|
|
|
|
/// Full blob metadata — stored as sidecar JSON in `_meta/{sha256}.json`.
|
|
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
|
pub struct BlobMeta {
|
|
/// Pixel dimensions ("WxH").
|
|
pub dim: String,
|
|
/// Blurhash string.
|
|
pub blurhash: String,
|
|
/// Full URL to thumbnail.
|
|
pub thumb_url: String,
|
|
/// File extension (e.g. "jpg").
|
|
pub ext: String,
|
|
/// MIME type (e.g. "image/jpeg").
|
|
pub mime_type: String,
|
|
/// File size in bytes.
|
|
pub size: u64,
|
|
/// Unix timestamp when the blob was first uploaded.
|
|
#[serde(default)]
|
|
pub uploaded_at: i64,
|
|
/// Video duration in seconds. `None` for non-video blobs.
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub duration_secs: Option<f64>,
|
|
}
|