1use std::fmt::Debug;
19use std::fmt::Formatter;
20use std::sync::Arc;
21
22use http::Response;
23use http::StatusCode;
24use log::debug;
25use reqsign::AzureStorageConfig;
26use reqsign::AzureStorageLoader;
27use reqsign::AzureStorageSigner;
28
29use super::core::AzdlsCore;
30use super::core::DIRECTORY;
31use super::delete::AzdlsDeleter;
32use super::error::parse_error;
33use super::lister::AzdlsLister;
34use super::writer::AzdlsWriter;
35use super::writer::AzdlsWriters;
36use super::DEFAULT_SCHEME;
37use crate::raw::*;
38use crate::services::AzdlsConfig;
39use crate::*;
40impl From<AzureStorageConfig> for AzdlsConfig {
41 fn from(config: AzureStorageConfig) -> Self {
42 AzdlsConfig {
43 endpoint: config.endpoint,
44 account_name: config.account_name,
45 account_key: config.account_key,
46 client_secret: config.client_secret,
47 tenant_id: config.tenant_id,
48 client_id: config.client_id,
49 sas_token: config.sas_token,
50 authority_host: config.authority_host,
51 ..Default::default()
52 }
53 }
54}
55
56impl Configurator for AzdlsConfig {
57 type Builder = AzdlsBuilder;
58
59 #[allow(deprecated)]
60 fn into_builder(self) -> Self::Builder {
61 AzdlsBuilder {
62 config: self,
63 http_client: None,
64 }
65 }
66}
67
68#[doc = include_str!("docs.md")]
70#[derive(Default, Clone)]
71pub struct AzdlsBuilder {
72 config: AzdlsConfig,
73
74 #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
75 http_client: Option<HttpClient>,
76}
77
78impl Debug for AzdlsBuilder {
79 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
80 let mut ds = f.debug_struct("AzdlsBuilder");
81
82 ds.field("config", &self.config);
83
84 ds.finish()
85 }
86}
87
88impl AzdlsBuilder {
89 pub fn root(mut self, root: &str) -> Self {
93 self.config.root = if root.is_empty() {
94 None
95 } else {
96 Some(root.to_string())
97 };
98
99 self
100 }
101
102 pub fn filesystem(mut self, filesystem: &str) -> Self {
104 self.config.filesystem = filesystem.to_string();
105
106 self
107 }
108
109 pub fn endpoint(mut self, endpoint: &str) -> Self {
116 if !endpoint.is_empty() {
117 self.config.endpoint = Some(endpoint.trim_end_matches('/').to_string());
119 }
120
121 self
122 }
123
124 pub fn account_name(mut self, account_name: &str) -> Self {
129 if !account_name.is_empty() {
130 self.config.account_name = Some(account_name.to_string());
131 }
132
133 self
134 }
135
136 pub fn account_key(mut self, account_key: &str) -> Self {
141 if !account_key.is_empty() {
142 self.config.account_key = Some(account_key.to_string());
143 }
144
145 self
146 }
147
148 pub fn client_secret(mut self, client_secret: &str) -> Self {
154 if !client_secret.is_empty() {
155 self.config.client_secret = Some(client_secret.to_string());
156 }
157
158 self
159 }
160
161 pub fn tenant_id(mut self, tenant_id: &str) -> Self {
167 if !tenant_id.is_empty() {
168 self.config.tenant_id = Some(tenant_id.to_string());
169 }
170
171 self
172 }
173
174 pub fn client_id(mut self, client_id: &str) -> Self {
180 if !client_id.is_empty() {
181 self.config.client_id = Some(client_id.to_string());
182 }
183
184 self
185 }
186
187 pub fn sas_token(mut self, sas_token: &str) -> Self {
189 if !sas_token.is_empty() {
190 self.config.sas_token = Some(sas_token.to_string());
191 }
192
193 self
194 }
195
196 pub fn authority_host(mut self, authority_host: &str) -> Self {
202 if !authority_host.is_empty() {
203 self.config.authority_host = Some(authority_host.to_string());
204 }
205
206 self
207 }
208
209 #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
216 #[allow(deprecated)]
217 pub fn http_client(mut self, client: HttpClient) -> Self {
218 self.http_client = Some(client);
219 self
220 }
221
222 pub fn from_connection_string(conn_str: &str) -> Result<Self> {
244 let config =
245 raw::azure_config_from_connection_string(conn_str, raw::AzureStorageService::Adls)?;
246
247 Ok(AzdlsConfig::from(config).into_builder())
248 }
249}
250
251impl Builder for AzdlsBuilder {
252 type Config = AzdlsConfig;
253
254 fn build(self) -> Result<impl Access> {
255 debug!("backend build started: {:?}", &self);
256
257 let root = normalize_root(&self.config.root.unwrap_or_default());
258 debug!("backend use root {root}");
259
260 let filesystem = match self.config.filesystem.is_empty() {
262 false => Ok(&self.config.filesystem),
263 true => Err(Error::new(ErrorKind::ConfigInvalid, "filesystem is empty")
264 .with_operation("Builder::build")
265 .with_context("service", Scheme::Azdls)),
266 }?;
267 debug!("backend use filesystem {}", &filesystem);
268
269 let endpoint = match &self.config.endpoint {
270 Some(endpoint) => Ok(endpoint.clone().trim_end_matches('/').to_string()),
271 None => Err(Error::new(ErrorKind::ConfigInvalid, "endpoint is empty")
272 .with_operation("Builder::build")
273 .with_context("service", Scheme::Azdls)),
274 }?;
275 debug!("backend use endpoint {}", &endpoint);
276
277 let config_loader = AzureStorageConfig {
278 account_name: self
279 .config
280 .account_name
281 .clone()
282 .or_else(|| raw::azure_account_name_from_endpoint(endpoint.as_str())),
283 account_key: self.config.account_key.clone(),
284 sas_token: self.config.sas_token,
285 client_id: self.config.client_id.clone(),
286 client_secret: self.config.client_secret.clone(),
287 tenant_id: self.config.tenant_id.clone(),
288 authority_host: self.config.authority_host.clone(),
289 ..Default::default()
290 };
291
292 let cred_loader = AzureStorageLoader::new(config_loader);
293 let signer = AzureStorageSigner::new();
294 Ok(AzdlsBackend {
295 core: Arc::new(AzdlsCore {
296 info: {
297 let am = AccessorInfo::default();
298 am.set_scheme(DEFAULT_SCHEME)
299 .set_root(&root)
300 .set_name(filesystem)
301 .set_native_capability(Capability {
302 stat: true,
303
304 read: true,
305
306 write: true,
307 write_can_append: true,
308 write_with_if_none_match: true,
309 write_with_if_not_exists: true,
310
311 create_dir: true,
312 delete: true,
313 rename: true,
314
315 list: true,
316
317 shared: true,
318
319 ..Default::default()
320 });
321
322 #[allow(deprecated)]
324 if let Some(client) = self.http_client {
325 am.update_http_client(|_| client);
326 }
327
328 am.into()
329 },
330 filesystem: self.config.filesystem.clone(),
331 root,
332 endpoint,
333 loader: cred_loader,
334 signer,
335 }),
336 })
337 }
338}
339
340#[derive(Debug, Clone)]
342pub struct AzdlsBackend {
343 core: Arc<AzdlsCore>,
344}
345
346impl Access for AzdlsBackend {
347 type Reader = HttpBody;
348 type Writer = AzdlsWriters;
349 type Lister = oio::PageLister<AzdlsLister>;
350 type Deleter = oio::OneShotDeleter<AzdlsDeleter>;
351
352 fn info(&self) -> Arc<AccessorInfo> {
353 self.core.info.clone()
354 }
355
356 async fn create_dir(&self, path: &str, _: OpCreateDir) -> Result<RpCreateDir> {
357 let resp = self
358 .core
359 .azdls_create(path, DIRECTORY, &OpWrite::default())
360 .await?;
361
362 let status = resp.status();
363 match status {
364 StatusCode::CREATED | StatusCode::OK => Ok(RpCreateDir::default()),
365 _ => Err(parse_error(resp)),
366 }
367 }
368
369 async fn stat(&self, path: &str, _: OpStat) -> Result<RpStat> {
370 if path == "/" {
373 return Ok(RpStat::new(Metadata::new(EntryMode::DIR)));
374 }
375
376 let metadata = self.core.azdls_stat_metadata(path).await?;
377 Ok(RpStat::new(metadata))
378 }
379
380 async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
381 let resp = self.core.azdls_read(path, args.range()).await?;
382
383 let status = resp.status();
384 match status {
385 StatusCode::OK | StatusCode::PARTIAL_CONTENT => Ok((RpRead::new(), resp.into_body())),
386 _ => {
387 let (part, mut body) = resp.into_parts();
388 let buf = body.to_buffer().await?;
389 Err(parse_error(Response::from_parts(part, buf)))
390 }
391 }
392 }
393
394 async fn write(&self, path: &str, args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
395 let w = AzdlsWriter::new(self.core.clone(), args.clone(), path.to_string());
396 let w = if args.append() {
397 AzdlsWriters::Two(oio::AppendWriter::new(w))
398 } else {
399 AzdlsWriters::One(oio::OneShotWriter::new(w))
400 };
401 Ok((RpWrite::default(), w))
402 }
403
404 async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
405 Ok((
406 RpDelete::default(),
407 oio::OneShotDeleter::new(AzdlsDeleter::new(self.core.clone())),
408 ))
409 }
410
411 async fn list(&self, path: &str, args: OpList) -> Result<(RpList, Self::Lister)> {
412 let l = AzdlsLister::new(self.core.clone(), path.to_string(), args.limit());
413
414 Ok((RpList::default(), oio::PageLister::new(l)))
415 }
416
417 async fn rename(&self, from: &str, to: &str, _args: OpRename) -> Result<RpRename> {
418 if let Some(resp) = self.core.azdls_ensure_parent_path(to).await? {
419 let status = resp.status();
420 match status {
421 StatusCode::CREATED | StatusCode::CONFLICT => {}
422 _ => return Err(parse_error(resp)),
423 }
424 }
425
426 let resp = self.core.azdls_rename(from, to).await?;
427
428 let status = resp.status();
429
430 match status {
431 StatusCode::CREATED => Ok(RpRename::default()),
432 _ => Err(parse_error(resp)),
433 }
434 }
435}