opendal/services/http/
backend.rs1use std::fmt::Debug;
19use std::fmt::Formatter;
20use std::sync::Arc;
21
22use http::Response;
23use http::StatusCode;
24use log::debug;
25
26use super::core::HttpCore;
27use super::error::parse_error;
28use super::DEFAULT_SCHEME;
29use crate::raw::*;
30use crate::services::HttpConfig;
31use crate::*;
32impl Configurator for HttpConfig {
33 type Builder = HttpBuilder;
34
35 #[allow(deprecated)]
36 fn into_builder(self) -> Self::Builder {
37 HttpBuilder {
38 config: self,
39 http_client: None,
40 }
41 }
42}
43
44#[doc = include_str!("docs.md")]
46#[derive(Default)]
47pub struct HttpBuilder {
48 config: HttpConfig,
49
50 #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
51 http_client: Option<HttpClient>,
52}
53
54impl Debug for HttpBuilder {
55 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
56 let mut de = f.debug_struct("HttpBuilder");
57
58 de.field("config", &self.config).finish()
59 }
60}
61
62impl HttpBuilder {
63 pub fn endpoint(mut self, endpoint: &str) -> Self {
67 self.config.endpoint = if endpoint.is_empty() {
68 None
69 } else {
70 Some(endpoint.to_string())
71 };
72
73 self
74 }
75
76 pub fn username(mut self, username: &str) -> Self {
80 if !username.is_empty() {
81 self.config.username = Some(username.to_owned());
82 }
83 self
84 }
85
86 pub fn password(mut self, password: &str) -> Self {
90 if !password.is_empty() {
91 self.config.password = Some(password.to_owned());
92 }
93 self
94 }
95
96 pub fn token(mut self, token: &str) -> Self {
100 if !token.is_empty() {
101 self.config.token = Some(token.to_string());
102 }
103 self
104 }
105
106 pub fn root(mut self, root: &str) -> Self {
108 self.config.root = if root.is_empty() {
109 None
110 } else {
111 Some(root.to_string())
112 };
113
114 self
115 }
116
117 #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
124 #[allow(deprecated)]
125 pub fn http_client(mut self, client: HttpClient) -> Self {
126 self.http_client = Some(client);
127 self
128 }
129}
130
131impl Builder for HttpBuilder {
132 type Config = HttpConfig;
133
134 fn build(self) -> Result<impl Access> {
135 debug!("backend build started: {:?}", &self);
136
137 let endpoint = match &self.config.endpoint {
138 Some(v) => v,
139 None => {
140 return Err(Error::new(ErrorKind::ConfigInvalid, "endpoint is empty")
141 .with_context("service", Scheme::Http))
142 }
143 };
144
145 let root = normalize_root(&self.config.root.unwrap_or_default());
146 debug!("backend use root {root}");
147
148 let mut auth = None;
149 if let Some(username) = &self.config.username {
150 auth = Some(format_authorization_by_basic(
151 username,
152 self.config.password.as_deref().unwrap_or_default(),
153 )?);
154 }
155 if let Some(token) = &self.config.token {
156 auth = Some(format_authorization_by_bearer(token)?)
157 }
158
159 let info = AccessorInfo::default();
160 info.set_scheme(DEFAULT_SCHEME)
161 .set_root(&root)
162 .set_native_capability(Capability {
163 stat: true,
164 stat_with_if_match: true,
165 stat_with_if_none_match: true,
166
167 read: true,
168
169 read_with_if_match: true,
170 read_with_if_none_match: true,
171
172 presign: auth.is_none(),
173 presign_read: auth.is_none(),
174 presign_stat: auth.is_none(),
175
176 shared: true,
177
178 ..Default::default()
179 });
180
181 #[allow(deprecated)]
183 if let Some(client) = self.http_client {
184 info.update_http_client(|_| client);
185 }
186
187 let accessor_info = Arc::new(info);
188
189 let core = Arc::new(HttpCore {
190 info: accessor_info,
191 endpoint: endpoint.to_string(),
192 root,
193 authorization: auth,
194 });
195
196 Ok(HttpBackend { core })
197 }
198}
199
200#[derive(Clone)]
202pub struct HttpBackend {
203 core: Arc<HttpCore>,
204}
205
206impl Debug for HttpBackend {
207 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
208 f.debug_struct("HttpBackend")
209 .field("core", &self.core)
210 .finish()
211 }
212}
213
214impl Access for HttpBackend {
215 type Reader = HttpBody;
216 type Writer = ();
217 type Lister = ();
218 type Deleter = ();
219
220 fn info(&self) -> Arc<AccessorInfo> {
221 self.core.info.clone()
222 }
223
224 async fn stat(&self, path: &str, args: OpStat) -> Result<RpStat> {
225 if path == "/" {
227 return Ok(RpStat::new(Metadata::new(EntryMode::DIR)));
228 }
229
230 let resp = self.core.http_head(path, &args).await?;
231
232 let status = resp.status();
233
234 match status {
235 StatusCode::OK => parse_into_metadata(path, resp.headers()).map(RpStat::new),
236 StatusCode::NOT_FOUND | StatusCode::FORBIDDEN if path.ends_with('/') => {
239 Ok(RpStat::new(Metadata::new(EntryMode::DIR)))
240 }
241 _ => Err(parse_error(resp)),
242 }
243 }
244
245 async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
246 let resp = self.core.http_get(path, args.range(), &args).await?;
247
248 let status = resp.status();
249
250 match status {
251 StatusCode::OK | StatusCode::PARTIAL_CONTENT => {
252 Ok((RpRead::default(), resp.into_body()))
253 }
254 _ => {
255 let (part, mut body) = resp.into_parts();
256 let buf = body.to_buffer().await?;
257 Err(parse_error(Response::from_parts(part, buf)))
258 }
259 }
260 }
261
262 async fn presign(&self, path: &str, args: OpPresign) -> Result<RpPresign> {
263 if self.core.has_authorization() {
264 return Err(Error::new(
265 ErrorKind::Unsupported,
266 "Http doesn't support presigned request on backend with authorization",
267 ));
268 }
269
270 let req = match args.operation() {
271 PresignOperation::Stat(v) => self.core.http_head_request(path, v)?,
272 PresignOperation::Read(v) => {
273 self.core.http_get_request(path, BytesRange::default(), v)?
274 }
275 _ => {
276 return Err(Error::new(
277 ErrorKind::Unsupported,
278 "Http doesn't support presigned write",
279 ))
280 }
281 };
282
283 let (parts, _) = req.into_parts();
284
285 Ok(RpPresign::new(PresignedRequest::new(
286 parts.method,
287 parts.uri,
288 parts.headers,
289 )))
290 }
291}