lance_io/object_store/providers/
azure.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright The Lance Authors
3
4use 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_opendal::OpendalStore;
13use opendal::{services::Azblob, Operator};
14use snafu::location;
15
16use object_store::{
17    azure::{AzureConfigKey, MicrosoftAzureBuilder},
18    RetryConfig,
19};
20use url::Url;
21
22use crate::object_store::{
23    ObjectStore, ObjectStoreParams, ObjectStoreProvider, StorageOptions, DEFAULT_CLOUD_BLOCK_SIZE,
24    DEFAULT_CLOUD_IO_PARALLELISM, DEFAULT_MAX_IOP_SIZE,
25};
26use lance_core::error::{Error, Result};
27
28#[derive(Default, Debug)]
29pub struct AzureBlobStoreProvider;
30
31impl AzureBlobStoreProvider {
32    async fn build_opendal_azure_store(
33        &self,
34        base_path: &Url,
35        storage_options: &StorageOptions,
36    ) -> Result<Arc<dyn OSObjectStore>> {
37        let container = base_path
38            .host_str()
39            .ok_or_else(|| {
40                Error::invalid_input("Azure URL must contain container name", location!())
41            })?
42            .to_string();
43
44        let prefix = base_path.path().trim_start_matches('/').to_string();
45
46        // Start with all storage options as the config map
47        // OpenDAL will handle environment variables through its default credentials chain
48        let mut config_map: HashMap<String, String> = storage_options.0.clone();
49
50        // Set required OpenDAL configuration
51        config_map.insert("container".to_string(), container);
52
53        if !prefix.is_empty() {
54            config_map.insert("root".to_string(), format!("/{}", prefix));
55        }
56
57        let operator = Operator::from_iter::<Azblob>(config_map)
58            .map_err(|e| {
59                Error::invalid_input(
60                    format!("Failed to create Azure Blob operator: {:?}", e),
61                    location!(),
62                )
63            })?
64            .finish();
65
66        Ok(Arc::new(OpendalStore::new(operator)) as Arc<dyn OSObjectStore>)
67    }
68
69    async fn build_microsoft_azure_store(
70        &self,
71        base_path: &Url,
72        storage_options: &StorageOptions,
73    ) -> Result<Arc<dyn OSObjectStore>> {
74        let max_retries = storage_options.client_max_retries();
75        let retry_timeout = storage_options.client_retry_timeout();
76        let retry_config = RetryConfig {
77            backoff: Default::default(),
78            max_retries,
79            retry_timeout: Duration::from_secs(retry_timeout),
80        };
81
82        let mut builder = MicrosoftAzureBuilder::new()
83            .with_url(base_path.as_ref())
84            .with_retry(retry_config);
85        for (key, value) in storage_options.as_azure_options() {
86            builder = builder.with_config(key, value);
87        }
88
89        Ok(Arc::new(builder.build()?) as Arc<dyn OSObjectStore>)
90    }
91}
92
93#[async_trait::async_trait]
94impl ObjectStoreProvider for AzureBlobStoreProvider {
95    async fn new_store(&self, base_path: Url, params: &ObjectStoreParams) -> Result<ObjectStore> {
96        let block_size = params.block_size.unwrap_or(DEFAULT_CLOUD_BLOCK_SIZE);
97        let mut storage_options =
98            StorageOptions(params.storage_options.clone().unwrap_or_default());
99        storage_options.with_env_azure();
100        let download_retry_count = storage_options.download_retry_count();
101
102        let use_opendal = storage_options
103            .0
104            .get("use_opendal")
105            .map(|v| v.as_str() == "true")
106            .unwrap_or(false);
107
108        let inner = if use_opendal {
109            self.build_opendal_azure_store(&base_path, &storage_options)
110                .await?
111        } else {
112            self.build_microsoft_azure_store(&base_path, &storage_options)
113                .await?
114        };
115
116        Ok(ObjectStore {
117            inner,
118            scheme: String::from("az"),
119            block_size,
120            max_iop_size: *DEFAULT_MAX_IOP_SIZE,
121            use_constant_size_upload_parts: false,
122            list_is_lexically_ordered: true,
123            io_parallelism: DEFAULT_CLOUD_IO_PARALLELISM,
124            download_retry_count,
125            io_tracker: Default::default(),
126        })
127    }
128
129    fn calculate_object_store_prefix(
130        &self,
131        url: &Url,
132        storage_options: Option<&HashMap<String, String>>,
133    ) -> Result<String> {
134        let authority = url.authority();
135        let (container, account) = match authority.find("@") {
136            Some(at_index) => {
137                // The URI looks like 'az://container@account.dfs.core.windows.net/path-part/file',
138                // or possibly 'az://container@account/path-part/file'.
139                let container = &authority[..at_index];
140                let account = &authority[at_index + 1..];
141                (
142                    container,
143                    account.split(".").next().unwrap_or_default().to_string(),
144                )
145            }
146            None => {
147                // The URI looks like 'az://container/path-part/file'.
148                // We must look at the storage options to find the account.
149                let mut account = match storage_options {
150                    Some(opts) => StorageOptions::find_configured_storage_account(opts),
151                    None => None,
152                };
153                if account.is_none() {
154                    account = StorageOptions::find_configured_storage_account(&ENV_OPTIONS.0);
155                }
156                let account = account.ok_or(Error::invalid_input(
157                    "Unable to find object store prefix: no Azure account name in URI, and no storage account configured.",
158                    location!(),
159                ))?;
160                (authority, account)
161            }
162        };
163        Ok(format!("{}${}@{}", url.scheme(), container, account))
164    }
165}
166
167static ENV_OPTIONS: LazyLock<StorageOptions> = LazyLock::new(StorageOptions::from_env);
168
169impl StorageOptions {
170    /// Iterate over all environment variables, looking for anything related to Azure.
171    fn from_env() -> Self {
172        let mut opts = HashMap::<String, String>::new();
173        for (os_key, os_value) in std::env::vars_os() {
174            if let (Some(key), Some(value)) = (os_key.to_str(), os_value.to_str()) {
175                if let Ok(config_key) = AzureConfigKey::from_str(&key.to_ascii_lowercase()) {
176                    opts.insert(config_key.as_ref().to_string(), value.to_string());
177                }
178            }
179        }
180        Self(opts)
181    }
182
183    /// Add values from the environment to storage options
184    pub fn with_env_azure(&mut self) {
185        for (os_key, os_value) in &ENV_OPTIONS.0 {
186            if !self.0.contains_key(os_key) {
187                self.0.insert(os_key.clone(), os_value.clone());
188            }
189        }
190    }
191
192    /// Subset of options relevant for azure storage
193    pub fn as_azure_options(&self) -> HashMap<AzureConfigKey, String> {
194        self.0
195            .iter()
196            .filter_map(|(key, value)| {
197                let az_key = AzureConfigKey::from_str(&key.to_ascii_lowercase()).ok()?;
198                Some((az_key, value.clone()))
199            })
200            .collect()
201    }
202
203    #[allow(clippy::manual_map)]
204    fn find_configured_storage_account(map: &HashMap<String, String>) -> Option<String> {
205        if let Some(account) = map.get("azure_storage_account_name") {
206            Some(account.clone())
207        } else if let Some(account) = map.get("account_name") {
208            Some(account.clone())
209        } else {
210            None
211        }
212    }
213}
214
215#[cfg(test)]
216mod tests {
217    use super::*;
218    use crate::object_store::ObjectStoreParams;
219    use std::collections::HashMap;
220
221    #[test]
222    fn test_azure_store_path() {
223        let provider = AzureBlobStoreProvider;
224
225        let url = Url::parse("az://bucket/path/to/file").unwrap();
226        let path = provider.extract_path(&url).unwrap();
227        let expected_path = object_store::path::Path::from("path/to/file");
228        assert_eq!(path, expected_path);
229    }
230
231    #[tokio::test]
232    async fn test_use_opendal_flag() {
233        let provider = AzureBlobStoreProvider;
234        let url = Url::parse("az://test-container/path").unwrap();
235        let params_with_flag = ObjectStoreParams {
236            storage_options: Some(HashMap::from([
237                ("use_opendal".to_string(), "true".to_string()),
238                ("account_name".to_string(), "test_account".to_string()),
239                (
240                    "endpoint".to_string(),
241                    "https://test_account.blob.core.windows.net".to_string(),
242                ),
243                (
244                    "account_key".to_string(),
245                    "dGVzdF9hY2NvdW50X2tleQ==".to_string(),
246                ),
247            ])),
248            ..Default::default()
249        };
250
251        let store = provider
252            .new_store(url.clone(), &params_with_flag)
253            .await
254            .unwrap();
255        assert_eq!(store.scheme, "az");
256    }
257
258    #[test]
259    fn test_find_configured_storage_account() {
260        assert_eq!(
261            Some("myaccount".to_string()),
262            StorageOptions::find_configured_storage_account(&HashMap::from_iter(
263                [
264                    ("access_key".to_string(), "myaccesskey".to_string()),
265                    (
266                        "azure_storage_account_name".to_string(),
267                        "myaccount".to_string()
268                    )
269                ]
270                .into_iter()
271            ))
272        );
273    }
274
275    #[test]
276    fn test_calculate_object_store_prefix_from_url_and_options() {
277        let provider = AzureBlobStoreProvider;
278        let options = HashMap::from_iter([("account_name".to_string(), "bob".to_string())]);
279        assert_eq!(
280            "az$container@bob",
281            provider
282                .calculate_object_store_prefix(
283                    &Url::parse("az://container/path").unwrap(),
284                    Some(&options)
285                )
286                .unwrap()
287        );
288    }
289
290    #[test]
291    fn test_calculate_object_store_prefix_from_url_and_ignored_options() {
292        let provider = AzureBlobStoreProvider;
293        let options = HashMap::from_iter([("account_name".to_string(), "bob".to_string())]);
294        assert_eq!(
295            "az$container@account",
296            provider
297                .calculate_object_store_prefix(
298                    &Url::parse("az://container@account.dfs.core.windows.net/path").unwrap(),
299                    Some(&options)
300                )
301                .unwrap()
302        );
303    }
304
305    #[test]
306    fn test_fail_to_calculate_object_store_prefix_from_url() {
307        let provider = AzureBlobStoreProvider;
308        let options = HashMap::from_iter([("access_key".to_string(), "myaccesskey".to_string())]);
309        let expected = "Invalid user input: Unable to find object store prefix: no Azure account name in URI, and no storage account configured.";
310        let result = provider
311            .calculate_object_store_prefix(
312                &Url::parse("az://container/path").unwrap(),
313                Some(&options),
314            )
315            .expect_err("expected error")
316            .to_string();
317        assert_eq!(expected, &result[..expected.len()]);
318    }
319}