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 stat_has_content_length: true,
150 stat_has_last_modified: true,
151 list_has_content_length: true,
152 list_has_last_modified: true,
153
154 ..Default::default()
155 });
156
157 #[allow(deprecated)]
159 if let Some(client) = self.http_client {
160 am.update_http_client(|_| client);
161 }
162
163 am.into()
164 },
165 root,
166 endpoint,
167 }),
168 })
169 }
170}
171
172#[derive(Debug, Clone)]
173pub struct AlluxioBackend {
174 core: Arc<AlluxioCore>,
175}
176
177impl Access for AlluxioBackend {
178 type Reader = HttpBody;
179 type Writer = AlluxioWriters;
180 type Lister = oio::PageLister<AlluxioLister>;
181 type Deleter = oio::OneShotDeleter<AlluxioDeleter>;
182
183 fn info(&self) -> Arc<AccessorInfo> {
184 self.core.info.clone()
185 }
186
187 async fn create_dir(&self, path: &str, _: OpCreateDir) -> Result<RpCreateDir> {
188 self.core.create_dir(path).await?;
189 Ok(RpCreateDir::default())
190 }
191
192 async fn stat(&self, path: &str, _: OpStat) -> Result<RpStat> {
193 let file_info = self.core.get_status(path).await?;
194
195 Ok(RpStat::new(file_info.try_into()?))
196 }
197
198 async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
199 let stream_id = self.core.open_file(path).await?;
200
201 let resp = self.core.read(stream_id, args.range()).await?;
202 if !resp.status().is_success() {
203 let (part, mut body) = resp.into_parts();
204 let buf = body.to_buffer().await?;
205 return Err(parse_error(Response::from_parts(part, buf)));
206 }
207 Ok((RpRead::new(), resp.into_body()))
208 }
209
210 async fn write(&self, path: &str, args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
211 let w = AlluxioWriter::new(self.core.clone(), args.clone(), path.to_string());
212
213 Ok((RpWrite::default(), w))
214 }
215
216 async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
217 Ok((
218 RpDelete::default(),
219 oio::OneShotDeleter::new(AlluxioDeleter::new(self.core.clone())),
220 ))
221 }
222
223 async fn list(&self, path: &str, _args: OpList) -> Result<(RpList, Self::Lister)> {
224 let l = AlluxioLister::new(self.core.clone(), path);
225 Ok((RpList::default(), oio::PageLister::new(l)))
226 }
227
228 async fn rename(&self, from: &str, to: &str, _: OpRename) -> Result<RpRename> {
229 self.core.rename(from, to).await?;
230
231 Ok(RpRename::default())
232 }
233}
234
235#[cfg(test)]
236mod test {
237 use std::collections::HashMap;
238
239 use super::*;
240
241 #[test]
242 fn test_builder_from_map() {
243 let mut map = HashMap::new();
244 map.insert("root".to_string(), "/".to_string());
245 map.insert("endpoint".to_string(), "http://127.0.0.1:39999".to_string());
246
247 let builder = AlluxioConfig::from_iter(map).unwrap();
248
249 assert_eq!(builder.root, Some("/".to_string()));
250 assert_eq!(builder.endpoint, Some("http://127.0.0.1:39999".to_string()));
251 }
252
253 #[test]
254 fn test_builder_build() {
255 let builder = AlluxioBuilder::default()
256 .root("/root")
257 .endpoint("http://127.0.0.1:39999")
258 .build();
259
260 assert!(builder.is_ok());
261 }
262}