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::AzfileCore;
30use super::delete::AzfileDeleter;
31use super::error::parse_error;
32use super::lister::AzfileLister;
33use super::writer::AzfileWriter;
34use super::writer::AzfileWriters;
35use super::DEFAULT_SCHEME;
36use crate::raw::*;
37use crate::services::AzfileConfig;
38use crate::*;
39impl From<AzureStorageConfig> for AzfileConfig {
40 fn from(config: AzureStorageConfig) -> Self {
41 AzfileConfig {
42 account_name: config.account_name,
43 account_key: config.account_key,
44 sas_token: config.sas_token,
45 endpoint: config.endpoint,
46 root: None, share_name: String::new(), }
49 }
50}
51
52impl Configurator for AzfileConfig {
53 type Builder = AzfileBuilder;
54
55 #[allow(deprecated)]
56 fn into_builder(self) -> Self::Builder {
57 AzfileBuilder {
58 config: self,
59 http_client: None,
60 }
61 }
62}
63
64#[doc = include_str!("docs.md")]
66#[derive(Default, Clone)]
67pub struct AzfileBuilder {
68 config: AzfileConfig,
69
70 #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
71 http_client: Option<HttpClient>,
72}
73
74impl Debug for AzfileBuilder {
75 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
76 let mut ds = f.debug_struct("AzfileBuilder");
77
78 ds.field("config", &self.config);
79
80 ds.finish()
81 }
82}
83
84impl AzfileBuilder {
85 pub fn root(mut self, root: &str) -> Self {
89 self.config.root = if root.is_empty() {
90 None
91 } else {
92 Some(root.to_string())
93 };
94
95 self
96 }
97
98 pub fn endpoint(mut self, endpoint: &str) -> Self {
100 if !endpoint.is_empty() {
101 self.config.endpoint = Some(endpoint.trim_end_matches('/').to_string());
103 }
104
105 self
106 }
107
108 pub fn account_name(mut self, account_name: &str) -> Self {
113 if !account_name.is_empty() {
114 self.config.account_name = Some(account_name.to_string());
115 }
116
117 self
118 }
119
120 pub fn account_key(mut self, account_key: &str) -> Self {
125 if !account_key.is_empty() {
126 self.config.account_key = Some(account_key.to_string());
127 }
128
129 self
130 }
131
132 pub fn share_name(mut self, share_name: &str) -> Self {
137 if !share_name.is_empty() {
138 self.config.share_name = share_name.to_string();
139 }
140
141 self
142 }
143
144 #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
151 #[allow(deprecated)]
152 pub fn http_client(mut self, client: HttpClient) -> Self {
153 self.http_client = Some(client);
154 self
155 }
156
157 pub fn from_connection_string(conn_str: &str) -> Result<Self> {
176 let config =
177 raw::azure_config_from_connection_string(conn_str, raw::AzureStorageService::File)?;
178
179 Ok(AzfileConfig::from(config).into_builder())
180 }
181}
182
183impl Builder for AzfileBuilder {
184 type Config = AzfileConfig;
185
186 fn build(self) -> Result<impl Access> {
187 debug!("backend build started: {:?}", &self);
188
189 let root = normalize_root(&self.config.root.unwrap_or_default());
190 debug!("backend use root {root}");
191
192 let endpoint = match &self.config.endpoint {
193 Some(endpoint) => Ok(endpoint.clone()),
194 None => Err(Error::new(ErrorKind::ConfigInvalid, "endpoint is empty")
195 .with_operation("Builder::build")
196 .with_context("service", Scheme::Azfile)),
197 }?;
198 debug!("backend use endpoint {}", &endpoint);
199
200 let account_name_option = self
201 .config
202 .account_name
203 .clone()
204 .or_else(|| raw::azure_account_name_from_endpoint(endpoint.as_str()));
205
206 let account_name = match account_name_option {
207 Some(account_name) => Ok(account_name),
208 None => Err(
209 Error::new(ErrorKind::ConfigInvalid, "account_name is empty")
210 .with_operation("Builder::build")
211 .with_context("service", Scheme::Azfile),
212 ),
213 }?;
214
215 let config_loader = AzureStorageConfig {
216 account_name: Some(account_name),
217 account_key: self.config.account_key.clone(),
218 sas_token: self.config.sas_token.clone(),
219 ..Default::default()
220 };
221
222 let cred_loader = AzureStorageLoader::new(config_loader);
223 let signer = AzureStorageSigner::new();
224 Ok(AzfileBackend {
225 core: Arc::new(AzfileCore {
226 info: {
227 let am = AccessorInfo::default();
228 am.set_scheme(DEFAULT_SCHEME)
229 .set_root(&root)
230 .set_native_capability(Capability {
231 stat: true,
232
233 read: true,
234
235 write: true,
236 create_dir: true,
237 delete: true,
238 rename: true,
239
240 list: true,
241
242 shared: true,
243
244 ..Default::default()
245 });
246
247 #[allow(deprecated)]
249 if let Some(client) = self.http_client {
250 am.update_http_client(|_| client);
251 }
252
253 am.into()
254 },
255 root,
256 endpoint,
257 loader: cred_loader,
258 signer,
259 share_name: self.config.share_name.clone(),
260 }),
261 })
262 }
263}
264
265#[derive(Debug, Clone)]
267pub struct AzfileBackend {
268 core: Arc<AzfileCore>,
269}
270
271impl Access for AzfileBackend {
272 type Reader = HttpBody;
273 type Writer = AzfileWriters;
274 type Lister = oio::PageLister<AzfileLister>;
275 type Deleter = oio::OneShotDeleter<AzfileDeleter>;
276
277 fn info(&self) -> Arc<AccessorInfo> {
278 self.core.info.clone()
279 }
280
281 async fn create_dir(&self, path: &str, _: OpCreateDir) -> Result<RpCreateDir> {
282 self.core.ensure_parent_dir_exists(path).await?;
283 let resp = self.core.azfile_create_dir(path).await?;
284 let status = resp.status();
285
286 match status {
287 StatusCode::CREATED => Ok(RpCreateDir::default()),
288 _ => {
289 if resp
295 .headers()
296 .get("x-ms-error-code")
297 .map(|value| value.to_str().unwrap_or(""))
298 .unwrap_or_else(|| "")
299 == "ResourceAlreadyExists"
300 {
301 Ok(RpCreateDir::default())
302 } else {
303 Err(parse_error(resp))
304 }
305 }
306 }
307 }
308
309 async fn stat(&self, path: &str, _: OpStat) -> Result<RpStat> {
310 let resp = if path.ends_with('/') {
311 self.core.azfile_get_directory_properties(path).await?
312 } else {
313 self.core.azfile_get_file_properties(path).await?
314 };
315
316 let status = resp.status();
317 match status {
318 StatusCode::OK => {
319 let meta = parse_into_metadata(path, resp.headers())?;
320 Ok(RpStat::new(meta))
321 }
322 _ => Err(parse_error(resp)),
323 }
324 }
325
326 async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
327 let resp = self.core.azfile_read(path, args.range()).await?;
328
329 let status = resp.status();
330 match status {
331 StatusCode::OK | StatusCode::PARTIAL_CONTENT => Ok((RpRead::new(), resp.into_body())),
332 _ => {
333 let (part, mut body) = resp.into_parts();
334 let buf = body.to_buffer().await?;
335 Err(parse_error(Response::from_parts(part, buf)))
336 }
337 }
338 }
339
340 async fn write(&self, path: &str, args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
341 self.core.ensure_parent_dir_exists(path).await?;
342 let w = AzfileWriter::new(self.core.clone(), args.clone(), path.to_string());
343 let w = if args.append() {
344 AzfileWriters::Two(oio::AppendWriter::new(w))
345 } else {
346 AzfileWriters::One(oio::OneShotWriter::new(w))
347 };
348 Ok((RpWrite::default(), w))
349 }
350
351 async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
352 Ok((
353 RpDelete::default(),
354 oio::OneShotDeleter::new(AzfileDeleter::new(self.core.clone())),
355 ))
356 }
357
358 async fn list(&self, path: &str, args: OpList) -> Result<(RpList, Self::Lister)> {
359 let l = AzfileLister::new(self.core.clone(), path.to_string(), args.limit());
360
361 Ok((RpList::default(), oio::PageLister::new(l)))
362 }
363
364 async fn rename(&self, from: &str, to: &str, _: OpRename) -> Result<RpRename> {
365 self.core.ensure_parent_dir_exists(to).await?;
366 let resp = self.core.azfile_rename(from, to).await?;
367 let status = resp.status();
368 match status {
369 StatusCode::OK => Ok(RpRename::default()),
370 _ => Err(parse_error(resp)),
371 }
372 }
373}