Skip to main content

storage_kit/backend/
s3.rs

1//! `S3Backend` — S3 / S3-compatible (Wasabi, B2, R2, MinIO) object storage.
2//!
3//! Each stored hash maps to exactly one object at
4//! `<key_prefix>/<partition_hex>/<hash_hex>`; the object body is
5//! `[codec_byte][payload]` using the same `Codec`/`encode`/`decode` bitchain
6//! uses for its packfile entries, so a value written by `bitchain pack`
7//! (once pushed) and one written by `S3Backend::put` decode identically.
8//!
9//! **Presigned direct-to-bucket uploads are the primary upload path**, per
10//! the standing design note for this crate: server-proxied
11//! uploads through this backend's `put()` incur AWS-style egress charges on
12//! the way back down and don't fit the "any S3-compatible vendor" goal as
13//! cleanly as a presigned PUT the client issues directly. `put()`/`get()`
14//! here exist for administrative/CLI use (`push`/`pull`, `verify`, tests) —
15//! real client uploads should call [`S3Backend::presigned_put_url`] and PUT
16//! straight to the bucket. Quota enforcement belongs at presign-issuance
17//! time, in the hosted control plane, never gated inside this OSS path.
18//!
19//! This crate's own test suite does not exercise `S3Backend` against a live
20//! endpoint (it needs credentials and a bucket or a MinIO instance); checksum
21//! header handling varies by vendor, so test against yours before relying on it.
22
23use crate::addressing::{Hash, PartitionId};
24use crate::backend::AsyncImmutableStore;
25use crate::error::StorageError;
26use crate::store::packfile::{decode, encode, Codec};
27use aws_sdk_s3::presigning::PresigningConfig;
28use bytes::Bytes;
29use std::time::Duration;
30
31pub struct S3Backend {
32    client: aws_sdk_s3::Client,
33    bucket: String,
34    key_prefix: String,
35    partition_id: PartitionId,
36}
37
38impl S3Backend {
39    pub fn new(
40        client: aws_sdk_s3::Client,
41        bucket: impl Into<String>,
42        key_prefix: impl Into<String>,
43        partition_id: PartitionId,
44    ) -> Self {
45        S3Backend {
46            client,
47            bucket: bucket.into(),
48            key_prefix: key_prefix.into(),
49            partition_id,
50        }
51    }
52
53    fn key_for(&self, hash: &Hash) -> String {
54        format!(
55            "{}/{}/{}",
56            self.key_prefix.trim_end_matches('/'),
57            self.partition_id.to_hex(),
58            hash.to_hex()
59        )
60    }
61
62    /// Presigned PUT URL for direct-to-bucket client upload of `hash`'s
63    /// content. The caller is responsible for encoding the body the same
64    /// way [`S3Backend::put`] would (`[codec_byte][payload]`) if it needs
65    /// to be readable by this backend's `get()` — for a purely
66    /// client-driven upload flow, prefer generating the URL for a raw
67    /// object and let the server-side ingest path (not this backend) do
68    /// the codec framing on confirmation.
69    pub async fn presigned_put_url(
70        &self,
71        hash: &Hash,
72        expires_in: Duration,
73    ) -> Result<String, StorageError> {
74        let presigned = self
75            .client
76            .put_object()
77            .bucket(&self.bucket)
78            .key(self.key_for(hash))
79            .presigned(
80                PresigningConfig::expires_in(expires_in)
81                    .map_err(|e| StorageError::Backend(e.to_string()))?,
82            )
83            .await
84            .map_err(|e| StorageError::Backend(e.to_string()))?;
85        Ok(presigned.uri().to_string())
86    }
87
88    pub async fn presigned_get_url(
89        &self,
90        hash: &Hash,
91        expires_in: Duration,
92    ) -> Result<String, StorageError> {
93        let presigned = self
94            .client
95            .get_object()
96            .bucket(&self.bucket)
97            .key(self.key_for(hash))
98            .presigned(
99                PresigningConfig::expires_in(expires_in)
100                    .map_err(|e| StorageError::Backend(e.to_string()))?,
101            )
102            .await
103            .map_err(|e| StorageError::Backend(e.to_string()))?;
104        Ok(presigned.uri().to_string())
105    }
106}
107
108#[async_trait::async_trait]
109impl AsyncImmutableStore for S3Backend {
110    async fn get(&self, hash: &Hash) -> Result<Vec<u8>, StorageError> {
111        let resp = self
112            .client
113            .get_object()
114            .bucket(&self.bucket)
115            .key(self.key_for(hash))
116            .send()
117            .await
118            .map_err(|e| StorageError::Backend(e.to_string()))?;
119        let body = resp
120            .body
121            .collect()
122            .await
123            .map_err(|e| StorageError::Backend(e.to_string()))?
124            .into_bytes();
125        if body.is_empty() {
126            return Err(StorageError::Backend("empty object body".into()));
127        }
128        let codec = match body[0] {
129            0 => Codec::Raw,
130            1 => Codec::Zstd,
131            other => return Err(StorageError::Backend(format!("unknown codec byte {other}"))),
132        };
133        let decoded = decode(codec, &body[1..])?;
134        let actual = Hash::of(&decoded);
135        if actual != *hash {
136            return Err(StorageError::HashMismatch {
137                expected: hash.to_hex(),
138                actual: actual.to_hex(),
139            });
140        }
141        Ok(decoded)
142    }
143
144    async fn put(&self, data: &[u8]) -> Result<Hash, StorageError> {
145        let hash = Hash::of(data);
146        if self.has(&hash).await.unwrap_or(false) {
147            return Ok(hash); // dedup: skip a redundant PUT
148        }
149        let (codec, payload) = encode(data)?;
150        let mut body = Vec::with_capacity(1 + payload.len());
151        body.push(codec as u8);
152        body.extend_from_slice(&payload);
153
154        self.client
155            .put_object()
156            .bucket(&self.bucket)
157            .key(self.key_for(&hash))
158            .body(Bytes::from(body).into())
159            .send()
160            .await
161            .map_err(|e| StorageError::Backend(e.to_string()))?;
162        Ok(hash)
163    }
164
165    async fn has(&self, hash: &Hash) -> Result<bool, StorageError> {
166        match self
167            .client
168            .head_object()
169            .bucket(&self.bucket)
170            .key(self.key_for(hash))
171            .send()
172            .await
173        {
174            Ok(_) => Ok(true),
175            Err(e) => {
176                if e.as_service_error()
177                    .map(|s| s.is_not_found())
178                    .unwrap_or(false)
179                {
180                    Ok(false)
181                } else {
182                    Err(StorageError::Backend(e.to_string()))
183                }
184            }
185        }
186    }
187
188    fn partition_id(&self) -> PartitionId {
189        self.partition_id
190    }
191}