Skip to main content

polars_io/cloud/
object_store_setup.rs

1use std::sync::{Arc, LazyLock};
2
3use object_store::ObjectStore;
4use object_store::local::LocalFileSystem;
5use polars_core::config::{self, verbose, verbose_print_sensitive};
6use polars_error::{PolarsError, PolarsResult, polars_bail, polars_err, to_compute_err};
7use polars_utils::aliases::PlHashMap;
8use polars_utils::cache::LruCache;
9use polars_utils::pl_path::{ALLOWED_EXT_SCHEMES, CloudScheme, PlPath, PlRefPath};
10use polars_utils::pl_str::PlSmallStr;
11use polars_utils::{format_pl_smallstr, pl_serialize};
12use tokio::sync::{OnceCell, RwLock};
13
14use super::{CloudLocation, CloudOptions, CloudType, PolarsObjectStore, split_http_url};
15use crate::cloud::http_rate_limit::{
16    DirectionalRateLimitConfig, InitPolicy, PacingBudget, RateLimiter,
17};
18use crate::cloud::{CloudConfig, CloudRateLimitConfig, CloudRetryConfig};
19
20/// Object stores must be cached. Every object-store will do DNS lookups and
21/// get rate limited when querying the DNS (can take up to 5s).
22/// Other reasons are connection pools that must be shared between as much as possible.
23#[allow(clippy::type_complexity)]
24static OBJECT_STORE_CACHE: LazyLock<RwLock<PlHashMap<Vec<u8>, PolarsObjectStore>>> =
25    LazyLock::new(Default::default);
26
27/// Per-origin HTTP stores; separate so that many origins don't evict the cloud stores.
28#[allow(clippy::type_complexity)]
29static HTTP_STORE_CACHE: LazyLock<
30    std::sync::Mutex<Option<LruCache<Vec<u8>, Arc<OnceCell<PolarsObjectStore>>>>>,
31> = LazyLock::new(Default::default);
32
33/// Trait for external ObjectStore builder (e.g., for HDFS). Unstable.
34pub trait ExtObjectStoreBuilder {
35    /// Build new object_store.
36    fn build(
37        &self,
38        url: &PlRefPath,
39        options: Option<&CloudOptions>,
40    ) -> PolarsResult<Arc<dyn ObjectStore + Send + Sync>>;
41
42    /// Return a stable cache key for this store.
43    /// Defaults to `None`, which uses the default key (URL authority + serialised CloudOptions).
44    fn stable_cache_key(
45        &self,
46        _url: &PlRefPath,
47        _options: Option<&CloudOptions>,
48    ) -> Option<Vec<u8>> {
49        None
50    }
51}
52
53static EXT_OBJECT_STORE_BUILDER_REGISTRY: LazyLock<
54    std::sync::RwLock<PlHashMap<PlSmallStr, Arc<dyn ExtObjectStoreBuilder + Send + Sync>>>,
55> = LazyLock::new(Default::default);
56
57/// Register custom object_store builder for a given cloud scheme.
58/// Example: for 'hdfs://', the scheme is "hdfs".
59/// Rejects native cloud schemes (e.g. "s3").
60pub fn register_object_store_builder(
61    scheme: &str,
62    builder: Arc<dyn ExtObjectStoreBuilder + Send + Sync>,
63) -> PolarsResult<()> {
64    // Reject schemes already handled natively.
65    // TODO: allow shadowing of existing schemes.
66    if CloudScheme::is_native_str(scheme) {
67        polars_bail!(
68            InvalidOperation:
69            "cannot register object_store_builder for scheme '{}': \
70             this scheme is handled natively",
71            scheme
72        );
73    }
74
75    if !polars_utils::pl_path::ext_scheme_allowed(scheme) {
76        polars_bail!(
77            InvalidOperation:
78            "cannot register object_store_builder for scheme '{}': \
79             allowed external schemes are: {:?}",
80            scheme,
81            ALLOWED_EXT_SCHEMES
82        );
83    }
84
85    if polars_config::config().verbose() {
86        eprintln!(
87            "[ObjectStoreBuilderRegistry]: register object_store_builder for scheme '{scheme}'"
88        )
89    }
90
91    EXT_OBJECT_STORE_BUILDER_REGISTRY
92        .write()
93        .unwrap()
94        .insert(scheme.into(), builder);
95    Ok(())
96}
97
98pub fn deregister_object_store_builder(scheme: &str) {
99    if polars_config::config().verbose() {
100        eprintln!(
101            "[ObjectStoreBuilderRegistry]: deregister object_store_builder for scheme '{scheme}'"
102        )
103    }
104
105    EXT_OBJECT_STORE_BUILDER_REGISTRY
106        .write()
107        .unwrap()
108        .remove(scheme);
109}
110
111/// Whether an object_store builder is registered for a given cloud scheme, e.g. "hdfs".
112pub fn has_object_store_builder(scheme: &str) -> bool {
113    EXT_OBJECT_STORE_BUILDER_REGISTRY
114        .read()
115        .unwrap()
116        .contains_key(scheme)
117}
118
119#[allow(dead_code)]
120fn err_missing_feature(
121    feature: &str,
122    cloud_type: &CloudType,
123) -> PolarsResult<Arc<dyn ObjectStore>> {
124    polars_bail!(
125        ComputeError:
126        "feature '{}' must be enabled in order to use '{:?}' cloud urls",
127        feature,
128        cloud_type,
129    );
130}
131
132/// Get the key of a url for object store registration.
133fn path_and_creds_to_key(path: &PlPath, options: Option<&CloudOptions>) -> PolarsResult<Vec<u8>> {
134    // We include credentials as they can expire, so users will send new credentials for the same url.
135
136    #[cfg(feature = "cloud")]
137    let credential_cache_key = CacheKeyBytes(
138        options
139            .and_then(|o| o.credential_provider.as_ref())
140            .map(|x| x.stable_cache_key())
141            .transpose()?
142            .unwrap_or_default(),
143    );
144
145    let cloud_options = options
146        .map(
147            |CloudOptions {
148                 // Destructure to ensure this breaks if anything changes.
149                 #[cfg(feature = "file_cache")]
150                 file_cache_ttl,
151                 config,
152                 retry_config,
153                 rate_limit_config,
154                 #[cfg(feature = "cloud")]
155                     credential_provider: _,
156             }|
157             -> PolarsResult<CloudOptionsKey> {
158                Ok(CloudOptionsKey {
159                    #[cfg(feature = "file_cache")]
160                    file_cache_ttl: *file_cache_ttl,
161                    config: config.clone(),
162                    retry_config: *retry_config,
163                    rate_limit_config: *rate_limit_config,
164                    #[cfg(feature = "cloud")]
165                    credential_provider: credential_cache_key,
166                })
167            },
168        )
169        .transpose()?;
170
171    let cache_key = CacheKey {
172        url_base: format_pl_smallstr!("{}", &path.as_str()[..path.authority_end_position()]),
173        cloud_options,
174    };
175
176    verbose_print_sensitive(|| {
177        format!(
178            "object store cache key for path at '{}': {:?}",
179            path, cache_key
180        )
181    });
182
183    return pl_serialize::serialize_to_bytes::<_, false>(&cache_key);
184
185    #[derive(Clone, Debug, PartialEq, Hash, Eq)]
186    #[cfg_attr(feature = "serde", derive(serde::Serialize))]
187    struct CacheKey {
188        url_base: PlSmallStr,
189        cloud_options: Option<CloudOptionsKey>,
190    }
191
192    #[derive(Clone, PartialEq, Hash, Eq)]
193    #[cfg_attr(feature = "serde", derive(serde::Serialize))]
194    struct CacheKeyBytes(Vec<u8>);
195
196    impl std::fmt::Debug for CacheKeyBytes {
197        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
198            if self.0.is_empty() {
199                write!(f, "None")
200            } else {
201                for b in &self.0 {
202                    write!(f, "{:02x}", b)?;
203                }
204                Ok(())
205            }
206        }
207    }
208
209    /// Variant of CloudOptions for serializing to a cache key. The credential
210    /// provider is replaced by the function address.
211    #[derive(Clone, Debug, PartialEq, Hash, Eq)]
212    #[cfg_attr(feature = "serde", derive(serde::Serialize))]
213    struct CloudOptionsKey {
214        #[cfg(feature = "file_cache")]
215        file_cache_ttl: u64,
216        config: Option<CloudConfig>,
217        retry_config: CloudRetryConfig,
218        rate_limit_config: CloudRateLimitConfig,
219        #[cfg(feature = "cloud")]
220        credential_provider: CacheKeyBytes,
221    }
222}
223
224/// Construct an object_store `Path` from a string without any encoding/decoding.
225pub fn object_path_from_str(path: &str) -> PolarsResult<object_store::path::Path> {
226    object_store::path::Path::parse(path).map_err(to_compute_err)
227}
228
229#[derive(Debug, Clone)]
230pub(crate) struct PolarsObjectStoreBuilder {
231    path: PlRefPath,
232    cloud_type: CloudType,
233    options: Option<CloudOptions>,
234    // RateLimiter. Authoritative for config and read/write request rate cells (atomics).
235    // The rate-limiter, below the object store, updates them dynamically. The concurrency controller,
236    // above the object store, uses the request rate to limit the number of concurrent requests.
237    rate_limiter: Option<Arc<RateLimiter>>,
238}
239
240impl PolarsObjectStoreBuilder {
241    /// The URL of the request that built the store.
242    pub(super) fn path(&self) -> &PlRefPath {
243        &self.path
244    }
245
246    /// The URL the store is rooted at.
247    pub(super) fn base_url(&self) -> PlRefPath {
248        match self.cloud_type {
249            // The origin, or the full URL for a store tied to one URL.
250            CloudType::Http => self.path.clone(),
251            _ => self.path.sliced(0..self.path.authority_end_position()),
252        }
253    }
254
255    pub(crate) fn rate_limit_signal(&self) -> Option<PacingBudget> {
256        self.rate_limiter.as_ref().map(|r| r.read_budget())
257    }
258
259    pub(super) async fn build_impl(
260        &self,
261        // On a rebuild, clear cached Python credentials and leave the URL out of build errors.
262        rebuild: bool,
263    ) -> PolarsResult<Arc<dyn ObjectStore>> {
264        let options = self
265            .options
266            .as_ref()
267            .unwrap_or_else(|| CloudOptions::default_static_ref());
268
269        if let Some(options) = &self.options
270            && verbose()
271        {
272            eprintln!(
273                "build object-store: file_cache_ttl: {}",
274                options.file_cache_ttl
275            );
276
277            fn eprint_rate_config(direction: &str, config: &DirectionalRateLimitConfig) {
278                eprintln!(
279                    "object-store rate_limiter config({})]: init_rate: {:.0}rps, floor_rate: {:.0}rps, ceiling_rate: {:.0}rps, horizon: {}ms, max_wait: {}ms, init_policy: {}",
280                    direction,
281                    config.init_rate,
282                    config.floor_rate,
283                    config.ceiling_rate,
284                    config.horizon.as_millis(),
285                    config.max_wait.as_millis(),
286                    {
287                        match config.init_policy {
288                            InitPolicy::SetToInit => "to_init",
289                            InitPolicy::SetToFloor => "to_floor",
290                            InitPolicy::Inherit => "inherit",
291                        }
292                    }
293                )
294            }
295
296            if let Some(rate_limiter) = &self.rate_limiter {
297                eprint_rate_config("read", &rate_limiter.config.read);
298                eprint_rate_config("write", &rate_limiter.config.write);
299            }
300        }
301
302        let store = match self.cloud_type {
303            CloudType::Aws => {
304                #[cfg(feature = "aws")]
305                {
306                    let store = options
307                        .build_aws(
308                            self.path.clone(),
309                            super::ObjectStoreErrorContext::for_build(self.path.clone(), rebuild),
310                            rebuild,
311                            self.rate_limiter.as_deref(),
312                        )
313                        .await?;
314                    Ok::<_, PolarsError>(Arc::new(store) as Arc<dyn ObjectStore>)
315                }
316                #[cfg(not(feature = "aws"))]
317                return err_missing_feature("aws", &self.cloud_type);
318            },
319            CloudType::Gcp => {
320                #[cfg(feature = "gcp")]
321                {
322                    let store = options.build_gcp(
323                        self.path.clone(),
324                        super::ObjectStoreErrorContext::for_build(self.path.clone(), rebuild),
325                        rebuild,
326                        self.rate_limiter.as_deref(),
327                    )?;
328
329                    Ok::<_, PolarsError>(Arc::new(store) as Arc<dyn ObjectStore>)
330                }
331                #[cfg(not(feature = "gcp"))]
332                return err_missing_feature("gcp", &self.cloud_type);
333            },
334            CloudType::Azure => {
335                {
336                    #[cfg(feature = "azure")]
337                    {
338                        let store = options.build_azure(
339                            self.path.clone(),
340                            super::ObjectStoreErrorContext::for_build(self.path.clone(), rebuild),
341                            rebuild,
342                            self.rate_limiter.as_deref(),
343                        )?;
344                        Ok::<_, PolarsError>(Arc::new(store) as Arc<dyn ObjectStore>)
345                    }
346                }
347                #[cfg(not(feature = "azure"))]
348                return err_missing_feature("azure", &self.cloud_type);
349            },
350            CloudType::File => {
351                let local = LocalFileSystem::new();
352                Ok::<_, PolarsError>(Arc::new(local) as Arc<dyn ObjectStore>)
353            },
354            CloudType::Http => {
355                {
356                    #[cfg(feature = "http")]
357                    {
358                        let store: Arc<dyn ObjectStore> = match split_http_url(&self.path) {
359                            Some((base_url, _)) => Arc::new(
360                                options.build_http_origin(self.path.sliced(0..base_url.len()))?,
361                            ),
362                            None => Arc::new(options.build_http(self.path.clone())?),
363                        };
364                        PolarsResult::Ok(store)
365                    }
366                }
367                #[cfg(not(feature = "http"))]
368                return err_missing_feature("http", &cloud_location.scheme);
369            },
370            CloudType::Hf => panic!("impl error: unresolved hf:// path"),
371            CloudType::Ext(scheme) => {
372                let prefix = &self.path.as_str()[..self.path.authority_end_position()];
373
374                verbose_print_sensitive(|| {
375                    format!(
376                        "build external object_store: scheme='{}', prefix='{}', options={:?}",
377                        scheme, prefix, self.options
378                    )
379                });
380
381                let store = EXT_OBJECT_STORE_BUILDER_REGISTRY
382                    .read()
383                    .unwrap()
384                    .get(scheme)
385                    .ok_or_else(|| {
386                        polars_err!(
387                            ComputeError:
388                            "no object_store_builder registered for prefix: {}; \
389                             call register_object_store_builder() before executing queries \
390                             against the scheme: {}",
391                            prefix, scheme
392                        )
393                    })?
394                    .build(&self.path, self.options.as_ref())?;
395
396                return Ok(store);
397            },
398        }?;
399
400        Ok(store)
401    }
402
403    /// Note: Use `build_impl` for a non-caching version.
404    pub(super) async fn build(self) -> PolarsResult<PolarsObjectStore> {
405        if self.cloud_type == CloudType::Http
406            && let Some((base_url, _)) = split_http_url(&self.path)
407        {
408            // The store serves the whole origin, so it must not keep this URL.
409            let path = self.path.sliced(0..base_url.len());
410            return Self { path, ..self }.build_http_cached().await;
411        }
412
413        let opt_cache_key = match self.cloud_type {
414            CloudType::Aws | CloudType::Gcp | CloudType::Azure => {
415                Some(path_and_creds_to_key(&self.path, self.options.as_ref())?)
416            },
417            CloudType::File | CloudType::Http | CloudType::Hf => None,
418            CloudType::Ext(scheme) => {
419                let registry = EXT_OBJECT_STORE_BUILDER_REGISTRY.read().unwrap();
420                let builder = registry.get(scheme).ok_or_else(|| {
421                    polars_err!(
422                        ComputeError:
423                        "no object_store_builder registered for scheme '{}'; \
424                         call register_object_store_builder() before executing queries \
425                         against this scheme",
426                        scheme
427                    )
428                })?;
429
430                let key = match builder.stable_cache_key(&self.path, self.options.as_ref()) {
431                    Some(key) => key,
432                    None => path_and_creds_to_key(&self.path, self.options.as_ref())?,
433                };
434
435                Some(key)
436            },
437        };
438
439        let opt_cache_write_guard = if let Some(cache_key) = opt_cache_key.as_deref() {
440            let cache = OBJECT_STORE_CACHE.read().await;
441
442            if let Some(store) = cache.get(cache_key) {
443                return Ok(store.clone().with_base_url(self.base_url()));
444            }
445
446            drop(cache);
447
448            let cache = OBJECT_STORE_CACHE.write().await;
449
450            if let Some(store) = cache.get(cache_key) {
451                return Ok(store.clone().with_base_url(self.base_url()));
452            }
453
454            Some(cache)
455        } else {
456            None
457        };
458
459        let store = self.build_impl(false).await?;
460        let store = PolarsObjectStore::new_from_inner(store, self);
461
462        if let Some(mut cache) = opt_cache_write_guard {
463            // Clear the cache if we surpass a certain amount of buckets.
464            if cache.len() >= 8 {
465                if config::verbose() {
466                    eprintln!(
467                        "build_object_store: clearing store cache (cache.len(): {})",
468                        cache.len()
469                    );
470                }
471                cache.clear()
472            }
473
474            cache.insert(opt_cache_key.unwrap(), store.clone());
475        }
476
477        Ok(store)
478    }
479
480    async fn build_http_cached(self) -> PolarsResult<PolarsObjectStore> {
481        // Clamped: the LRU allocates its capacity up front.
482        let capacity = polars_config::config().http_store_cache_size().min(1 << 16) as usize;
483
484        // An uncached cell builds a store that is dropped with its last user.
485        let cell = if capacity == 0 {
486            Default::default()
487        } else {
488            let cache_key = path_and_creds_to_key(&self.path, self.options.as_ref())?;
489            let mut cache = HTTP_STORE_CACHE.lock().unwrap();
490            let cache = match &mut *cache {
491                Some(cache) if cache.max_capacity() == capacity => cache,
492                // First use, or capacity changed at runtime.
493                cache => cache.insert(LruCache::with_capacity(capacity)),
494            };
495            let was_full = cache.len() == capacity;
496            let cell =
497                Arc::clone(cache.get_or_insert_with(cache_key.as_slice(), |_| Default::default()));
498            if !was_full && cache.len() == capacity && config::verbose() {
499                eprintln!(
500                    "build_object_store: http store cache full ({capacity} hosts), evicting \
501                     least recently used from now on (POLARS_HTTP_STORE_CACHE_SIZE)"
502                );
503            }
504            cell
505        };
506
507        let base_url = self.base_url();
508
509        cell.get_or_try_init(|| async {
510            let store = self.build_impl(false).await?;
511            PolarsResult::Ok(PolarsObjectStore::new_from_inner(store, self))
512        })
513        .await
514        .map(|store| store.clone().with_base_url(base_url))
515    }
516
517    pub(crate) fn is_azure(&self) -> bool {
518        matches!(&self.cloud_type, CloudType::Azure)
519    }
520
521    /// Http has no credentials to refresh; a rebuild would drop the connection pool.
522    pub(crate) fn rebuild_on_error(&self) -> bool {
523        !matches!(&self.cloud_type, CloudType::Http)
524    }
525}
526
527/// Build an [`ObjectStore`] based on the URL and passed in url. Return the cloud location and an implementation of the object store.
528pub async fn build_object_store(
529    path: PlRefPath,
530    #[cfg_attr(
531        not(any(feature = "aws", feature = "gcp", feature = "azure")),
532        allow(unused_variables)
533    )]
534    options: Option<&CloudOptions>,
535    glob: bool,
536) -> PolarsResult<(CloudLocation, PolarsObjectStore)> {
537    let path = path.to_absolute_path()?.into_owned();
538
539    let cloud_type = path
540        .scheme()
541        .map_or(CloudType::File, CloudType::from_cloud_scheme);
542    let cloud_location = CloudLocation::new(path.clone(), glob)?;
543
544    let disable_http_rate_limit = polars_config::config().disable_http_rate_limit();
545    let rate_limiter = match cloud_type {
546        CloudType::Aws | CloudType::Azure | CloudType::Gcp if !disable_http_rate_limit => {
547            Some(Arc::new(RateLimiter::new(
548                options
549                    .map(|options| options.rate_limit_config)
550                    .unwrap_or_default()
551                    .into(),
552            )))
553        },
554        _ => None,
555    };
556
557    let store = PolarsObjectStoreBuilder {
558        path,
559        cloud_type,
560        options: options.cloned(),
561        rate_limiter,
562    }
563    .build()
564    .await?;
565
566    Ok((cloud_location, store))
567}
568
569mod test {
570    #[test]
571    fn test_object_path_from_str() {
572        use super::object_path_from_str;
573
574        let path = "%25";
575        let out = object_path_from_str(path).unwrap();
576
577        assert_eq!(out.as_ref(), path);
578    }
579}
580
581#[cfg(all(test, feature = "cloud"))]
582mod ext_store_tests {
583    use std::sync::Arc;
584
585    use object_store::ObjectStore;
586    use object_store::memory::InMemory;
587    use polars_utils::pl_path::PlRefPath;
588    use polars_utils::relaxed_cell::RelaxedCell;
589
590    use super::*;
591
592    struct TestBuilder {
593        store: Arc<dyn ObjectStore + Send + Sync>,
594        build_count: RelaxedCell<usize>,
595    }
596
597    impl TestBuilder {
598        fn new() -> Arc<Self> {
599            Arc::new(Self {
600                store: Arc::new(InMemory::new()),
601                build_count: RelaxedCell::new_usize(0),
602            })
603        }
604
605        fn build_count(&self) -> usize {
606            self.build_count.load()
607        }
608
609        fn inc_build_count(&self) {
610            self.build_count.fetch_add(1);
611        }
612    }
613
614    impl ExtObjectStoreBuilder for TestBuilder {
615        fn build(
616            &self,
617            _url: &PlRefPath,
618            _options: Option<&CloudOptions>,
619        ) -> PolarsResult<Arc<dyn ObjectStore + Send + Sync>> {
620            self.inc_build_count();
621            Ok(self.store.clone())
622        }
623    }
624
625    #[tokio::test]
626    async fn test_register_and_resolve() -> PolarsResult<()> {
627        let builder = TestBuilder::new();
628        polars_utils::pl_path::_allow_ext_scheme("pl-test1")?;
629        register_object_store_builder("pl-test1", builder.clone()).unwrap();
630
631        let path = PlRefPath::new("pl-test1://host:1234/data/file.parquet");
632        let result = build_object_store(path, None, false).await;
633        assert!(result.is_ok());
634        assert_eq!(builder.build_count(), 1);
635
636        deregister_object_store_builder("pl-test1");
637        polars_utils::pl_path::_disallow_ext_scheme("pl-test1");
638        Ok(())
639    }
640
641    #[tokio::test]
642    async fn test_cache_hit_after_first_build() -> PolarsResult<()> {
643        let builder = TestBuilder::new();
644        polars_utils::pl_path::_allow_ext_scheme("pl-test2")?;
645        register_object_store_builder("pl-test2", builder.clone()).unwrap();
646
647        let path = PlRefPath::new("pl-test2://host:1234/data/file.parquet");
648
649        // First call — cache miss, build_impl called
650        build_object_store(path.clone(), None, false).await.unwrap();
651        assert_eq!(builder.build_count(), 1);
652
653        // Second call — cache hit, build_impl not called
654        build_object_store(path.clone(), None, false).await.unwrap();
655        assert_eq!(builder.build_count(), 1);
656
657        deregister_object_store_builder("pl-test2");
658        polars_utils::pl_path::_disallow_ext_scheme("pl-test2");
659        Ok(())
660    }
661
662    #[test]
663    fn test_native_scheme_rejected() {
664        let builder = TestBuilder::new();
665        let result = register_object_store_builder("s3", builder);
666        assert!(result.is_err());
667        assert!(result.unwrap_err().to_string().contains("handled natively"));
668    }
669
670    #[tokio::test]
671    async fn test_stable_cache_key_override() -> PolarsResult<()> {
672        #[derive(Clone)]
673        struct AuthorityOnlyBuilder {
674            store: Arc<dyn ObjectStore + Send + Sync>,
675            build_count: Arc<RelaxedCell<usize>>,
676        }
677
678        impl AuthorityOnlyBuilder {
679            fn new() -> Self {
680                Self {
681                    store: Arc::new(InMemory::new()),
682                    build_count: Arc::new(RelaxedCell::new_usize(0)),
683                }
684            }
685
686            fn build_count(&self) -> usize {
687                self.build_count.load()
688            }
689
690            fn inc_build_count(&self) -> usize {
691                self.build_count.fetch_add(1)
692            }
693        }
694
695        impl ExtObjectStoreBuilder for AuthorityOnlyBuilder {
696            fn build(
697                &self,
698                _url: &PlRefPath,
699                _options: Option<&CloudOptions>,
700            ) -> PolarsResult<Arc<dyn ObjectStore + Send + Sync>> {
701                self.inc_build_count();
702                Ok(self.store.clone())
703            }
704
705            fn stable_cache_key(
706                &self,
707                url: &PlRefPath,
708                _options: Option<&CloudOptions>,
709            ) -> Option<Vec<u8>> {
710                let authority = &url.as_str()[..url.authority_end_position()];
711                Some(authority.as_bytes().to_vec())
712            }
713        }
714
715        let builder = AuthorityOnlyBuilder::new();
716        polars_utils::pl_path::_allow_ext_scheme("pl-test3")?;
717        register_object_store_builder("pl-test3", Arc::new(builder.clone())).unwrap();
718
719        use crate::cloud::{CloudConfig, CloudOptions};
720
721        let options_a = CloudOptions {
722            config: Some(CloudConfig::Ext {
723                options: vec![("user".to_string(), "alice".to_string())],
724            }),
725            ..CloudOptions::default()
726        };
727
728        let options_b = CloudOptions {
729            config: Some(CloudConfig::Ext {
730                options: vec![("user".to_string(), "bob".to_string())],
731            }),
732            ..CloudOptions::default()
733        };
734
735        let path = PlRefPath::new("pl-test3://host:1234/data/file.parquet");
736
737        build_object_store(path.clone(), Some(&options_a), false)
738            .await
739            .unwrap();
740        build_object_store(path.clone(), Some(&options_b), false)
741            .await
742            .unwrap();
743
744        assert_eq!(builder.build_count(), 1);
745
746        deregister_object_store_builder("pl-test3");
747        polars_utils::pl_path::_disallow_ext_scheme("pl-test3");
748        Ok(())
749    }
750
751    #[tokio::test]
752    async fn test_storage_options_passed_to_builder() -> PolarsResult<()> {
753        use crate::cloud::{CloudConfig, CloudOptions};
754
755        #[allow(clippy::type_complexity)]
756        struct CapturingBuilder {
757            received_options: Arc<std::sync::Mutex<Option<Vec<(String, String)>>>>,
758            store: Arc<dyn ObjectStore + Send + Sync>,
759        }
760
761        impl ExtObjectStoreBuilder for CapturingBuilder {
762            fn build(
763                &self,
764                _url: &PlRefPath,
765                options: Option<&CloudOptions>,
766            ) -> PolarsResult<Arc<dyn ObjectStore + Send + Sync>> {
767                let captured = match options {
768                    Some(CloudOptions {
769                        config: Some(CloudConfig::Ext { options }),
770                        ..
771                    }) => Some(options.clone()),
772                    _ => None,
773                };
774                *self.received_options.lock().unwrap() = captured;
775                Ok(self.store.clone())
776            }
777        }
778
779        let received = Arc::new(std::sync::Mutex::new(None));
780
781        let builder = Arc::new(CapturingBuilder {
782            received_options: received.clone(),
783            store: Arc::new(InMemory::new()),
784        });
785
786        polars_utils::pl_path::_allow_ext_scheme("pl-test4")?;
787        register_object_store_builder("pl-test4", builder).unwrap();
788
789        let options = CloudOptions {
790            config: Some(CloudConfig::Ext {
791                options: vec![
792                    ("user".to_string(), "hadoop".to_string()),
793                    ("token".to_string(), "abc123".to_string()),
794                ],
795            }),
796            ..CloudOptions::default()
797        };
798
799        let path = PlRefPath::new("pl-test4://host:1234/data/file.parquet");
800        build_object_store(path, Some(&options), false)
801            .await
802            .unwrap();
803
804        let captured = received.lock().unwrap().clone().unwrap();
805        assert_eq!(captured.len(), 2);
806        assert!(captured.iter().any(|(k, v)| k == "user" && v == "hadoop"));
807        assert!(captured.iter().any(|(k, v)| k == "token" && v == "abc123"));
808
809        deregister_object_store_builder("pl-test4");
810        polars_utils::pl_path::_disallow_ext_scheme("pl-test4");
811        Ok(())
812    }
813}