1use std::{
5 collections::HashMap,
6 str::FromStr,
7 sync::{Arc, LazyLock},
8 time::Duration,
9};
10
11use object_store::ObjectStore as OSObjectStore;
12use object_store::list::PaginatedListStore;
13use opendal::{Operator, services::Azblob, services::Azdls};
14
15use object_store::{
16 RetryConfig,
17 azure::{AzureConfigKey, AzureCredential, MicrosoftAzure, MicrosoftAzureBuilder},
18};
19use url::Url;
20
21use crate::object_store::opendal_store::OpendalStore;
22use crate::object_store::{
23 DEFAULT_CLOUD_BLOCK_SIZE, DEFAULT_CLOUD_IO_PARALLELISM, DEFAULT_MAX_IOP_SIZE, ObjectStore,
24 ObjectStoreParams, ObjectStoreProvider, StorageOptions, StorageOptionsAccessor,
25 dynamic_credentials::build_dynamic_credential_provider,
26 throttle::{AimdThrottleState, cloud_http_connector, shared_throttle_state, with_throttling},
27};
28use lance_core::error::{Error, Result};
29use lance_core::utils::parse::str_is_truthy;
30
31#[derive(Default, Debug)]
32pub struct AzureBlobStoreProvider;
33
34impl AzureBlobStoreProvider {
35 fn normalize_opendal_azure_options(
40 options: &HashMap<String, String>,
41 ) -> HashMap<String, String> {
42 let mut config_map = options.clone();
44
45 let alias_groups: &[(&str, &[&str])] = &[
48 ("account_name", &["azure_storage_account_name"]),
49 ("endpoint", &["azure_storage_endpoint", "azure_endpoint"]),
50 (
51 "account_key",
52 &[
53 "azure_storage_account_key",
54 "azure_storage_access_key",
55 "azure_storage_master_key",
56 "access_key",
57 "master_key",
58 ],
59 ),
60 (
61 "sas_token",
62 &[
63 "azure_storage_sas_token",
64 "azure_storage_sas_key",
65 "sas_key",
66 ],
67 ),
68 ];
69
70 for (canonical, aliases) in alias_groups {
71 if !config_map.contains_key(*canonical) {
72 for alias in *aliases {
73 if let Some(value) = config_map.remove(*alias) {
74 config_map.insert(canonical.to_string(), value);
75 break;
76 }
77 }
78 } else {
79 for alias in *aliases {
81 config_map.remove(*alias);
82 }
83 }
84 }
85
86 config_map
87 }
88
89 fn build_opendal_operator(
90 base_path: &Url,
91 storage_options: &StorageOptions,
92 ) -> Result<Operator> {
93 let mut config_map = Self::normalize_opendal_azure_options(&storage_options.0);
96
97 match base_path.scheme() {
98 "az" => {
99 let container = base_path
100 .host_str()
101 .ok_or_else(|| Error::invalid_input("Azure URL must contain container name"))?
102 .to_string();
103
104 config_map.insert("container".to_string(), container);
105
106 let prefix = base_path.path().trim_start_matches('/');
107 if !prefix.is_empty() {
108 config_map.insert("root".to_string(), format!("/{}", prefix));
109 }
110
111 Operator::from_iter::<Azblob>(config_map).map_err(|e| {
112 Error::invalid_input(format!("Failed to create Azure Blob operator: {:?}", e))
113 })
114 }
115 "abfss" => {
116 let filesystem = base_path.username();
117 if filesystem.is_empty() {
118 return Err(Error::invalid_input(
119 "abfss:// URL must include account: abfss://<filesystem>@<account>.dfs.core.windows.net/path",
120 ));
121 }
122 let host = base_path.host_str().ok_or_else(|| {
123 Error::invalid_input(
124 "abfss:// URL must include account: abfss://<filesystem>@<account>.dfs.core.windows.net/path"
125 )
126 })?;
127
128 config_map.insert("filesystem".to_string(), filesystem.to_string());
129 config_map.insert("endpoint".to_string(), format!("https://{}", host));
130 config_map
131 .entry("account_name".to_string())
132 .or_insert_with(|| host.split('.').next().unwrap_or(host).to_string());
133
134 let root_path = base_path.path().trim_start_matches('/');
135 if !root_path.is_empty() {
136 config_map.insert("root".to_string(), format!("/{}", root_path));
137 }
138
139 Operator::from_iter::<Azdls>(config_map).map_err(|e| {
140 Error::invalid_input(format!(
141 "Failed to create Azure DFS (ADLS Gen2) operator: {:?}",
142 e
143 ))
144 })
145 }
146 _ => Err(Error::invalid_input(format!(
147 "Unsupported Azure scheme: {}",
148 base_path.scheme()
149 ))),
150 }
151 }
152
153 async fn build_opendal_azure_store(
154 &self,
155 base_path: &Url,
156 storage_options: &StorageOptions,
157 ) -> Result<Arc<dyn OSObjectStore>> {
158 let operator = Self::build_opendal_operator(base_path, storage_options)?;
159 Ok(Arc::new(OpendalStore::new(operator)))
160 }
161
162 async fn build_microsoft_azure_store(
163 &self,
164 base_path: &Url,
165 storage_options: &StorageOptions,
166 accessor: Option<Arc<StorageOptionsAccessor>>,
167 throttle_state: Option<&AimdThrottleState>,
168 ) -> Result<Arc<MicrosoftAzure>> {
171 let retry_config = RetryConfig {
174 backoff: Default::default(),
175 max_retries: storage_options.client_max_retries(),
176 retry_timeout: Duration::from_secs(storage_options.client_retry_timeout()),
177 };
178
179 let mut builder = MicrosoftAzureBuilder::new()
180 .with_url(base_path.as_ref())
181 .with_retry(retry_config)
182 .with_client_options(storage_options.client_options()?);
183 for (key, value) in storage_options.as_azure_options() {
184 builder = builder.with_config(key, value);
185 }
186
187 if let Some(credentials) =
188 build_dynamic_credential_provider::<AzureCredential>(accessor).await?
189 {
190 builder = builder.with_credentials(credentials);
191 }
192
193 let store_prefix =
194 self.calculate_object_store_prefix(base_path, Some(&storage_options.0))?;
195 builder = builder.with_http_connector(cloud_http_connector(
196 throttle_state,
197 crate::object_store::metrics_base(&store_prefix, base_path),
198 ));
199
200 Ok(Arc::new(builder.build()?))
201 }
202
203 fn calculate_object_store_prefix_with_env(
204 url: &Url,
205 storage_options: Option<&HashMap<String, String>>,
206 env_options: &HashMap<String, String>,
207 ) -> Result<String> {
208 let authority = url.authority();
209 let (container, account) = match authority.find("@") {
210 Some(at_index) => {
211 let container = &authority[..at_index];
216 let account = &authority[at_index + 1..];
217 (
218 container,
219 account.split(".").next().unwrap_or_default().to_string(),
220 )
221 }
222 None => {
223 let mut account = match storage_options {
226 Some(opts) => StorageOptions::find_configured_storage_account(opts),
227 None => None,
228 };
229 if account.is_none() {
230 account = StorageOptions::find_configured_storage_account(env_options);
231 }
232 let account = account.ok_or(Error::invalid_input("Unable to find object store prefix: no Azure account name in URI, and no storage account configured."))?;
233 (authority, account)
234 }
235 };
236 Ok(format!("{}${}@{}", url.scheme(), container, account))
237 }
238}
239
240#[async_trait::async_trait]
241impl ObjectStoreProvider for AzureBlobStoreProvider {
242 async fn new_store(&self, base_path: Url, params: &ObjectStoreParams) -> Result<ObjectStore> {
243 let scheme = base_path.scheme().to_string();
244 if scheme != "az" && scheme != "abfss" {
245 return Err(Error::invalid_input(format!(
246 "Unsupported Azure scheme '{}', expected 'az' or 'abfss'",
247 scheme
248 )));
249 }
250
251 let block_size = params.block_size.unwrap_or(DEFAULT_CLOUD_BLOCK_SIZE);
252 let mut storage_options =
253 StorageOptions::new(params.storage_options().cloned().unwrap_or_default());
254 storage_options.with_env_azure();
255 let download_retry_count = storage_options.download_retry_count();
256
257 let use_opendal = storage_options
258 .0
259 .get("use_opendal")
260 .map(|v| str_is_truthy(v.as_str()))
261 .unwrap_or(false);
262
263 let accessor = params.get_accessor();
264
265 let store_prefix =
267 self.calculate_object_store_prefix(&base_path, params.storage_options())?;
268 let throttle_state = shared_throttle_state(&store_prefix, params)?;
269
270 let (inner, paginated_lister) = if use_opendal {
271 (
275 self.build_opendal_azure_store(&base_path, &storage_options)
276 .await?,
277 None,
278 )
279 } else {
280 let store = self
281 .build_microsoft_azure_store(
282 &base_path,
283 &storage_options,
284 accessor,
285 throttle_state.as_ref(),
286 )
287 .await?;
288 (
289 store.clone() as Arc<dyn OSObjectStore>,
290 Some(store as Arc<dyn PaginatedListStore>),
291 )
292 };
293 let (inner, paginated_lister) =
294 with_throttling(throttle_state, !use_opendal, inner, paginated_lister);
295
296 Ok(ObjectStore {
297 inner,
298 local_dir_operations: None,
299 scheme,
300 block_size,
301 max_iop_size: *DEFAULT_MAX_IOP_SIZE,
302 use_constant_size_upload_parts: false,
303 list_is_lexically_ordered: true,
304 io_parallelism: DEFAULT_CLOUD_IO_PARALLELISM,
305 download_retry_count,
306 io_tracker: Default::default(),
307 store_prefix: self
308 .calculate_object_store_prefix(&base_path, params.storage_options())?,
309 paginated_lister,
310 })
311 }
312
313 fn calculate_object_store_prefix(
314 &self,
315 url: &Url,
316 storage_options: Option<&HashMap<String, String>>,
317 ) -> Result<String> {
318 Self::calculate_object_store_prefix_with_env(url, storage_options, &ENV_OPTIONS.0)
319 }
320}
321
322static ENV_OPTIONS: LazyLock<StorageOptions> = LazyLock::new(StorageOptions::from_env);
323
324impl StorageOptions {
325 fn from_env() -> Self {
327 let mut opts = HashMap::<String, String>::new();
328 for (os_key, os_value) in std::env::vars_os() {
329 if let (Some(key), Some(value)) = (os_key.to_str(), os_value.to_str())
330 && let Ok(config_key) = AzureConfigKey::from_str(&key.to_ascii_lowercase())
331 {
332 opts.insert(config_key.as_ref().to_string(), value.to_string());
333 }
334 }
335 Self(opts)
336 }
337
338 pub fn with_env_azure(&mut self) {
340 for (os_key, os_value) in &ENV_OPTIONS.0 {
341 if !self.0.contains_key(os_key) {
342 self.0.insert(os_key.clone(), os_value.clone());
343 }
344 }
345 }
346
347 pub fn as_azure_options(&self) -> HashMap<AzureConfigKey, String> {
349 self.0
350 .iter()
351 .filter_map(|(key, value)| {
352 let az_key = AzureConfigKey::from_str(&key.to_ascii_lowercase()).ok()?;
353 Some((az_key, value.clone()))
354 })
355 .collect()
356 }
357
358 #[allow(clippy::manual_map)]
359 fn find_configured_storage_account(map: &HashMap<String, String>) -> Option<String> {
360 if let Some(account) = map.get("azure_storage_account_name") {
361 Some(account.clone())
362 } else if let Some(account) = map.get("account_name") {
363 Some(account.clone())
364 } else {
365 None
366 }
367 }
368}
369
370#[cfg(test)]
371mod tests {
372 use super::*;
373 use std::sync::Arc;
374
375 use crate::object_store::test_utils::StaticMockStorageOptionsProvider;
376 use crate::object_store::{ObjectStoreParams, StorageOptionsAccessor};
377 use std::collections::HashMap;
378
379 #[test]
380 fn test_azure_store_path() {
381 let provider = AzureBlobStoreProvider;
382
383 let url = Url::parse("az://bucket/path/to/file").unwrap();
384 let path = provider.extract_path(&url).unwrap();
385 let expected_path = object_store::path::Path::from("path/to/file");
386 assert_eq!(path, expected_path);
387 }
388
389 #[tokio::test]
390 async fn test_use_opendal_flag() {
391 let provider = AzureBlobStoreProvider;
392 let url = Url::parse("az://test-container/path").unwrap();
393 let params_with_flag = ObjectStoreParams {
394 storage_options_accessor: Some(Arc::new(StorageOptionsAccessor::with_static_options(
395 HashMap::from([
396 ("use_opendal".to_string(), "true".to_string()),
397 ("account_name".to_string(), "test_account".to_string()),
398 (
399 "endpoint".to_string(),
400 "https://test_account.blob.core.windows.net".to_string(),
401 ),
402 (
403 "account_key".to_string(),
404 "dGVzdF9hY2NvdW50X2tleQ==".to_string(),
405 ),
406 ]),
407 ))),
408 ..Default::default()
409 };
410
411 let store = provider
412 .new_store(url.clone(), ¶ms_with_flag)
413 .await
414 .unwrap();
415 assert_eq!(store.scheme, "az");
416 let inner_desc = store.inner.to_string();
417 assert!(
418 inner_desc.contains("Opendal") && inner_desc.contains("azblob"),
419 "az:// with use_opendal=true should use OpenDAL Azblob, got: {}",
420 inner_desc
421 );
422 }
423
424 #[tokio::test]
425 async fn test_dynamic_azure_credentials_provider() {
426 let accessor = Arc::new(StorageOptionsAccessor::with_provider(Arc::new(
427 StaticMockStorageOptionsProvider {
428 options: HashMap::from([(
429 "azure_storage_sas_token".to_string(),
430 "?sv=2022-11-02&sp=rl&sig=test".to_string(),
431 )]),
432 },
433 )));
434
435 let credentials = build_dynamic_credential_provider::<AzureCredential>(Some(accessor))
436 .await
437 .expect("dynamic azure credentials should build")
438 .expect("expected credential provider")
439 .get_credential()
440 .await
441 .expect("expected azure credential");
442
443 match credentials.as_ref() {
444 AzureCredential::SASToken(pairs) => {
445 assert!(
446 pairs
447 .iter()
448 .any(|(key, value)| key == "sig" && value == "test")
449 );
450 }
451 other => panic!("expected SAS token, got {other:?}"),
452 }
453 }
454
455 #[test]
456 fn test_find_configured_storage_account() {
457 assert_eq!(
458 Some("myaccount".to_string()),
459 StorageOptions::find_configured_storage_account(&HashMap::from_iter(
460 [
461 ("access_key".to_string(), "myaccesskey".to_string()),
462 (
463 "azure_storage_account_name".to_string(),
464 "myaccount".to_string()
465 )
466 ]
467 .into_iter()
468 ))
469 );
470 }
471
472 #[test]
473 fn test_calculate_object_store_prefix_from_url_and_options() {
474 let provider = AzureBlobStoreProvider;
475 let options = HashMap::from_iter([("account_name".to_string(), "bob".to_string())]);
476 assert_eq!(
477 "az$container@bob",
478 provider
479 .calculate_object_store_prefix(
480 &Url::parse("az://container/path").unwrap(),
481 Some(&options)
482 )
483 .unwrap()
484 );
485 }
486
487 #[test]
488 fn test_calculate_object_store_prefix_from_url_and_ignored_options() {
489 let provider = AzureBlobStoreProvider;
490 let options = HashMap::from_iter([("account_name".to_string(), "bob".to_string())]);
491 assert_eq!(
492 "az$container@account",
493 provider
494 .calculate_object_store_prefix(
495 &Url::parse("az://container@account.dfs.core.windows.net/path").unwrap(),
496 Some(&options)
497 )
498 .unwrap()
499 );
500 }
501
502 #[test]
503 fn test_calculate_object_store_prefix_from_url_short_account() {
504 let provider = AzureBlobStoreProvider;
505 let options = HashMap::from_iter([("account_name".to_string(), "bob".to_string())]);
506 assert_eq!(
507 "az$container@account",
508 provider
509 .calculate_object_store_prefix(
510 &Url::parse("az://container@account/path").unwrap(),
511 Some(&options)
512 )
513 .unwrap()
514 );
515 }
516
517 #[test]
518 fn test_fail_to_calculate_object_store_prefix_from_url() {
519 let options = HashMap::from_iter([("access_key".to_string(), "myaccesskey".to_string())]);
520 let expected = "Invalid user input: Unable to find object store prefix: no Azure account name in URI, and no storage account configured.";
521 let result = AzureBlobStoreProvider::calculate_object_store_prefix_with_env(
522 &Url::parse("az://container/path").unwrap(),
523 Some(&options),
524 &HashMap::new(),
525 )
526 .expect_err("expected error")
527 .to_string();
528 assert_eq!(expected, &result[..expected.len()]);
529 }
530
531 #[test]
534 fn test_abfss_extract_path() {
535 let provider = AzureBlobStoreProvider;
536 let url = Url::parse("abfss://myfs@myaccount.dfs.core.windows.net/path/to/dataset.lance")
537 .unwrap();
538 let path = provider.extract_path(&url).unwrap();
539 assert_eq!(
540 path,
541 object_store::path::Path::from("path/to/dataset.lance")
542 );
543 }
544
545 #[test]
546 fn test_calculate_abfss_prefix() {
547 let provider = AzureBlobStoreProvider;
548 let url = Url::parse("abfss://myfs@myaccount.dfs.core.windows.net/path/to/data").unwrap();
549 let prefix = provider.calculate_object_store_prefix(&url, None).unwrap();
550 assert_eq!(prefix, "abfss$myfs@myaccount");
551 }
552
553 #[test]
554 fn test_calculate_abfss_prefix_ignores_storage_options() {
555 let provider = AzureBlobStoreProvider;
556 let options =
557 HashMap::from_iter([("account_name".to_string(), "other_account".to_string())]);
558 let url = Url::parse("abfss://myfs@myaccount.dfs.core.windows.net/path").unwrap();
559 let prefix = provider
560 .calculate_object_store_prefix(&url, Some(&options))
561 .unwrap();
562 assert_eq!(prefix, "abfss$myfs@myaccount");
563 }
564
565 #[tokio::test]
566 async fn test_abfss_default_uses_microsoft_builder() {
567 use crate::object_store::StorageOptionsAccessor;
568 let provider = AzureBlobStoreProvider;
569 let url = Url::parse("abfss://testfs@testaccount.dfs.core.windows.net/data").unwrap();
570 let params = ObjectStoreParams {
571 storage_options_accessor: Some(Arc::new(StorageOptionsAccessor::with_static_options(
572 HashMap::from([
573 ("account_name".to_string(), "testaccount".to_string()),
574 ("account_key".to_string(), "dGVzdA==".to_string()),
575 ]),
576 ))),
577 ..Default::default()
578 };
579
580 let store = provider.new_store(url, ¶ms).await.unwrap();
581 assert_eq!(store.scheme, "abfss");
582 assert!(!store.is_local());
583 assert!(store.is_cloud());
584 let inner_desc = store.inner.to_string();
585 assert!(
586 inner_desc.contains("MicrosoftAzure"),
587 "abfss:// without use_opendal should use MicrosoftAzureBuilder, got: {}",
588 inner_desc
589 );
590 assert!(
591 store.paginated_lister.is_some(),
592 "the native store pages an ADLS Gen2 account by continuation token"
593 );
594 }
595
596 #[tokio::test]
597 async fn test_a_blob_container_is_paged() {
598 use crate::object_store::StorageOptionsAccessor;
599 let provider = AzureBlobStoreProvider;
600 let url = Url::parse("az://container@testaccount.blob.core.windows.net/data").unwrap();
601 let params = ObjectStoreParams {
602 storage_options_accessor: Some(Arc::new(StorageOptionsAccessor::with_static_options(
603 HashMap::from([
604 ("account_name".to_string(), "testaccount".to_string()),
605 ("account_key".to_string(), "dGVzdA==".to_string()),
606 ]),
607 ))),
608 ..Default::default()
609 };
610
611 let store = provider.new_store(url, ¶ms).await.unwrap();
612 assert!(store.paginated_lister.is_some());
613 }
614
615 #[tokio::test]
616 async fn test_unsupported_scheme_rejected() {
617 use crate::object_store::StorageOptionsAccessor;
618 let provider = AzureBlobStoreProvider;
619 let url = Url::parse("wasbs://container@myaccount.blob.core.windows.net/path").unwrap();
620 let params = ObjectStoreParams {
621 storage_options_accessor: Some(Arc::new(StorageOptionsAccessor::with_static_options(
622 HashMap::from([
623 ("account_name".to_string(), "myaccount".to_string()),
624 ("account_key".to_string(), "dGVzdA==".to_string()),
625 ]),
626 ))),
627 ..Default::default()
628 };
629
630 let err = provider
631 .new_store(url, ¶ms)
632 .await
633 .expect_err("expected error for unsupported scheme");
634 assert!(
635 err.to_string().contains("Unsupported Azure scheme"),
636 "unexpected error: {}",
637 err
638 );
639 }
640
641 #[tokio::test]
642 async fn test_abfss_with_opendal_uses_azdls() {
643 use crate::object_store::StorageOptionsAccessor;
644 let provider = AzureBlobStoreProvider;
645 let url = Url::parse("abfss://testfs@testaccount.dfs.core.windows.net/data").unwrap();
646 let params = ObjectStoreParams {
647 storage_options_accessor: Some(Arc::new(StorageOptionsAccessor::with_static_options(
648 HashMap::from([
649 ("use_opendal".to_string(), "true".to_string()),
650 ("account_name".to_string(), "testaccount".to_string()),
651 ("account_key".to_string(), "dGVzdA==".to_string()),
652 ]),
653 ))),
654 ..Default::default()
655 };
656
657 let store = provider.new_store(url, ¶ms).await.unwrap();
658 assert_eq!(store.scheme, "abfss");
659 assert!(!store.is_local());
660 assert!(store.is_cloud());
661 let inner_desc = store.inner.to_string();
662 assert!(
663 inner_desc.contains("Opendal") && inner_desc.contains("azdls"),
664 "abfss:// with use_opendal=true should use OpenDAL Azdls, got: {}",
665 inner_desc
666 );
667 }
668
669 #[test]
670 fn test_azdls_capabilities_differ_from_azblob() {
671 let common_opts = StorageOptions(HashMap::from([
672 ("account_name".to_string(), "testaccount".to_string()),
673 ("account_key".to_string(), "dGVzdA==".to_string()),
674 (
675 "endpoint".to_string(),
676 "https://testaccount.blob.core.windows.net".to_string(),
677 ),
678 ]));
679
680 let az_url = Url::parse("az://test-container/path").unwrap();
682 let az_operator =
683 AzureBlobStoreProvider::build_opendal_operator(&az_url, &common_opts).unwrap();
684
685 let abfss_url = Url::parse("abfss://testfs@testaccount.dfs.core.windows.net/data").unwrap();
687 let abfss_operator =
688 AzureBlobStoreProvider::build_opendal_operator(&abfss_url, &common_opts).unwrap();
689
690 let azblob_cap = az_operator.info().capability();
691 let azdls_cap = abfss_operator.info().capability();
692
693 assert!(azblob_cap.read);
695 assert!(azdls_cap.read);
696 assert!(azblob_cap.write);
697 assert!(azdls_cap.write);
698 assert!(azblob_cap.list);
699 assert!(azdls_cap.list);
700
701 assert!(azdls_cap.rename, "Azdls should support rename");
703 assert!(azdls_cap.create_dir, "Azdls should support create_dir");
704 assert!(!azblob_cap.rename, "Azblob should not support rename");
705 }
706}