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 crate::raw::*;
32use crate::services::AlluxioConfig;
33use crate::*;
34
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 const SCHEME: Scheme = Scheme::Alluxio;
108 type Config = AlluxioConfig;
109
110 fn build(self) -> Result<impl Access> {
112 debug!("backend build started: {:?}", &self);
113
114 let root = normalize_root(&self.config.root.clone().unwrap_or_default());
115 debug!("backend use root {}", &root);
116
117 let endpoint = match &self.config.endpoint {
118 Some(endpoint) => Ok(endpoint.clone()),
119 None => Err(Error::new(ErrorKind::ConfigInvalid, "endpoint is empty")
120 .with_operation("Builder::build")
121 .with_context("service", Scheme::Alluxio)),
122 }?;
123 debug!("backend use endpoint {}", &endpoint);
124
125 Ok(AlluxioBackend {
126 core: Arc::new(AlluxioCore {
127 info: {
128 let am = AccessorInfo::default();
129 am.set_scheme(Scheme::Alluxio)
130 .set_root(&root)
131 .set_native_capability(Capability {
132 stat: true,
133
134 read: false,
139
140 write: true,
141 write_can_multi: true,
142
143 create_dir: true,
144 delete: true,
145
146 list: true,
147
148 shared: true,
149
150 ..Default::default()
151 });
152
153 #[allow(deprecated)]
155 if let Some(client) = self.http_client {
156 am.update_http_client(|_| client);
157 }
158
159 am.into()
160 },
161 root,
162 endpoint,
163 }),
164 })
165 }
166}
167
168#[derive(Debug, Clone)]
169pub struct AlluxioBackend {
170 core: Arc<AlluxioCore>,
171}
172
173impl Access for AlluxioBackend {
174 type Reader = HttpBody;
175 type Writer = AlluxioWriters;
176 type Lister = oio::PageLister<AlluxioLister>;
177 type Deleter = oio::OneShotDeleter<AlluxioDeleter>;
178
179 fn info(&self) -> Arc<AccessorInfo> {
180 self.core.info.clone()
181 }
182
183 async fn create_dir(&self, path: &str, _: OpCreateDir) -> Result<RpCreateDir> {
184 self.core.create_dir(path).await?;
185 Ok(RpCreateDir::default())
186 }
187
188 async fn stat(&self, path: &str, _: OpStat) -> Result<RpStat> {
189 let file_info = self.core.get_status(path).await?;
190
191 Ok(RpStat::new(file_info.try_into()?))
192 }
193
194 async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
195 let stream_id = self.core.open_file(path).await?;
196
197 let resp = self.core.read(stream_id, args.range()).await?;
198 if !resp.status().is_success() {
199 let (part, mut body) = resp.into_parts();
200 let buf = body.to_buffer().await?;
201 return Err(parse_error(Response::from_parts(part, buf)));
202 }
203 Ok((RpRead::new(), resp.into_body()))
204 }
205
206 async fn write(&self, path: &str, args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
207 let w = AlluxioWriter::new(self.core.clone(), args.clone(), path.to_string());
208
209 Ok((RpWrite::default(), w))
210 }
211
212 async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
213 Ok((
214 RpDelete::default(),
215 oio::OneShotDeleter::new(AlluxioDeleter::new(self.core.clone())),
216 ))
217 }
218
219 async fn list(&self, path: &str, _args: OpList) -> Result<(RpList, Self::Lister)> {
220 let l = AlluxioLister::new(self.core.clone(), path);
221 Ok((RpList::default(), oio::PageLister::new(l)))
222 }
223
224 async fn rename(&self, from: &str, to: &str, _: OpRename) -> Result<RpRename> {
225 self.core.rename(from, to).await?;
226
227 Ok(RpRename::default())
228 }
229}
230
231#[cfg(test)]
232mod test {
233 use std::collections::HashMap;
234
235 use super::*;
236
237 #[test]
238 fn test_builder_from_map() {
239 let mut map = HashMap::new();
240 map.insert("root".to_string(), "/".to_string());
241 map.insert("endpoint".to_string(), "http://127.0.0.1:39999".to_string());
242
243 let builder = AlluxioConfig::from_iter(map).unwrap();
244
245 assert_eq!(builder.root, Some("/".to_string()));
246 assert_eq!(builder.endpoint, Some("http://127.0.0.1:39999".to_string()));
247 }
248
249 #[test]
250 fn test_builder_build() {
251 let builder = AlluxioBuilder::default()
252 .root("/root")
253 .endpoint("http://127.0.0.1:39999")
254 .build();
255
256 assert!(builder.is_ok());
257 }
258}