Skip to main content

kitchen_contract/
documents.rs

1//! Documents on disk, as JSON or TOML, in every app ([standard §2.2](../../../standard/spec/02-ops.md),
2//! decision 0017): pipelines, recipes, op descriptions, settings. TOML is easier to write by hand
3//! (dsp-kitchen's pipelines were the first to take it); JSON is what tools write. Either reads into
4//! the same document, and a document's content id is the hash of its canonical JSON
5//! ([`content_id`]), so the format a person chose never changes an id.
6
7use std::path::Path;
8
9use serde::Serialize;
10use serde::de::DeserializeOwned;
11
12use crate::results::ContentId;
13
14/// How a document is written.
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16pub enum DocFormat {
17    /// `.json`
18    Json,
19    /// `.toml`
20    Toml,
21}
22
23impl DocFormat {
24    /// The format of a file, by its extension (`.json`, `.toml`); `None` for anything else.
25    pub fn of(path: &Path) -> Option<DocFormat> {
26        match path.extension()?.to_str()? {
27            "json" => Some(DocFormat::Json),
28            "toml" => Some(DocFormat::Toml),
29            _ => None,
30        }
31    }
32}
33
34/// `text` in `format` as a JSON value (what a document is, whatever it was written in).
35pub fn to_value(text: &str, format: DocFormat) -> Result<serde_json::Value, String> {
36    match format {
37        DocFormat::Json => serde_json::from_str(text).map_err(|e| e.to_string()),
38        DocFormat::Toml => {
39            let value: toml::Value = toml::from_str(text).map_err(|e| e.to_string())?;
40            serde_json::to_value(value).map_err(|e| e.to_string())
41        }
42    }
43}
44
45/// `text` in `format` as a `T` (a [`Pipeline`](crate::Pipeline), an [`OpSpec`](crate::OpSpec), …).
46pub fn parse<T: DeserializeOwned>(text: &str, format: DocFormat) -> Result<T, String> {
47    serde_json::from_value(to_value(text, format)?).map_err(|e| e.to_string())
48}
49
50/// The document at `path` (`.json` or `.toml`).
51pub fn read<T: DeserializeOwned>(path: &Path) -> Result<T, String> {
52    let format = DocFormat::of(path).ok_or_else(|| format!("{}: a document is .json or .toml", path.display()))?;
53    let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
54    parse(&text, format).map_err(|e| format!("{}: {e}", path.display()))
55}
56
57/// `value` as text in `format`: pretty JSON, or TOML (which has no null: absent fields are left
58/// out, as the contract's types already do).
59pub fn render<T: Serialize>(value: &T, format: DocFormat) -> Result<String, String> {
60    match format {
61        DocFormat::Json => serde_json::to_string_pretty(value).map(|s| s + "\n").map_err(|e| e.to_string()),
62        DocFormat::Toml => toml::to_string_pretty(value).map_err(|e| e.to_string()),
63    }
64}
65
66/// Writes `value` to `path` in the format its extension names.
67pub fn write<T: Serialize>(path: &Path, value: &T) -> Result<(), String> {
68    let format = DocFormat::of(path).ok_or_else(|| format!("{}: a document is .json or .toml", path.display()))?;
69    std::fs::write(path, render(value, format)?).map_err(|e| format!("{}: {e}", path.display()))
70}
71
72/// A document's content id: the hash of its canonical JSON, the same for its JSON and TOML forms.
73pub fn content_id(text: &str, format: DocFormat) -> Result<ContentId, String> {
74    Ok(ContentId::of_json(&to_value(text, format)?))
75}
76
77#[cfg(test)]
78mod tests {
79    use super::*;
80    use crate::{OpSpec, Pipeline};
81
82    const PIPELINE_TOML: &str = r#"
83version = 1
84app = "lucem"
85edges = [["image", "denoise.image"], ["denoise.image", "threshold.image"]]
86
87[sources]
88image = "image"
89
90[nodes.denoise]
91op = "lucem:denoise"
92params = { sigma = 2.0 }
93
94[nodes.threshold]
95op = "lucem:threshold"
96
97[outputs]
98mask = "threshold.mask"
99"#;
100
101    const PIPELINE_JSON: &str = r#"{"version": 1, "app": "lucem", "sources": {"image": "image"},
102      "nodes": {"denoise": {"op": "lucem:denoise", "params": {"sigma": 2.0}}, "threshold": {"op": "lucem:threshold"}},
103      "edges": [["image", "denoise.image"], ["denoise.image", "threshold.image"]],
104      "outputs": {"mask": "threshold.mask"}}"#;
105
106    #[test]
107    fn toml_and_json_read_into_the_same_document_with_the_same_id() {
108        let from_toml: Pipeline = parse(PIPELINE_TOML, DocFormat::Toml).unwrap();
109        let from_json: Pipeline = parse(PIPELINE_JSON, DocFormat::Json).unwrap();
110        assert_eq!(from_toml, from_json);
111        assert_eq!(
112            content_id(PIPELINE_TOML, DocFormat::Toml).unwrap(),
113            content_id(PIPELINE_JSON, DocFormat::Json).unwrap(),
114            "the format never changes an id"
115        );
116    }
117
118    #[test]
119    fn documents_write_and_read_back_in_either_format() {
120        let dir = std::env::temp_dir().join(format!("kitchen-contract-docs-{}", std::process::id()));
121        std::fs::create_dir_all(&dir).unwrap();
122        let p: Pipeline = parse(PIPELINE_JSON, DocFormat::Json).unwrap();
123        for name in ["p.json", "p.toml"] {
124            let path = dir.join(name);
125            write(&path, &p).unwrap();
126            assert_eq!(read::<Pipeline>(&path).unwrap(), p, "{name}");
127        }
128        let op: OpSpec = parse("id = \"x\"\ntitle = \"X\"\ninputs = []\noutputs = [{ name = \"o\", type = \"image\" }]\nsource = { from = \"builtin\" }\n", DocFormat::Toml).unwrap();
129        assert_eq!(op.version, 1);
130        assert!(read::<Pipeline>(&dir.join("p.yaml")).is_err(), "only JSON and TOML");
131    }
132}