Skip to main content

crisol_core/data/
source.rs

1//! Lazy, paged data sources without an async runtime.
2
3use std::collections::BTreeMap;
4use std::ops::Range;
5
6use super::column::{Column, ColumnType};
7use super::dataset::Dataset;
8
9/// The schema of one column, without its values.
10#[derive(Clone, Debug, PartialEq, Eq)]
11#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
12#[non_exhaustive]
13/// # Example
14///
15/// ```
16/// use crisol_core::data::ColumnSchema;
17/// ```
18pub struct ColumnSchema {
19    /// Column name.
20    pub name: String,
21    /// Column type.
22    pub kind: ColumnType,
23    /// Unit.
24    pub unit: Option<String>,
25    /// Metadata.
26    pub metadata: BTreeMap<String, String>,
27}
28
29impl ColumnSchema {
30    /// A schema from a name and type.
31    pub fn new(name: impl Into<String>, kind: ColumnType) -> Self {
32        Self {
33            name: name.into(),
34            kind,
35            unit: None,
36            metadata: BTreeMap::new(),
37        }
38    }
39
40    /// A schema from a column.
41    pub fn from_column(column: &Column) -> Self {
42        Self {
43            name: column.name.clone(),
44            kind: column.kind(),
45            unit: column.unit.clone(),
46            metadata: column.metadata.clone(),
47        }
48    }
49}
50
51/// Why a data source could not read.
52#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
53#[non_exhaustive]
54/// # Example
55///
56/// ```
57/// use crisol_core::data::DataError;
58/// ```
59pub enum DataError {
60    /// The requested range is outside the source.
61    #[error("rows {start}..{end} are outside {rows} available rows")]
62    OutOfRange {
63        /// Requested start.
64        start: usize,
65        /// Requested end.
66        end: usize,
67        /// Available rows.
68        rows: usize,
69    },
70    /// The source cannot answer without more information.
71    #[error("{0}")]
72    Unsupported(String),
73    /// The connector failed.
74    #[error("{0}")]
75    Connector(String),
76}
77
78/// A lazy, paged table. A source can be backed by a file, a database, a channel, or a
79/// thread; the trait is synchronous and never pulls in an async runtime.
80/// # Example
81///
82/// ```
83/// use crisol_core::data::DataSource;
84/// ```
85pub trait DataSource {
86    /// The column schema.
87    fn schema(&self) -> &[ColumnSchema];
88
89    /// The total number of rows, when known.
90    fn row_count(&self) -> usize;
91
92    /// Read rows in `range`. Implementations may return fewer rows at the end.
93    ///
94    /// # Errors
95    /// When the range is invalid or the backing store fails.
96    fn read_range(&self, range: Range<usize>) -> Result<Dataset, DataError>;
97
98    /// A revision that changes when the source changes.
99    fn revision(&self) -> u64 {
100        0
101    }
102
103    /// Cancel an in-flight read, when the implementation supports it.
104    fn cancel(&self) {}
105}
106
107/// A source backed by an in-memory dataset.
108#[derive(Clone, Debug, PartialEq)]
109/// # Example
110///
111/// ```
112/// use crisol_core::data::MemorySource;
113/// ```
114pub struct MemorySource {
115    schema: Vec<ColumnSchema>,
116    data: Dataset,
117    revision: u64,
118}
119
120impl MemorySource {
121    /// A source over `data`.
122    pub fn new(data: Dataset) -> Self {
123        let schema = data.columns().iter().map(ColumnSchema::from_column).collect();
124        Self {
125            schema,
126            data,
127            revision: 0,
128        }
129    }
130
131    /// The backing data.
132    pub fn data(&self) -> &Dataset {
133        &self.data
134    }
135}
136
137impl DataSource for MemorySource {
138    fn schema(&self) -> &[ColumnSchema] {
139        &self.schema
140    }
141
142    fn row_count(&self) -> usize {
143        self.data.row_count()
144    }
145
146    fn read_range(&self, range: Range<usize>) -> Result<Dataset, DataError> {
147        check_range(&range, self.row_count())?;
148        Ok(self.data.slice(range))
149    }
150
151    fn revision(&self) -> u64 {
152        self.revision
153    }
154}
155
156/// Largest file a connector or the viewer reads into memory.
157/// # Example
158///
159/// ```
160/// use crisol_core::data::MAX_FILE_BYTES;
161/// ```
162pub const MAX_FILE_BYTES: u64 = 512 * 1024 * 1024;
163
164#[cfg(feature = "threads")]
165/// Read a file, refusing one larger than [`MAX_FILE_BYTES`].
166///
167/// The limit applies to what is read, not to the size the file system reports, so a file
168/// that grows (or a special file that reports zero) cannot exhaust memory.
169///
170/// # Errors
171/// When the file cannot be read or is too large.
172#[cfg(feature = "threads")]
173/// # Example
174///
175/// ```
176/// use crisol_core::data::read_limited;
177/// ```
178pub fn read_limited(path: impl AsRef<std::path::Path>) -> Result<Vec<u8>, DataError> {
179    use std::io::Read;
180    let file = std::fs::File::open(path).map_err(|error| DataError::Connector(error.to_string()))?;
181    // Refuse early when the file system already reports too much; the `take` below still
182    // bounds files that grow or report a zero size.
183    if file.metadata().is_ok_and(|metadata| metadata.len() > MAX_FILE_BYTES) {
184        return Err(DataError::Connector(format!(
185            "the file is larger than {} MiB",
186            MAX_FILE_BYTES / (1024 * 1024)
187        )));
188    }
189    let mut bytes = Vec::new();
190    file.take(MAX_FILE_BYTES + 1)
191        .read_to_end(&mut bytes)
192        .map_err(|error| DataError::Connector(error.to_string()))?;
193    if bytes.len() as u64 > MAX_FILE_BYTES {
194        return Err(DataError::Connector(format!(
195            "the file is larger than {} MiB",
196            MAX_FILE_BYTES / (1024 * 1024)
197        )));
198    }
199    Ok(bytes)
200}
201
202pub(crate) fn check_range(range: &Range<usize>, rows: usize) -> Result<(), DataError> {
203    if range.start > range.end || range.end > rows {
204        Err(DataError::OutOfRange {
205            start: range.start,
206            end: range.end,
207            rows,
208        })
209    } else {
210        Ok(())
211    }
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217    use crate::data::{Column, ColumnType};
218
219    #[test]
220    fn a_memory_source_pages_and_reports_schema() {
221        let data = Dataset::from_columns([Column::floats("v", vec![1.0, 2.0, 3.0])]);
222        let source = MemorySource::new(data);
223        assert_eq!(source.schema()[0].kind, ColumnType::Float);
224        assert_eq!(source.row_count(), 3);
225        let page = source.read_range(1..3).expect("page");
226        assert_eq!(page.row_count(), 2);
227        assert!(source.read_range(2..9).is_err());
228    }
229}