Skip to main content

isothrum_runner/
manifest.rs

1//! Reading a run manifest from its file: the contract's own parser (`isoloom-manifest`, which
2//! checks the version, the types and what spans fields), plus where it lives.
3
4use std::path::{Path, PathBuf};
5
6use isoloom_manifest::contract::OUTPUT_DIR;
7use isoloom_manifest::{Manifest, Part, Placeholder, RunVar};
8
9use crate::Result;
10use crate::error::Error;
11
12/// A manifest read from its file.
13#[derive(Debug, Clone)]
14#[non_exhaustive]
15pub struct LoadedManifest {
16    /// The manifest.
17    pub manifest: Manifest,
18    /// Its file, absolute.
19    pub path: PathBuf,
20    /// Its folder, absolute: `${run.dir}`, and the folder its relative paths start from.
21    pub dir: PathBuf,
22}
23
24/// Reads and checks the manifest at `path`.
25///
26/// # Errors
27///
28/// Fails with `io` when the file can't be read, with `manifest_invalid` when it isn't UTF-8
29/// (naming the byte), and with `manifest_invalid` or `manifest_version` when the contract refuses
30/// it (the error names the field and the fix).
31pub fn load_manifest(path: &Path) -> Result<LoadedManifest> {
32    let path = std::path::absolute(path).map_err(Error::io(path, "read"))?;
33    let bytes = std::fs::read(&path).map_err(Error::io(&path, "read"))?;
34    let text = std::str::from_utf8(&bytes).map_err(|e| Error::Malformed {
35        at: path.display().to_string(),
36        reason: format!("not UTF-8 at byte {}", e.valid_up_to()),
37    })?;
38    let manifest = isoloom_manifest::parse(text).map_err(|source| Error::Manifest { path: path.clone(), source })?;
39    let dir = path.parent().map_or_else(|| path.clone(), Path::to_path_buf);
40    Ok(LoadedManifest { manifest, path, dir })
41}
42
43/// The file Isoloom writes a target's run manifest to, in the target's folder of an outputs
44/// folder ([`is_outputs_folder`]): `.isoloom/docker/run.json`, `.isoloom-2/cloud-vm/aws/run.json`.
45pub const MANIFEST_FILE: &str = "run.json";
46
47/// Whether a folder named `name`, at a project's top, is one Isoloom writes the project's outputs
48/// under: [`OUTPUT_DIR`] (`.isoloom`), or an instance's `.isoloom-<n>`, `n` an instance Isoloom
49/// takes ([`isoloom_manifest::Instance::new`]: 1 to 99) as it writes it (no sign, no leading
50/// zero). No other `.isoloom*` name. Isoloom publishes the way there
51/// (`isoloom_spec::instance::output_dir`) but not this way back; a test holds this copy to the
52/// folders Isoloom generates.
53#[must_use]
54pub fn is_outputs_folder(name: &str) -> bool {
55    let Some(rest) = name.strip_prefix(OUTPUT_DIR) else {
56        return false;
57    };
58    let Some(n) = rest.strip_prefix('-') else {
59        return rest.is_empty();
60    };
61    !n.starts_with('0') && n.bytes().all(|b| b.is_ascii_digit()) && n.parse::<u8>().is_ok_and(|n| isoloom_manifest::Instance::new(n).is_ok())
62}
63
64/// Whether a template of `manifest` names a `${run.<var>}` that `wanted` takes.
65pub(crate) fn names_run_var(manifest: &Manifest, wanted: impl Fn(RunVar) -> bool) -> bool {
66    manifest
67        .templates()
68        .iter()
69        .any(|(_, t)| t.parts().iter().any(|p| matches!(p, Part::Placeholder(Placeholder::Run(v)) if wanted(*v))))
70}
71
72#[cfg(test)]
73mod tests {
74    use super::*;
75
76    /// The rule held to what Isoloom generates: the project's own outputs and every instance's
77    /// (1 to 99, the numbers Isoloom takes) are in a folder it names, under the file it names;
78    /// nothing else that starts the same is.
79    #[test]
80    fn an_outputs_folder_is_one_isoloom_generates_into() {
81        let spec = "version: 1\nname: one\nnetworks:\n  app: { cidr: 10.80.0.0/24 }\nmachines:\n  web: { app: { image: nginx }, networks: { app: 10 } }\n";
82        let lab = isoloom_targets::Lab::parse(spec).unwrap();
83        let docker = lab.possible().into_iter().find(|t| t.id() == "docker").unwrap();
84        let manifest_of = |files: Vec<isoloom_targets::GeneratedFile>| {
85            files
86                .into_iter()
87                .map(|f| f.path)
88                .find(|p| p.ends_with("/run.json") && p.contains("/docker/"))
89                .unwrap()
90        };
91        let mut paths = vec![manifest_of(isoloom_targets::generate(&lab, docker).unwrap())];
92        let instances: Vec<u8> = (1..=u8::MAX).take_while(|n| isoloom_manifest::Instance::new(*n).is_ok()).collect();
93        paths.extend(
94            instances
95                .iter()
96                .map(|n| manifest_of(isoloom_targets::generate_instance(&lab, docker, *n).unwrap())),
97        );
98        for path in &paths {
99            let (folder, rest) = path.split_once('/').unwrap();
100            assert!(is_outputs_folder(folder), "{path}");
101            assert_eq!(rest, format!("docker/{MANIFEST_FILE}"), "{path}");
102        }
103        for n in [0, instances.len() + 1] {
104            let n = u8::try_from(n).unwrap();
105            assert!(isoloom_targets::generate_instance(&lab, docker, n).is_err(), "Isoloom makes no instance {n}");
106        }
107        for other in [
108            ".isoloom-0",
109            ".isoloom-100",
110            ".isoloom-02",
111            ".isoloom-+2",
112            ".isoloom-",
113            ".isoloom-old",
114            ".isoloomfoo",
115            "isoloom",
116            ".isoloom-2/",
117        ] {
118            assert!(!is_outputs_folder(other), "{other}");
119        }
120    }
121
122    #[test]
123    fn a_missing_file_is_an_io_error_naming_it() {
124        let err = load_manifest(Path::new("no/such/run.json")).unwrap_err();
125        assert_eq!(err.code(), crate::ErrorCode::Io);
126        assert!(err.to_string().contains("run.json couldn't be read"), "{err}");
127    }
128
129    /// Regression: bytes that weren't UTF-8 inside a JSON string read as U+FFFD, so a path or a
130    /// template of the contract changed without a word.
131    #[test]
132    fn a_manifest_that_isnt_utf8_is_invalid_naming_the_byte() {
133        let dir = tempfile::tempdir().unwrap();
134        let path = dir.path().join("run.json");
135        let mut bytes = crate::testing::WEB_PORTAL.as_bytes().to_vec();
136        let at = crate::testing::WEB_PORTAL.find("web-portal").unwrap();
137        bytes[at] = 0xff;
138        std::fs::write(&path, &bytes).unwrap();
139        let err = load_manifest(&path).unwrap_err();
140        assert_eq!(err.code(), crate::ErrorCode::ManifestInvalid, "{err}");
141        assert!(err.to_string().ends_with(&format!("run.json: not UTF-8 at byte {at}")), "{err}");
142    }
143}