Skip to main content

polars_io/cloud/
polars_object_store.rs

1use std::fmt::Display;
2use std::ops::Range;
3use std::sync::Arc;
4use std::time::Instant;
5
6use futures::{Stream, StreamExt as _, TryStreamExt as _};
7use hashbrown::hash_map::RawEntryMut;
8use object_store::client::{HttpError, HttpErrorKind};
9use object_store::path::Path;
10use object_store::{ObjectMeta, ObjectStore, ObjectStoreExt};
11use polars_buffer::Buffer;
12use polars_core::config;
13use polars_core::prelude::{InitHashMaps, PlHashMap};
14use polars_error::{PolarsError, PolarsResult};
15use polars_utils::pl_path::PlRefPath;
16use tokio::io::AsyncWriteExt;
17
18use super::concurrency::{ConcurrencyController, IoSample};
19use super::concurrency_config::{ConcurrencyStrategy, FetchConfig, get_download_chunk_size};
20use crate::pl_async::{
21    self, MAX_BUDGET_PER_REQUEST, get_concurrency_limit, tune_with_concurrency_budget,
22    with_concurrency_budget,
23};
24
25#[derive(Debug)]
26pub struct PolarsObjectStoreError {
27    /// The URL of the failing object or of the store being built. Empty on a rebuild.
28    pub base_url: PlRefPath,
29    pub source: object_store::Error,
30}
31
32impl Display for PolarsObjectStoreError {
33    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
34        write!(f, "object-store error: {}", self.source)?;
35        if !self.base_url.as_str().is_empty() {
36            write!(f, " (path: {})", self.base_url)?;
37        }
38        Ok(())
39    }
40}
41
42impl std::error::Error for PolarsObjectStoreError {
43    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
44        Some(&self.source)
45    }
46}
47
48/// The `io::ErrorKind` for an `object_store::Error`, taken from the error
49/// variant or from the innermost `io::Error` in its source chain.
50pub fn object_store_error_kind(source: &object_store::Error) -> std::io::ErrorKind {
51    use std::io::ErrorKind::*;
52
53    match source {
54        object_store::Error::NotFound { .. } => NotFound,
55        object_store::Error::PermissionDenied { .. }
56        | object_store::Error::Unauthenticated { .. } => PermissionDenied,
57        _ => io_error_kind_from_source(source),
58    }
59}
60
61/// The kind of the innermost `io::Error` in the source chain of `error`,
62/// falling back to the kind of the innermost `HttpError`, or `Other`.
63pub fn io_error_kind_from_source(error: &(dyn std::error::Error + 'static)) -> std::io::ErrorKind {
64    use std::io::ErrorKind::*;
65
66    let mut kind = Other;
67    let mut http_kind = None;
68    let mut cur = Some(error);
69    while let Some(e) = cur {
70        if let Some(io) = e.downcast_ref::<std::io::Error>()
71            && io.kind() != Other
72        {
73            kind = io.kind();
74        } else if let Some(http) = e.downcast_ref::<HttpError>() {
75            http_kind = Some(http.kind());
76        }
77        cur = e.source();
78    }
79    if kind == Other {
80        // object_store maps this in its private `From<RetryError> for io::Error`,
81        // but the kind is lost when the error is boxed into `Error::Generic`.
82        kind = match http_kind {
83            Some(HttpErrorKind::Timeout) => TimedOut,
84            Some(HttpErrorKind::Connect) => NotConnected,
85            Some(HttpErrorKind::Interrupted) => ConnectionAborted,
86            _ => Other,
87        };
88    }
89    kind
90}
91
92impl From<PolarsObjectStoreError> for std::io::Error {
93    fn from(value: PolarsObjectStoreError) -> Self {
94        let kind = object_store_error_kind(&value.source);
95        std::io::Error::new(kind, value)
96    }
97}
98
99impl From<PolarsObjectStoreError> for PolarsError {
100    fn from(value: PolarsObjectStoreError) -> Self {
101        PolarsError::IO {
102            error: Arc::new(value.into()),
103            msg: None,
104        }
105    }
106}
107
108mod inner {
109
110    use std::borrow::Cow;
111    use std::future::Future;
112    use std::sync::Arc;
113
114    use object_store::ObjectStore;
115    use object_store::path::Path;
116    use polars_core::config;
117    use polars_error::{PolarsError, PolarsResult};
118    use polars_utils::pl_path::PlRefPath;
119    use polars_utils::relaxed_cell::RelaxedCell;
120
121    use crate::cloud::concurrency::{ConcurrencyController, ControllerConfig};
122    use crate::cloud::{ObjectStoreErrorContext, PolarsObjectStoreBuilder};
123    use crate::metrics::{IOMetrics, OptIOMetrics};
124
125    #[derive(Debug)]
126    struct Inner {
127        store: tokio::sync::RwLock<Arc<dyn ObjectStore>>,
128        builder: PolarsObjectStoreBuilder,
129        rebuilt: RelaxedCell<bool>,
130        suffix_range_supported: RelaxedCell<bool>,
131    }
132
133    /// Polars wrapper around [`ObjectStore`] functionality. This struct is cheaply cloneable.
134    #[derive(Clone, Debug)]
135    pub struct PolarsObjectStore {
136        inner: Arc<Inner>,
137        /// The URL the store is rooted at, as this caller spelled it.
138        base_url: PlRefPath,
139        /// Avoid contending the Mutex `lock()` until the first re-build.
140        initial_store: std::sync::Arc<dyn ObjectStore>,
141        io_metrics: OptIOMetrics,
142        /// In-flight concurrency control using the (new) BDP model.
143        concurrency: Arc<std::sync::OnceLock<Arc<ConcurrencyController>>>,
144    }
145
146    impl PolarsObjectStore {
147        pub(crate) fn new_from_inner(
148            store: Arc<dyn ObjectStore>,
149            builder: PolarsObjectStoreBuilder,
150        ) -> Self {
151            let initial_store = store.clone();
152            // Azure accepts only `bytes=start-` and `bytes=start-end`, so never attempt a
153            // suffix range there: https://learn.microsoft.com/en-us/rest/api/storageservices/specifying-the-range-header-for-blob-service-operations
154            let suffix_range_supported = RelaxedCell::from(!builder.is_azure());
155            Self {
156                base_url: builder.base_url(),
157                inner: Arc::new(Inner {
158                    store: tokio::sync::RwLock::new(store),
159                    builder,
160                    rebuilt: RelaxedCell::from(false),
161                    suffix_range_supported,
162                }),
163                initial_store,
164                io_metrics: OptIOMetrics(None),
165                concurrency: Arc::new(std::sync::OnceLock::new()),
166            }
167        }
168
169        pub(crate) fn with_base_url(mut self, base_url: PlRefPath) -> Self {
170            self.base_url = base_url;
171            self
172        }
173
174        pub fn set_io_metrics(&mut self, io_metrics: Option<Arc<IOMetrics>>) -> &mut Self {
175            self.io_metrics = OptIOMetrics(io_metrics);
176            self
177        }
178
179        pub fn io_metrics(&self) -> &OptIOMetrics {
180            &self.io_metrics
181        }
182
183        pub fn get_or_init_concurrency(&self) -> &Arc<ConcurrencyController> {
184            self.concurrency.get_or_init(|| {
185                // Valid across rebuilds: the signal wraps the stable cell.
186                let signal = self.inner.builder.rate_limit_signal();
187                Arc::new(ConcurrencyController::new(
188                    ControllerConfig::default(),
189                    signal,
190                ))
191            })
192        }
193
194        /// Gets the underlying [`ObjectStore`] implementation.
195        pub async fn to_dyn_object_store(&self) -> Cow<'_, Arc<dyn ObjectStore>> {
196            if !self.inner.rebuilt.load() {
197                Cow::Borrowed(&self.initial_store)
198            } else {
199                Cow::Owned(self.inner.store.read().await.clone())
200            }
201        }
202
203        pub async fn rebuild_inner(
204            &self,
205            from_version: &Arc<dyn ObjectStore>,
206        ) -> PolarsResult<Arc<dyn ObjectStore>> {
207            let mut current_store = self.inner.store.write().await;
208
209            // If this does not eq, then `inner` was already re-built by another thread.
210            if Arc::ptr_eq(&*current_store, from_version) {
211                *current_store =
212                    self.inner
213                        .builder
214                        .clone()
215                        .build_impl(true)
216                        .await
217                        .map_err(|e| {
218                            let url = self.inner.builder.path();
219                            e.wrap_msg(|e| {
220                                format!(
221                                    "attempt to rebuild object store failed: {e} \
222                                     (store built for: {url})"
223                                )
224                            })
225                        })?;
226            }
227
228            self.inner.rebuilt.store(true);
229
230            Ok((*current_store).clone())
231        }
232
233        /// `path` is the object `func` addresses.
234        pub async fn exec_with_rebuild_retry_on_err<'s, 'f, Fn, Fut, O>(
235            &'s self,
236            path: &Path,
237            mut func: Fn,
238        ) -> PolarsResult<O>
239        where
240            Fn: FnMut(Cow<'s, Arc<dyn ObjectStore>>) -> Fut + 'f,
241            Fut: Future<Output = object_store::Result<O>>,
242        {
243            let store = self.to_dyn_object_store().await;
244
245            let out = func(store.clone()).await;
246
247            let orig_err = match out {
248                Ok(v) => return Ok(v),
249                Err(e) => e,
250            };
251
252            let rebuild = self.inner.builder.rebuild_on_error();
253
254            if config::verbose() {
255                eprintln!(
256                    "[PolarsObjectStore]: got error: {}, will {}retry",
257                    orig_err,
258                    if rebuild { "rebuild store and " } else { "" }
259                );
260            }
261
262            let store = if rebuild {
263                let store = self.rebuild_inner(&store).await.map_err(|e| {
264                    // The failing request first, then the rebuild error.
265                    let orig_err = self.error_context(path).attach_err_info(orig_err);
266                    e.wrap_msg(|e| format!("{orig_err}; {e}"))
267                })?;
268                Cow::Owned(store)
269            } else {
270                store
271            };
272
273            func(store).await.map_err(|e| {
274                let e: PolarsError = self.error_context(path).attach_err_info(e).into();
275
276                if self.inner.builder.is_azure()
277                    && std::env::var("POLARS_AUTO_USE_AZURE_STORAGE_ACCOUNT_KEY").as_deref()
278                        != Ok("1")
279                {
280                    // Note: This error is intended for Python audiences. The logic for retrieving
281                    // these keys exist only on the Python side.
282                    e.wrap_msg(|e| {
283                        format!(
284                            "{e}; note: if you are using Python, consider setting \
285POLARS_AUTO_USE_AZURE_STORAGE_ACCOUNT_KEY=1 if you would like polars to try to retrieve \
286and use the storage account keys from Azure CLI to authenticate"
287                        )
288                    })
289                } else {
290                    e
291                }
292            })
293        }
294
295        pub(crate) fn suffix_range_supported(&self) -> bool {
296            self.inner.suffix_range_supported.load()
297        }
298
299        pub(crate) fn disable_suffix_range(&self) {
300            self.inner.suffix_range_supported.store(false);
301        }
302
303        /// Context for an error of a request to `path`.
304        pub fn error_context(&self, path: &Path) -> ObjectStoreErrorContext {
305            ObjectStoreErrorContext::new(self.base_url.clone()).with_path(path.clone())
306        }
307    }
308}
309
310#[derive(Clone)]
311pub struct ObjectStoreErrorContext {
312    base_url: PlRefPath,
313    path: Option<Path>,
314}
315
316impl ObjectStoreErrorContext {
317    pub fn new(base_url: PlRefPath) -> Self {
318        Self {
319            base_url,
320            path: None,
321        }
322    }
323
324    /// Context for building a store for `url`. Empty on a rebuild, whose error names `url`.
325    pub fn for_build(url: PlRefPath, rebuild: bool) -> Self {
326        Self::new(if rebuild { PlRefPath::new("") } else { url })
327    }
328
329    pub fn with_path(mut self, path: Path) -> Self {
330        self.path = Some(path);
331        self
332    }
333
334    pub fn attach_err_info(self, err: object_store::Error) -> PolarsObjectStoreError {
335        let ObjectStoreErrorContext { base_url, path } = self;
336
337        let base_url = match path {
338            Some(path) if !path.as_ref().is_empty() => {
339                // An empty base URL is a local path, which on Windows starts with its drive.
340                let sep = if base_url.as_str().is_empty() && cfg!(windows) {
341                    ""
342                } else {
343                    "/"
344                };
345                PlRefPath::new(format!("{base_url}{sep}{path}"))
346            },
347            // The root of a local filesystem.
348            Some(_) if base_url.scheme().is_none_or(|s| s.is_file()) => {
349                PlRefPath::new(format!("{base_url}/"))
350            },
351            _ => base_url,
352        };
353
354        PolarsObjectStoreError {
355            base_url,
356            source: err,
357        }
358    }
359}
360
361pub use inner::PolarsObjectStore;
362
363/// `GetResult::bytes` for a streamed body of `len` bytes (the returned range) that reports arrived
364/// bytes to the controller as they come in, per `ARRIVAL_FLUSH_BYTES`.
365async fn collect_body(
366    stream: futures::stream::BoxStream<'static, object_store::Result<bytes::Bytes>>,
367    len: u64,
368    controller: &ConcurrencyController,
369) -> object_store::Result<bytes::Bytes> {
370    const ARRIVAL_FLUSH_BYTES: u64 = 64 * 1024;
371
372    let mut pending = 0;
373    let out = object_store::collect_bytes(
374        stream.inspect_ok(|chunk| {
375            pending += chunk.len() as u64;
376            if pending >= ARRIVAL_FLUSH_BYTES {
377                controller.record_arrived(std::mem::take(&mut pending));
378            }
379        }),
380        Some(len),
381    )
382    .await;
383    controller.record_arrived(pending);
384    out
385}
386
387pub type ObjectStorePath = object_store::path::Path;
388
389impl PolarsObjectStore {
390    pub fn build_buffered_ranges_stream<'a, T: Iterator<Item = Range<usize>>>(
391        &'a self,
392        path: &'a Path,
393        ranges: T,
394        strategy: ConcurrencyStrategy,
395    ) -> impl Stream<Item = PolarsResult<Buffer<u8>>> + use<'a, T> {
396        let controller = match strategy {
397            ConcurrencyStrategy::BytesBased => Some(self.get_or_init_concurrency().clone()),
398            ConcurrencyStrategy::Unbounded | ConcurrencyStrategy::Legacy => None,
399        };
400
401        let n_buffered = match strategy {
402            // In case of bytes-based concurrency, the concurrency is controlled by the
403            // admission semaphore in the pipeline.
404            // The buffered size is set to a large constant as a backstop. Once all
405            // callsites are verified to pass finite, metadata-derived ranges, this can be
406            // set to usize::MAX.
407            ConcurrencyStrategy::BytesBased => 4096,
408            ConcurrencyStrategy::Unbounded | ConcurrencyStrategy::Legacy => {
409                get_concurrency_limit() as usize
410            },
411        };
412
413        futures::stream::iter(ranges.map(move |range| {
414            let controller = controller.clone();
415            async move {
416                if range.is_empty() {
417                    return Ok(Buffer::new());
418                }
419                let bytes_req = range.len() as u64;
420
421                // Held until end of block to bound in-flight bytes.
422                let _permit = match &controller {
423                    Some(controller) => Some(controller.acquire(bytes_req).await),
424                    None => None,
425                };
426                let t_start = Instant::now();
427
428                let controller_ref = controller.as_deref();
429                let (out, ttfb) = self
430                    .io_metrics()
431                    .record_io_read(
432                        bytes_req,
433                        self.exec_with_rebuild_retry_on_err(path, |s| async move {
434                            let t0 = Instant::now();
435                            let response = s
436                                .get_opts(
437                                    path,
438                                    object_store::GetOptions {
439                                        range: Some((range.start as u64..range.end as u64).into()),
440                                        ..Default::default()
441                                    },
442                                )
443                                .await?;
444                            let ttfb = t0.elapsed();
445                            let out = match controller_ref {
446                                Some(controller)
447                                    if matches!(
448                                        response.payload,
449                                        object_store::GetResultPayload::Stream(_)
450                                    ) =>
451                                {
452                                    let len = response.range.end - response.range.start;
453                                    collect_body(response.into_stream(), len, controller).await?
454                                },
455                                _ => {
456                                    let out = response.bytes().await?;
457                                    // Not streamed (local files): the bytes arrive at completion.
458                                    if let Some(controller) = controller_ref {
459                                        controller.record_arrived(out.len() as u64);
460                                    }
461                                    out
462                                },
463                            };
464
465                            Ok((out, ttfb))
466                        }),
467                    )
468                    .await?;
469
470                if let Some(controller) = &controller {
471                    let completion_time = Instant::now();
472                    controller.record_io(IoSample {
473                        n_bytes: out.len() as u64,
474                        ttfb,
475                        ttlb: completion_time - t_start,
476                        completion_time,
477                    });
478                }
479
480                Ok(Buffer::from_owner(out))
481            }
482        }))
483        .buffered(n_buffered)
484    }
485
486    pub async fn get_range(
487        &self,
488        path: &Path,
489        range: Range<usize>,
490        config: FetchConfig,
491    ) -> PolarsResult<Buffer<u8>> {
492        if range.is_empty() {
493            return Ok(Buffer::new());
494        }
495
496        let parts = split_range(range.clone(), Some(config.chunk_size));
497
498        match config.strategy {
499            ConcurrencyStrategy::Legacy => self.get_range_legacy(path, range).await,
500            ConcurrencyStrategy::Unbounded | ConcurrencyStrategy::BytesBased => self
501                .build_buffered_ranges_stream(path, parts, config.strategy)
502                .try_collect::<Vec<_>>()
503                .await
504                .map(|parts| {
505                    if parts.len() == 1 {
506                        return parts.into_iter().next().unwrap();
507                    }
508                    let mut combined = Vec::with_capacity(range.len());
509                    for part in parts {
510                        combined.extend_from_slice(&part);
511                    }
512                    assert_eq!(combined.len(), range.len());
513                    Buffer::from_vec(combined)
514                }),
515        }
516    }
517
518    async fn get_range_legacy(&self, path: &Path, range: Range<usize>) -> PolarsResult<Buffer<u8>> {
519        if range.is_empty() {
520            return Ok(Buffer::new());
521        }
522
523        let parts = split_range(range.clone(), None);
524
525        if parts.len() == 1 {
526            let out = tune_with_concurrency_budget(1, move || async move {
527                let bytes = self
528                    .io_metrics()
529                    .record_io_read(
530                        range.len() as u64,
531                        self.exec_with_rebuild_retry_on_err(path, |s| async move {
532                            s.get_range(path, range.start as u64..range.end as u64)
533                                .await
534                        }),
535                    )
536                    .await?;
537
538                PolarsResult::Ok(Buffer::from_owner(bytes))
539            })
540            .await?;
541
542            Ok(out)
543        } else {
544            let parts = tune_with_concurrency_budget(
545                parts.len().clamp(0, MAX_BUDGET_PER_REQUEST) as u32,
546                || {
547                    self.build_buffered_ranges_stream(path, parts, ConcurrencyStrategy::Legacy)
548                        .try_collect::<Vec<Buffer<u8>>>()
549                },
550            )
551            .await?;
552
553            let mut combined = Vec::with_capacity(range.len());
554
555            for part in parts {
556                combined.extend_from_slice(&part)
557            }
558
559            assert_eq!(combined.len(), range.len());
560
561            PolarsResult::Ok(Buffer::from_vec(combined))
562        }
563    }
564
565    pub async fn get_ranges_sort(
566        &self,
567        path: &Path,
568        ranges: &mut [Range<usize>],
569        config: FetchConfig,
570    ) -> PolarsResult<PlHashMap<usize, Buffer<u8>>> {
571        if ranges.is_empty() {
572            return Ok(Default::default());
573        }
574
575        ranges.sort_unstable_by_key(|x| x.start);
576
577        let ranges_len = ranges.len();
578        let (merged_ranges, merged_ends): (Vec<_>, Vec<_>) =
579            merge_ranges(ranges, Some(config.chunk_size)).unzip();
580
581        let mut out = PlHashMap::with_capacity(ranges_len);
582
583        // Build an inflight admission-aware stream over the merged ranges.
584        let mut stream =
585            self.build_buffered_ranges_stream(path, merged_ranges.iter().cloned(), config.strategy);
586
587        let mut current_offset = 0;
588        let mut ends_iter = merged_ends.iter();
589        let mut splitted_parts: Vec<Buffer<u8>> = vec![];
590
591        while let Some(bytes) = stream.try_next().await? {
592            let end = *ends_iter.next().unwrap();
593
594            if end == 0 {
595                splitted_parts.push(bytes);
596                continue;
597            }
598
599            let full_range = ranges[current_offset..end]
600                .iter()
601                .cloned()
602                .reduce(|l, r| l.start.min(r.start)..l.end.max(r.end))
603                .unwrap();
604
605            let bytes = if splitted_parts.is_empty() {
606                bytes
607            } else {
608                let mut out = Vec::with_capacity(full_range.len());
609                for x in splitted_parts.drain(..) {
610                    out.extend_from_slice(&x);
611                }
612                out.extend_from_slice(&bytes);
613                Buffer::from(out)
614            };
615
616            assert_eq!(bytes.len(), full_range.len());
617
618            for range in &ranges[current_offset..end] {
619                let slice = bytes
620                    .clone()
621                    .sliced(range.start - full_range.start..range.end - full_range.start);
622
623                match out.raw_entry_mut().from_key(&range.start) {
624                    RawEntryMut::Vacant(slot) => {
625                        slot.insert(range.start, slice);
626                    },
627                    RawEntryMut::Occupied(mut slot) => {
628                        if slot.get_mut().len() < slice.len() {
629                            *slot.get_mut() = slice;
630                        }
631                    },
632                }
633            }
634
635            current_offset = end;
636        }
637
638        assert!(splitted_parts.is_empty());
639
640        Ok(out)
641    }
642
643    // TODO: Refactor for updated concurrency strategy.
644    pub async fn download(&self, path: &Path, file: &mut tokio::fs::File) -> PolarsResult<()> {
645        let size = self.head(path, ConcurrencyStrategy::Unbounded).await?.size;
646        let parts = split_range(0..size as usize, None);
647
648        // TODO: Replace the legacy concurrency_budget call and switch to BytesBased inflight
649        // admission control.
650        tune_with_concurrency_budget(
651            parts.len().clamp(0, MAX_BUDGET_PER_REQUEST) as u32,
652            || async {
653                let mut stream =
654                    self.build_buffered_ranges_stream(path, parts, ConcurrencyStrategy::Unbounded);
655                let mut len = 0;
656                while let Some(bytes) = stream.try_next().await? {
657                    len += bytes.len();
658                    file.write_all(&bytes).await?;
659                }
660
661                assert_eq!(len, size as usize);
662
663                PolarsResult::Ok(pl_async::Size::from(len as u64))
664            },
665        )
666        .await?;
667
668        // Dropping is delayed for tokio async files so we need to explicitly
669        // flush here (https://github.com/tokio-rs/tokio/issues/2307#issuecomment-596336451).
670        file.sync_all().await.map_err(PolarsError::from)?;
671
672        Ok(())
673    }
674
675    /// Fetch the last `n` bytes of the object, and the total size of the object. Returns fewer
676    /// than `n` bytes if the object is smaller than `n`.
677    ///
678    /// A suffix range request (`Range: bytes=-n`) carries the object size in its `Content-Range`,
679    /// saving a HEAD. Backends rejecting them (e.g. Azure) fall back to HEAD + bounded range.
680    pub async fn get_suffix(
681        &self,
682        path: &Path,
683        n: usize,
684        config: FetchConfig,
685    ) -> PolarsResult<(Buffer<u8>, usize)> {
686        let mut suffix_rejected = false;
687
688        if n > 0 && self.suffix_range_supported() {
689            match self
690                .try_get_with_size(path, SizedRange::Suffix(n), config.strategy)
691                .await
692            {
693                Ok(v) => return Ok(v),
694                Err(e) if is_suffix_range_rejection(&e) => {
695                    suffix_rejected = true;
696
697                    if config::verbose() {
698                        eprintln!(
699                            "[PolarsObjectStore]: suffix range request rejected ({e}), \
700                            falling back to head + range request"
701                        );
702                    }
703                },
704                Err(e) => return Err(e),
705            }
706        }
707
708        let size = self.head(path, config.strategy).await?.size as usize;
709
710        // An empty object is rejected regardless of backend support, so it proves nothing.
711        if suffix_rejected && size > 0 {
712            self.disable_suffix_range();
713        }
714
715        let bytes = self
716            .get_range(path, size.saturating_sub(n)..size, config)
717            .await?;
718
719        Ok((bytes, size))
720    }
721
722    /// Fetch the first `n` bytes of the object, and the total size of the object. Returns fewer
723    /// than `n` bytes if the object is smaller than `n`.
724    ///
725    /// A bounded range request carries the object size in its `Content-Range`, saving a HEAD.
726    /// Empty objects and backends ignoring the range fall back to HEAD + bounded range.
727    pub async fn get_prefix(
728        &self,
729        path: &Path,
730        n: usize,
731        config: FetchConfig,
732    ) -> PolarsResult<(Buffer<u8>, usize)> {
733        if n > 0 {
734            match self
735                .try_get_with_size(path, SizedRange::Prefix(n), config.strategy)
736                .await
737            {
738                Err(e) if is_prefix_range_rejection(&e) => {},
739                out => return out,
740            }
741        }
742
743        let size = self.head(path, config.strategy).await?.size as usize;
744        let bytes = self.get_range(path, 0..n.min(size), config).await?;
745
746        Ok((bytes, size))
747    }
748
749    /// Range request that also returns the total object size.
750    async fn try_get_with_size(
751        &self,
752        path: &Path,
753        range: SizedRange,
754        strategy: ConcurrencyStrategy,
755    ) -> PolarsResult<(Buffer<u8>, usize)> {
756        match strategy {
757            ConcurrencyStrategy::BytesBased => {
758                let controller = self.get_or_init_concurrency();
759                let _permit = controller.acquire(range.len() as u64).await;
760                self.try_get_with_size_inner(path, range, Some(&**controller))
761                    .await
762            },
763            ConcurrencyStrategy::Legacy => {
764                with_concurrency_budget(1, || self.try_get_with_size_inner(path, range, None)).await
765            },
766            ConcurrencyStrategy::Unbounded => self.try_get_with_size_inner(path, range, None).await,
767        }
768    }
769
770    async fn try_get_with_size_inner(
771        &self,
772        path: &Path,
773        range: SizedRange,
774        controller: Option<&ConcurrencyController>,
775    ) -> PolarsResult<(Buffer<u8>, usize)> {
776        let metrics = self.io_metrics();
777
778        // A prefix range is clamped to the object size, so it is accounted for once the response
779        // carries the size, once across retries.
780        if let SizedRange::Suffix(n) = range {
781            metrics.add_bytes_requested(n as u64);
782        }
783        let prefix_requested_recorded = &std::sync::atomic::AtomicBool::new(false);
784
785        let io_session = metrics.start_rx_session();
786
787        let t_start = Instant::now();
788        let out = self
789            .exec_with_rebuild_retry_on_err(path, |s| async move {
790                let t0 = Instant::now();
791                let response = s
792                    .get_opts(
793                        path,
794                        object_store::GetOptions {
795                            range: Some(range.into()),
796                            ..Default::default()
797                        },
798                    )
799                    .await?;
800                let ttfb = t0.elapsed();
801                // `get_opts()` rewrites this from `Content-Range`: the full object size.
802                let size = response.meta.size as usize;
803
804                if let SizedRange::Prefix(n) = range
805                    && !prefix_requested_recorded.swap(true, std::sync::atomic::Ordering::Relaxed)
806                {
807                    metrics.add_bytes_requested(n.min(size) as u64);
808                }
809
810                let bytes = response.bytes().await?;
811
812                if let Some(controller) = controller {
813                    controller.record_arrived(bytes.len() as u64);
814                    let completion_time = Instant::now();
815                    controller.record_io(IoSample {
816                        n_bytes: bytes.len() as u64,
817                        ttfb,
818                        ttlb: completion_time - t_start,
819                        completion_time,
820                    });
821                }
822
823                Ok((Buffer::from_owner(bytes), size))
824            })
825            .await;
826
827        drop(io_session);
828
829        let (bytes, size) = out?;
830
831        // The response is short when the object is smaller than the range.
832        metrics.add_bytes_received(bytes.len() as u64);
833
834        Ok((bytes, size))
835    }
836
837    /// Fetch the object metadata with a HEAD request, do not memoize it.
838    pub async fn head(
839        &self,
840        path: &Path,
841        strategy: ConcurrencyStrategy,
842    ) -> PolarsResult<ObjectMeta> {
843        match strategy {
844            ConcurrencyStrategy::BytesBased => {
845                let controller = self.get_or_init_concurrency();
846                let _permit = controller.acquire(0).await;
847                self.head_inner(path, Some(&**controller)).await
848            },
849            ConcurrencyStrategy::Legacy => {
850                with_concurrency_budget(1, || self.head_inner(path, None)).await
851            },
852            ConcurrencyStrategy::Unbounded => self.head_inner(path, None).await,
853        }
854    }
855
856    async fn head_inner(
857        &self,
858        path: &Path,
859        controller: Option<&ConcurrencyController>,
860    ) -> PolarsResult<ObjectMeta> {
861        self.exec_with_rebuild_retry_on_err(path, |s| {
862            async move {
863                let t0 = Instant::now();
864                let head_result = self.io_metrics().record_io_read(0, s.head(path)).await;
865
866                if head_result.is_err() {
867                    let t0 = Instant::now();
868
869                    // Pre-signed URLs forbid the HEAD method, but we can still retrieve the header
870                    // information with a range 0-1 request.
871                    let get_range_0_1_result = self
872                        .io_metrics()
873                        .record_io_read(
874                            0,
875                            s.get_opts(
876                                path,
877                                object_store::GetOptions {
878                                    range: Some((0..1).into()),
879                                    ..Default::default()
880                                },
881                            ),
882                        )
883                        .await;
884
885                    if let Ok(v) = get_range_0_1_result {
886                        if let Some(controller) = controller {
887                            controller.record_head_rtt(t0.elapsed());
888                        }
889                        return Ok(v.meta);
890                    }
891                }
892
893                let out = head_result?;
894
895                if let Some(controller) = controller {
896                    controller.record_head_rtt(t0.elapsed());
897                }
898
899                Ok(out)
900            }
901        })
902        .await
903    }
904}
905
906/// Whether the error is about the suffix range rather than the object. Azure rejects them
907/// client-side, backends ignoring the header answer 200 instead of 206, strict ones answer 416.
908fn is_suffix_range_rejection(err: &PolarsError) -> bool {
909    let msg = err.to_string();
910
911    msg.contains("does not support suffix range requests")
912        || msg.contains("Received non-partial response")
913        || msg.contains("416 Range Not Satisfiable")
914}
915
916/// Range request forms whose response carries the total object size in its `Content-Range`.
917#[derive(Clone, Copy, Debug)]
918enum SizedRange {
919    /// The first `n` bytes.
920    Prefix(usize),
921    /// The last `n` bytes.
922    Suffix(usize),
923}
924
925impl SizedRange {
926    /// Number of bytes requested.
927    fn len(self) -> usize {
928        match self {
929            Self::Prefix(n) | Self::Suffix(n) => n,
930        }
931    }
932}
933
934impl From<SizedRange> for object_store::GetRange {
935    fn from(value: SizedRange) -> Self {
936        match value {
937            SizedRange::Prefix(n) => Self::Bounded(0..n as u64),
938            SizedRange::Suffix(n) => Self::Suffix(n as u64),
939        }
940    }
941}
942
943/// Whether a prefix range request was rejected rather than the object. Empty objects have
944/// no satisfiable range: the backend answers 416, or `object_store` rejects the range against the
945/// size. Backends ignoring the range answer 200 instead of 206, the HEAD fallback then decides
946/// (e.g. an empty object needs no further request).
947///
948/// The rejection can be nested in the source chain, e.g. for the local file system store.
949fn is_prefix_range_rejection(err: &PolarsError) -> bool {
950    std::iter::successors(Some(err as &dyn std::error::Error), |e| e.source()).any(|e| {
951        let msg = e.to_string();
952
953        msg.contains("416 Range Not Satisfiable")
954            || msg.contains("Wanted range starting at")
955            || msg.contains("Received non-partial response")
956            // `object_store` HTTP store.
957            || msg.contains("Range request not supported")
958    })
959}
960
961/// Splits a single range into multiple smaller ranges, which can be downloaded concurrently for
962/// much higher throughput.
963fn split_range(
964    range: Range<usize>,
965    chunk_size: Option<usize>,
966) -> impl ExactSizeIterator<Item = Range<usize>> {
967    let chunk_size = chunk_size.unwrap_or_else(get_download_chunk_size);
968
969    // Calculate n_parts such that we are as close as possible to the `chunk_size`.
970    let n_parts = [
971        (range.len().div_ceil(chunk_size)).max(1),
972        (range.len() / chunk_size).max(1),
973    ]
974    .into_iter()
975    .min_by_key(|x| (range.len() / *x).abs_diff(chunk_size))
976    .unwrap();
977
978    let chunk_size = (range.len() / n_parts).max(1);
979
980    assert_eq!(n_parts, (range.len() / chunk_size).max(1));
981    let bytes_rem = range.len() % chunk_size;
982
983    (0..n_parts).map(move |part_no| {
984        let (start, end) = if part_no == 0 {
985            // Download remainder length in the first chunk since it starts downloading first.
986            let end = range.start + chunk_size + bytes_rem;
987            let end = if end > range.end { range.end } else { end };
988            (range.start, end)
989        } else {
990            let start = bytes_rem + range.start + part_no * chunk_size;
991            (start, start + chunk_size)
992        };
993
994        start..end
995    })
996}
997
998/// Note: For optimal performance, `ranges` should be sorted. More generally,
999/// ranges placed next to each other should also be close in range value.
1000///
1001/// # Returns
1002/// `[(range1, end1), (range2, end2)]`, where:
1003/// * `range1` contains bytes for the ranges from `ranges[0..end1]`
1004/// * `range2` contains bytes for the ranges from `ranges[end1..end2]`
1005/// * etc..
1006///
1007/// Note that if an end value is 0, it means the range is a splitted part and should be combined.
1008fn merge_ranges(
1009    ranges: &[Range<usize>],
1010    chunk_size: Option<usize>,
1011) -> impl Iterator<Item = (Range<usize>, usize)> + '_ {
1012    let chunk_size = chunk_size.unwrap_or_else(get_download_chunk_size);
1013
1014    let mut current_merged_range = ranges.first().map_or(0..0, Clone::clone);
1015    // Number of fetched bytes excluding excess.
1016    let mut current_n_bytes = current_merged_range.len();
1017
1018    (0..ranges.len())
1019        .filter_map(move |current_idx| {
1020            let current_idx = 1 + current_idx;
1021
1022            if current_idx == ranges.len() {
1023                // No more items - flush current state.
1024                Some((current_merged_range.clone(), current_idx))
1025            } else {
1026                let range = ranges[current_idx].clone();
1027
1028                let new_merged = current_merged_range.start.min(range.start)
1029                    ..current_merged_range.end.max(range.end);
1030
1031                // E.g.:
1032                // |--------|
1033                //  oo        // range1
1034                //       oo   // range2
1035                //    ^^^     // distance = 3, is_overlapping = false
1036                // E.g.:
1037                // |--------|
1038                //  ooooo     // range1
1039                //     ooooo  // range2
1040                //     ^^     // distance = 2, is_overlapping = true
1041                let (distance, is_overlapping) = {
1042                    let l = current_merged_range.end.min(range.end);
1043                    let r = current_merged_range.start.max(range.start);
1044
1045                    (r.abs_diff(l), r < l)
1046                };
1047
1048                let should_merge = is_overlapping || {
1049                    let leq_current_len_dist_to_chunk_size = new_merged.len().abs_diff(chunk_size)
1050                        <= current_merged_range.len().abs_diff(chunk_size);
1051                    let gap_tolerance =
1052                        (current_n_bytes.max(range.len()) / 8).clamp(1024 * 1024, 8 * 1024 * 1024);
1053
1054                    leq_current_len_dist_to_chunk_size && distance <= gap_tolerance
1055                };
1056
1057                if should_merge {
1058                    // Merge to existing range
1059                    current_merged_range = new_merged;
1060                    current_n_bytes += if is_overlapping {
1061                        range.len() - distance
1062                    } else {
1063                        range.len()
1064                    };
1065                    None
1066                } else {
1067                    let out = (current_merged_range.clone(), current_idx);
1068                    current_merged_range = range;
1069                    current_n_bytes = current_merged_range.len();
1070                    Some(out)
1071                }
1072            }
1073        })
1074        .flat_map(move |x| {
1075            // Split large individual ranges within the list of ranges.
1076            let (range, end) = x;
1077            let split = split_range(range, Some(chunk_size));
1078            let len = split.len();
1079
1080            split
1081                .enumerate()
1082                .map(move |(i, range)| (range, if 1 + i == len { end } else { 0 }))
1083        })
1084}
1085
1086#[cfg(test)]
1087mod tests {
1088
1089    #[test]
1090    fn test_split_range() {
1091        use super::{get_download_chunk_size, split_range};
1092
1093        let chunk_size = get_download_chunk_size();
1094
1095        assert_eq!(chunk_size, 64 * 1024 * 1024);
1096
1097        #[allow(clippy::single_range_in_vec_init)]
1098        {
1099            // Round-trip empty ranges.
1100            assert_eq!(split_range(0..0, None).collect::<Vec<_>>(), [0..0]);
1101            assert_eq!(split_range(3..3, None).collect::<Vec<_>>(), [3..3]);
1102        }
1103
1104        // Threshold to start splitting to 2 ranges
1105        //
1106        // n - chunk_size == chunk_size - n / 2
1107        // n + n / 2 == 2 * chunk_size
1108        // 3 * n == 4 * chunk_size
1109        // n = 4 * chunk_size / 3
1110        let n = 4 * chunk_size / 3;
1111
1112        #[allow(clippy::single_range_in_vec_init)]
1113        {
1114            assert_eq!(split_range(0..n, None).collect::<Vec<_>>(), [0..89478485]);
1115        }
1116
1117        assert_eq!(
1118            split_range(0..n + 1, None).collect::<Vec<_>>(),
1119            [0..44739243, 44739243..89478486]
1120        );
1121
1122        // Threshold to start splitting to 3 ranges
1123        //
1124        // n / 2 - chunk_size == chunk_size - n / 3
1125        // n / 2 + n / 3 == 2 * chunk_size
1126        // 5 * n == 12 * chunk_size
1127        // n == 12 * chunk_size / 5
1128        let n = 12 * chunk_size / 5;
1129
1130        assert_eq!(
1131            split_range(0..n, None).collect::<Vec<_>>(),
1132            [0..80530637, 80530637..161061273]
1133        );
1134
1135        assert_eq!(
1136            split_range(0..n + 1, None).collect::<Vec<_>>(),
1137            [0..53687092, 53687092..107374183, 107374183..161061274]
1138        );
1139    }
1140
1141    #[test]
1142    fn test_merge_ranges() {
1143        use super::{get_download_chunk_size, merge_ranges};
1144
1145        let chunk_size = get_download_chunk_size();
1146
1147        assert_eq!(chunk_size, 64 * 1024 * 1024);
1148
1149        // Round-trip empty slice
1150        assert_eq!(merge_ranges(&[], None).collect::<Vec<_>>(), []);
1151
1152        // We have 1 tiny request followed by 1 huge request. They are combined as it reduces the
1153        // `abs_diff()` to the `chunk_size`, but afterwards they are split to 2 evenly sized
1154        // requests.
1155        assert_eq!(
1156            merge_ranges(&[0..1, 1..127 * 1024 * 1024], None).collect::<Vec<_>>(),
1157            [(0..66584576, 0), (66584576..133169152, 2)]
1158        );
1159
1160        // <= 1MiB gap, merge
1161        assert_eq!(
1162            merge_ranges(&[0..1, 1024 * 1024 + 1..1024 * 1024 + 2], None).collect::<Vec<_>>(),
1163            [(0..1048578, 2)]
1164        );
1165
1166        // > 1MiB gap, do not merge
1167        assert_eq!(
1168            merge_ranges(&[0..1, 1024 * 1024 + 2..1024 * 1024 + 3], None).collect::<Vec<_>>(),
1169            [(0..1, 1), (1048578..1048579, 2)]
1170        );
1171
1172        // <= 12.5% gap, merge
1173        assert_eq!(
1174            merge_ranges(&[0..8, 10..11], None).collect::<Vec<_>>(),
1175            [(0..11, 2)]
1176        );
1177
1178        // <= 12.5% gap relative to RHS, merge
1179        assert_eq!(
1180            merge_ranges(&[0..1, 3..11], None).collect::<Vec<_>>(),
1181            [(0..11, 2)]
1182        );
1183
1184        // Overlapping range, merge
1185        assert_eq!(
1186            merge_ranges(
1187                &[0..80 * 1024 * 1024, 10 * 1024 * 1024..70 * 1024 * 1024],
1188                None
1189            )
1190            .collect::<Vec<_>>(),
1191            [(0..80 * 1024 * 1024, 2)]
1192        );
1193    }
1194}