| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | use std::path::Path; |
| 13 | use std::sync::Arc; |
| 14 | |
| 15 | use bytes::Bytes; |
| 16 | use forge_core::config::{R2Config, S3Config, StorageBackend, StorageConfig}; |
| 17 | use forge_core::{Error, Result}; |
| 18 | use futures_util::{StreamExt, TryStreamExt, stream::BoxStream}; |
| 19 | use object_store::aws::AmazonS3Builder; |
| 20 | use object_store::local::LocalFileSystem; |
| 21 | use object_store::path::Path as ObjectPath; |
| 22 | use object_store::prefix::PrefixStore; |
| 23 | use object_store::{ObjectStore, ObjectStoreExt, WriteMultipart}; |
| 24 | use sha2::{Digest, Sha256}; |
| 25 | |
| 26 | |
| 27 | const PART_BYTES: usize = 8 * 1024 * 1024; |
| 28 | |
| 29 | const PARTS_IN_FLIGHT: usize = 4; |
| 30 | |
| 31 | |
| 32 | pub fn asset_key(asset_id: &str) -> String { |
| 33 | format!("assets/{asset_id}") |
| 34 | } |
| 35 | |
| 36 | |
| 37 | pub fn attachment_key(attachment_id: &str) -> String { |
| 38 | format!("attachments/{attachment_id}") |
| 39 | } |
| 40 | |
| 41 | fn storage_err<E>(e: E) -> Error |
| 42 | where |
| 43 | E: std::error::Error + Send + Sync + 'static, |
| 44 | { |
| 45 | Error::Io(std::io::Error::other(e)) |
| 46 | } |
| 47 | |
| 48 | |
| 49 | |
| 50 | struct S3Connection<'a> { |
| 51 | bucket: &'a str, |
| 52 | region: &'a str, |
| 53 | |
| 54 | endpoint: Option<&'a str>, |
| 55 | prefix: &'a str, |
| 56 | access_key_id: &'a str, |
| 57 | secret_access_key_file: &'a Path, |
| 58 | allow_http: bool, |
| 59 | virtual_hosted_style: bool, |
| 60 | } |
| 61 | |
| 62 | |
| 63 | #[derive(Clone)] |
| 64 | pub struct BlobStore { |
| 65 | store: Arc<dyn ObjectStore>, |
| 66 | } |
| 67 | |
| 68 | |
| 69 | pub struct BlobRead { |
| 70 | pub size: u64, |
| 71 | pub stream: BoxStream<'static, std::io::Result<Bytes>>, |
| 72 | } |
| 73 | |
| 74 | impl BlobStore { |
| 75 | |
| 76 | pub fn from_config(cfg: &StorageConfig, data_dir: &Path) -> Result<Self> { |
| 77 | match cfg.backend { |
| 78 | StorageBackend::Fs => Self::open(&data_dir.join("blobs")), |
| 79 | StorageBackend::S3 => Self::s3(&cfg.s3), |
| 80 | StorageBackend::R2 => Self::r2(&cfg.r2), |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | |
| 85 | pub fn open(root: &Path) -> Result<Self> { |
| 86 | std::fs::create_dir_all(root)?; |
| 87 | let fs = LocalFileSystem::new_with_prefix(root).map_err(storage_err)?; |
| 88 | Ok(Self::from_store(Arc::new(fs))) |
| 89 | } |
| 90 | |
| 91 | |
| 92 | fn s3(cfg: &S3Config) -> Result<Self> { |
| 93 | Self::s3_store(S3Connection { |
| 94 | bucket: &cfg.bucket, |
| 95 | region: &cfg.region, |
| 96 | endpoint: (!cfg.endpoint.is_empty()).then_some(cfg.endpoint.as_str()), |
| 97 | prefix: &cfg.prefix, |
| 98 | access_key_id: &cfg.access_key_id, |
| 99 | secret_access_key_file: &cfg.secret_access_key_file, |
| 100 | allow_http: cfg.allow_http, |
| 101 | virtual_hosted_style: cfg.virtual_hosted_style, |
| 102 | }) |
| 103 | } |
| 104 | |
| 105 | |
| 106 | |
| 107 | |
| 108 | |
| 109 | |
| 110 | |
| 111 | |
| 112 | fn r2(cfg: &R2Config) -> Result<Self> { |
| 113 | let endpoint = cfg.endpoint(); |
| 114 | Self::s3_store(S3Connection { |
| 115 | bucket: &cfg.bucket, |
| 116 | region: "auto", |
| 117 | endpoint: Some(&endpoint), |
| 118 | prefix: &cfg.prefix, |
| 119 | access_key_id: &cfg.access_key_id, |
| 120 | secret_access_key_file: &cfg.secret_access_key_file, |
| 121 | allow_http: false, |
| 122 | virtual_hosted_style: false, |
| 123 | }) |
| 124 | } |
| 125 | |
| 126 | |
| 127 | fn s3_store(conn: S3Connection<'_>) -> Result<Self> { |
| 128 | let secret = std::fs::read_to_string(conn.secret_access_key_file)?; |
| 129 | let mut builder = AmazonS3Builder::new() |
| 130 | .with_bucket_name(conn.bucket) |
| 131 | .with_region(conn.region) |
| 132 | .with_access_key_id(conn.access_key_id) |
| 133 | .with_secret_access_key(secret.trim()) |
| 134 | .with_allow_http(conn.allow_http) |
| 135 | .with_virtual_hosted_style_request(conn.virtual_hosted_style); |
| 136 | if let Some(endpoint) = conn.endpoint { |
| 137 | builder = builder.with_endpoint(endpoint); |
| 138 | } |
| 139 | let s3 = builder.build().map_err(storage_err)?; |
| 140 | let prefix = conn.prefix.trim_matches('/'); |
| 141 | let store: Arc<dyn ObjectStore> = if prefix.is_empty() { |
| 142 | Arc::new(s3) |
| 143 | } else { |
| 144 | Arc::new(PrefixStore::new(s3, prefix)) |
| 145 | }; |
| 146 | Ok(Self::from_store(store)) |
| 147 | } |
| 148 | |
| 149 | fn from_store(store: Arc<dyn ObjectStore>) -> Self { |
| 150 | Self { store } |
| 151 | } |
| 152 | |
| 153 | |
| 154 | pub async fn begin(&self, key: &str, max_bytes: u64) -> Result<BlobWriter> { |
| 155 | let upload = self |
| 156 | .store |
| 157 | .put_multipart(&ObjectPath::from(key)) |
| 158 | .await |
| 159 | .map_err(storage_err)?; |
| 160 | Ok(BlobWriter { |
| 161 | writer: WriteMultipart::new_with_chunk_size(upload, PART_BYTES), |
| 162 | hasher: Sha256::new(), |
| 163 | size: 0, |
| 164 | max_bytes, |
| 165 | }) |
| 166 | } |
| 167 | |
| 168 | |
| 169 | pub async fn read(&self, key: &str) -> Result<Option<BlobRead>> { |
| 170 | match self.store.get(&ObjectPath::from(key)).await { |
| 171 | Ok(result) => { |
| 172 | let size = result.meta.size; |
| 173 | let stream = result.into_stream().map_err(std::io::Error::other).boxed(); |
| 174 | Ok(Some(BlobRead { size, stream })) |
| 175 | } |
| 176 | Err(object_store::Error::NotFound { .. }) => Ok(None), |
| 177 | Err(e) => Err(storage_err(e)), |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | |
| 182 | pub async fn exists(&self, key: &str) -> Result<bool> { |
| 183 | match self.store.head(&ObjectPath::from(key)).await { |
| 184 | Ok(_) => Ok(true), |
| 185 | Err(object_store::Error::NotFound { .. }) => Ok(false), |
| 186 | Err(e) => Err(storage_err(e)), |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | |
| 191 | pub async fn rename(&self, from: &str, to: &str) -> Result<()> { |
| 192 | self.store |
| 193 | .rename(&ObjectPath::from(from), &ObjectPath::from(to)) |
| 194 | .await |
| 195 | .map_err(storage_err) |
| 196 | } |
| 197 | |
| 198 | |
| 199 | pub async fn delete(&self, key: &str) -> Result<()> { |
| 200 | match self.store.delete(&ObjectPath::from(key)).await { |
| 201 | Ok(()) | Err(object_store::Error::NotFound { .. }) => Ok(()), |
| 202 | Err(e) => Err(storage_err(e)), |
| 203 | } |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | |
| 208 | |
| 209 | pub struct BlobWriter { |
| 210 | writer: WriteMultipart, |
| 211 | hasher: Sha256, |
| 212 | size: u64, |
| 213 | max_bytes: u64, |
| 214 | } |
| 215 | |
| 216 | impl BlobWriter { |
| 217 | |
| 218 | pub async fn push(&mut self, chunk: &[u8]) -> Result<()> { |
| 219 | let next = self.size.saturating_add(chunk.len() as u64); |
| 220 | if next > self.max_bytes { |
| 221 | return Err(Error::Invalid( |
| 222 | "the file is larger than the upload limit".into(), |
| 223 | )); |
| 224 | } |
| 225 | self.size = next; |
| 226 | self.hasher.update(chunk); |
| 227 | self.writer |
| 228 | .wait_for_capacity(PARTS_IN_FLIGHT) |
| 229 | .await |
| 230 | .map_err(storage_err)?; |
| 231 | self.writer.write(chunk); |
| 232 | Ok(()) |
| 233 | } |
| 234 | |
| 235 | |
| 236 | pub async fn finish(self) -> Result<(u64, String)> { |
| 237 | let digest = hex::encode(self.hasher.finalize()); |
| 238 | self.writer.finish().await.map_err(storage_err)?; |
| 239 | Ok((self.size, digest)) |
| 240 | } |
| 241 | |
| 242 | |
| 243 | pub async fn abort(self) { |
| 244 | let _ = self.writer.abort().await; |
| 245 | } |
| 246 | } |
| 247 | |
| 248 | #[cfg(test)] |
| 249 | mod tests { |
| 250 | use object_store::memory::InMemory; |
| 251 | |
| 252 | use super::*; |
| 253 | |
| 254 | |
| 255 | async fn exercise(blobs: &BlobStore) { |
| 256 | let mut writer = blobs.begin("tmp/upload", 1024).await.unwrap(); |
| 257 | writer.push(b"hello ").await.unwrap(); |
| 258 | writer.push(b"world").await.unwrap(); |
| 259 | let (size, digest) = writer.finish().await.unwrap(); |
| 260 | assert_eq!(size, 11); |
| 261 | assert_eq!(digest, hex::encode(Sha256::digest(b"hello world"))); |
| 262 | |
| 263 | blobs.rename("tmp/upload", &asset_key("a1")).await.unwrap(); |
| 264 | assert!(blobs.read("tmp/upload").await.unwrap().is_none()); |
| 265 | let read = blobs.read(&asset_key("a1")).await.unwrap().unwrap(); |
| 266 | assert_eq!(read.size, 11); |
| 267 | let chunks: Vec<Bytes> = read.stream.try_collect().await.unwrap(); |
| 268 | assert_eq!(chunks.concat(), b"hello world"); |
| 269 | |
| 270 | blobs.delete(&asset_key("a1")).await.unwrap(); |
| 271 | blobs.delete(&asset_key("a1")).await.unwrap(); |
| 272 | assert!(blobs.read(&asset_key("a1")).await.unwrap().is_none()); |
| 273 | } |
| 274 | |
| 275 | #[tokio::test] |
| 276 | async fn fs_backend_round_trip() { |
| 277 | let dir = tempfile::tempdir().unwrap(); |
| 278 | let blobs = BlobStore::open(&dir.path().join("blobs")).unwrap(); |
| 279 | exercise(&blobs).await; |
| 280 | } |
| 281 | |
| 282 | #[tokio::test] |
| 283 | async fn non_fs_backend_round_trip() { |
| 284 | |
| 285 | let blobs = BlobStore::from_store(Arc::new(InMemory::new())); |
| 286 | exercise(&blobs).await; |
| 287 | } |
| 288 | |
| 289 | #[tokio::test] |
| 290 | async fn upload_past_the_limit_is_refused() { |
| 291 | let blobs = BlobStore::from_store(Arc::new(InMemory::new())); |
| 292 | let mut writer = blobs.begin("tmp/big", 4).await.unwrap(); |
| 293 | writer.push(b"abc").await.unwrap(); |
| 294 | assert!(writer.push(b"de").await.is_err()); |
| 295 | writer.abort().await; |
| 296 | assert!(blobs.read("tmp/big").await.unwrap().is_none()); |
| 297 | } |
| 298 | |
| 299 | #[test] |
| 300 | fn fs_config_uses_blobs_under_data_dir() { |
| 301 | let dir = tempfile::tempdir().unwrap(); |
| 302 | let cfg = StorageConfig::default(); |
| 303 | BlobStore::from_config(&cfg, dir.path()).unwrap(); |
| 304 | assert!(dir.path().join("blobs").is_dir()); |
| 305 | } |
| 306 | |
| 307 | #[test] |
| 308 | fn s3_config_reads_the_secret_file() { |
| 309 | let dir = tempfile::tempdir().unwrap(); |
| 310 | let secret = dir.path().join("secret"); |
| 311 | std::fs::write(&secret, "s3cret\n").unwrap(); |
| 312 | let cfg = S3Config { |
| 313 | bucket: "forge".into(), |
| 314 | region: "us-east-1".into(), |
| 315 | endpoint: "http://127.0.0.1:9000".into(), |
| 316 | prefix: "/forge/".into(), |
| 317 | access_key_id: "AKIA".into(), |
| 318 | secret_access_key_file: secret, |
| 319 | allow_http: true, |
| 320 | virtual_hosted_style: false, |
| 321 | }; |
| 322 | assert!(BlobStore::s3(&cfg).is_ok()); |
| 323 | let missing = S3Config { |
| 324 | secret_access_key_file: dir.path().join("absent"), |
| 325 | ..cfg |
| 326 | }; |
| 327 | assert!(BlobStore::s3(&missing).is_err()); |
| 328 | } |
| 329 | |
| 330 | #[test] |
| 331 | fn r2_config_builds_a_store_from_the_secret_file() { |
| 332 | let dir = tempfile::tempdir().unwrap(); |
| 333 | let secret = dir.path().join("secret"); |
| 334 | std::fs::write(&secret, "r2s3cret\n").unwrap(); |
| 335 | let cfg = StorageConfig { |
| 336 | backend: StorageBackend::R2, |
| 337 | r2: R2Config { |
| 338 | account_id: "0123abcd".into(), |
| 339 | bucket: "forge".into(), |
| 340 | jurisdiction: "eu".into(), |
| 341 | prefix: "/forge/".into(), |
| 342 | access_key_id: "AKIA".into(), |
| 343 | secret_access_key_file: secret, |
| 344 | }, |
| 345 | ..StorageConfig::default() |
| 346 | }; |
| 347 | BlobStore::from_config(&cfg, dir.path()).unwrap(); |
| 348 | let missing = StorageConfig { |
| 349 | r2: R2Config { |
| 350 | secret_access_key_file: dir.path().join("absent"), |
| 351 | ..cfg.r2.clone() |
| 352 | }, |
| 353 | ..cfg |
| 354 | }; |
| 355 | assert!(BlobStore::from_config(&missing, dir.path()).is_err()); |
| 356 | } |
| 357 | } |