crisol-core 1.3.0

Crisol core: an egui-free data model, themes, metrics, localization, commands, state, and storage.
Documentation
//! Project files: datasets, views, scripts, settings, and a workspace in one file.
//!
//! ```
//! use crisol_core::state::Project;
//! let _ = Project::new("study");
//! ```

#[cfg(feature = "threads")]
use std::path::Path;

use serde::{Deserialize, Serialize};

use super::session::Workspace;
use crate::storage::StorageError;

/// One dataset reference in a project.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
/// # Example
///
/// ```
/// # use crisol_core::state::ProjectDataset;
/// # let _ = std::marker::PhantomData::<ProjectDataset>;
/// ```
pub struct ProjectDataset {
    /// Dataset name.
    pub name: String,
    /// Path or URL.
    pub source: String,
    /// Connector hint, such as `csv`, `parquet`, or `netcdf`.
    pub format: String,
}

/// One saved view.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
/// # Example
///
/// ```
/// # use crisol_core::state::ProjectView;
/// # let _ = std::marker::PhantomData::<ProjectView>;
/// ```
pub struct ProjectView {
    /// View name.
    pub name: String,
    /// View kind, such as `plot` or `table`.
    pub kind: String,
    /// Application-specific payload.
    #[serde(default)]
    pub payload: serde_json::Value,
}

/// One script in a project.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
/// # Example
///
/// ```
/// # use crisol_core::state::ProjectScript;
/// # let _ = std::marker::PhantomData::<ProjectScript>;
/// ```
pub struct ProjectScript {
    /// Script name.
    pub name: String,
    /// Inline source; `None` reads `path`.
    pub source: Option<String>,
    /// Script path.
    pub path: Option<String>,
}

/// A complete project file.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
/// # Example
///
/// ```
/// use crisol_core::state::Project;
///
/// let project = Project::new("study");
/// assert_eq!(project.version, Project::VERSION);
/// ```
pub struct Project {
    /// File format version.
    pub version: u32,
    /// Project name.
    pub name: String,
    /// Dataset references.
    #[serde(default)]
    pub datasets: Vec<ProjectDataset>,
    /// Saved views.
    #[serde(default)]
    pub views: Vec<ProjectView>,
    /// Scripts.
    #[serde(default)]
    pub scripts: Vec<ProjectScript>,
    /// Free-form settings.
    #[serde(default)]
    pub settings: std::collections::BTreeMap<String, String>,
    /// The embedded workspace.
    #[serde(default)]
    pub workspace: Option<Workspace>,
}

impl Default for Project {
    fn default() -> Self {
        Self::new("Untitled")
    }
}

impl Project {
    /// The current version.
    pub const VERSION: u32 = 1;

    /// An empty project.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            version: Self::VERSION,
            name: name.into(),
            datasets: Vec::new(),
            views: Vec::new(),
            scripts: Vec::new(),
            settings: std::collections::BTreeMap::new(),
            workspace: None,
        }
    }

    /// Add a dataset reference.
    pub fn dataset(&mut self, name: impl Into<String>, source: impl Into<String>, format: impl Into<String>) {
        self.datasets.push(ProjectDataset {
            name: name.into(),
            source: source.into(),
            format: format.into(),
        });
    }

    /// Add a view.
    pub fn view(&mut self, name: impl Into<String>, kind: impl Into<String>, payload: serde_json::Value) {
        self.views.push(ProjectView {
            name: name.into(),
            kind: kind.into(),
            payload,
        });
    }

    /// Add an inline script.
    pub fn script(&mut self, name: impl Into<String>, source: impl Into<String>) {
        self.scripts.push(ProjectScript {
            name: name.into(),
            source: Some(source.into()),
            path: None,
        });
    }

    /// Save atomically as JSON.
    ///
    /// # Errors
    /// When serialization or the atomic write fails.
    #[cfg(feature = "threads")]
    pub fn save(&self, path: impl AsRef<Path>) -> Result<(), ProjectError> {
        let text = serde_json::to_vec_pretty(self).map_err(ProjectError::Json)?;
        crate::storage::atomic_write(path.as_ref(), &text).map_err(ProjectError::Storage)
    }

    /// Load a project from JSON.
    ///
    /// # Errors
    /// When the file cannot be read, is invalid JSON, or has a newer version.
    #[cfg(feature = "threads")]
    pub fn load(path: impl AsRef<Path>) -> Result<Self, ProjectError> {
        let text = crate::storage::read_to_string(path).map_err(ProjectError::Storage)?;
        let project: Self = serde_json::from_str(&text).map_err(ProjectError::Json)?;
        if project.version > Self::VERSION {
            return Err(ProjectError::Version(project.version));
        }
        Ok(project)
    }
}

/// Why a project file could not be saved or loaded.
///
/// # Example
///
/// ```
/// use crisol_core::state::ProjectError;
/// let error = ProjectError::Version(9);
/// assert!(error.to_string().contains("9"));
/// ```
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ProjectError {
    /// Serialization failed.
    #[error("project JSON: {0}")]
    Json(serde_json::Error),
    /// The file could not be read or written.
    #[error("{0}")]
    Storage(StorageError),
    /// The file was written by a newer version.
    #[error("project version {0} is newer than 1")]
    Version(u32),
}

#[cfg(all(test, feature = "threads", not(target_family = "wasm")))]
mod tests {
    use super::*;

    #[test]
    fn a_project_round_trips() {
        let mut project = Project::new("study");
        project.dataset("signal", "data.csv", "csv");
        project.view("plot", "plot", serde_json::json!({"title": "signal"}));
        project.script("load", "print('hello')");
        project.workspace = Some(Workspace::default());
        let directory = std::env::temp_dir().join(format!("crisol-project-{}", std::process::id()));
        std::fs::create_dir_all(&directory).expect("directory");
        let path = directory.join("study.crisol");
        project.save(&path).expect("save");
        let restored = Project::load(&path).expect("load");
        assert_eq!(restored, project);
        let _ = std::fs::remove_dir_all(directory);
    }

    #[test]
    fn a_newer_version_is_rejected() {
        let directory = std::env::temp_dir().join(format!("crisol-project-new-{}", std::process::id()));
        std::fs::create_dir_all(&directory).expect("directory");
        let path = directory.join("newer.crisol");
        std::fs::write(&path, r#"{"version":9,"name":"x"}"#).expect("write");
        assert!(matches!(Project::load(&path), Err(ProjectError::Version(9))));
        let _ = std::fs::remove_dir_all(directory);
    }
}