storage_kit/backend/
http.rs1use crate::addressing::{Hash, PartitionId};
8use crate::backend::AsyncImmutableStore;
9use crate::error::StorageError;
10use crate::store::packfile::{decode, encode, Codec};
11
12pub struct HttpBackend {
13 client: reqwest::Client,
14 base_url: String,
15 partition_id: PartitionId,
16}
17
18impl HttpBackend {
19 pub fn new(base_url: impl Into<String>, partition_id: PartitionId) -> Self {
20 HttpBackend {
21 client: reqwest::Client::new(),
22 base_url: base_url.into(),
23 partition_id,
24 }
25 }
26
27 fn url_for(&self, hash: &Hash) -> String {
28 format!(
29 "{}/{}/{}",
30 self.base_url.trim_end_matches('/'),
31 self.partition_id.to_hex(),
32 hash.to_hex()
33 )
34 }
35}
36
37#[async_trait::async_trait]
38impl AsyncImmutableStore for HttpBackend {
39 async fn get(&self, hash: &Hash) -> Result<Vec<u8>, StorageError> {
40 let resp = self
41 .client
42 .get(self.url_for(hash))
43 .send()
44 .await
45 .map_err(|e| StorageError::Backend(e.to_string()))?;
46 if resp.status() == reqwest::StatusCode::NOT_FOUND {
47 return Err(StorageError::NotFound(hash.to_hex()));
48 }
49 if !resp.status().is_success() {
50 return Err(StorageError::Backend(format!(
51 "GET {} returned {}",
52 self.url_for(hash),
53 resp.status()
54 )));
55 }
56 let body = resp
57 .bytes()
58 .await
59 .map_err(|e| StorageError::Backend(e.to_string()))?;
60 if body.is_empty() {
61 return Err(StorageError::Backend("empty response body".into()));
62 }
63 let codec = match body[0] {
64 0 => Codec::Raw,
65 1 => Codec::Zstd,
66 other => return Err(StorageError::Backend(format!("unknown codec byte {other}"))),
67 };
68 let decoded = decode(codec, &body[1..])?;
69 let actual = Hash::of(&decoded);
70 if actual != *hash {
71 return Err(StorageError::HashMismatch {
72 expected: hash.to_hex(),
73 actual: actual.to_hex(),
74 });
75 }
76 Ok(decoded)
77 }
78
79 async fn put(&self, data: &[u8]) -> Result<Hash, StorageError> {
80 let hash = Hash::of(data);
81 if self.has(&hash).await.unwrap_or(false) {
82 return Ok(hash);
83 }
84 let (codec, payload) = encode(data)?;
85 let mut body = Vec::with_capacity(1 + payload.len());
86 body.push(codec as u8);
87 body.extend_from_slice(&payload);
88
89 let resp = self
90 .client
91 .put(self.url_for(&hash))
92 .body(body)
93 .send()
94 .await
95 .map_err(|e| StorageError::Backend(e.to_string()))?;
96 if !resp.status().is_success() {
97 return Err(StorageError::Backend(format!(
98 "PUT {} returned {}",
99 self.url_for(&hash),
100 resp.status()
101 )));
102 }
103 Ok(hash)
104 }
105
106 async fn has(&self, hash: &Hash) -> Result<bool, StorageError> {
107 let resp = self
108 .client
109 .head(self.url_for(hash))
110 .send()
111 .await
112 .map_err(|e| StorageError::Backend(e.to_string()))?;
113 Ok(resp.status().is_success())
114 }
115
116 fn partition_id(&self) -> PartitionId {
117 self.partition_id
118 }
119}