1use std::sync::Arc;
38
39use async_trait::async_trait;
40use futures_util::stream::BoxStream;
41use futures_util::{StreamExt, TryStreamExt};
42use itertools::Itertools;
43use url::Url;
44
45use crate::client::get::GetClientExt;
46use crate::client::header::get_etag;
47use crate::client::{HttpConnector, http_connector};
48use crate::http::client::Client;
49use crate::path::Path;
50use crate::{
51 ClientConfigKey, ClientOptions, CopyMode, CopyOptions, GetOptions, GetResult, ListResult,
52 MultipartUpload, ObjectMeta, ObjectStore, PutMode, PutMultipartOptions, PutOptions, PutPayload,
53 PutResult, Result, RetryConfig,
54};
55
56mod client;
57
58const STORE: &str = "HTTP";
59
60#[derive(Debug, thiserror::Error)]
61enum Error {
62 #[error("Must specify a URL")]
63 MissingUrl,
64
65 #[error("Unable parse source url. Url: {}, Error: {}", url, source)]
66 UnableToParseUrl {
67 source: url::ParseError,
68 url: String,
69 },
70
71 #[error("Unable to extract metadata from headers: {}", source)]
72 Metadata {
73 source: crate::client::header::Error,
74 },
75}
76
77impl From<Error> for crate::Error {
78 fn from(err: Error) -> Self {
79 Self::Generic {
80 store: STORE,
81 source: Box::new(err),
82 }
83 }
84}
85
86#[derive(Debug)]
90pub struct HttpStore {
91 client: Arc<Client>,
92}
93
94impl std::fmt::Display for HttpStore {
95 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96 write!(f, "HttpStore")
97 }
98}
99
100#[async_trait]
101impl ObjectStore for HttpStore {
102 async fn put_opts(
103 &self,
104 location: &Path,
105 payload: PutPayload,
106 opts: PutOptions,
107 ) -> Result<PutResult> {
108 if opts.mode != PutMode::Overwrite {
109 return Err(crate::Error::NotImplemented {
111 operation: "`put_opts` with a mode other than `PutMode::Overwrite`".into(),
112 implementer: self.to_string(),
113 });
114 }
115
116 let response = self.client.put(location, payload, opts.attributes).await?;
117 let (parts, _) = response.into_parts();
118 let e_tag = match get_etag(&parts.headers) {
119 Ok(e_tag) => Some(e_tag),
120 Err(crate::client::header::Error::MissingEtag) => None,
121 Err(source) => return Err(Error::Metadata { source }.into()),
122 };
123
124 Ok(PutResult {
125 e_tag,
126 version: None,
127 extensions: parts.extensions,
128 })
129 }
130
131 async fn put_multipart_opts(
132 &self,
133 _location: &Path,
134 _opts: PutMultipartOptions,
135 ) -> Result<Box<dyn MultipartUpload>> {
136 Err(crate::Error::NotImplemented {
137 operation: "`put_multipart_opts`".into(),
138 implementer: self.to_string(),
139 })
140 }
141
142 async fn get_opts(&self, location: &Path, options: GetOptions) -> Result<GetResult> {
143 self.client.get_opts(location, options).await
144 }
145
146 fn delete_stream(
147 &self,
148 locations: BoxStream<'static, Result<Path>>,
149 ) -> BoxStream<'static, Result<Path>> {
150 let client = Arc::clone(&self.client);
151 locations
152 .map(move |location| {
153 let client = Arc::clone(&client);
154 async move {
155 let location = location?;
156 client.delete(&location).await?;
157 Ok(location)
158 }
159 })
160 .buffered(10)
161 .boxed()
162 }
163
164 fn list(&self, prefix: Option<&Path>) -> BoxStream<'static, Result<ObjectMeta>> {
165 let prefix_len = prefix.map(|p| p.as_ref().len()).unwrap_or_default();
166 let prefix = prefix.cloned();
167 let client = Arc::clone(&self.client);
168 futures_util::stream::once(async move {
169 let status = client.list(prefix.as_ref(), "infinity").await?;
170
171 let iter = status
172 .response
173 .into_iter()
174 .filter(|r| !r.is_dir())
175 .map(move |response| {
176 response.check_ok()?;
177 response.object_meta(client.base_url())
178 })
179 .filter_ok(move |r| r.location.as_ref().len() > prefix_len);
181
182 Ok::<_, crate::Error>(futures_util::stream::iter(iter))
183 })
184 .try_flatten()
185 .boxed()
186 }
187
188 async fn list_with_delimiter(&self, prefix: Option<&Path>) -> Result<ListResult> {
189 let status = self.client.list(prefix, "1").await?;
190 let prefix_len = prefix.map(|p| p.as_ref().len()).unwrap_or(0);
191
192 let mut objects: Vec<ObjectMeta> = Vec::with_capacity(status.response.len());
193 let mut common_prefixes = Vec::with_capacity(status.response.len());
194 for response in status.response {
195 response.check_ok()?;
196 match response.is_dir() {
197 false => {
198 let meta = response.object_meta(self.client.base_url())?;
199 if meta.location.as_ref().len() > prefix_len {
201 objects.push(meta);
202 }
203 }
204 true => {
205 let path = response.path(self.client.base_url())?;
206 if path.as_ref().len() > prefix_len {
208 common_prefixes.push(path);
209 }
210 }
211 }
212 }
213
214 Ok(ListResult {
215 common_prefixes,
216 objects,
217 extensions: status.extensions,
218 })
219 }
220
221 async fn copy_opts(&self, from: &Path, to: &Path, options: CopyOptions) -> Result<()> {
222 let CopyOptions {
223 mode,
224 extensions: _,
225 } = options;
226
227 match mode {
228 CopyMode::Overwrite => self.client.copy(from, to, true).await,
229 CopyMode::Create => self.client.copy(from, to, false).await,
230 }
231 }
232}
233
234#[derive(Debug, Default, Clone)]
236pub struct HttpBuilder {
237 url: Option<String>,
238 client_options: ClientOptions,
239 retry_config: RetryConfig,
240 http_connector: Option<Arc<dyn HttpConnector>>,
241}
242
243impl HttpBuilder {
244 pub fn new() -> Self {
246 Default::default()
247 }
248
249 pub fn with_url(mut self, url: impl Into<String>) -> Self {
251 self.url = Some(url.into());
252 self
253 }
254
255 pub fn with_retry(mut self, retry_config: RetryConfig) -> Self {
257 self.retry_config = retry_config;
258 self
259 }
260
261 pub fn with_config(mut self, key: ClientConfigKey, value: impl Into<String>) -> Self {
263 self.client_options = self.client_options.with_config(key, value);
264 self
265 }
266
267 pub fn with_client_options(mut self, options: ClientOptions) -> Self {
269 self.client_options = options;
270 self
271 }
272
273 pub fn with_http_connector<C: HttpConnector>(mut self, connector: C) -> Self {
277 self.http_connector = Some(Arc::new(connector));
278 self
279 }
280
281 pub fn build(self) -> Result<HttpStore> {
283 let url = self.url.ok_or(Error::MissingUrl)?;
284 let parsed = Url::parse(&url).map_err(|source| Error::UnableToParseUrl { url, source })?;
285
286 let client = http_connector(self.http_connector)?.connect(&self.client_options)?;
287
288 Ok(HttpStore {
289 client: Arc::new(Client::new(
290 parsed,
291 client,
292 self.client_options,
293 self.retry_config,
294 )),
295 })
296 }
297}
298
299#[cfg(test)]
300mod tests {
301 use crate::integration::*;
302 use crate::tests::*;
303
304 use super::*;
305
306 #[tokio::test]
307 async fn http_test() {
308 maybe_skip_integration!();
309 let url = std::env::var("HTTP_URL").expect("HTTP_URL must be set");
310 let options = ClientOptions::new().with_allow_http(true);
311 let integration = HttpBuilder::new()
314 .with_url(url)
315 .with_client_options(options)
316 .with_http_connector(MarkerHttpConnector::default())
317 .build()
318 .unwrap();
319
320 put_get_delete_list(&integration).await;
321 list_uses_directories_correctly(&integration).await;
322 list_with_delimiter(&integration).await;
323 rename_and_copy(&integration).await;
324 copy_if_not_exists(&integration).await;
325 response_extensions(&integration, false).await;
326 }
327}