scrusted-yaml 0.2.0

Validates, loads and resolves scripted-yaml files: YAML with FEEL formulas in marked keys, reloaded live.
Documentation
//! Scrusted-yaml: validates, loads and resolves scripted-yaml files, YAML with small pieces of
//! logic in marked keys (`key!:`), with formulas written in FEEL (SPEC.md).
//!
//! ```
//! use scrusted_yaml::{MemoryFiles, ScrustedYaml, ResolveOptions, vars};
//!
//! let files = MemoryFiles::from_pairs([("limits.yml", "$vars:\n  plan: {}\nper_minute!: if vars.plan = \"pro\" then 600 else 60\n")]);
//! let scrusted = ScrustedYaml::builder().files(files).build().unwrap();
//! let document = scrusted.load("limits.yml").unwrap();
//! let value = document.resolve(&vars! { plan: "pro" }, &ResolveOptions::default()).unwrap();
//! assert_eq!(value.as_map().unwrap()["per_minute"], scrusted_feel::Value::from(600));
//! ```
#![forbid(unsafe_code)]
#![warn(missing_docs)]

/// The examples of the README, run as doctests.
#[cfg(doctest)]
#[doc = include_str!("../../../README.md")]
pub struct ReadmeDoctests;

pub mod api;
pub mod checker;
pub mod document;
pub mod files;
#[cfg(feature = "live")]
pub mod live;
pub mod marker;
pub mod merged;
pub mod node;
pub mod patch;
pub mod problem;
pub mod reader;
pub mod resolution;
pub mod schema;
pub mod scope;
pub mod source;
pub mod types;
pub mod yaml_out;

use indexmap::IndexMap;
use std::collections::HashSet;
use std::sync::Arc;

pub use api::{AsVars, FromValue, Functions, HostFunction, IntoValue, Marked, Typed, Vars};
pub use document::{Data, Document, MarkedKey, ResolveError, ResolveOptions, TestResult};
pub use files::{DiskFiles, Files, MemoryFiles, Source, Templates};
pub use marker::{MarkerFn, MarkerOutput, Placeholder, placeholder};
pub use problem::{Problem, Severity};
pub use scrusted_feel::{self as feel, HostError, HostValue, Limits, Map, Value};
pub use source::{HostFunctionDecl, Input, Variable};

use crate::checker::Checker;
use crate::files::WithTemplates;
use crate::marker::Markers;
use crate::problem::{Place, Problems};
use crate::source::Loader;

/// Why a file does not load.
#[derive(Debug, Clone, PartialEq)]
pub enum LoadError {
    /// The file has errors: every problem found, warnings included.
    Invalid(Vec<Problem>),
}

impl LoadError {
    /// The problems.
    pub fn problems(&self) -> &[Problem] {
        match self {
            LoadError::Invalid(p) => p,
        }
    }
}

impl std::fmt::Display for LoadError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&problem::error_text(self.problems()))
    }
}

impl std::error::Error for LoadError {}

struct Library {
    files: Arc<dyn Files>,
    markers: Markers,
    strict: bool,
    #[cfg_attr(not(feature = "live"), allow(dead_code))]
    live: LiveConfig,
}

/// What a live set checks before a change goes live, and how it learns of changes (SPEC 6).
#[derive(Clone)]
#[cfg_attr(not(feature = "live"), allow(dead_code))]
pub(crate) struct LiveConfig {
    pub(crate) run_tests: bool,
    pub(crate) shapes: Vec<(String, Arc<ShapeCheck>)>,
    pub(crate) samples: Vec<(String, Map)>,
    pub(crate) debounce: std::time::Duration,
    pub(crate) poll: Option<std::time::Duration>,
}

/// The shape gate of one file: checks a document against a Rust type.
pub(crate) type ShapeCheck = dyn Fn(&Document, &[Map], &ResolveOptions) -> Vec<String> + Send + Sync;

impl Default for LiveConfig {
    fn default() -> Self {
        LiveConfig {
            run_tests: false,
            shapes: Vec::new(),
            samples: Vec::new(),
            debounce: std::time::Duration::from_millis(150),
            poll: None,
        }
    }
}

/// Validates and loads scripted-yaml files. `Send + Sync + Clone`.
#[derive(Clone)]
pub struct ScrustedYaml {
    inner: Arc<Library>,
}

/// Builds a [`ScrustedYaml`].
pub struct Builder {
    files: Arc<dyn Files>,
    markers: Markers,
    strict: bool,
    live: LiveConfig,
}

impl Builder {
    /// Where paths are read from. Default: no files (memory).
    pub fn files(mut self, files: impl Files + 'static) -> Self {
        self.files = Arc::new(files);
        self
    }

    /// Files shared with something else.
    pub fn shared_files(mut self, files: Arc<dyn Files>) -> Self {
        self.files = files;
        self
    }

    /// A marker function: it gets the value as written.
    pub fn marker(mut self, name: &str, f: impl Fn(&Value) -> Result<MarkerOutput, HostError> + Send + Sync + 'static) -> Self {
        self.markers.functions.insert(name.to_string(), Some(Arc::new(f)));
        self
    }

    /// A computed marker: its value is checked and computed like any value; at resolve its
    /// function gets the computed value (SPEC 4.6).
    pub fn computed_marker(mut self, name: &str, f: impl Fn(&Value) -> Result<MarkerOutput, HostError> + Send + Sync + 'static) -> Self {
        self.markers.functions.insert(name.to_string(), Some(Arc::new(f)));
        self.markers.computed.insert(name.to_string());
        self
    }

    /// Markers by name only, for a checker that validates and does not load.
    pub fn marker_names<S: AsRef<str>>(mut self, names: impl IntoIterator<Item = S>) -> Self {
        for n in names {
            self.markers.functions.entry(n.as_ref().to_string()).or_insert(None);
        }
        self
    }

    /// Names of markers whose value is computed like any value.
    pub fn computed_names<S: AsRef<str>>(mut self, names: impl IntoIterator<Item = S>) -> Self {
        for n in names {
            self.markers.computed.insert(n.as_ref().to_string());
            self.markers.functions.entry(n.as_ref().to_string()).or_insert(None);
        }
        self
    }

    /// Every warning is an error.
    pub fn strict(mut self, strict: bool) -> Self {
        self.strict = strict;
        self
    }

    /// Runs each `$tests` entry of every file before a change goes live (SPEC 6.2, gate 5).
    pub fn run_tests(mut self, run: bool) -> Self {
        self.live.run_tests = run;
        self
    }

    /// A file whose result must deserialize into `T` (SPEC 6.2, gate 6).
    #[cfg(feature = "live")]
    pub fn shape<T: serde::de::DeserializeOwned + 'static>(mut self, file: &str) -> Self {
        self.live.shapes.push((file.to_string(), live::shape_check::<T>()));
        self
    }

    /// Variables a file is resolved with before a change goes live; the result must fit its shape.
    pub fn sample(mut self, file: &str, vars: impl Into<Map>) -> Self {
        self.live.samples.push((file.to_string(), vars.into()));
        self
    }

    /// How long a change on disk settles before it is read (default 150 ms).
    pub fn debounce(mut self, wait: std::time::Duration) -> Self {
        self.live.debounce = wait;
        self
    }

    /// Asks the source for versions at this interval, for sources that are not a folder on disk.
    pub fn poll(mut self, every: std::time::Duration) -> Self {
        self.live.poll = Some(every);
        self
    }

    /// The library.
    pub fn build(self) -> Result<ScrustedYaml, LoadError> {
        Ok(ScrustedYaml {
            inner: Arc::new(Library {
                files: Arc::new(WithTemplates(self.files)),
                markers: self.markers,
                strict: self.strict,
                live: self.live,
            }),
        })
    }
}

/// What `check` leaves: the model and its validation, and the problems.
pub(crate) struct CheckedFile {
    pub(crate) model: Option<source::Model>,
    pub(crate) checked: checker::Checked,
    pub(crate) problems: Problems,
}

impl ScrustedYaml {
    /// A builder.
    pub fn builder() -> Builder {
        Builder { files: Arc::new(MemoryFiles::new()), markers: Markers::default(), strict: false, live: LiveConfig::default() }
    }

    /// The files the library reads.
    pub fn files(&self) -> Arc<dyn Files> {
        self.inner.files.clone()
    }

    /// True when warnings are errors.
    pub fn is_strict(&self) -> bool {
        self.inner.strict
    }

    fn read_file(&self, path: &str) -> Result<files::Source, Vec<Problem>> {
        let fail = |message: String| {
            vec![Problem { file: path.to_string(), line: 0, column: 0, key: String::new(), message, severity: Severity::Error }]
        };
        match self.inner.files.read(path, None) {
            Ok(Some(found)) => Ok(found),
            Ok(None) => Err(fail("cannot read the file: it does not exist".into())),
            Err(e) => Err(fail(e.to_string())),
        }
    }

    /// Checks a file and returns its problems (SPEC 5.3).
    pub fn validate(&self, path: &str) -> Vec<Problem> {
        match self.read_file(path) {
            Ok(found) => self.validate_text(&found.text, &found.name),
            Err(problems) => problems,
        }
    }

    /// Checks text that is not in a file; `file` names it in the problems.
    pub fn validate_text(&self, text: &str, file: &str) -> Vec<Problem> {
        self.check(&Input::Text(text.to_string()), file, None).problems.list
    }

    /// Checks text or data, optionally as a patch of a base the application holds.
    pub fn validate_input(&self, input: &Input, file: &str, base: Option<&Input>) -> Vec<Problem> {
        let base_name = format!("{file} (base)");
        self.check(input, file, base.map(|b| (base_name.as_str(), b))).problems.list
    }

    pub(crate) fn check(&self, input: &Input, file: &str, base: Option<(&str, &Input)>) -> CheckedFile {
        let mut problems = Problems::default();
        let loader = Loader { files: &*self.inner.files };
        let mut model = loader.load(input, file, base, &mut problems);
        let mut checked = checker::Checked::default();
        if let Some(m) = model.as_mut() {
            let names = self.inner.markers.names();
            checked = Checker::new(m, &names, &self.inner.markers.computed, &mut problems).run();
        }
        if self.inner.strict {
            problems.strict();
        }
        problems.sort();
        CheckedFile { model, checked, problems }
    }

    /// Validates a file, applies `$extends`, loads `.yml` imports and calls each marker function
    /// once. No formula is computed (SPEC 5.4).
    pub fn load(&self, path: &str) -> Result<Document, LoadError> {
        let found = self.read_file(path).map_err(LoadError::Invalid)?;
        self.load_text(&found.text, &found.name)
    }

    /// The same for text that is not in a file.
    pub fn load_text(&self, text: &str, file: &str) -> Result<Document, LoadError> {
        self.load_input(&Input::Text(text.to_string()), file, None)
    }

    /// The same for text or data, optionally as a patch of a base the application holds.
    pub fn load_input(&self, input: &Input, file: &str, base: Option<&Input>) -> Result<Document, LoadError> {
        let base_name = format!("{file} (base)");
        self.open(input, file, base.map(|b| (base_name.as_str(), b)), &mut Vec::new())
    }

    fn open(&self, input: &Input, file: &str, base: Option<(&str, &Input)>, chain: &mut Vec<String>) -> Result<Document, LoadError> {
        let CheckedFile { model, checked, mut problems } = self.check(input, file, base);
        let Some(model) = model else { return Err(LoadError::Invalid(problems.list)) };
        if problems.failed() {
            return Err(LoadError::Invalid(problems.list));
        }
        let key = self.inner.files.key(file);
        let mut imports = IndexMap::new();
        let specs: Vec<source::ImportSpec> = model.imported.values().filter(|s| s.found).cloned().collect();
        for spec in specs {
            let at: Place = model.tree.entry_place(spec.entry);
            let target = self.inner.files.key(&spec.file);
            if target == key || chain.contains(&target) {
                problems.error(&at, "the import comes back to this file: an import cycle");
                continue;
            }
            chain.push(key.clone());
            let opened = self.open(&Input::Text(spec.text.clone()), &spec.file, None, chain);
            chain.pop();
            match opened {
                Ok(doc) => {
                    imports.insert(spec.name.clone(), doc);
                }
                Err(e) => {
                    let first = e.problems().iter().find(|p| p.severity == Severity::Error).map(|p| p.to_string()).unwrap_or_default();
                    problems.error(&at, format!("cannot import \"{}\": {first}", spec.path));
                }
            }
        }
        let document = Document::build(model, checked, imports, self.inner.markers.clone(), &mut problems);
        problems.sort();
        if problems.failed() {
            return Err(LoadError::Invalid(problems.list));
        }
        Ok(document)
    }

    /// The names of the registered markers.
    pub fn marker_names_registered(&self) -> HashSet<String> {
        self.inner.markers.functions.keys().cloned().collect()
    }
}

/// Builds the variables of a resolve from `name: value` pairs; values are anything
/// `serde::Serialize` (SPEC 5.6).
///
/// ```
/// let vars = scrusted_yaml::vars! { plan: "pro", per_day: 1000 };
/// assert_eq!(vars.len(), 2);
/// ```
#[macro_export]
macro_rules! vars {
    () => { $crate::Vars::new() };
    ($($name:ident : $value:expr),+ $(,)?) => {{
        let mut map = $crate::Vars::new();
        $( map.insert(stringify!($name).into(), $crate::to_value(&$value).expect("a variable that serializes")); )+
        map
    }};
}

/// Any `serde::Serialize` as a value.
pub fn to_value<T: serde::Serialize + ?Sized>(value: &T) -> Result<Value, String> {
    feel::serde_value::to_value(value).map_err(|e| e.0)
}