Skip to main content

robonix_cli/
config_spec.rs

1// SPDX-License-Identifier: MulanPSL-2.0
2//! A package's `config.spec`, in its strict form.
3//!
4//! `config.spec` documents what a package's `config:` accepts. It may be
5//! free text. When it is YAML with `specVersion: 1` at the top it is strict:
6//! a JSON Schema subset that tools (the hub's deployment editor among them)
7//! build forms from, so it has to be exactly that subset. Robonix's own
8//! system and bundled services ship strict specs.
9//!
10//! The subset, at the top: `specVersion`, `description`, `properties`,
11//! `required`. For each property: `type` (string, integer, number, boolean,
12//! array, object, null, or a list of them; required), `description`,
13//! `default`, `enum`, `minimum` and `maximum` (both inclusive), `items`,
14//! `properties`, `required`, and three extensions: `x-secret` (a credential,
15//! to be written as `${VAR}`), `x-group` (a heading the field is shown under)
16//! and `x-provider` (the value names another entry of the deployment: the
17//! contract it must provide, or `true` for any). Anything else a field needs
18//! to say (units, environment fallbacks, defaults computed at run time,
19//! conditions, deprecation) goes in its description. `status` is the
20//! deployment's switch, read by rbnx, and is never a property.
21
22use anyhow::{Result, bail};
23use serde_yaml::Value;
24
25const TOP: &[&str] = &["specVersion", "description", "properties", "required"];
26const FIELD: &[&str] = &[
27    "type",
28    "description",
29    "default",
30    "enum",
31    "minimum",
32    "maximum",
33    "items",
34    "properties",
35    "required",
36    "x-secret",
37    "x-group",
38    "x-provider",
39];
40const TYPES: &[&str] = &[
41    "string", "integer", "number", "boolean", "array", "object", "null",
42];
43
44/// `Ok(false)` for a free-text spec, `Ok(true)` for a strict one that keeps
45/// to the subset, and the first departure from it otherwise.
46pub fn check(text: &str) -> Result<bool> {
47    let Ok(root) = serde_yaml::from_str::<Value>(text) else {
48        return Ok(false);
49    };
50    let Some(version) = root.get("specVersion") else {
51        return Ok(false);
52    };
53    if version.as_u64() != Some(1) {
54        bail!("specVersion must be 1, not {version:?}");
55    }
56    keys(&root, TOP, "top level")?;
57    object(&root, "config")?;
58    Ok(true)
59}
60
61fn keys(node: &Value, allowed: &[&str], at: &str) -> Result<()> {
62    let Some(map) = node.as_mapping() else {
63        bail!("{at}: must be a mapping");
64    };
65    for k in map.keys() {
66        let k = k.as_str().unwrap_or_default();
67        if !allowed.contains(&k) {
68            bail!("{at}: `{k}` is not part of the strict config.spec format");
69        }
70    }
71    Ok(())
72}
73
74/// The `properties` and `required` of an object, at the top or nested.
75fn object(node: &Value, at: &str) -> Result<()> {
76    let props = match node.get("properties") {
77        None => serde_yaml::Mapping::new(),
78        Some(Value::Mapping(m)) => m.clone(),
79        Some(_) => bail!("{at}.properties: must be a mapping"),
80    };
81    for (k, field) in &props {
82        let name = k.as_str().unwrap_or_default();
83        if name == "status" && at == "config" {
84            bail!(
85                "config.status: `status` is the deployment's switch, read by rbnx; it is not a config property"
86            );
87        }
88        property(field, &format!("{at}.{name}"))?;
89    }
90    if let Some(required) = node.get("required") {
91        let Some(list) = required.as_sequence() else {
92            bail!("{at}.required: must be a list");
93        };
94        for r in list {
95            let r = r.as_str().unwrap_or_default();
96            if !props.contains_key(r) {
97                bail!("{at}.required: `{r}` is not one of its properties");
98            }
99        }
100    }
101    Ok(())
102}
103
104fn property(field: &Value, at: &str) -> Result<()> {
105    keys(field, FIELD, at)?;
106    let types: Vec<&str> = match field.get("type") {
107        None => bail!("{at}.type: every property declares its type"),
108        Some(Value::String(t)) => vec![t.as_str()],
109        Some(Value::Sequence(ts)) => ts.iter().map(|t| t.as_str().unwrap_or("?")).collect(),
110        Some(t) => bail!("{at}.type: must be a name or a list of names, not {t:?}"),
111    };
112    for t in &types {
113        if !TYPES.contains(t) {
114            bail!("{at}.type: unknown type `{t}`");
115        }
116    }
117    if let Some(desc) = field.get("description")
118        && !desc.is_string()
119    {
120        bail!("{at}.description: must be text");
121    }
122    for bound in ["minimum", "maximum"] {
123        if let Some(b) = field.get(bound)
124            && b.as_f64().is_none()
125        {
126            bail!("{at}.{bound}: must be a number");
127        }
128    }
129    if let Some(secret) = field.get("x-secret")
130        && !secret.is_bool()
131    {
132        bail!("{at}.x-secret: must be true or false");
133    }
134    match field.get("x-provider") {
135        None => {}
136        Some(Value::Bool(true)) => {}
137        Some(Value::String(c)) if !c.trim().is_empty() => {}
138        Some(p) => bail!("{at}.x-provider: a contract ID or true, not {p:?}"),
139    }
140    if field.get("x-provider").is_some() && !types.contains(&"string") {
141        bail!("{at}.x-provider: only a string names a provider");
142    }
143    if let Some(items) = field.get("items") {
144        property(items, &format!("{at}.items"))?;
145    }
146    if field.get("properties").is_some() || field.get("required").is_some() {
147        object(field, at)?;
148    }
149    let choices = match field.get("enum") {
150        None => None,
151        Some(Value::Sequence(c)) if !c.is_empty() => Some(c),
152        Some(_) => bail!("{at}.enum: must be a non-empty list"),
153    };
154    if let Some(choices) = choices {
155        for c in choices {
156            if !fits(c, &types) {
157                bail!("{at}.enum: {c:?} is not of type {types:?}");
158            }
159        }
160    }
161    if let Some(default) = field.get("default") {
162        if !fits(default, &types) {
163            bail!("{at}.default: {default:?} is not of type {types:?}");
164        }
165        if let Some(choices) = choices
166            && !default.is_null()
167            && !choices.contains(default)
168        {
169            bail!("{at}.default: {default:?} is not one of its enum");
170        }
171        if let Some(n) = default.as_f64() {
172            let bound = |k: &str| field.get(k).and_then(Value::as_f64);
173            let out =
174                bound("minimum").is_some_and(|m| n < m) || bound("maximum").is_some_and(|m| n > m);
175            if out {
176                bail!("{at}.default: {n} is outside its own bounds");
177            }
178        }
179    }
180    Ok(())
181}
182
183/// Whether a value is of one of the declared types.
184fn fits(v: &Value, types: &[&str]) -> bool {
185    types.iter().any(|t| match *t {
186        "string" => v.is_string(),
187        "integer" => v.as_i64().is_some() || v.as_u64().is_some(),
188        "number" => v.as_f64().is_some(),
189        "boolean" => v.is_bool(),
190        "array" => v.is_sequence(),
191        "object" => v.is_mapping(),
192        "null" => v.is_null(),
193        _ => false,
194    })
195}
196
197#[cfg(test)]
198mod tests {
199    use super::*;
200    use std::path::{Path, PathBuf};
201
202    #[test]
203    fn free_text_is_left_alone_and_the_subset_is_held_to() {
204        assert!(!check("Set `rate` to the sensor's rate.").unwrap());
205        assert!(!check("config:\n  rate: 10\n").unwrap());
206        assert!(
207            check(
208                "specVersion: 1\nproperties:\n  rate: {type: integer, default: 10, minimum: 1}\n  cam: {type: string, x-provider: robonix/primitive/camera/rgb}\n"
209            )
210            .unwrap()
211        );
212        for bad in [
213            "specVersion: 2\n",
214            "specVersion: 1\nschema: {}\n",
215            "specVersion: 1\nproperties:\n  rate: {type: int}\n",
216            "specVersion: 1\nproperties:\n  rate: {type: integer, default: fast}\n",
217            "specVersion: 1\nproperties:\n  rate: {type: integer, default: 0, minimum: 1}\n",
218            "specVersion: 1\nproperties:\n  mode: {type: string, enum: [a, b], default: c}\n",
219            "specVersion: 1\nproperties:\n  rate: {type: integer, pattern: x}\n",
220            "specVersion: 1\nproperties:\n  rate: {type: integer, exclusiveMinimum: 0}\n",
221            "specVersion: 1\nproperties:\n  rate: {default: 1}\n",
222            "specVersion: 1\nproperties:\n  cam: {type: integer, x-provider: robonix/primitive/camera/rgb}\n",
223            "specVersion: 1\nproperties:\n  cam: {type: string, x-provider: false}\n",
224            "specVersion: 1\nproperties:\n  status: {type: string}\n",
225            "specVersion: 1\nproperties: {}\nrequired: [rate]\n",
226        ] {
227            assert!(check(bad).is_err(), "{bad}");
228        }
229    }
230
231    /// Robonix's own services ship strict specs, and they keep to the format.
232    #[test]
233    fn robonix_services_ship_strict_specs() {
234        let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
235        let mut specs: Vec<PathBuf> = Vec::new();
236        for entry in std::fs::read_dir(root.join("system")).unwrap().flatten() {
237            let spec = entry.path().join("config.spec");
238            if spec.is_file() {
239                specs.push(spec);
240            }
241        }
242        let mut stack = vec![root.join("services")];
243        while let Some(dir) = stack.pop() {
244            if dir.join("package_manifest.yaml").is_file() {
245                specs.push(dir.join("config.spec"));
246            } else {
247                stack.extend(
248                    std::fs::read_dir(&dir)
249                        .unwrap()
250                        .flatten()
251                        .map(|e| e.path())
252                        .filter(|p| p.is_dir()),
253                );
254            }
255        }
256        assert!(specs.len() >= 13, "{specs:?}");
257        for spec in specs {
258            let text = std::fs::read_to_string(&spec)
259                .unwrap_or_else(|_| panic!("{} is missing", spec.display()));
260            match check(&text) {
261                Ok(true) => {}
262                Ok(false) => panic!("{} is not a strict config.spec", spec.display()),
263                Err(e) => panic!("{}: {e}", spec.display()),
264            }
265        }
266    }
267}
浙ICP备2023005800号-2 浙公网安备33010902005384号