opendal/services/alluxio/
backend.rs1use std::fmt::Debug;
19use std::fmt::Formatter;
20use std::sync::Arc;
21
22use http::Response;
23use log::debug;
24
25use super::core::AlluxioCore;
26use super::delete::AlluxioDeleter;
27use super::error::parse_error;
28use super::lister::AlluxioLister;
29use super::writer::AlluxioWriter;
30use super::writer::AlluxioWriters;
31use super::DEFAULT_SCHEME;
32use crate::raw::*;
33use crate::services::AlluxioConfig;
34use crate::*;
35impl Configurator for AlluxioConfig {
36 type Builder = AlluxioBuilder;
37
38 #[allow(deprecated)]
39 fn into_builder(self) -> Self::Builder {
40 AlluxioBuilder {
41 config: self,
42 http_client: None,
43 }
44 }
45}
46
47#[doc = include_str!("docs.md")]
49#[derive(Default)]
50pub struct AlluxioBuilder {
51 config: AlluxioConfig,
52
53 #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
54 http_client: Option<HttpClient>,
55}
56
57impl Debug for AlluxioBuilder {
58 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
59 let mut d = f.debug_struct("AlluxioBuilder");
60
61 d.field("config", &self.config);
62 d.finish_non_exhaustive()
63 }
64}
65
66impl AlluxioBuilder {
67 pub fn root(mut self, root: &str) -> Self {
71 self.config.root = if root.is_empty() {
72 None
73 } else {
74 Some(root.to_string())
75 };
76
77 self
78 }
79
80 pub fn endpoint(mut self, endpoint: &str) -> Self {
84 if !endpoint.is_empty() {
85 self.config.endpoint = Some(endpoint.trim_end_matches('/').to_string())
87 }
88
89 self
90 }
91
92 #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
99 #[allow(deprecated)]
100 pub fn http_client(mut self, client: HttpClient) -> Self {
101 self.http_client = Some(client);
102 self
103 }
104}
105
106impl Builder for AlluxioBuilder {
107 type Config = AlluxioConfig;
108
109 fn build(self) -> Result<impl Access> {
111 debug!("backend build started: {:?}", &self);
112
113 let root = normalize_root(&self.config.root.clone().unwrap_or_default());
114 debug!("backend use root {}", &root);
115
116 let endpoint = match &self.config.endpoint {
117 Some(endpoint) => Ok(endpoint.clone()),
118 None => Err(Error::new(ErrorKind::ConfigInvalid, "endpoint is empty")
119 .with_operation("Builder::build")
120 .with_context("service", Scheme::Alluxio)),
121 }?;
122 debug!("backend use endpoint {}", &endpoint);
123
124 Ok(AlluxioBackend {
125 core: Arc::new(AlluxioCore {
126 info: {
127 let am = AccessorInfo::default();
128 am.set_scheme(DEFAULT_SCHEME)
129 .set_root(&root)
130 .set_native_capability(Capability {
131 stat: true,
132
133 read: false,
138
139 write: true,
140 write_can_multi: true,
141
142 create_dir: true,
143 delete: true,
144
145 list: true,
146
147 shared: true,
148
149 ..Default::default()
150 });
151
152 #[allow(deprecated)]
154 if let Some(client) = self.http_client {
155 am.update_http_client(|_| client);
156 }
157
158 am.into()
159 },
160 root,
161 endpoint,
162 }),
163 })
164 }
165}
166
167#[derive(Debug, Clone)]
168pub struct AlluxioBackend {
169 core: Arc<AlluxioCore>,
170}
171
172impl Access for AlluxioBackend {
173 type Reader = HttpBody;
174 type Writer = AlluxioWriters;
175 type Lister = oio::PageLister<AlluxioLister>;
176 type Deleter = oio::OneShotDeleter<AlluxioDeleter>;
177
178 fn info(&self) -> Arc<AccessorInfo> {
179 self.core.info.clone()
180 }
181
182 async fn create_dir(&self, path: &str, _: OpCreateDir) -> Result<RpCreateDir> {
183 self.core.create_dir(path).await?;
184 Ok(RpCreateDir::default())
185 }
186
187 async fn stat(&self, path: &str, _: OpStat) -> Result<RpStat> {
188 let file_info = self.core.get_status(path).await?;
189
190 Ok(RpStat::new(file_info.try_into()?))
191 }
192
193 async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
194 let stream_id = self.core.open_file(path).await?;
195
196 let resp = self.core.read(stream_id, args.range()).await?;
197 if !resp.status().is_success() {
198 let (part, mut body) = resp.into_parts();
199 let buf = body.to_buffer().await?;
200 return Err(parse_error(Response::from_parts(part, buf)));
201 }
202 Ok((RpRead::new(), resp.into_body()))
203 }
204
205 async fn write(&self, path: &str, args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
206 let w = AlluxioWriter::new(self.core.clone(), args.clone(), path.to_string());
207
208 Ok((RpWrite::default(), w))
209 }
210
211 async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
212 Ok((
213 RpDelete::default(),
214 oio::OneShotDeleter::new(AlluxioDeleter::new(self.core.clone())),
215 ))
216 }
217
218 async fn list(&self, path: &str, _args: OpList) -> Result<(RpList, Self::Lister)> {
219 let l = AlluxioLister::new(self.core.clone(), path);
220 Ok((RpList::default(), oio::PageLister::new(l)))
221 }
222
223 async fn rename(&self, from: &str, to: &str, _: OpRename) -> Result<RpRename> {
224 self.core.rename(from, to).await?;
225
226 Ok(RpRename::default())
227 }
228}
229
230#[cfg(test)]
231mod test {
232 use std::collections::HashMap;
233
234 use super::*;
235
236 #[test]
237 fn test_builder_from_map() {
238 let mut map = HashMap::new();
239 map.insert("root".to_string(), "/".to_string());
240 map.insert("endpoint".to_string(), "http://127.0.0.1:39999".to_string());
241
242 let builder = AlluxioConfig::from_iter(map).unwrap();
243
244 assert_eq!(builder.root, Some("/".to_string()));
245 assert_eq!(builder.endpoint, Some("http://127.0.0.1:39999".to_string()));
246 }
247
248 #[test]
249 fn test_builder_build() {
250 let builder = AlluxioBuilder::default()
251 .root("/root")
252 .endpoint("http://127.0.0.1:39999")
253 .build();
254
255 assert!(builder.is_ok());
256 }
257}