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