1use crate::client::Oci;
4use crate::client::request_executor::{RequestPayload, RequestTarget};
5use crate::error::{Error, Result};
6use crate::services::object_storage::models::*;
7use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
8use bytes::Bytes;
9use reqwest::Method;
10use reqwest::header::HeaderMap;
11use serde::Deserialize;
12use serde::Serialize;
13use serde::de::DeserializeOwned;
14use sha2::{Digest as ShaDigest, Sha256, Sha384};
15
16#[derive(Clone)]
18pub struct ObjectStorage {
19 oci_client: Oci,
21 pub namespace: String,
23 endpoint: String,
25 protocol: String,
27}
28
29impl ObjectStorage {
30 pub fn new(oci_client: &Oci, namespace: impl Into<String>) -> Self {
36 let region = oci_client.region().to_string();
37 let endpoint = format!("objectstorage.{region}.{}", oci_client.realm_domain());
38
39 Self {
40 oci_client: oci_client.clone(),
41 namespace: namespace.into(),
42 endpoint,
43 protocol: "https".to_string(),
44 }
45 }
46
47 pub async fn get_bucket(&self, bucket_name: &str) -> Result<Bucket> {
52 let path = format!("/n/{}/b/{}/", self.namespace, bucket_name);
53 self.oci_client
54 .executor()
55 .execute(
56 Method::GET,
57 RequestTarget {
58 scheme: &self.protocol,
59 host: &self.endpoint,
60 path: &path,
61 },
62 RequestPayload {
63 body: None,
64 content_type: None,
65 extra_headers: Vec::new(),
66 },
67 )
68 .await?;
69 Ok(Bucket {
70 oci_client: self.oci_client.clone(),
71 namespace: self.namespace.clone(),
72 name: bucket_name.to_string(),
73 endpoint: self.endpoint.clone(),
74 protocol: self.protocol.clone(),
75 })
76 }
77}
78
79#[derive(Clone)]
81pub struct Bucket {
82 oci_client: Oci,
84 pub namespace: String,
86 pub name: String,
88 endpoint: String,
90 protocol: String,
92}
93
94impl Bucket {
95 async fn execute(
96 &self,
97 method: Method,
98 path: &str,
99 body: Option<Bytes>,
100 content_type: Option<&str>,
101 extra_headers: Vec<(String, String)>,
102 ) -> Result<reqwest::Response> {
103 self.oci_client
104 .executor()
105 .execute(
106 method,
107 RequestTarget {
108 scheme: &self.protocol,
109 host: &self.endpoint,
110 path,
111 },
112 RequestPayload {
113 body,
114 content_type,
115 extra_headers,
116 },
117 )
118 .await
119 }
120
121 async fn request<T, B>(&self, method: &str, path: &str, body: Option<B>) -> Result<T>
123 where
124 T: DeserializeOwned,
125 B: Serialize,
126 {
127 let body_bytes = if let Some(b) = body {
128 Some(Bytes::from(serde_json::to_vec(&b)?))
129 } else {
130 None
131 };
132 let method = parse_method(method)?;
133 let response = self
134 .execute(
135 method,
136 path,
137 body_bytes,
138 Some("application/json"),
139 Vec::new(),
140 )
141 .await?;
142 let text = response.text().await?;
143 serde_json::from_str(&text).map_err(Into::into)
144 }
145
146 async fn request_no_content<B>(&self, method: &str, path: &str, body: Option<B>) -> Result<()>
147 where
148 B: Serialize,
149 {
150 let body_bytes = if let Some(b) = body {
151 Some(Bytes::from(serde_json::to_vec(&b)?))
152 } else {
153 None
154 };
155 let method = parse_method(method)?;
156 self.execute(
157 method,
158 path,
159 body_bytes,
160 Some("application/json"),
161 Vec::new(),
162 )
163 .await?;
164 Ok(())
165 }
166
167 pub async fn put_object<B>(&self, object_name: &str, content: B) -> Result<Object>
173 where
174 B: AsRef<[u8]>,
175 {
176 self.put_object_internal(object_name, Bytes::copy_from_slice(content.as_ref()), None)
177 .await
178 }
179
180 pub async fn put_object_with_checksum(
187 &self,
188 object_name: &str,
189 content: impl AsRef<[u8]>,
190 algorithm: ChecksumAlgorithm,
191 ) -> Result<Object> {
192 self.put_object_internal(
193 object_name,
194 Bytes::copy_from_slice(content.as_ref()),
195 Some(algorithm),
196 )
197 .await
198 }
199
200 async fn put_object_internal(
201 &self,
202 object_name: &str,
203 content: Bytes,
204 algorithm: Option<ChecksumAlgorithm>,
205 ) -> Result<Object> {
206 let path = format!("/n/{}/b/{}/o/{}", self.namespace, self.name, object_name);
207 let mut extra_headers = Vec::new();
208 let data = content.as_ref();
209
210 if let Some(algo) = algorithm {
211 match algo {
212 ChecksumAlgorithm::SHA256 => {
213 let mut hasher = Sha256::new();
214 hasher.update(data);
215 let result = hasher.finalize();
216 let b64 = BASE64.encode(result);
217 extra_headers.push(("opc-checksum-algorithm".to_owned(), "SHA256".to_owned()));
218 extra_headers.push(("opc-content-sha256".to_owned(), b64));
219 }
220 ChecksumAlgorithm::SHA384 => {
221 let mut hasher = Sha384::new();
222 hasher.update(data);
223 let result = hasher.finalize();
224 let b64 = BASE64.encode(result);
225 extra_headers.push(("opc-checksum-algorithm".to_owned(), "SHA384".to_owned()));
226 extra_headers.push(("opc-content-sha384".to_owned(), b64));
227 }
228 ChecksumAlgorithm::CRC32C => {
229 let crc = crc32c::crc32c(data);
230 let bytes = crc.to_be_bytes();
231 let b64 = BASE64.encode(bytes);
232 extra_headers.push(("opc-checksum-algorithm".to_owned(), "CRC32C".to_owned()));
233 extra_headers.push(("opc-content-crc32c".to_owned(), b64));
234 }
235 }
236 }
237
238 let response = self
239 .execute(
240 Method::PUT,
241 &path,
242 Some(content.clone()),
243 Some("application/octet-stream"),
244 extra_headers,
245 )
246 .await?;
247 let headers = response.headers();
248 let md5 = headers
249 .get("opc-content-md5")
250 .and_then(|h| h.to_str().ok())
251 .ok_or_else(|| Error::Other("Missing required header: opc-content-md5".to_string()))?
252 .to_string();
253
254 Ok(Object {
255 name: object_name.to_string(),
256 value: content,
257 md5,
258 checksum: checksum_from_headers(headers),
259 })
260 }
261
262 pub async fn get_object(&self, object_name: &str) -> Result<Object> {
269 let path = format!("/n/{}/b/{}/o/{}", self.namespace, self.name, object_name);
270 let response = self
271 .execute(Method::GET, &path, None, None, Vec::new())
272 .await?;
273
274 let headers = response.headers().clone();
275 let md5 = headers
276 .get("content-md5")
277 .or_else(|| headers.get("opc-multipart-md5"))
278 .and_then(|h| h.to_str().ok())
279 .ok_or_else(|| Error::Other("Missing required header: content-md5".to_string()))?
280 .to_string();
281 let checksum = checksum_from_headers(&headers);
282 let value = response.bytes().await?;
283
284 Ok(Object {
285 name: object_name.to_string(),
286 value,
287 md5,
288 checksum,
289 })
290 }
291
292 pub async fn get_or_create_object<B>(&self, object_name: &str, content: B) -> Result<Object>
300 where
301 B: AsRef<[u8]>,
302 {
303 let content = Bytes::copy_from_slice(content.as_ref());
304 match self.get_object(object_name).await {
305 Ok(obj) => Ok(obj),
306 Err(Error::ApiError { code, .. }) if code.contains("404") => {
307 self.put_object_internal(object_name, content, None).await
308 }
309 Err(e) => Err(e),
310 }
311 }
312
313 pub async fn delete_object(&self, object_name: &str) -> Result<()> {
318 let path = format!("/n/{}/b/{}/o/{}", self.namespace, self.name, object_name);
319 self.request_no_content("DELETE", &path, None::<()>).await
320 }
321
322 pub async fn get_retention_rules(&self) -> Result<Vec<RetentionRule>> {
324 let path = format!("/n/{}/b/{}/retentionRules", self.namespace, self.name);
325
326 #[derive(Deserialize)]
327 struct ResponseWrapper {
328 items: Vec<RetentionRule>,
329 }
330
331 let wrapper: ResponseWrapper = self
332 .request::<ResponseWrapper, ()>("GET", &path, None)
333 .await?;
334 Ok(wrapper.items)
335 }
336
337 pub async fn create_retention_rule(
339 &self,
340 details: RetentionRuleDetails,
341 ) -> Result<RetentionRule> {
342 let path = format!("/n/{}/b/{}/retentionRules", self.namespace, self.name);
343 self.request("POST", &path, Some(details)).await
344 }
345
346 pub async fn get_retention_rule(&self, rule_id: &str) -> Result<RetentionRule> {
348 let path = format!(
349 "/n/{}/b/{}/retentionRules/{}",
350 self.namespace, self.name, rule_id
351 );
352 self.request("GET", &path, None::<()>).await
353 }
354
355 pub async fn update_retention_rule(
357 &self,
358 rule_or_id: impl Into<String>,
359 details: RetentionRuleDetails,
360 ) -> Result<RetentionRule> {
361 let rule_id = rule_or_id.into();
362 let path = format!(
363 "/n/{}/b/{}/retentionRules/{}",
364 self.namespace, self.name, rule_id
365 );
366 self.request("PUT", &path, Some(details)).await
367 }
368
369 pub async fn delete_retention_rule(&self, rule_or_id: impl Into<String>) -> Result<()> {
371 let rule_id = rule_or_id.into();
372 let path = format!(
373 "/n/{}/b/{}/retentionRules/{}",
374 self.namespace, self.name, rule_id
375 );
376 self.request_no_content("DELETE", &path, None::<()>).await
377 }
378}
379
380fn parse_method(method: &str) -> Result<Method> {
381 Method::from_bytes(method.as_bytes())
382 .map_err(|e| Error::Other(format!("Unsupported method {method}: {e}")))
383}
384
385fn checksum_from_headers(headers: &HeaderMap) -> Option<Checksum> {
386 if let Some(val) = headers
387 .get("opc-content-sha256")
388 .and_then(|h| h.to_str().ok())
389 {
390 Some(Checksum {
391 algorithm: ChecksumAlgorithm::SHA256,
392 value: val.to_string(),
393 })
394 } else if let Some(val) = headers
395 .get("opc-content-sha384")
396 .and_then(|h| h.to_str().ok())
397 {
398 Some(Checksum {
399 algorithm: ChecksumAlgorithm::SHA384,
400 value: val.to_string(),
401 })
402 } else {
403 headers
404 .get("opc-content-crc32c")
405 .and_then(|h| h.to_str().ok())
406 .map(|val| Checksum {
407 algorithm: ChecksumAlgorithm::CRC32C,
408 value: val.to_string(),
409 })
410 }
411}
412
413#[cfg(test)]
414#[path = "tests.rs"]
415mod tests;