use std::path::Path; use std::sync::Arc; use std::time::SystemTime; use bytes::Bytes; use forge_core::config::{R2Config, S3Config, StorageBackend, StorageConfig}; use forge_core::{Error, Result}; use futures_util::{StreamExt, TryStreamExt, stream::BoxStream}; use object_store::aws::AmazonS3Builder; use object_store::local::LocalFileSystem; use object_store::path::Path as ObjectPath; use object_store::prefix::PrefixStore; use object_store::{ObjectStore, ObjectStoreExt, WriteMultipart}; use sha2::{Digest, Sha256}; const PART_BYTES: usize = 8 * 1024 * 1024; const PARTS_IN_FLIGHT: usize = 4; pub fn asset_key(asset_id: &str) -> String { format!("assets/{asset_id}") } pub fn attachment_key(attachment_id: &str) -> String { format!("attachments/{attachment_id}") } fn storage_err(e: E) -> Error where E: std::error::Error + Send + Sync + 'static, { Error::Io(std::io::Error::other(e)) } struct S3Connection<'a> { bucket: &'a str, region: &'a str, endpoint: Option<&'a str>, prefix: &'a str, access_key_id: &'a str, secret_access_key_file: &'a Path, allow_http: bool, virtual_hosted_style: bool, } #[derive(Clone)] pub struct BlobStore { store: Arc, } pub struct BlobRead { pub size: u64, pub stream: BoxStream<'static, std::io::Result>, } impl BlobStore { pub fn from_config(cfg: &StorageConfig, data_dir: &Path) -> Result { match cfg.backend { StorageBackend::Fs => Self::open(&data_dir.join("blobs")), StorageBackend::S3 => Self::s3(&cfg.s3), StorageBackend::R2 => Self::r2(&cfg.r2), } } pub fn open(root: &Path) -> Result { std::fs::create_dir_all(root)?; let fs = LocalFileSystem::new_with_prefix(root).map_err(storage_err)?; Ok(Self::from_store(Arc::new(fs))) } fn s3(cfg: &S3Config) -> Result { Self::s3_store(S3Connection { bucket: &cfg.bucket, region: &cfg.region, endpoint: (!cfg.endpoint.is_empty()).then_some(cfg.endpoint.as_str()), prefix: &cfg.prefix, access_key_id: &cfg.access_key_id, secret_access_key_file: &cfg.secret_access_key_file, allow_http: cfg.allow_http, virtual_hosted_style: cfg.virtual_hosted_style, }) } fn r2(cfg: &R2Config) -> Result { let endpoint = cfg.endpoint(); Self::s3_store(S3Connection { bucket: &cfg.bucket, region: "auto", endpoint: Some(&endpoint), prefix: &cfg.prefix, access_key_id: &cfg.access_key_id, secret_access_key_file: &cfg.secret_access_key_file, allow_http: false, virtual_hosted_style: false, }) } fn s3_store(conn: S3Connection<'_>) -> Result { let secret = std::fs::read_to_string(conn.secret_access_key_file)?; let mut builder = AmazonS3Builder::new() .with_bucket_name(conn.bucket) .with_region(conn.region) .with_access_key_id(conn.access_key_id) .with_secret_access_key(secret.trim()) .with_allow_http(conn.allow_http) .with_virtual_hosted_style_request(conn.virtual_hosted_style); if let Some(endpoint) = conn.endpoint { builder = builder.with_endpoint(endpoint); } let s3 = builder.build().map_err(storage_err)?; let prefix = conn.prefix.trim_matches('/'); let store: Arc = if prefix.is_empty() { Arc::new(s3) } else { Arc::new(PrefixStore::new(s3, prefix)) }; Ok(Self::from_store(store)) } fn from_store(store: Arc) -> Self { Self { store } } pub async fn begin(&self, key: &str, max_bytes: u64) -> Result { let upload = self .store .put_multipart(&ObjectPath::from(key)) .await .map_err(storage_err)?; Ok(BlobWriter { writer: WriteMultipart::new_with_chunk_size(upload, PART_BYTES), hasher: Sha256::new(), size: 0, max_bytes, }) } pub async fn read(&self, key: &str) -> Result> { match self.store.get(&ObjectPath::from(key)).await { Ok(result) => { let size = result.meta.size; let stream = result.into_stream().map_err(std::io::Error::other).boxed(); Ok(Some(BlobRead { size, stream })) } Err(object_store::Error::NotFound { .. }) => Ok(None), Err(e) => Err(storage_err(e)), } } pub async fn exists(&self, key: &str) -> Result { match self.store.head(&ObjectPath::from(key)).await { Ok(_) => Ok(true), Err(object_store::Error::NotFound { .. }) => Ok(false), Err(e) => Err(storage_err(e)), } } pub async fn rename(&self, from: &str, to: &str) -> Result<()> { self.store .rename(&ObjectPath::from(from), &ObjectPath::from(to)) .await .map_err(storage_err) } pub async fn keys_older_than(&self, prefix: &str, cutoff: SystemTime) -> Result> { let mut listing = self.store.list(Some(&ObjectPath::from(prefix))); let mut keys = Vec::new(); while let Some(meta) = listing.try_next().await.map_err(storage_err)? { if SystemTime::from(meta.last_modified) < cutoff { keys.push(meta.location.to_string()); } } Ok(keys) } pub async fn delete(&self, key: &str) -> Result<()> { match self.store.delete(&ObjectPath::from(key)).await { Ok(()) | Err(object_store::Error::NotFound { .. }) => Ok(()), Err(e) => Err(storage_err(e)), } } } pub struct BlobWriter { writer: WriteMultipart, hasher: Sha256, size: u64, max_bytes: u64, } impl BlobWriter { pub async fn push(&mut self, chunk: &[u8]) -> Result<()> { let next = self.size.saturating_add(chunk.len() as u64); if next > self.max_bytes { return Err(Error::Invalid( "the file is larger than the upload limit".into(), )); } self.size = next; self.hasher.update(chunk); self.writer .wait_for_capacity(PARTS_IN_FLIGHT) .await .map_err(storage_err)?; self.writer.write(chunk); Ok(()) } pub async fn finish(self) -> Result<(u64, String)> { let digest = hex::encode(self.hasher.finalize()); self.writer.finish().await.map_err(storage_err)?; Ok((self.size, digest)) } pub async fn abort(self) { let _ = self.writer.abort().await; } } #[cfg(test)] mod tests { use forge_core::config::R2Jurisdiction; use object_store::memory::InMemory; use super::*; async fn exercise(blobs: &BlobStore) { let mut writer = blobs.begin("tmp/upload", 1024).await.unwrap(); writer.push(b"hello ").await.unwrap(); writer.push(b"world").await.unwrap(); let (size, digest) = writer.finish().await.unwrap(); assert_eq!(size, 11); assert_eq!(digest, hex::encode(Sha256::digest(b"hello world"))); blobs.rename("tmp/upload", &asset_key("a1")).await.unwrap(); assert!(blobs.read("tmp/upload").await.unwrap().is_none()); let read = blobs.read(&asset_key("a1")).await.unwrap().unwrap(); assert_eq!(read.size, 11); let chunks: Vec = read.stream.try_collect().await.unwrap(); assert_eq!(chunks.concat(), b"hello world"); blobs.delete(&asset_key("a1")).await.unwrap(); blobs.delete(&asset_key("a1")).await.unwrap(); assert!(blobs.read(&asset_key("a1")).await.unwrap().is_none()); } #[tokio::test] async fn fs_backend_round_trip() { let dir = tempfile::tempdir().unwrap(); let blobs = BlobStore::open(&dir.path().join("blobs")).unwrap(); exercise(&blobs).await; } #[tokio::test] async fn non_fs_backend_round_trip() { let blobs = BlobStore::from_store(Arc::new(InMemory::new())); exercise(&blobs).await; } #[tokio::test] async fn upload_past_the_limit_is_refused() { let blobs = BlobStore::from_store(Arc::new(InMemory::new())); let mut writer = blobs.begin("tmp/big", 4).await.unwrap(); writer.push(b"abc").await.unwrap(); assert!(writer.push(b"de").await.is_err()); writer.abort().await; assert!(blobs.read("tmp/big").await.unwrap().is_none()); } #[test] fn remote_config_reads_the_secret_file() { let dir = tempfile::tempdir().unwrap(); let secret = dir.path().join("secret"); std::fs::write(&secret, "s3cret\n").unwrap(); let s3 = S3Config { bucket: "forge".into(), region: "us-east-1".into(), endpoint: "http://127.0.0.1:9000".into(), prefix: "/forge/".into(), access_key_id: "AKIA".into(), secret_access_key_file: secret.clone(), allow_http: true, virtual_hosted_style: false, }; let r2 = R2Config { account_id: "0123abcd".into(), bucket: "forge".into(), jurisdiction: R2Jurisdiction::Eu, prefix: "/forge/".into(), access_key_id: "AKIA".into(), secret_access_key_file: secret, }; let s3_cfg = StorageConfig { backend: StorageBackend::S3, s3: s3.clone(), ..StorageConfig::default() }; let r2_cfg = StorageConfig { backend: StorageBackend::R2, r2: r2.clone(), ..StorageConfig::default() }; assert!(BlobStore::from_config(&s3_cfg, dir.path()).is_ok()); assert!(BlobStore::from_config(&r2_cfg, dir.path()).is_ok()); let absent = dir.path().join("absent"); let missing_s3 = StorageConfig { s3: S3Config { secret_access_key_file: absent.clone(), ..s3 }, ..s3_cfg }; let missing_r2 = StorageConfig { r2: R2Config { secret_access_key_file: absent, ..r2 }, ..r2_cfg }; assert!(BlobStore::from_config(&missing_s3, dir.path()).is_err()); assert!(BlobStore::from_config(&missing_r2, dir.path()).is_err()); } }