1#[cfg(feature = "aws")]
2use std::io::Read;
3#[cfg(feature = "aws")]
4use std::path::Path;
5use std::str::FromStr;
6#[cfg(any(feature = "aws", feature = "gcp", feature = "azure", feature = "http"))]
7use std::sync::Arc;
8use std::sync::LazyLock;
9
10#[cfg(any(feature = "aws", feature = "gcp", feature = "azure", feature = "http"))]
11use object_store::ClientOptions;
12#[cfg(feature = "aws")]
13use object_store::aws::AmazonS3Builder;
14#[cfg(feature = "aws")]
15pub use object_store::aws::AmazonS3ConfigKey;
16#[cfg(feature = "azure")]
17pub use object_store::azure::AzureConfigKey;
18#[cfg(feature = "azure")]
19use object_store::azure::MicrosoftAzureBuilder;
20#[cfg(feature = "gcp")]
21use object_store::gcp::GoogleCloudStorageBuilder;
22#[cfg(feature = "gcp")]
23pub use object_store::gcp::GoogleConfigKey;
24use polars_error::*;
25#[cfg(feature = "aws")]
26use polars_utils::cache::LruCache;
27use polars_utils::pl_path::{CloudScheme, PlRefPath};
28use polars_utils::total_ord::TotalOrdWrap;
29#[cfg(feature = "http")]
30use reqwest::header::HeaderMap;
31#[cfg(feature = "serde")]
32use serde::{Deserialize, Serialize};
33
34#[cfg(feature = "cloud")]
35use super::credential_provider::PlCredentialProvider;
36#[cfg(feature = "cloud")]
37use crate::cloud::ObjectStoreErrorContext;
38#[cfg(any(feature = "aws", feature = "gcp", feature = "azure", feature = "http"))]
39use crate::cloud::dns::{CachingResolver, DnsResolverConfig};
40#[cfg(feature = "http")]
41use crate::cloud::http_origin_store::HttpOriginStore;
42#[cfg(any(feature = "aws", feature = "gcp", feature = "azure"))]
43use crate::cloud::http_rate_limit::PacedHttpConnector;
44#[cfg(any(feature = "aws", feature = "gcp", feature = "azure"))]
45use crate::cloud::http_rate_limit::RateLimiter;
46#[cfg(feature = "file_cache")]
47use crate::file_cache::get_env_file_cache_ttl;
48#[cfg(feature = "aws")]
49use crate::pl_async::with_concurrency_budget;
50
51#[cfg(feature = "aws")]
52fn to_io_err(err: reqwest::Error) -> PolarsError {
53 let kind = super::polars_object_store::io_error_kind_from_source(&err);
54 PolarsError::IO {
55 error: Arc::new(std::io::Error::new(kind, err)),
56 msg: None,
57 }
58}
59
60#[cfg(feature = "aws")]
61static BUCKET_REGION: LazyLock<
62 std::sync::Mutex<LruCache<polars_utils::pl_str::PlSmallStr, polars_utils::pl_str::PlSmallStr>>,
63> = LazyLock::new(|| std::sync::Mutex::new(LruCache::with_capacity(32)));
64
65#[allow(dead_code)]
72type Configs<T> = Vec<(T, String)>;
73
74#[derive(Clone, Debug, PartialEq, Hash, Eq)]
75#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
76#[cfg_attr(feature = "dsl-schema", derive(schemars::JsonSchema))]
77pub enum CloudConfig {
78 #[cfg(feature = "aws")]
79 Aws(
80 #[cfg_attr(feature = "dsl-schema", schemars(with = "Vec<(String, String)>"))]
81 Configs<AmazonS3ConfigKey>,
82 ),
83 #[cfg(feature = "azure")]
84 Azure(
85 #[cfg_attr(feature = "dsl-schema", schemars(with = "Vec<(String, String)>"))]
86 Configs<AzureConfigKey>,
87 ),
88 #[cfg(feature = "gcp")]
89 Gcp(
90 #[cfg_attr(feature = "dsl-schema", schemars(with = "Vec<(String, String)>"))]
91 Configs<GoogleConfigKey>,
92 ),
93 #[cfg(feature = "http")]
94 Http {
95 headers: Vec<(String, String)>,
96 },
97 Ext {
98 options: Vec<(String, String)>,
99 },
100}
101
102#[derive(Clone, Debug, PartialEq, Hash, Eq)]
103#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
104#[cfg_attr(feature = "dsl-schema", derive(schemars::JsonSchema))]
105pub struct CloudOptions {
107 #[cfg(feature = "file_cache")]
108 pub file_cache_ttl: u64,
109 pub config: Option<CloudConfig>,
110 #[cfg_attr(feature = "serde", serde(default))]
111 pub retry_config: CloudRetryConfig,
112 #[cfg_attr(feature = "serde", serde(default))]
113 pub rate_limit_config: CloudRateLimitConfig,
114 #[cfg(feature = "cloud")]
115 pub(crate) credential_provider: Option<PlCredentialProvider>,
118}
119
120impl Default for CloudOptions {
121 fn default() -> Self {
122 Self::default_static_ref().clone()
123 }
124}
125
126impl CloudOptions {
127 pub fn default_static_ref() -> &'static Self {
128 static DEFAULT: LazyLock<CloudOptions> = LazyLock::new(|| CloudOptions {
129 #[cfg(feature = "file_cache")]
130 file_cache_ttl: get_env_file_cache_ttl(),
131 config: None,
132 retry_config: CloudRetryConfig::default(),
133 rate_limit_config: CloudRateLimitConfig::default(),
134 #[cfg(feature = "cloud")]
135 credential_provider: None,
136 });
137
138 &DEFAULT
139 }
140}
141
142#[derive(Clone, Copy, Default, Debug, PartialEq, Hash, Eq)]
143#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
144#[cfg_attr(feature = "dsl-schema", derive(schemars::JsonSchema))]
145pub struct CloudRetryConfig {
146 pub max_retries: Option<usize>,
147 pub retry_timeout: Option<std::time::Duration>,
148 pub retry_init_backoff: Option<std::time::Duration>,
149 pub retry_max_backoff: Option<std::time::Duration>,
150 pub retry_base_multiplier: Option<TotalOrdWrap<f64>>,
151}
152
153#[cfg(any(feature = "aws", feature = "gcp", feature = "azure"))]
154impl From<CloudRetryConfig> for object_store::RetryConfig {
155 fn from(value: CloudRetryConfig) -> Self {
156 use std::time::Duration;
157
158 use polars_core::config::verbose;
159
160 let out = object_store::RetryConfig {
161 backoff: object_store::BackoffConfig {
162 init_backoff: value
163 .retry_init_backoff
164 .unwrap_or_else(|| DEFAULTS.backoff.init_backoff),
165 max_backoff: value
166 .retry_max_backoff
167 .unwrap_or_else(|| DEFAULTS.backoff.max_backoff),
168 base: value
169 .retry_base_multiplier
170 .map_or_else(|| DEFAULTS.backoff.base, |x| x.0),
171 },
172 max_retries: value.max_retries.unwrap_or_else(|| DEFAULTS.max_retries),
173 retry_timeout: value
174 .retry_timeout
175 .unwrap_or_else(|| DEFAULTS.retry_timeout),
176 };
177
178 if verbose() {
179 eprintln!("object-store retry config: {:?}", out)
180 }
181
182 return out;
183
184 static DEFAULTS: LazyLock<object_store::RetryConfig> =
192 LazyLock::new(|| object_store::RetryConfig {
193 backoff: object_store::BackoffConfig {
194 init_backoff: Duration::from_millis(parse_env_var(
195 250,
196 "POLARS_CLOUD_RETRY_INIT_BACKOFF_MS",
197 )),
198 max_backoff: Duration::from_millis(parse_env_var(
199 5 * 1000,
200 "POLARS_CLOUD_RETRY_MAX_BACKOFF_MS",
201 )),
202 base: parse_env_var(2., "POLARS_CLOUD_RETRY_BASE_MULTIPLIER"),
203 },
204 max_retries: parse_env_var(8, "POLARS_CLOUD_MAX_RETRIES"),
205 retry_timeout: Duration::from_millis(parse_env_var(
206 30 * 1000,
207 "POLARS_CLOUD_RETRY_TIMEOUT_MS",
208 )),
209 });
210
211 fn parse_env_var<T: FromStr>(default: T, name: &'static str) -> T {
212 std::env::var(name).map_or(default, |x| {
213 x.parse::<T>()
214 .ok()
215 .unwrap_or_else(|| panic!("invalid value for {name}: {x}"))
216 })
217 }
218 }
219}
220
221#[derive(Clone, Copy, Default, Debug, PartialEq, Hash, Eq)]
223#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
224#[cfg_attr(feature = "dsl-schema", derive(schemars::JsonSchema))]
225pub struct CloudDirectionalRateLimitConfig {
226 pub init_rate: Option<u64>,
227 pub floor_rate: Option<u64>,
228 pub ceiling_rate: Option<u64>,
229}
230
231#[derive(Clone, Copy, Default, Debug, PartialEq, Hash, Eq)]
232#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
233#[cfg_attr(feature = "dsl-schema", derive(schemars::JsonSchema))]
234pub struct CloudRateLimitConfig {
235 pub read: CloudDirectionalRateLimitConfig,
236 pub write: CloudDirectionalRateLimitConfig,
237}
238
239#[cfg(feature = "http")]
240pub(crate) fn try_build_http_header_map_from_items_slice<S: AsRef<str>>(
241 headers: &[(S, S)],
242) -> PolarsResult<HeaderMap> {
243 use reqwest::header::{HeaderName, HeaderValue};
244
245 let mut map = HeaderMap::with_capacity(headers.len());
246 for (k, v) in headers {
247 let (k, v) = (k.as_ref(), v.as_ref());
248 map.insert(
249 HeaderName::from_str(k).map_err(to_compute_err)?,
250 HeaderValue::from_str(v).map_err(to_compute_err)?,
251 );
252 }
253
254 Ok(map)
255}
256
257#[allow(dead_code)]
258fn parse_untyped_config<T, I: IntoIterator<Item = (impl AsRef<str>, impl Into<String>)>>(
260 config: I,
261) -> PolarsResult<Configs<T>>
262where
263 T: FromStr + Eq + std::hash::Hash,
264{
265 Ok(config
266 .into_iter()
267 .filter_map(|(key, val)| {
269 T::from_str(key.as_ref().to_ascii_lowercase().as_str())
270 .ok()
271 .map(|typed_key| (typed_key, val.into()))
272 })
273 .collect::<Configs<T>>())
274}
275
276#[derive(Debug, Copy, Clone, PartialEq)]
277pub enum CloudType {
278 Aws,
279 Azure,
280 File,
282 Gcp,
284 Http,
285 Hf,
287 Ext(&'static str),
289}
290
291impl CloudType {
292 pub fn from_cloud_scheme(scheme: CloudScheme) -> Self {
293 match scheme {
294 CloudScheme::Abfs
295 | CloudScheme::Abfss
296 | CloudScheme::Adl
297 | CloudScheme::Az
298 | CloudScheme::Azure => Self::Azure,
299
300 CloudScheme::File | CloudScheme::FileNoHostname => Self::File,
301
302 CloudScheme::Gcs | CloudScheme::Gs => Self::Gcp,
303
304 CloudScheme::Hf => Self::Hf,
305
306 CloudScheme::Http | CloudScheme::Https => Self::Http,
307
308 CloudScheme::S3 | CloudScheme::S3a => Self::Aws,
309
310 CloudScheme::Ext(scheme) => Self::Ext(scheme),
311 }
312 }
313
314 pub fn is_writable(&self) -> bool {
319 match self {
320 Self::Aws => cfg!(feature = "aws"),
321 Self::Azure => cfg!(feature = "azure"),
322 Self::Gcp => cfg!(feature = "gcp"),
323 Self::Http => cfg!(feature = "http"),
324 Self::File => true,
325 Self::Hf => false,
326 #[cfg(feature = "cloud")]
327 Self::Ext(scheme) => super::has_object_store_builder(scheme),
328 #[cfg(not(feature = "cloud"))]
329 Self::Ext(_) => false,
330 }
331 }
332}
333
334pub static USER_AGENT: &str = concat!("polars", "/", env!("CARGO_PKG_VERSION"),);
335
336#[cfg(any(feature = "aws", feature = "gcp", feature = "azure", feature = "http"))]
338struct HttpTimeouts {
339 connect: Option<std::time::Duration>,
341 read: Option<std::time::Duration>,
344 request: Option<std::time::Duration>,
346}
347
348#[cfg(any(feature = "aws", feature = "gcp", feature = "azure", feature = "http"))]
349impl HttpTimeouts {
350 fn from_env() -> Self {
351 fn secs(name: &str, default: u64) -> Option<std::time::Duration> {
352 let secs = std::env::var(name).map_or(default, |x| {
353 x.parse::<u64>()
354 .unwrap_or_else(|_| panic!("invalid value for {name}: {x}"))
355 });
356 (secs > 0).then(|| std::time::Duration::from_secs(secs))
357 }
358
359 Self {
360 connect: secs("POLARS_HTTP_CONNECT_TIMEOUT_SECONDS", 10),
361 read: secs("POLARS_HTTP_READ_TIMEOUT_SECONDS", 0),
362 request: secs("POLARS_HTTP_REQUEST_TIMEOUT_SECONDS", 0),
363 }
364 }
365}
366
367#[cfg(any(feature = "aws", feature = "gcp", feature = "azure", feature = "http"))]
368pub(super) fn get_client_options() -> ClientOptions {
369 use reqwest::header::HeaderValue;
370
371 let HttpTimeouts {
372 connect,
373 read,
374 request,
375 } = HttpTimeouts::from_env();
376
377 let opts = ClientOptions::new()
378 .with_user_agent(HeaderValue::from_static(USER_AGENT))
379 .with_allow_http(true)
380 .with_dns_resolver(Arc::new(
381 CachingResolver::new(DnsResolverConfig::from_env()),
382 ));
383
384 let opts = match connect {
386 Some(v) => opts.with_connect_timeout(v),
387 None => opts.with_connect_timeout_disabled(),
388 };
389 let opts = match read {
390 Some(v) => opts.with_read_timeout(v),
391 None => opts.with_read_timeout_disabled(),
392 };
393 match request {
394 Some(v) => opts.with_timeout(v),
395 None => opts.with_timeout_disabled(),
396 }
397}
398
399#[cfg(any(feature = "aws", feature = "gcp", feature = "azure", feature = "http"))]
401fn log_http_timeouts(get_config_value: impl Fn(object_store::ClientConfigKey) -> Option<String>) {
402 use object_store::ClientConfigKey as K;
403
404 let get = |key| get_config_value(key).unwrap_or_else(|| "disabled".to_string());
405 eprintln!(
406 "object-store http timeouts: connect: {}, read: {}, request: {}",
407 get(K::ConnectTimeout),
408 get(K::ReadTimeout),
409 get(K::Timeout),
410 );
411}
412
413#[cfg(feature = "aws")]
414fn read_config(
415 builder: &mut AmazonS3Builder,
416 items: &[(&Path, &[(&str, AmazonS3ConfigKey)])],
417) -> Option<()> {
418 use crate::path_utils::resolve_homedir;
419
420 for (path, keys) in items {
421 if keys
422 .iter()
423 .all(|(_, key)| builder.get_config_value(key).is_some())
424 {
425 continue;
426 }
427
428 let mut config = std::fs::File::open(resolve_homedir(path)).ok()?;
429 let mut buf = vec![];
430 config.read_to_end(&mut buf).ok()?;
431 let content = std::str::from_utf8(buf.as_ref()).ok()?;
432
433 for (pattern, key) in keys.iter() {
434 if builder.get_config_value(key).is_none() {
435 let reg = polars_utils::regex_cache::compile_regex(pattern).unwrap();
436 let cap = reg.captures(content)?;
437 let m = cap.get(1)?;
438 let parsed = m.as_str();
439 *builder = std::mem::take(builder).with_config(*key, parsed);
440 }
441 }
442 }
443 Some(())
444}
445
446impl CloudOptions {
447 pub fn with_retry_config(mut self, retry_config: CloudRetryConfig) -> Self {
448 self.retry_config = retry_config;
449 self
450 }
451
452 pub fn with_rate_limit_config(mut self, rate_limit_config: CloudRateLimitConfig) -> Self {
453 self.rate_limit_config = rate_limit_config;
454 self
455 }
456
457 #[cfg(feature = "cloud")]
458 pub fn with_credential_provider(
459 mut self,
460 credential_provider: Option<PlCredentialProvider>,
461 ) -> Self {
462 self.credential_provider = credential_provider;
463 self
464 }
465
466 #[cfg(feature = "aws")]
468 pub fn with_aws<I: IntoIterator<Item = (AmazonS3ConfigKey, impl Into<String>)>>(
469 mut self,
470 configs: I,
471 ) -> Self {
472 self.config = Some(CloudConfig::Aws(
473 configs.into_iter().map(|(k, v)| (k, v.into())).collect(),
474 ));
475 self
476 }
477
478 #[cfg(feature = "aws")]
480 pub(crate) async fn build_aws(
481 &self,
482 url: PlRefPath,
483 clear_cached_credentials: bool,
484 rate_limiter: Option<&RateLimiter>,
485 ) -> PolarsResult<impl object_store::ObjectStore> {
486 use object_store::client::ReqwestConnector;
487
488 use super::credential_provider::IntoCredentialProvider;
489
490 let opt_credential_provider =
491 self.initialized_credential_provider(clear_cached_credentials)?;
492
493 let mut builder = AmazonS3Builder::from_env()
494 .with_client_options(get_client_options())
495 .with_url(url.clone().to_string());
496
497 if let Some(credential_provider) = &opt_credential_provider {
498 let storage_update_options = parse_untyped_config::<AmazonS3ConfigKey, _>(
499 credential_provider
500 .storage_update_options()?
501 .into_iter()
502 .map(|(k, v)| (k, v.to_string())),
503 )?;
504
505 for (key, value) in storage_update_options {
506 builder = builder.with_config(key, value);
507 }
508 }
509
510 read_config(
511 &mut builder,
512 &[(
513 Path::new("~/.aws/config"),
514 &[("region\\s*=\\s*([^\r\n]*)", AmazonS3ConfigKey::Region)],
515 )],
516 );
517
518 read_config(
519 &mut builder,
520 &[(
521 Path::new("~/.aws/credentials"),
522 &[
523 (
524 "aws_access_key_id\\s*=\\s*([^\\r\\n]*)",
525 AmazonS3ConfigKey::AccessKeyId,
526 ),
527 (
528 "aws_secret_access_key\\s*=\\s*([^\\r\\n]*)",
529 AmazonS3ConfigKey::SecretAccessKey,
530 ),
531 (
532 "aws_session_token\\s*=\\s*([^\\r\\n]*)",
533 AmazonS3ConfigKey::Token,
534 ),
535 ],
536 )],
537 );
538
539 if let Some(options) = &self.config {
540 let CloudConfig::Aws(options) = options else {
541 panic!("impl error: cloud type mismatch")
542 };
543 for (key, value) in options {
544 builder = builder.with_config(*key, value);
545 }
546 }
547
548 if polars_core::config::verbose() {
549 log_http_timeouts(|key| builder.get_config_value(&AmazonS3ConfigKey::Client(key)));
550 }
551
552 if builder
553 .get_config_value(&AmazonS3ConfigKey::DefaultRegion)
554 .is_none()
555 && builder
556 .get_config_value(&AmazonS3ConfigKey::Region)
557 .is_none()
558 {
559 let bucket = crate::cloud::CloudLocation::new(url.clone(), false)?.bucket;
560 let region = {
561 let mut bucket_region = BUCKET_REGION.lock().unwrap();
562 bucket_region.get(bucket.as_str()).cloned()
563 };
564
565 match region {
566 Some(region) => {
567 builder = builder.with_config(AmazonS3ConfigKey::Region, region.as_str())
568 },
569 None => {
570 if builder
571 .get_config_value(&AmazonS3ConfigKey::Endpoint)
572 .is_some()
573 {
574 builder = builder.with_config(AmazonS3ConfigKey::Region, "us-east-1");
577 } else {
578 polars_warn!(
579 "'(default_)region' not set; polars will try to get it from bucket\n\nSet the region manually to silence this warning."
580 );
581 let result = with_concurrency_budget(1, || async {
582 let mut client = reqwest::Client::builder()
584 .user_agent(USER_AGENT)
585 .timeout(std::time::Duration::from_secs(30));
586 if let Some(v) = HttpTimeouts::from_env().connect {
587 client = client.connect_timeout(v);
588 }
589 client
590 .build()
591 .unwrap()
592 .head(format!("https://{bucket}.s3.amazonaws.com"))
593 .send()
594 .await
595 .map_err(to_io_err)
596 })
597 .await?;
598 if let Some(region) = result.headers().get("x-amz-bucket-region") {
599 let region =
600 std::str::from_utf8(region.as_bytes()).map_err(to_compute_err)?;
601 let mut bucket_region = BUCKET_REGION.lock().unwrap();
602 bucket_region.insert(bucket, region.into());
603 builder = builder.with_config(AmazonS3ConfigKey::Region, region)
604 }
605 }
606 },
607 };
608 };
609
610 let builder = builder.with_retry(self.retry_config.into());
611
612 let opt_credential_provider = match opt_credential_provider {
613 #[cfg(feature = "python")]
614 Some(PlCredentialProvider::Python(object)) => {
615 if pyo3::Python::attach(|py| {
616 let Ok(func_object) = object
617 .unwrap_as_provider_ref()
618 .getattr(py, "_can_use_as_provider")
619 else {
620 return PolarsResult::Ok(true);
621 };
622
623 Ok(func_object.call0(py)?.extract::<bool>(py).unwrap())
624 })? {
625 Some(PlCredentialProvider::Python(object))
626 } else {
627 None
628 }
629 },
630
631 v => v,
632 };
633
634 let builder = if let Some(credential_provider) = opt_credential_provider {
635 builder.with_credentials(credential_provider.into_aws_provider())
636 } else {
637 builder
638 };
639
640 let builder = if builder
641 .get_config_value(&AmazonS3ConfigKey::Checksum)
642 .is_none()
643 {
644 builder.with_checksum_algorithm(object_store::aws::Checksum::CRC64NVME)
646 } else {
647 builder
648 };
649
650 let builder = match &rate_limiter {
652 Some(rate_limiter) => {
653 let paced_http_connector =
654 PacedHttpConnector::new(Box::new(ReqwestConnector::default()), rate_limiter);
655 builder.with_http_connector(paced_http_connector)
656 },
657 None => builder,
658 };
659
660 let out = builder
661 .with_unsigned_payload(true)
662 .build()
663 .map_err(|e| ObjectStoreErrorContext::new(url).attach_err_info(e))?;
664
665 Ok(out)
666 }
667
668 #[cfg(feature = "azure")]
670 pub fn with_azure<I: IntoIterator<Item = (AzureConfigKey, impl Into<String>)>>(
671 mut self,
672 configs: I,
673 ) -> Self {
674 self.config = Some(CloudConfig::Azure(
675 configs.into_iter().map(|(k, v)| (k, v.into())).collect(),
676 ));
677 self
678 }
679
680 #[cfg(feature = "azure")]
682 pub(crate) fn build_azure(
683 &self,
684 url: PlRefPath,
685 clear_cached_credentials: bool,
686 rate_limiter: Option<&RateLimiter>,
687 ) -> PolarsResult<impl object_store::ObjectStore> {
688 use object_store::client::ReqwestConnector;
689
690 use super::credential_provider::IntoCredentialProvider;
691 use crate::cloud::ObjectStoreErrorContext;
692
693 let verbose = polars_core::config::verbose();
694
695 let mut builder =
698 MicrosoftAzureBuilder::from_env().with_client_options(get_client_options());
699
700 if let Some(options) = &self.config {
701 let CloudConfig::Azure(options) = options else {
702 panic!("impl error: cloud type mismatch")
703 };
704 for (key, value) in options.iter() {
705 builder = builder.with_config(*key, value);
706 }
707 }
708
709 if verbose {
710 log_http_timeouts(|key| builder.get_config_value(&AzureConfigKey::Client(key)));
711 }
712
713 let builder = builder
714 .with_url(url.to_string())
715 .with_retry(self.retry_config.into());
716
717 let builder =
718 if let Some(v) = self.initialized_credential_provider(clear_cached_credentials)? {
719 if verbose {
720 eprintln!(
721 "[CloudOptions::build_azure]: Using credential provider {:?}",
722 v
723 );
724 }
725 builder.with_credentials(v.into_azure_provider())
726 } else {
727 builder
728 };
729
730 let builder = match &rate_limiter {
732 Some(rate_limiter) => {
733 let paced_http_connector =
734 PacedHttpConnector::new(Box::new(ReqwestConnector::default()), rate_limiter);
735 builder.with_http_connector(paced_http_connector)
736 },
737 None => builder,
738 };
739
740 let out = builder
741 .build()
742 .map_err(|e| ObjectStoreErrorContext::new(url).attach_err_info(e))?;
743
744 Ok(out)
745 }
746
747 #[cfg(feature = "gcp")]
749 pub fn with_gcp<I: IntoIterator<Item = (GoogleConfigKey, impl Into<String>)>>(
750 mut self,
751 configs: I,
752 ) -> Self {
753 self.config = Some(CloudConfig::Gcp(
754 configs.into_iter().map(|(k, v)| (k, v.into())).collect(),
755 ));
756 self
757 }
758
759 #[cfg(feature = "gcp")]
761 pub(crate) fn build_gcp(
762 &self,
763 url: PlRefPath,
764 clear_cached_credentials: bool,
765 rate_limiter: Option<&RateLimiter>,
766 ) -> PolarsResult<impl object_store::ObjectStore> {
767 use object_store::client::ReqwestConnector;
768
769 use super::credential_provider::IntoCredentialProvider;
770
771 let credential_provider = self.initialized_credential_provider(clear_cached_credentials)?;
772
773 let builder = if credential_provider.is_none() {
774 GoogleCloudStorageBuilder::from_env()
775 } else {
776 GoogleCloudStorageBuilder::new()
777 };
778
779 let mut builder = builder.with_client_options(get_client_options());
780
781 if let Some(options) = &self.config {
782 let CloudConfig::Gcp(options) = options else {
783 panic!("impl error: cloud type mismatch")
784 };
785 for (key, value) in options.iter() {
786 builder = builder.with_config(*key, value);
787 }
788 }
789
790 if polars_core::config::verbose() {
791 log_http_timeouts(|key| builder.get_config_value(&GoogleConfigKey::Client(key)));
792 }
793
794 let builder = builder
795 .with_url(url.to_string())
796 .with_retry(self.retry_config.into());
797
798 let builder = if let Some(v) = credential_provider {
799 builder.with_credentials(v.into_gcp_provider())
800 } else {
801 builder
802 };
803
804 let builder = match &rate_limiter {
806 Some(rate_limiter) => {
807 let paced_http_connector =
808 PacedHttpConnector::new(Box::new(ReqwestConnector::default()), rate_limiter);
809 builder.with_http_connector(paced_http_connector)
810 },
811 None => builder,
812 };
813
814 let out = builder
815 .build()
816 .map_err(|e| ObjectStoreErrorContext::new(url).attach_err_info(e))?;
817
818 Ok(out)
819 }
820
821 #[cfg(feature = "http")]
822 fn http_client_options(&self, url: &PlRefPath) -> PolarsResult<object_store::ClientOptions> {
823 let mut opts = super::get_client_options();
824 if url.scheme() == Some(CloudScheme::Http)
825 && polars_config::config().http_skip_system_certificates()
826 {
827 opts = opts.with_no_system_certificates(true);
828 }
829 if let Some(CloudConfig::Http { headers }) = &self.config {
830 opts = opts.with_default_headers(try_build_http_header_map_from_items_slice(
831 headers.as_slice(),
832 )?);
833 }
834 if polars_core::config::verbose() {
835 log_http_timeouts(|key| opts.get_config_value(&key));
836 }
837 Ok(opts)
838 }
839
840 #[cfg(feature = "http")]
842 pub fn build_http(&self, url: PlRefPath) -> PolarsResult<impl object_store::ObjectStore> {
843 let out = object_store::http::HttpBuilder::new()
844 .with_url(url.to_string())
845 .with_client_options(self.http_client_options(&url)?)
846 .build()
847 .map_err(|e| ObjectStoreErrorContext::new(url).attach_err_info(e))?;
848
849 Ok(out)
850 }
851
852 #[cfg(feature = "http")]
854 pub(crate) fn build_http_origin(&self, base_url: PlRefPath) -> PolarsResult<HttpOriginStore> {
855 let out = HttpOriginStore::new(base_url.as_str(), self.http_client_options(&base_url)?)
856 .map_err(|e| ObjectStoreErrorContext::new(base_url).attach_err_info(e))?;
857
858 Ok(out)
859 }
860
861 #[allow(unused_variables)]
863 pub fn from_untyped_config<I: IntoIterator<Item = (impl AsRef<str>, impl Into<String>)>>(
864 scheme: Option<CloudScheme>,
865 config: I,
866 ) -> PolarsResult<Self> {
867 match scheme.map_or(CloudType::File, CloudType::from_cloud_scheme) {
868 CloudType::Aws => {
869 #[cfg(feature = "aws")]
870 {
871 parse_untyped_config::<AmazonS3ConfigKey, _>(config)
872 .map(|aws| Self::default().with_aws(aws))
873 }
874 #[cfg(not(feature = "aws"))]
875 {
876 polars_bail!(ComputeError: "'aws' feature is not enabled");
877 }
878 },
879 CloudType::Azure => {
880 #[cfg(feature = "azure")]
881 {
882 parse_untyped_config::<AzureConfigKey, _>(config)
883 .map(|azure| Self::default().with_azure(azure))
884 }
885 #[cfg(not(feature = "azure"))]
886 {
887 polars_bail!(ComputeError: "'azure' feature is not enabled");
888 }
889 },
890 CloudType::File => Ok(Self::default()),
891 CloudType::Http => Ok(Self::default()),
892 CloudType::Gcp => {
893 #[cfg(feature = "gcp")]
894 {
895 parse_untyped_config::<GoogleConfigKey, _>(config)
896 .map(|gcp| Self::default().with_gcp(gcp))
897 }
898 #[cfg(not(feature = "gcp"))]
899 {
900 polars_bail!(ComputeError: "'gcp' feature is not enabled");
901 }
902 },
903 CloudType::Hf => {
904 #[cfg(feature = "http")]
905 {
906 use polars_core::config;
907
908 use crate::path_utils::resolve_homedir;
909
910 let mut this = Self::default();
911 let mut token = None;
912 let verbose = config::verbose();
913
914 for (i, (k, v)) in config.into_iter().enumerate() {
915 let (k, v) = (k.as_ref(), v.into());
916
917 if i == 0 && k == "token" {
918 if verbose {
919 eprintln!("HF token sourced from storage_options");
920 }
921 token = Some(v);
922 } else {
923 polars_bail!(ComputeError: "unknown configuration key for HF: {}", k)
924 }
925 }
926
927 token = token
928 .or_else(|| {
929 let v = std::env::var("HF_TOKEN").ok();
930 if v.is_some() && verbose {
931 eprintln!("HF token sourced from HF_TOKEN env var");
932 }
933 v
934 })
935 .or_else(|| {
936 let hf_home = std::env::var("HF_HOME");
937 let hf_home = hf_home.as_deref();
938 let hf_home = hf_home.unwrap_or("~/.cache/huggingface");
939 let hf_home = resolve_homedir(hf_home);
940 let cached_token_path = hf_home.join("token");
941
942 let v = std::string::String::from_utf8(
943 std::fs::read(&cached_token_path).ok()?,
944 )
945 .ok()
946 .filter(|x| !x.is_empty());
947
948 if v.is_some() && verbose {
949 eprintln!("HF token sourced from {:?}", cached_token_path);
950 }
951
952 v
953 });
954
955 if let Some(v) = token {
956 this.config = Some(CloudConfig::Http {
957 headers: vec![("Authorization".into(), format!("Bearer {v}"))],
958 })
959 }
960
961 Ok(this)
962 }
963 #[cfg(not(feature = "http"))]
964 {
965 polars_bail!(ComputeError: "'http' feature is not enabled");
966 }
967 },
968 CloudType::Ext(_) => {
969 let pairs: Vec<(String, String)> = config
970 .into_iter()
971 .map(|(k, v)| (k.as_ref().to_string(), v.into()))
972 .collect();
973
974 Ok(Self {
975 config: if pairs.is_empty() {
976 None
977 } else {
978 Some(CloudConfig::Ext { options: pairs })
979 },
980 ..Self::default()
981 })
982 },
983 }
984 }
985
986 #[cfg(feature = "cloud")]
989 fn initialized_credential_provider(
990 &self,
991 clear_cached_credentials: bool,
992 ) -> PolarsResult<Option<PlCredentialProvider>> {
993 if let Some(v) = self.credential_provider.clone() {
994 v.try_into_initialized(clear_cached_credentials)
995 } else {
996 Ok(None)
997 }
998 }
999}
1000
1001#[cfg(feature = "cloud")]
1002#[cfg(test)]
1003mod tests {
1004 use hashbrown::HashMap;
1005
1006 use super::parse_untyped_config;
1007
1008 #[cfg(feature = "aws")]
1009 #[test]
1010 fn test_parse_untyped_config() {
1011 use object_store::aws::AmazonS3ConfigKey;
1012
1013 let aws_config = [
1014 ("aws_secret_access_key", "a_key"),
1015 ("aws_s3_allow_unsafe_rename", "true"),
1016 ]
1017 .into_iter()
1018 .collect::<HashMap<_, _>>();
1019 let aws_keys = parse_untyped_config::<AmazonS3ConfigKey, _>(aws_config)
1020 .expect("Parsing keys shouldn't have thrown an error");
1021
1022 assert_eq!(
1023 aws_keys.first().unwrap().0,
1024 AmazonS3ConfigKey::SecretAccessKey
1025 );
1026 assert_eq!(aws_keys.len(), 1);
1027
1028 let aws_config = [
1029 ("AWS_SECRET_ACCESS_KEY", "a_key"),
1030 ("aws_s3_allow_unsafe_rename", "true"),
1031 ]
1032 .into_iter()
1033 .collect::<HashMap<_, _>>();
1034 let aws_keys = parse_untyped_config::<AmazonS3ConfigKey, _>(aws_config)
1035 .expect("Parsing keys shouldn't have thrown an error");
1036
1037 assert_eq!(
1038 aws_keys.first().unwrap().0,
1039 AmazonS3ConfigKey::SecretAccessKey
1040 );
1041 assert_eq!(aws_keys.len(), 1);
1042 }
1043}