Skip to main content

ab_farmer/single_disk_farm/farming/
rayon_files.rs

1//! Files abstraction that allows reading concurrently using thread pool
2
3use ab_aligned_buffer::OwnedAlignedBuffer;
4use ab_aligned_buffer::alignment::Align1;
5use ab_direct_io_file::{IoBufError, OwnedPages};
6use ab_farmer_components::ReadAtSync;
7use ab_farmer_components::file_ext::{FileExt, OpenOptionsExt};
8use std::fs::{File, OpenOptions};
9use std::path::Path;
10use std::{io, iter};
11
12/// Wrapper data structure for multiple files to be used with [`rayon`] thread pool, where the same
13/// file is opened multiple times, once for each thread for faster concurrent reads.
14///
15/// The benefit of multiple handles was measured (it is especially large on Windows), don't replace
16/// them with a single shared file.
17#[derive(Debug)]
18pub struct RayonFiles<File> {
19    files: Vec<File>,
20}
21
22impl<File> ReadAtSync for RayonFiles<File>
23where
24    File: ReadAtSync,
25{
26    fn read_at(
27        &self,
28        buffer: OwnedPages,
29        len: u32,
30        offset: u64,
31    ) -> Result<OwnedAlignedBuffer<Align1>, IoBufError<OwnedPages>> {
32        let thread_index = rayon::current_thread_index().unwrap_or_default();
33        let Some(file) = self.files.get(thread_index) else {
34            return Err(IoBufError {
35                error: io::Error::other("No files entry for this rayon thread").into(),
36                buffer,
37            });
38        };
39
40        file.read_at(buffer, len, offset)
41    }
42}
43
44impl RayonFiles<File> {
45    /// Open file at specified path as many times as there is number of threads in current [`rayon`]
46    /// thread pool.
47    pub fn open<P>(path: P) -> io::Result<Self>
48    where
49        P: AsRef<Path>,
50    {
51        let files = iter::repeat_with(|| {
52            let file = OpenOptions::new()
53                .read(true)
54                .advise_random_access()
55                .open(path.as_ref())?;
56            file.advise_random_access()?;
57
58            Ok::<_, io::Error>(file)
59        })
60        .take(rayon::current_num_threads())
61        .collect::<Result<Vec<_>, _>>()?;
62
63        Ok(Self { files })
64    }
65}
66
67impl<File> RayonFiles<File>
68where
69    File: ReadAtSync,
70{
71    /// Open file at specified path as many times as there is number of threads in current [`rayon`]
72    /// thread pool with a provided function
73    pub fn open_with<P>(path: P, open: fn(&Path) -> io::Result<File>) -> io::Result<Self>
74    where
75        P: AsRef<Path>,
76    {
77        let files = iter::repeat_with(|| open(path.as_ref()))
78            .take(rayon::current_num_threads())
79            .collect::<Result<Vec<_>, _>>()?;
80
81        Ok(Self { files })
82    }
83}