1use std::ops::Range;
2#[cfg(target_os = "linux")]
3use std::os::fd::AsRawFd;
4use std::path::Path;
5use std::sync::{Arc, LazyLock};
6
7use dio_align::DioAlign;
8use futures::{StreamExt, TryStreamExt};
9use polars_buffer::Buffer;
10use polars_config::FileAdvice;
11use polars_core::prelude::PlHashMap;
12use polars_core::runtime::ASYNC;
13use polars_error::{PolarsResult, feature_gated, polars_bail, polars_err};
14use polars_utils::aliases::InitHashMaps;
15use polars_utils::io::_limit_path_len_io_err;
16use polars_utils::mmap::MMapSemaphore;
17use polars_utils::pl_path::PlRefPath;
18use tokio::sync::Semaphore;
19
20#[cfg(feature = "cloud")]
21use crate::cloud::concurrency_config::PipelineWindow;
22use crate::cloud::concurrency_config::{ConcurrencyStrategy, FetchConfig};
23use crate::cloud::options::CloudOptions;
24#[cfg(feature = "cloud")]
25use crate::cloud::{
26 CloudLocation, ObjectStorePath, PolarsObjectStore, build_object_store, object_path_from_str,
27};
28use crate::metrics::{IOMetrics, OptIOMetrics};
29
30pub mod dio_align;
31#[cfg(target_os = "linux")]
32mod direct_io;
33#[allow(async_fn_in_trait)]
34pub trait ByteSource: Send + Sync {
35 async fn get_size(&self) -> PolarsResult<usize>;
36 async fn get_suffix(&self, n: usize) -> PolarsResult<(Buffer<u8>, usize)>;
39 async fn get_prefix(&self, n: usize) -> PolarsResult<(Buffer<u8>, usize)>;
42 async fn get_range(&self, range: Range<usize>) -> PolarsResult<Buffer<u8>>;
45 async fn get_ranges(
47 &self,
48 ranges: &mut [Range<usize>],
49 ) -> PolarsResult<PlHashMap<usize, Buffer<u8>>>;
50}
51
52pub struct BufferByteSource(pub Buffer<u8>);
54
55impl BufferByteSource {
56 async fn try_new_mmap_from_path(
57 path: &Path,
58 _cloud_options: Option<&CloudOptions>,
59 ) -> PolarsResult<Self> {
60 let file = Arc::new(
61 tokio::fs::File::open(path)
62 .await
63 .map_err(|err| _limit_path_len_io_err(path, err))?
64 .into_std()
65 .await,
66 );
67
68 Ok(Self(Buffer::from_owner(MMapSemaphore::new_from_file(
69 &file,
70 )?)))
71 }
72}
73
74impl ByteSource for BufferByteSource {
75 async fn get_size(&self) -> PolarsResult<usize> {
76 Ok(self.0.as_ref().len())
77 }
78
79 async fn get_suffix(&self, n: usize) -> PolarsResult<(Buffer<u8>, usize)> {
80 let len = self.0.as_ref().len();
81 Ok((self.0.clone().sliced(len.saturating_sub(n)..len), len))
82 }
83
84 async fn get_prefix(&self, n: usize) -> PolarsResult<(Buffer<u8>, usize)> {
85 let len = self.0.as_ref().len();
86 Ok((self.0.clone().sliced(0..n.min(len)), len))
87 }
88
89 async fn get_range(&self, range: Range<usize>) -> PolarsResult<Buffer<u8>> {
90 let out = self.0.clone().sliced(range);
91 Ok(out)
92 }
93
94 async fn get_ranges(
95 &self,
96 ranges: &mut [Range<usize>],
97 ) -> PolarsResult<PlHashMap<usize, Buffer<u8>>> {
98 Ok(ranges
99 .iter()
100 .map(|x| (x.start, self.0.clone().sliced(x.clone())))
101 .collect())
102 }
103}
104
105pub struct FileByteSource {
107 file: Arc<std::fs::File>,
108 o_direct_align: Option<DioAlign>,
110 concurrency: usize,
112 permits: Arc<Semaphore>,
113 size: u64,
115 io_metrics: OptIOMetrics,
116}
117
118pub fn global_read_permits() -> Arc<Semaphore> {
120 static PERMITS: LazyLock<Arc<Semaphore>> = LazyLock::new(|| {
121 Arc::new(Semaphore::new(
122 polars_config::config().file_read_concurrency().max(1) as usize,
123 ))
124 });
125
126 PERMITS.clone()
127}
128
129#[derive(Clone)]
130pub struct FileReadContext {
131 pub enable_o_direct: bool,
132 pub concurrency: usize,
133 pub permits: Arc<Semaphore>,
134 pub advice: FileAdvice,
136}
137
138impl FileReadContext {
139 pub fn from_config(name: &str) -> Self {
140 let cfg = polars_config::config();
141 let enable_o_direct = cfg.direct_io();
142 let concurrency = cfg.file_read_concurrency().max(1) as usize;
143
144 let fadv = cfg.file_posix_fadv();
147
148 if cfg.verbose() {
149 eprintln!(
150 "[{name}]: file read_context as configured: \
151 read_concurrency: {concurrency}, \
152 posix_fadv: {fadv}, \
153 o_direct: {enable_o_direct}"
154 );
155 }
156
157 Self {
158 enable_o_direct,
159 concurrency,
160 permits: global_read_permits(),
161 advice: fadv,
162 }
163 }
164}
165
166impl std::fmt::Debug for FileReadContext {
167 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
168 f.debug_struct("FileReadContext")
169 .field("available_permits", &self.permits.available_permits())
170 .field("enable_odirect", &self.enable_o_direct)
171 .field("concurrency", &self.concurrency)
172 .field("advice", &self.advice)
173 .finish()
174 }
175}
176
177#[cfg(target_os = "linux")]
178fn _fadvise(file: &std::fs::File, advice: FileAdvice) {
179 let advice = match advice {
180 FileAdvice::Normal => return,
182 FileAdvice::Sequential => libc::POSIX_FADV_SEQUENTIAL,
183 FileAdvice::Random => libc::POSIX_FADV_RANDOM,
184 FileAdvice::WillNeed => libc::POSIX_FADV_WILLNEED,
185 };
186
187 unsafe {
188 libc::posix_fadvise(file.as_raw_fd(), 0, 0, advice);
189 }
190}
191
192#[cfg(all(unix, not(feature = "nightly")))]
193fn pread_exact(file: &std::fs::File, buf: &mut [u8], offset: u64) -> std::io::Result<()> {
194 use std::os::unix::fs::FileExt;
195 file.read_exact_at(buf, offset)
196}
197
198#[cfg(all(windows, not(feature = "nightly")))]
199fn pread_exact(file: &std::fs::File, buf: &mut [u8], offset: u64) -> std::io::Result<()> {
200 use std::os::windows::fs::FileExt;
201 let mut filled = 0;
202 while filled < buf.len() {
203 match file.seek_read(&mut buf[filled..], offset + filled as u64)? {
204 0 => return Err(std::io::ErrorKind::UnexpectedEof.into()),
205 n => filled += n,
206 }
207 }
208 Ok(())
209}
210
211#[cfg(all(feature = "nightly", unix))]
214fn pread_exact_uninit(
215 file: &std::fs::File,
216 buf: std::io::BorrowedCursor<'_, u8>,
217 offset: u64,
218) -> std::io::Result<()> {
219 use std::os::unix::fs::FileExt;
220 file.read_buf_exact_at(buf, offset)
221}
222
223#[cfg(all(feature = "nightly", windows))]
224fn pread_exact_uninit(
225 file: &std::fs::File,
226 mut buf: std::io::BorrowedCursor<'_, u8>,
227 mut offset: u64,
228) -> std::io::Result<()> {
229 use std::os::windows::fs::FileExt;
230 while buf.capacity() > 0 {
232 let written = buf.written();
233 file.seek_read_buf(buf.reborrow(), offset)?;
234 match buf.written() - written {
235 0 => return Err(std::io::ErrorKind::UnexpectedEof.into()),
236 n => offset += n as u64,
237 }
238 }
239 Ok(())
240}
241
242#[cfg(feature = "nightly")]
248fn read_buffered(file: &std::fs::File, offset: u64, len: usize) -> PolarsResult<Buffer<u8>> {
249 let mut v: Vec<u8> = Vec::with_capacity(len);
250
251 let filled = {
252 let mut buf = std::io::BorrowedBuf::from(&mut v.spare_capacity_mut()[..len]);
253 pread_exact_uninit(file, buf.unfilled(), offset)?;
254 buf.len()
255 };
256
257 debug_assert_eq!(filled, len);
258 unsafe { v.set_len(filled) };
261
262 Ok(Buffer::from(v))
263}
264
265#[cfg(not(feature = "nightly"))]
266fn read_buffered(file: &std::fs::File, offset: u64, len: usize) -> PolarsResult<Buffer<u8>> {
267 let mut buf = vec![0u8; len];
268 pread_exact(file, &mut buf, offset)?;
269 Ok(Buffer::from(buf))
270}
271
272#[cfg(target_os = "linux")]
275fn read_at(
276 file: &std::fs::File,
277 align: Option<DioAlign>,
278 offset: u64,
279 len: usize,
280 size: u64,
281) -> PolarsResult<Buffer<u8>> {
282 match align {
283 Some(align) => direct_io::read_aligned(file, align, offset, len, size),
284 None => read_buffered(file, offset, len),
285 }
286}
287
288#[cfg(not(target_os = "linux"))]
289fn read_at(
290 file: &std::fs::File,
291 _align: Option<DioAlign>,
292 offset: u64,
293 len: usize,
294 _size: u64,
295) -> PolarsResult<Buffer<u8>> {
296 read_buffered(file, offset, len)
297}
298
299impl FileByteSource {
300 async fn try_new_from_path(
301 path: PlRefPath,
302 read_context: FileReadContext,
303 io_metrics: Option<Arc<IOMetrics>>,
304 ) -> PolarsResult<Self> {
305 ASYNC
307 .spawn_blocking(move || Self::open_blocking(path, read_context, io_metrics))
308 .await
309 .expect("blocking task panicked")
310 }
311
312 fn open_blocking(
313 path: PlRefPath,
314 read_context: FileReadContext,
315 io_metrics: Option<Arc<IOMetrics>>,
316 ) -> PolarsResult<Self> {
317 let path = path.as_std_path();
318 let enable_o_direct = read_context.enable_o_direct;
319
320 let file = {
321 #[cfg(target_os = "linux")]
322 let f = if enable_o_direct {
323 direct_io::open_o_direct(path).or_else(|e| match e.raw_os_error() {
324 Some(libc::EINVAL) => std::fs::File::open(path),
326 _ => Err(e),
327 })
328 } else {
329 std::fs::File::open(path)
330 };
331 #[cfg(not(target_os = "linux"))]
332 let f = std::fs::File::open(path);
333
334 f.map_err(|e| _limit_path_len_io_err(path, e))?
335 };
336
337 let file = Arc::new(file);
338
339 #[cfg(target_os = "linux")]
340 let o_direct_align =
341 direct_io::probe_or_disable(&file).map_err(|e| _limit_path_len_io_err(path, e))?;
342
343 #[cfg(not(target_os = "linux"))]
344 let o_direct_align: Option<DioAlign> = None;
345
346 #[cfg(target_os = "linux")]
347 if o_direct_align.is_none() {
348 _fadvise(&file, read_context.advice);
350 }
351
352 let concurrency = read_context.concurrency;
353 let permits = read_context.permits;
354
355 let size = file
356 .metadata()
357 .map_err(|e| _limit_path_len_io_err(path, e))?
358 .len();
359
360 if polars_config::config().verbose() {
361 let name = if polars_config::config().verbose_sensitive() {
362 path.display().to_string()
363 } else {
364 "<file>".to_string()
365 };
366 match (enable_o_direct, o_direct_align) {
367 (true, Some(a)) => eprintln!(
368 "[FileByteSource]: {name}: direct IO active, \
369 alignment offset: {}, memory: {}",
370 a.offset, a.memory
371 ),
372 (true, None) => eprintln!(
373 "[FileByteSource]: {name}: direct IO requested but not active, \
374 using buffered reads"
375 ),
376 (false, _) => {},
377 }
378 }
379
380 Ok(FileByteSource {
381 file,
382 o_direct_align,
383 concurrency,
384 permits,
385 size,
386 io_metrics: OptIOMetrics(io_metrics),
387 })
388 }
389
390 pub fn try_new_from_std(
391 file: std::fs::File,
392 read_context: FileReadContext,
393 io_metrics: Option<Arc<IOMetrics>>,
394 ) -> PolarsResult<Self> {
395 let size = file.metadata()?.len();
396
397 #[cfg(target_os = "linux")]
398 let o_direct_align = direct_io::probe_or_disable(&file)?;
399
400 #[cfg(not(target_os = "linux"))]
401 let o_direct_align: Option<DioAlign> = None;
402
403 #[cfg(target_os = "linux")]
404 if o_direct_align.is_none() {
405 _fadvise(&file, read_context.advice);
406 }
407
408 let concurrency = read_context.concurrency;
409 let permits = read_context.permits;
410
411 let enable_o_direct = read_context.enable_o_direct;
413
414 if polars_config::config().verbose() {
415 match (enable_o_direct, o_direct_align) {
416 (true, Some(a)) => eprintln!(
417 "[FileByteSource]: direct IO active, alignment offset: {}, memory: {}",
418 a.offset, a.memory
419 ),
420 (true, None) => eprintln!(
421 "[FileByteSource]: direct IO requested but not active, using buffered reads",
422 ),
423 (false, _) => {},
424 }
425 }
426
427 Ok(Self {
428 file: Arc::new(file),
429 o_direct_align,
430 concurrency,
431 permits,
432 size,
433 io_metrics: OptIOMetrics(io_metrics),
434 })
435 }
436
437 pub fn set_io_metrics(&mut self, io_metrics: Option<Arc<IOMetrics>>) -> &mut Self {
438 self.io_metrics = OptIOMetrics(io_metrics);
439 self
440 }
441
442 pub fn io_metrics(&self) -> &OptIOMetrics {
443 &self.io_metrics
444 }
445
446 pub fn is_cached(&self, ranges: &[Range<usize>]) -> bool {
449 #[cfg(all(
450 target_os = "linux",
451 any(target_arch = "x86_64", target_arch = "aarch64")
452 ))]
453 if self.o_direct_align.is_none() {
454 return cachestat::all_cached(&self.file, ranges);
455 }
456
457 let _ = ranges;
458 false
459 }
460
461 pub fn read_blocking(&self, range: Range<usize>) -> PolarsResult<Buffer<u8>> {
463 assert!(range.end as u64 <= self.size);
464
465 self.io_metrics()
466 .record_io_read_blocking(range.len() as u64, || {
467 read_at(
468 &self.file,
469 self.o_direct_align,
470 range.start as u64,
471 range.len(),
472 self.size,
473 )
474 })
475 }
476}
477
478#[cfg(all(
480 target_os = "linux",
481 any(target_arch = "x86_64", target_arch = "aarch64")
482))]
483mod cachestat {
484 use std::ops::Range;
485 use std::os::fd::AsRawFd;
486 use std::sync::atomic::{AtomicBool, Ordering};
487
488 use polars_utils::mem::PAGE_SIZE;
489
490 #[repr(C)]
491 struct CachestatRange {
492 off: u64,
493 len: u64,
494 }
495
496 #[repr(C)]
497 #[derive(Default)]
498 struct Cachestat {
499 nr_cache: u64,
500 nr_dirty: u64,
501 nr_writeback: u64,
502 nr_evicted: u64,
503 nr_recently_evicted: u64,
504 }
505
506 const SYS_CACHESTAT: libc::c_long = 451;
508
509 static UNSUPPORTED: AtomicBool = AtomicBool::new(false);
511
512 pub(super) fn all_cached(file: &std::fs::File, ranges: &[Range<usize>]) -> bool {
514 if UNSUPPORTED.load(Ordering::Relaxed) {
515 return false;
516 }
517
518 let mut spans: Vec<Range<usize>> =
521 ranges.iter().filter(|r| !r.is_empty()).cloned().collect();
522 spans.sort_unstable_by_key(|r| r.start);
523 spans.dedup_by(|next, cur| {
524 let merge = next.start <= cur.end;
525 if merge {
526 cur.end = cur.end.max(next.end);
527 }
528 merge
529 });
530
531 let page = *PAGE_SIZE;
532 for r in &spans {
533 let mut range = CachestatRange {
534 off: r.start as u64,
535 len: r.len() as u64,
536 };
537 let mut cs = Cachestat::default();
538 let ret = unsafe {
540 libc::syscall(
541 SYS_CACHESTAT,
542 file.as_raw_fd() as libc::c_long,
543 &mut range as *mut CachestatRange,
544 &mut cs as *mut Cachestat,
545 0 as libc::c_long,
546 )
547 };
548 if ret != 0 {
549 if let Some(libc::ENOSYS | libc::EPERM) =
552 std::io::Error::last_os_error().raw_os_error()
553 {
554 UNSUPPORTED.store(true, Ordering::Relaxed);
555 }
556 return false;
557 }
558 let pages = (r.end - 1) / page - r.start / page + 1;
560 if cs.nr_cache < pages as u64 {
561 return false;
562 }
563 }
564 true
565 }
566}
567
568impl ByteSource for FileByteSource {
569 async fn get_size(&self) -> PolarsResult<usize> {
570 usize::try_from(self.size)
571 .map_err(|_| polars_err!(ComputeError: "file size {} does not fit in usize", self.size))
572 }
573
574 async fn get_suffix(&self, n: usize) -> PolarsResult<(Buffer<u8>, usize)> {
575 let size = self.get_size().await?;
576 let bytes = self.get_range(size.saturating_sub(n)..size).await?;
577 Ok((bytes, size))
578 }
579
580 async fn get_prefix(&self, n: usize) -> PolarsResult<(Buffer<u8>, usize)> {
581 let size = self.get_size().await?;
582 let bytes = self.get_range(0..n.min(size)).await?;
583 Ok((bytes, size))
584 }
585
586 async fn get_range(&self, range: Range<usize>) -> PolarsResult<Buffer<u8>> {
587 assert!(range.end as u64 <= self.size);
588
589 let file = self.file.clone();
590 let offset = range.start as u64;
591 let len = range.len();
592 let size = self.size;
593 let o_direct = self.o_direct_align;
594
595 let permit = self.permits.clone().acquire_owned().await.unwrap();
596
597 self.io_metrics()
598 .record_io_read(len as u64, async move {
599 ASYNC
600 .spawn_blocking(move || {
601 let _permit = permit;
602 read_at(&file, o_direct, offset, len, size)
603 })
604 .await
605 })
606 .await
607 .expect("blocking task panicked")
608 }
609
610 async fn get_ranges(
611 &self,
612 ranges: &mut [Range<usize>],
613 ) -> PolarsResult<PlHashMap<usize, Buffer<u8>>> {
614 if let [range] = ranges {
615 let mut out = PlHashMap::with_capacity(1);
616 out.insert(range.start, self.get_range(range.clone()).await?);
617 return Ok(out);
618 }
619
620 ranges.sort_unstable_by_key(|r| r.start);
621
622 let mut spans: Vec<Range<usize>> = Vec::with_capacity(ranges.len());
623
624 const MAX_SPAN: usize = 8 << 20;
626 const MAX_GAP: usize = 4096;
628
629 for r in ranges.iter() {
630 match spans.last_mut() {
631 Some(last)
632 if r.start.saturating_sub(last.end) <= MAX_GAP
633 && r.end.saturating_sub(last.start) <= MAX_SPAN =>
634 {
635 last.end = last.end.max(r.end)
636 },
637 _ => spans.push(r.clone()),
638 }
639 }
640
641 let mut fetched: Vec<(Range<usize>, Buffer<u8>)> = futures::stream::iter(spans)
642 .map(|span| async move {
643 let buf = self.get_range(span.clone()).await?;
644 PolarsResult::Ok((span, buf))
645 })
646 .buffer_unordered(self.concurrency)
647 .try_collect()
648 .await?;
649
650 fetched.sort_unstable_by_key(|(s, _)| s.start);
652
653 if let Some(w) = ranges.windows(2).find(|w| w[0].start == w[1].start) {
654 polars_bail!(
655 ComputeError:
656 "duplicate range start {} in read request ({:?} and {:?})",
657 w[0].start, w[0], w[1]
658 );
659 }
660
661 let mut out = PlHashMap::with_capacity(ranges.len());
662 for r in ranges.iter() {
663 if r.is_empty() {
665 out.insert(r.start, Buffer::new());
666 continue;
667 }
668
669 let idx = fetched.partition_point(|(s, _)| s.start <= r.start);
672 let (span, buf) = &fetched[idx - 1];
673 debug_assert!(span.start <= r.start && r.end <= span.end);
674
675 let off = r.start - span.start;
676 out.insert(r.start, buf.clone().sliced(off..off + r.len()));
677 }
678
679 debug_assert_eq!(out.len(), ranges.len());
680 Ok(out)
681 }
682}
683
684#[cfg(feature = "cloud")]
685#[derive(Clone)]
686pub struct ObjectStoreByteSource {
687 store: PolarsObjectStore,
688 path: ObjectStorePath,
689 config: FetchConfig,
690}
691
692#[cfg(feature = "cloud")]
693impl ObjectStoreByteSource {
694 async fn try_new_from_path(
695 path: PlRefPath,
696 cloud_options: Option<&CloudOptions>,
697 io_metrics: Option<Arc<IOMetrics>>,
698 mut config: FetchConfig,
699 ) -> PolarsResult<Self> {
700 if path.scheme().is_none_or(|s| s.is_file()) {
702 config.pipeline_window = PipelineWindow::Fixed;
703 }
704 let (CloudLocation { prefix, .. }, mut store) =
705 build_object_store(path, cloud_options, false).await?;
706 let path = object_path_from_str(&prefix)?;
707
708 store.set_io_metrics(io_metrics);
709
710 Ok(Self {
711 store,
712 path,
713 config,
714 })
715 }
716
717 #[allow(unused)]
718 fn chunk_size(&self) -> usize {
719 self.config.chunk_size
720 }
721
722 fn concurrency_strategy(&self) -> ConcurrencyStrategy {
723 self.config.strategy
724 }
725}
726
727#[cfg(feature = "cloud")]
728impl ByteSource for ObjectStoreByteSource {
729 async fn get_size(&self) -> PolarsResult<usize> {
730 Ok(self
731 .store
732 .head(&self.path, self.concurrency_strategy())
733 .await?
734 .size as usize)
735 }
736
737 async fn get_suffix(&self, n: usize) -> PolarsResult<(Buffer<u8>, usize)> {
738 self.store.get_suffix(&self.path, n, self.config).await
739 }
740
741 async fn get_prefix(&self, n: usize) -> PolarsResult<(Buffer<u8>, usize)> {
742 self.store.get_prefix(&self.path, n, self.config).await
743 }
744
745 async fn get_range(&self, range: Range<usize>) -> PolarsResult<Buffer<u8>> {
746 self.store.get_range(&self.path, range, self.config).await
747 }
748
749 async fn get_ranges(
750 &self,
751 ranges: &mut [Range<usize>],
752 ) -> PolarsResult<PlHashMap<usize, Buffer<u8>>> {
753 self.store
754 .get_ranges_sort(&self.path, ranges, self.config)
755 .await
756 }
757}
758
759pub enum DynByteSource {
761 Buffer(BufferByteSource),
762 File(FileByteSource),
763 #[cfg(feature = "cloud")]
764 Cloud(ObjectStoreByteSource),
765}
766
767impl DynByteSource {
768 pub fn variant_name(&self) -> &str {
769 match self {
770 Self::Buffer(_) => "Buffer",
771 Self::File(_) => "File",
772 #[cfg(feature = "cloud")]
773 Self::Cloud(_) => "Cloud",
774 }
775 }
776
777 #[cfg_attr(not(feature = "cloud"), allow(unused_variables))]
781 pub fn with_fetch_config(&self, config: FetchConfig) -> Option<Self> {
782 match self {
783 Self::Buffer(_) | Self::File(_) => None,
784 #[cfg(feature = "cloud")]
785 Self::Cloud(v) => Some(Self::Cloud(ObjectStoreByteSource {
786 config: FetchConfig {
787 pipeline_window: v.config.pipeline_window,
788 ..config
789 },
790 ..v.clone()
791 })),
792 }
793 }
794
795 pub fn is_cloud(&self) -> bool {
796 match self {
797 Self::Buffer(_) => false,
798 Self::File(_) => false,
799 #[cfg(feature = "cloud")]
800 Self::Cloud(_) => true,
801 }
802 }
803
804 pub fn chunk_size(&self) -> Option<usize> {
805 match self {
806 Self::Buffer(_) => None,
807 Self::File(_) => None,
808 #[cfg(feature = "cloud")]
809 Self::Cloud(source) => Some(source.config.chunk_size),
810 }
811 }
812
813 pub fn concurrency_strategy(&self) -> Option<ConcurrencyStrategy> {
814 match self {
815 Self::Buffer(_) => None,
816 Self::File(_) => None,
818 #[cfg(feature = "cloud")]
819 Self::Cloud(source) => Some(source.concurrency_strategy()),
820 }
821 }
822
823 #[cfg(feature = "cloud")]
826 pub fn window_inflight_budget(&self) -> Option<Arc<crate::cloud::concurrency::InFlightBudget>> {
827 match self {
828 Self::Cloud(source)
829 if matches!(
830 source.concurrency_strategy(),
831 ConcurrencyStrategy::BytesBased
832 ) && source.config.pipeline_window == PipelineWindow::FollowInflight =>
833 {
834 Some(
835 source
836 .store
837 .get_or_init_concurrency()
838 .inflight_budget()
839 .clone(),
840 )
841 },
842 _ => None,
843 }
844 }
845}
846
847impl Default for DynByteSource {
848 fn default() -> Self {
849 Self::Buffer(BufferByteSource(Buffer::new()))
850 }
851}
852
853impl ByteSource for DynByteSource {
854 async fn get_size(&self) -> PolarsResult<usize> {
855 match self {
856 Self::Buffer(v) => v.get_size().await,
857 Self::File(v) => v.get_size().await,
858 #[cfg(feature = "cloud")]
859 Self::Cloud(v) => v.get_size().await,
860 }
861 }
862
863 async fn get_suffix(&self, n: usize) -> PolarsResult<(Buffer<u8>, usize)> {
864 match self {
865 Self::Buffer(v) => v.get_suffix(n).await,
866 Self::File(v) => v.get_suffix(n).await,
867 #[cfg(feature = "cloud")]
868 Self::Cloud(v) => v.get_suffix(n).await,
869 }
870 }
871
872 async fn get_prefix(&self, n: usize) -> PolarsResult<(Buffer<u8>, usize)> {
873 match self {
874 Self::Buffer(v) => v.get_prefix(n).await,
875 Self::File(v) => v.get_prefix(n).await,
876 #[cfg(feature = "cloud")]
877 Self::Cloud(v) => v.get_prefix(n).await,
878 }
879 }
880
881 async fn get_range(&self, range: Range<usize>) -> PolarsResult<Buffer<u8>> {
882 match self {
883 Self::Buffer(v) => v.get_range(range).await,
884 Self::File(v) => v.get_range(range).await,
885 #[cfg(feature = "cloud")]
886 Self::Cloud(v) => v.get_range(range).await,
887 }
888 }
889
890 async fn get_ranges(
891 &self,
892 ranges: &mut [Range<usize>],
893 ) -> PolarsResult<PlHashMap<usize, Buffer<u8>>> {
894 match self {
895 Self::Buffer(v) => v.get_ranges(ranges).await,
896 Self::File(v) => v.get_ranges(ranges).await,
897 #[cfg(feature = "cloud")]
898 Self::Cloud(v) => v.get_ranges(ranges).await,
899 }
900 }
901}
902
903impl From<BufferByteSource> for DynByteSource {
904 fn from(value: BufferByteSource) -> Self {
905 Self::Buffer(value)
906 }
907}
908
909impl From<FileByteSource> for DynByteSource {
910 fn from(value: FileByteSource) -> Self {
911 Self::File(value)
912 }
913}
914
915#[cfg(feature = "cloud")]
916impl From<ObjectStoreByteSource> for DynByteSource {
917 fn from(value: ObjectStoreByteSource) -> Self {
918 Self::Cloud(value)
919 }
920}
921
922impl From<Buffer<u8>> for DynByteSource {
923 fn from(value: Buffer<u8>) -> Self {
924 Self::Buffer(BufferByteSource(value))
925 }
926}
927
928#[derive(Clone, Debug)]
929pub enum DynByteSourceBuilder {
930 Mmap,
931 FilePread(FileReadContext),
933 ObjectStore(FetchConfig),
935}
936
937impl DynByteSourceBuilder {
938 pub async fn try_build_from_path(
939 &self,
940 path: PlRefPath,
941 cloud_options: Option<&CloudOptions>,
942 io_metrics: Option<Arc<IOMetrics>>,
943 ) -> PolarsResult<DynByteSource> {
944 Ok(match self {
945 Self::Mmap => {
946 BufferByteSource::try_new_mmap_from_path(path.as_std_path(), cloud_options)
947 .await?
948 .into()
949 },
950 Self::FilePread(read_context) => {
951 FileByteSource::try_new_from_path(path, read_context.clone(), io_metrics)
952 .await?
953 .into()
954 },
955 Self::ObjectStore(fetch_config) => feature_gated!("cloud", {
956 ObjectStoreByteSource::try_new_from_path(
957 path,
958 cloud_options,
959 io_metrics,
960 *fetch_config,
961 )
962 .await?
963 .into()
964 }),
965 })
966 }
967
968 pub fn chunk_size(&self) -> Option<usize> {
969 match self {
970 Self::Mmap => None,
971 Self::FilePread(_) => None,
972 Self::ObjectStore(fetch_config) => Some(fetch_config.chunk_size),
973 }
974 }
975
976 pub fn concurrency_strategy(&self) -> Option<&ConcurrencyStrategy> {
977 match self {
978 Self::Mmap => None,
979 Self::FilePread(_) => None,
980 Self::ObjectStore(fetch_config) => Some(&fetch_config.strategy),
981 }
982 }
983}
984
985#[cfg(test)]
986mod tests {
987 use super::*;
988
989 const MIB: usize = 1 << 20;
990
991 fn source(dir: &std::path::Path, len: usize) -> (FileByteSource, Vec<u8>) {
993 let path = dir.join("f.bin");
994 let contents: Vec<u8> = (0..len).map(|i| (i % 251) as u8).collect();
995 std::fs::write(&path, &contents).unwrap();
996
997 let read_context = FileReadContext {
998 enable_o_direct: false,
999 concurrency: 4,
1000 permits: Arc::new(Semaphore::new(4)),
1001 advice: FileAdvice::Normal,
1002 };
1003 let source = FileByteSource::try_new_from_std(
1004 std::fs::File::open(&path).unwrap(),
1005 read_context,
1006 None,
1007 )
1008 .unwrap();
1009 (source, contents)
1010 }
1011
1012 fn runtime() -> tokio::runtime::Runtime {
1013 tokio::runtime::Builder::new_multi_thread()
1014 .worker_threads(2)
1015 .enable_all()
1016 .build()
1017 .unwrap()
1018 }
1019
1020 #[test]
1021 fn get_ranges_resolves_every_range() {
1022 let dir = tempfile::tempdir().unwrap();
1023 let (source, contents) = source(dir.path(), 17 * MIB);
1024 let rt = runtime();
1025
1026 let cases: [(&str, &[Range<usize>]); 6] = [
1027 ("disjoint", &[0..100, 500..600, 900..1000]),
1028 ("unsorted", &[900..1000, 0..100, 500..600]),
1029 ("partial overlap", &[0..100, 50..150]),
1030 ("contained", &[0..200, 50..100]),
1031 ("empty range at a span end", &[0..100, 100..100]),
1033 (
1036 "overlapping spans",
1037 &[
1038 0..4096,
1039 5_000_000..14_000_000,
1040 13_000_000..13_500_000,
1041 13_500_000..16_000_000,
1042 ],
1043 ),
1044 ];
1045
1046 for (name, ranges) in cases {
1047 let mut ranges = ranges.to_vec();
1048 let expect = ranges.clone();
1049 let out = rt.block_on(source.get_ranges(&mut ranges)).unwrap();
1050
1051 assert_eq!(out.len(), expect.len(), "{name}");
1052 for r in &expect {
1053 let got = out
1054 .get(&r.start)
1055 .unwrap_or_else(|| panic!("{name}: {r:?} missing"));
1056 assert_eq!(got.as_ref(), &contents[r.clone()], "{name}: {r:?}");
1057 }
1058 }
1059 }
1060
1061 #[test]
1062 fn read_blocking_reads_the_range() {
1063 let dir = tempfile::tempdir().unwrap();
1064 let (source, contents) = source(dir.path(), 3 * MIB);
1065
1066 for r in [0..0, 0..1, 100..4096, MIB - 7..MIB + 9, 0..3 * MIB] {
1067 let got = source.read_blocking(r.clone()).unwrap();
1068 assert_eq!(got.as_ref(), &contents[r.clone()], "{r:?}");
1069 }
1070 }
1071
1072 #[cfg(all(
1073 target_os = "linux",
1074 any(target_arch = "x86_64", target_arch = "aarch64")
1075 ))]
1076 #[test]
1077 fn is_cached_follows_the_page_cache() {
1078 let dir = tempfile::tempdir().unwrap();
1079 let (source, _) = source(dir.path(), 4 * MIB);
1080 let ranges = [0..100, MIB + 1..2 * MIB + 1, 4 * MIB - 1..4 * MIB, 5..5];
1081
1082 if !source.is_cached(&ranges) {
1084 return;
1085 }
1086 assert!(source.is_cached(&[]));
1087
1088 source.file.sync_all().unwrap();
1090 unsafe { libc::posix_fadvise(source.file.as_raw_fd(), 0, 0, libc::POSIX_FADV_DONTNEED) };
1091 let mut st: libc::statfs = unsafe { std::mem::zeroed() };
1092 let path = std::ffi::CString::new(dir.path().as_os_str().as_encoded_bytes()).unwrap();
1093 assert_eq!(unsafe { libc::statfs(path.as_ptr(), &mut st) }, 0);
1094 if st.f_type == libc::TMPFS_MAGIC {
1095 return;
1096 }
1097 assert!(!source.is_cached(&ranges));
1098
1099 let read = MIB + 1..2 * MIB + 1;
1100 source.read_blocking(read.clone()).unwrap();
1101 assert!(source.is_cached(std::slice::from_ref(&read)));
1102 assert!(!source.is_cached(&ranges));
1103 }
1104
1105 #[cfg(all(
1106 target_os = "linux",
1107 any(target_arch = "x86_64", target_arch = "aarch64")
1108 ))]
1109 #[test]
1110 fn is_cached_does_not_bridge_gaps() {
1111 let page = *polars_utils::mem::PAGE_SIZE;
1112 let dir = tempfile::tempdir().unwrap();
1113 let (source, _) = source(dir.path(), 3 * page);
1114 let (all, middle) = (0..3 * page, page..2 * page);
1115 if !source.is_cached(std::slice::from_ref(&all)) {
1117 return;
1118 }
1119
1120 source.file.sync_all().unwrap();
1122 unsafe {
1123 libc::posix_fadvise(
1124 source.file.as_raw_fd(),
1125 page as libc::off_t,
1126 page as libc::off_t,
1127 libc::POSIX_FADV_DONTNEED,
1128 )
1129 };
1130 if source.is_cached(std::slice::from_ref(&middle)) {
1131 return;
1132 }
1133 assert!(source.is_cached(&[2 * page..3 * page, 0..page]));
1134 assert!(!source.is_cached(&[0..page, page..2 * page]));
1135 assert!(!source.is_cached(std::slice::from_ref(&all)));
1136 }
1137}