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 crate::raw::*;
36use crate::services::AzfileConfig;
37use crate::*;
38
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 const SCHEME: Scheme = Scheme::Azfile;
185 type Config = AzfileConfig;
186
187 fn build(self) -> Result<impl Access> {
188 debug!("backend build started: {:?}", &self);
189
190 let root = normalize_root(&self.config.root.unwrap_or_default());
191 debug!("backend use root {root}");
192
193 let endpoint = match &self.config.endpoint {
194 Some(endpoint) => Ok(endpoint.clone()),
195 None => Err(Error::new(ErrorKind::ConfigInvalid, "endpoint is empty")
196 .with_operation("Builder::build")
197 .with_context("service", Scheme::Azfile)),
198 }?;
199 debug!("backend use endpoint {}", &endpoint);
200
201 let account_name_option = self
202 .config
203 .account_name
204 .clone()
205 .or_else(|| raw::azure_account_name_from_endpoint(endpoint.as_str()));
206
207 let account_name = match account_name_option {
208 Some(account_name) => Ok(account_name),
209 None => Err(
210 Error::new(ErrorKind::ConfigInvalid, "account_name is empty")
211 .with_operation("Builder::build")
212 .with_context("service", Scheme::Azfile),
213 ),
214 }?;
215
216 let config_loader = AzureStorageConfig {
217 account_name: Some(account_name),
218 account_key: self.config.account_key.clone(),
219 sas_token: self.config.sas_token.clone(),
220 ..Default::default()
221 };
222
223 let cred_loader = AzureStorageLoader::new(config_loader);
224 let signer = AzureStorageSigner::new();
225 Ok(AzfileBackend {
226 core: Arc::new(AzfileCore {
227 info: {
228 let am = AccessorInfo::default();
229 am.set_scheme(Scheme::Azfile)
230 .set_root(&root)
231 .set_native_capability(Capability {
232 stat: true,
233
234 read: true,
235
236 write: true,
237 create_dir: true,
238 delete: true,
239 rename: true,
240
241 list: true,
242
243 shared: true,
244
245 ..Default::default()
246 });
247
248 #[allow(deprecated)]
250 if let Some(client) = self.http_client {
251 am.update_http_client(|_| client);
252 }
253
254 am.into()
255 },
256 root,
257 endpoint,
258 loader: cred_loader,
259 signer,
260 share_name: self.config.share_name.clone(),
261 }),
262 })
263 }
264}
265
266#[derive(Debug, Clone)]
268pub struct AzfileBackend {
269 core: Arc<AzfileCore>,
270}
271
272impl Access for AzfileBackend {
273 type Reader = HttpBody;
274 type Writer = AzfileWriters;
275 type Lister = oio::PageLister<AzfileLister>;
276 type Deleter = oio::OneShotDeleter<AzfileDeleter>;
277
278 fn info(&self) -> Arc<AccessorInfo> {
279 self.core.info.clone()
280 }
281
282 async fn create_dir(&self, path: &str, _: OpCreateDir) -> Result<RpCreateDir> {
283 self.core.ensure_parent_dir_exists(path).await?;
284 let resp = self.core.azfile_create_dir(path).await?;
285 let status = resp.status();
286
287 match status {
288 StatusCode::CREATED => Ok(RpCreateDir::default()),
289 _ => {
290 if resp
296 .headers()
297 .get("x-ms-error-code")
298 .map(|value| value.to_str().unwrap_or(""))
299 .unwrap_or_else(|| "")
300 == "ResourceAlreadyExists"
301 {
302 Ok(RpCreateDir::default())
303 } else {
304 Err(parse_error(resp))
305 }
306 }
307 }
308 }
309
310 async fn stat(&self, path: &str, _: OpStat) -> Result<RpStat> {
311 let resp = if path.ends_with('/') {
312 self.core.azfile_get_directory_properties(path).await?
313 } else {
314 self.core.azfile_get_file_properties(path).await?
315 };
316
317 let status = resp.status();
318 match status {
319 StatusCode::OK => {
320 let meta = parse_into_metadata(path, resp.headers())?;
321 Ok(RpStat::new(meta))
322 }
323 _ => Err(parse_error(resp)),
324 }
325 }
326
327 async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
328 let resp = self.core.azfile_read(path, args.range()).await?;
329
330 let status = resp.status();
331 match status {
332 StatusCode::OK | StatusCode::PARTIAL_CONTENT => Ok((RpRead::new(), resp.into_body())),
333 _ => {
334 let (part, mut body) = resp.into_parts();
335 let buf = body.to_buffer().await?;
336 Err(parse_error(Response::from_parts(part, buf)))
337 }
338 }
339 }
340
341 async fn write(&self, path: &str, args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
342 self.core.ensure_parent_dir_exists(path).await?;
343 let w = AzfileWriter::new(self.core.clone(), args.clone(), path.to_string());
344 let w = if args.append() {
345 AzfileWriters::Two(oio::AppendWriter::new(w))
346 } else {
347 AzfileWriters::One(oio::OneShotWriter::new(w))
348 };
349 Ok((RpWrite::default(), w))
350 }
351
352 async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
353 Ok((
354 RpDelete::default(),
355 oio::OneShotDeleter::new(AzfileDeleter::new(self.core.clone())),
356 ))
357 }
358
359 async fn list(&self, path: &str, args: OpList) -> Result<(RpList, Self::Lister)> {
360 let l = AzfileLister::new(self.core.clone(), path.to_string(), args.limit());
361
362 Ok((RpList::default(), oio::PageLister::new(l)))
363 }
364
365 async fn rename(&self, from: &str, to: &str, _: OpRename) -> Result<RpRename> {
366 self.core.ensure_parent_dir_exists(to).await?;
367 let resp = self.core.azfile_rename(from, to).await?;
368 let status = resp.status();
369 match status {
370 StatusCode::OK => Ok(RpRename::default()),
371 _ => Err(parse_error(resp)),
372 }
373 }
374}