Skip to main content

iota_storage/object_store/http/
mod.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5mod gcs;
6mod local;
7mod s3;
8
9use std::sync::Arc;
10
11use anyhow::{Context, Result, anyhow};
12use chrono::{DateTime, Utc};
13use futures::{StreamExt, TryStreamExt};
14use iota_config::object_storage_config::{ObjectStoreConfig, ObjectStoreType};
15use object_store::{Error, GetResult, GetResultPayload, ObjectMeta, path::Path};
16use reqwest::{
17    Client, Method,
18    header::{CONTENT_LENGTH, ETAG, HeaderMap, LAST_MODIFIED},
19};
20
21use crate::object_store::{
22    ObjectStoreGetExt,
23    http::{gcs::GoogleCloudStorage, local::LocalStorage, s3::AmazonS3},
24};
25
26// https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
27//
28// Do not URI-encode any of the unreserved characters that RFC 3986 defines:
29// A-Z, a-z, 0-9, hyphen ( - ), underscore ( _ ), period ( . ), and tilde ( ~ ).
30pub(crate) const STRICT_ENCODE_SET: percent_encoding::AsciiSet = percent_encoding::NON_ALPHANUMERIC
31    .remove(b'-')
32    .remove(b'.')
33    .remove(b'_')
34    .remove(b'~');
35const STRICT_PATH_ENCODE_SET: percent_encoding::AsciiSet = STRICT_ENCODE_SET.remove(b'/');
36static DEFAULT_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"),);
37
38pub trait HttpDownloaderBuilder {
39    fn make_http(&self) -> Result<Arc<dyn ObjectStoreGetExt>>;
40}
41
42impl HttpDownloaderBuilder for ObjectStoreConfig {
43    fn make_http(&self) -> Result<Arc<dyn ObjectStoreGetExt>> {
44        match self.object_store {
45            Some(ObjectStoreType::File) => {
46                Ok(LocalStorage::new(self.directory.as_ref().unwrap()).map(Arc::new)?)
47            }
48            Some(ObjectStoreType::S3) => {
49                let bucket_endpoint = if let Some(endpoint) = &self.aws_endpoint {
50                    if self.aws_virtual_hosted_style_request {
51                        endpoint.clone()
52                    } else {
53                        let bucket = self.bucket.as_ref().unwrap();
54                        format!("{endpoint}/{bucket}")
55                    }
56                } else {
57                    let bucket = self.bucket.as_ref().unwrap();
58                    let region = self.aws_region.as_ref().unwrap();
59                    if self.aws_virtual_hosted_style_request {
60                        format!("https://{bucket}.s3.{region}.amazonaws.com")
61                    } else {
62                        format!("https://s3.{region}.amazonaws.com/{bucket}")
63                    }
64                };
65                Ok(AmazonS3::new(&bucket_endpoint).map(Arc::new)?)
66            }
67            Some(ObjectStoreType::GCS) => {
68                Ok(GoogleCloudStorage::new(self.bucket.as_ref().unwrap()).map(Arc::new)?)
69            }
70            _ => Err(anyhow!("At least one storage backend should be provided")),
71        }
72    }
73}
74
75async fn get(
76    url: &str,
77    store: &'static str,
78    location: &Path,
79    client: &Client,
80) -> Result<GetResult> {
81    let request = client.request(Method::GET, url);
82    let response = request
83        .send()
84        .await
85        .context("failed to get")?
86        .error_for_status()
87        .with_context(|| format!("{store} returned an error status for {location}"))?;
88    let meta = header_meta(location, response.headers()).context("Failed to get header")?;
89    let stream = response
90        .bytes_stream()
91        .map_err(|source| Error::Generic {
92            store,
93            source: Box::new(source),
94        })
95        .boxed();
96    Ok(GetResult {
97        range: 0..meta.size,
98        payload: GetResultPayload::Stream(stream),
99        meta,
100        attributes: object_store::Attributes::new(),
101        extensions: Default::default(),
102    })
103}
104
105async fn exists(url: &str, store: &'static str, location: &Path, client: &Client) -> Result<bool> {
106    let request = client.request(Method::HEAD, url);
107    let response = request
108        .send()
109        .await
110        .with_context(|| format!("failed to send HEAD request for {location} to {store}"))?;
111    let status = response.status();
112    if status.is_success() {
113        Ok(true)
114    } else if status == reqwest::StatusCode::NOT_FOUND {
115        Ok(false)
116    } else {
117        Err(anyhow!(
118            "{store} returned unexpected status {status} for {location}"
119        ))
120    }
121}
122
123async fn size(url: &str, store: &'static str, location: &Path, client: &Client) -> Result<u64> {
124    let request = client.request(Method::HEAD, url);
125    let response = request
126        .send()
127        .await
128        .with_context(|| format!("failed to send HEAD request for {location} to {store}"))?
129        .error_for_status()
130        .with_context(|| format!("{store} returned an error status for {location}"))?;
131    let content_length = response
132        .headers()
133        .get(CONTENT_LENGTH)
134        .with_context(|| format!("{store} returned no content length for {location}"))?;
135    content_length
136        .to_str()
137        .context("bad content length header")?
138        .parse()
139        .context("invalid content length")
140}
141
142fn header_meta(location: &Path, headers: &HeaderMap) -> Result<ObjectMeta> {
143    let last_modified = headers
144        .get(LAST_MODIFIED)
145        .context("Missing last modified")?;
146
147    let content_length = headers
148        .get(CONTENT_LENGTH)
149        .context("Missing content length")?;
150
151    let last_modified = last_modified.to_str().context("bad header")?;
152    let last_modified = DateTime::parse_from_rfc2822(last_modified)
153        .context("invalid last modified")?
154        .with_timezone(&Utc);
155
156    let content_length = content_length.to_str().context("bad header")?;
157    let content_length = content_length.parse().context("invalid content length")?;
158
159    let e_tag = headers.get(ETAG).context("missing etag")?;
160    let e_tag = e_tag.to_str().context("bad header")?;
161
162    Ok(ObjectMeta {
163        location: location.clone(),
164        last_modified,
165        size: content_length,
166        e_tag: Some(e_tag.to_string()),
167        version: None,
168    })
169}
170
171#[cfg(test)]
172mod tests {
173    use std::fs;
174
175    use iota_config::object_storage_config::{ObjectStoreConfig, ObjectStoreType};
176    use object_store::path::Path;
177    use tempfile::TempDir;
178
179    use crate::object_store::{ObjectStoreGetExt, http::HttpDownloaderBuilder};
180
181    #[tokio::test]
182    pub async fn test_local_download() -> anyhow::Result<()> {
183        let input = TempDir::new()?;
184        let input_path = input.path();
185        let child = input_path.join("child");
186        fs::create_dir(&child)?;
187        let file1 = child.join("file1");
188        fs::write(file1, b"Lorem ipsum")?;
189        let grandchild = child.join("grand_child");
190        fs::create_dir(&grandchild)?;
191        let file2 = grandchild.join("file2");
192        fs::write(file2, b"Lorem ipsum")?;
193
194        let input_store = ObjectStoreConfig {
195            object_store: Some(ObjectStoreType::File),
196            directory: Some(input_path.to_path_buf()),
197            ..Default::default()
198        }
199        .make_http()?;
200
201        let downloaded = input_store.get_bytes(&Path::from("child/file1")).await?;
202        assert_eq!(downloaded.to_vec(), b"Lorem ipsum");
203        Ok(())
204    }
205
206    #[tokio::test]
207    pub async fn test_local_exists() -> anyhow::Result<()> {
208        let input = TempDir::new()?;
209        let input_path = input.path();
210        fs::write(input_path.join("file1"), b"Lorem ipsum")?;
211
212        let input_store = ObjectStoreConfig {
213            object_store: Some(ObjectStoreType::File),
214            directory: Some(input_path.to_path_buf()),
215            ..Default::default()
216        }
217        .make_http()?;
218
219        assert!(input_store.exists(&Path::from("file1")).await?);
220        assert!(!input_store.exists(&Path::from("missing")).await?);
221        Ok(())
222    }
223
224    #[tokio::test]
225    pub async fn test_local_object_size() -> anyhow::Result<()> {
226        let input = TempDir::new()?;
227        let input_path = input.path();
228        fs::write(input_path.join("file1"), b"Lorem ipsum")?;
229
230        let input_store = ObjectStoreConfig {
231            object_store: Some(ObjectStoreType::File),
232            directory: Some(input_path.to_path_buf()),
233            ..Default::default()
234        }
235        .make_http()?;
236
237        assert_eq!(input_store.object_size(&Path::from("file1")).await?, 11);
238        assert!(
239            input_store
240                .object_size(&Path::from("missing"))
241                .await
242                .is_err()
243        );
244        Ok(())
245    }
246}