forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

blobs.rs357 lines, 13.1 KiBHistoryRawDownload
1//! Blob storage for release assets and CI artifacts. A thin wrapper over object_store, backed by
2//! the local filesystem (the default), any S3-compatible store, or Cloudflare R2, chosen by `[storage]`.
3//!
4//! Only operations that every backend supports are used. `rename` is a server-side copy followed
5//! by a delete on S3, and a delete of a missing key is not an error on either backend.
6//!
7//! Keys are `assets/<asset id>`. Writes stream through object_store's multipart upload, which
8//! assembles the object in a temporary file and renames it into place on `finish`. Every chunk
9//! is hashed as it passes, so the sha256 is known without a second read. Blobs are immutable:
10//! an asset is never rewritten, only added or deleted.
11
12use std::path::Path;
13use std::sync::Arc;
14
15use bytes::Bytes;
16use forge_core::config::{R2Config, S3Config, StorageBackend, StorageConfig};
17use forge_core::{Error, Result};
18use futures_util::{StreamExt, TryStreamExt, stream::BoxStream};
19use object_store::aws::AmazonS3Builder;
20use object_store::local::LocalFileSystem;
21use object_store::path::Path as ObjectPath;
22use object_store::prefix::PrefixStore;
23use object_store::{ObjectStore, ObjectStoreExt, WriteMultipart};
24use sha2::{Digest, Sha256};
25
26/// Bytes buffered per upload part before it is handed to the store.
27const PART_BYTES: usize = 8 * 1024 * 1024;
28/// Parts uploaded at once while a stream is being written.
29const PARTS_IN_FLIGHT: usize = 4;
30
31/// The object key of a release asset.
32pub fn asset_key(asset_id: &str) -> String {
33 format!("assets/{asset_id}")
34}
35
36/// The object key of a markdown attachment.
37pub fn attachment_key(attachment_id: &str) -> String {
38 format!("attachments/{attachment_id}")
39}
40
41fn storage_err<E>(e: E) -> Error
42where
43 E: std::error::Error + Send + Sync + 'static,
44{
45 Error::Io(std::io::Error::other(e))
46}
47
48/// What `BlobStore::s3_store` needs to reach an S3-compatible bucket. Built from `[storage.s3]`
49/// or derived from `[storage.r2]`.
50struct S3Connection<'a> {
51 bucket: &'a str,
52 region: &'a str,
53 /// `None` uses AWS.
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/// The blob store rooted at `<data_dir>/blobs`. Cheap to clone.
63#[derive(Clone)]
64pub struct BlobStore {
65 store: Arc<dyn ObjectStore>,
66}
67
68/// A blob opened for reading: its size and its bytes.
69pub struct BlobRead {
70 pub size: u64,
71 pub stream: BoxStream<'static, std::io::Result<Bytes>>,
72}
73
74impl BlobStore {
75 /// Opens the backend chosen by `[storage]`. `fs` keeps blobs under `<data_dir>/blobs`.
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 /// Opens the store at `root`, creating the directory if needed.
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 /// Opens an S3-compatible bucket. The secret is read from its file here, once at startup.
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 /// Opens a Cloudflare R2 bucket. The endpoint comes from the account id and jurisdiction, and
106 /// R2 ignores the region, so the signing region is the literal `auto`. Path style and https only.
107 ///
108 /// Defaults checked against R2 (object_store 0.14): conditional writes use ETag preconditions,
109 /// which R2 supports; no `x-amz-checksum-*` headers are sent unless a checksum algorithm is set,
110 /// so none is set here; and payloads are SigV4-signed, which R2 accepts. Do not enable
111 /// `with_unsigned_payload` or a checksum algorithm without retesting against R2.
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 /// The constructor shared by every S3-compatible backend.
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 /// Starts a write of `key`. The bytes are not visible under `key` until `finish`.
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 /// Opens `key` for reading, or `None` if there is no such blob.
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 /// True when `key` holds a blob. Reads only the metadata, not the bytes.
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 /// Moves `from` to `to`, replacing `to`. Used to give a finished upload its final key.
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 /// Deletes `key`. A blob that is already gone is not an error.
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/// An upload in progress. Dropping it without `finish` leaves no object behind only if `abort`
208/// is called, so every error path in the caller must call `abort`.
209pub struct BlobWriter {
210 writer: WriteMultipart,
211 hasher: Sha256,
212 size: u64,
213 max_bytes: u64,
214}
215
216impl BlobWriter {
217 /// Appends a chunk. Going past the size limit is `Invalid` and writes nothing more.
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 /// Completes the object. Returns its size and lowercase hex sha256.
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 /// Discards the partial object. Errors are ignored: the object was never visible.
243 pub async fn abort(self) {
244 let _ = self.writer.abort().await;
245 }
246}
247
248#[cfg(test)]
249mod tests {
250 use object_store::memory::InMemory;
251
252 use super::*;
253
254 /// The operations the pages use, run against any backend.
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 // InMemory has no rename, so this exercises the copy-then-delete path an S3 store takes.
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}