Skip to main content

surjection_core/model/
validate.rs

1//! Validation results and per-file dispatch for store files (SPEC 5).
2//!
3//! Every model has a `validate` method returning [`Diagnostics`]. Errors make
4//! a file invalid; warnings (unknown client ids, unknown OS names) are
5//! reported but the data is kept, so a store written by a newer build
6//! survives being opened by an older one.
7
8use std::fmt;
9use std::path::{Component, Path};
10
11use crate::error::{CoreError, ErrorCode};
12use crate::model::TomlDocument;
13use crate::model::applied::AppliedRecord;
14use crate::model::catalogs::CatalogsFile;
15use crate::model::clients::{ClientPrefsFile, ClientSelection, known_client};
16use crate::model::ids::{self, IdKind};
17use crate::model::machine::MachineOverlay;
18use crate::model::project::{ManifestLayer, ProjectManifest};
19use crate::model::secrets::SecretCatalog;
20use crate::model::server::Server;
21use crate::model::settings::Settings;
22use crate::model::skill_meta::SkillMeta;
23use crate::model::sources::SourcesFile;
24use crate::secrets::grammar::{SecretRef, parse_template};
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
27pub enum Severity {
28    Error,
29    Warning,
30}
31
32impl Severity {
33    pub const fn as_str(self) -> &'static str {
34        match self {
35            Severity::Error => "error",
36            Severity::Warning => "warning",
37        }
38    }
39}
40
41/// One finding about one field.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct Diagnostic {
44    pub severity: Severity,
45    pub code: ErrorCode,
46    /// Dotted TOML key path (`enable.clients[1]`, `client.codex.foo`);
47    /// empty for the whole file.
48    pub path: String,
49    /// English detail for logs and the CLI; frontends localize from `code`.
50    pub message: String,
51}
52
53impl Diagnostic {
54    pub fn error(code: ErrorCode, path: impl Into<String>, message: impl Into<String>) -> Self {
55        Self {
56            severity: Severity::Error,
57            code,
58            path: path.into(),
59            message: message.into(),
60        }
61    }
62
63    pub fn warning(code: ErrorCode, path: impl Into<String>, message: impl Into<String>) -> Self {
64        Self {
65            severity: Severity::Warning,
66            ..Self::error(code, path, message)
67        }
68    }
69
70    pub fn is_error(&self) -> bool {
71        self.severity == Severity::Error
72    }
73
74    /// The diagnostic as a [`CoreError`] about `file`.
75    pub fn to_core_error(&self, file: Option<&Path>) -> CoreError {
76        let error = CoreError::new(self.code, self.to_string());
77        match file {
78            Some(file) => error.with_path(file),
79            None => error,
80        }
81    }
82}
83
84impl fmt::Display for Diagnostic {
85    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86        if self.path.is_empty() {
87            f.write_str(&self.message)
88        } else {
89            write!(f, "{}: {}", self.path, self.message)
90        }
91    }
92}
93
94/// All findings for one file, in discovery order.
95#[derive(Debug, Clone, Default, PartialEq, Eq)]
96pub struct Diagnostics(Vec<Diagnostic>);
97
98impl Diagnostics {
99    pub fn new() -> Self {
100        Self::default()
101    }
102
103    pub fn push(&mut self, diagnostic: Diagnostic) {
104        self.0.push(diagnostic);
105    }
106
107    pub fn error(&mut self, code: ErrorCode, path: impl Into<String>, message: impl Into<String>) {
108        self.push(Diagnostic::error(code, path, message));
109    }
110
111    pub fn warning(
112        &mut self,
113        code: ErrorCode,
114        path: impl Into<String>,
115        message: impl Into<String>,
116    ) {
117        self.push(Diagnostic::warning(code, path, message));
118    }
119
120    /// No errors (warnings allowed).
121    pub fn is_valid(&self) -> bool {
122        !self.0.iter().any(Diagnostic::is_error)
123    }
124
125    pub fn errors(&self) -> impl Iterator<Item = &Diagnostic> {
126        self.0.iter().filter(|d| d.is_error())
127    }
128
129    pub fn warnings(&self) -> impl Iterator<Item = &Diagnostic> {
130        self.0.iter().filter(|d| !d.is_error())
131    }
132
133    pub fn iter(&self) -> impl Iterator<Item = &Diagnostic> {
134        self.0.iter()
135    }
136
137    pub fn len(&self) -> usize {
138        self.0.len()
139    }
140
141    pub fn is_empty(&self) -> bool {
142        self.0.is_empty()
143    }
144
145    pub fn into_vec(self) -> Vec<Diagnostic> {
146        self.0
147    }
148
149    /// The first error as a [`CoreError`] about `file`, if any.
150    pub fn first_error(&self, file: Option<&Path>) -> Option<CoreError> {
151        self.errors().next().map(|d| d.to_core_error(file))
152    }
153
154    pub(crate) fn check_id(&mut self, kind: IdKind, value: &str, path: &str) -> bool {
155        let valid = ids::is_valid(kind, value);
156        if !valid {
157            self.error(
158                ErrorCode::InvalidId,
159                path,
160                ids::invalid_message(kind, value),
161            );
162        }
163        valid
164    }
165
166    /// `id` must be valid for `kind` and, when the file or directory name is
167    /// known, equal to it (SPEC 5.1).
168    pub(crate) fn check_named_id(
169        &mut self,
170        kind: IdKind,
171        id: &str,
172        path: &str,
173        expected: Option<&str>,
174    ) {
175        if self.check_id(kind, id, path)
176            && let Some(expected) = expected.filter(|expected| *expected != id)
177        {
178            self.error(
179                ErrorCode::IdMismatch,
180                path,
181                format!(
182                    "{} {id:?} does not match its file name {expected:?}",
183                    kind.noun()
184                ),
185            );
186        }
187    }
188
189    /// Template grammar (SPEC 11.2) for one string field.
190    pub(crate) fn check_template(&mut self, value: &str, path: &str) {
191        if let Err(err) = parse_template(value) {
192            self.error(ErrorCode::InvalidRef, path, err.message());
193        }
194    }
195
196    /// Whole-value provider reference (`secrets.toml` `ref`).
197    pub(crate) fn check_secret_ref(&mut self, value: &str, path: &str) {
198        if let Err(err) = SecretRef::parse(value) {
199            self.error(ErrorCode::InvalidRef, path, err.message());
200        }
201    }
202
203    /// Unknown client ids are warnings and are kept as written.
204    pub(crate) fn check_client_ids<'a>(
205        &mut self,
206        ids: impl IntoIterator<Item = &'a String>,
207        path: &str,
208    ) {
209        for (index, id) in ids.into_iter().enumerate() {
210            if known_client(id).is_none() {
211                self.warning(
212                    ErrorCode::UnknownClient,
213                    at(path, index),
214                    format!("unknown client {id:?}; kept as written"),
215                );
216            }
217        }
218    }
219
220    pub(crate) fn check_client_selection(&mut self, selection: &ClientSelection, path: &str) {
221        if let ClientSelection::List(ids) = selection {
222            self.check_client_ids(ids, path);
223        }
224    }
225}
226
227impl IntoIterator for Diagnostics {
228    type Item = Diagnostic;
229    type IntoIter = std::vec::IntoIter<Diagnostic>;
230
231    fn into_iter(self) -> Self::IntoIter {
232        self.0.into_iter()
233    }
234}
235
236/// `prefix.key`, quoting `key` when it is not a bare TOML key.
237pub(crate) fn join(prefix: &str, key: &str) -> String {
238    let bare = !key.is_empty()
239        && key
240            .bytes()
241            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-'));
242    let key = if bare {
243        key.to_owned()
244    } else {
245        format!("{key:?}")
246    };
247    if prefix.is_empty() {
248        key
249    } else {
250        format!("{prefix}.{key}")
251    }
252}
253
254/// `prefix[index]`.
255pub(crate) fn at(prefix: &str, index: usize) -> String {
256    format!("{prefix}[{index}]")
257}
258
259/// A store file, identified by its path relative to the store root
260/// (SPEC 4.5). Carries the id implied by the file or directory name.
261#[derive(Debug, Clone, PartialEq, Eq)]
262pub enum StoreFile {
263    /// `servers/<id>.toml`
264    Server { id: String },
265    /// `secrets.toml`
266    Secrets,
267    /// `clients.toml`
268    Clients,
269    /// `settings.toml`
270    Settings,
271    /// `sources.toml`
272    Sources,
273    /// `catalogs.toml`
274    Catalogs,
275    /// `skill-meta/<id>.toml`
276    SkillMeta { id: String },
277    /// `projects/<id>/project.toml` or `projects/<id>/project.local.toml`
278    Project { id: String, local: bool },
279    /// `machines/<machine-id>.toml`
280    Machine { machine_id: String },
281    /// `machines/<machine-id>.applied.toml`
282    Applied { machine_id: String },
283}
284
285impl StoreFile {
286    /// Classifies a store-relative path; `None` for files that are not
287    /// schema files (skill content, `loadout.toml`, unknown files).
288    pub fn classify(relative: &Path) -> Option<Self> {
289        let parts: Vec<&str> = relative
290            .components()
291            .map(|component| match component {
292                Component::Normal(part) => part.to_str(),
293                _ => None,
294            })
295            .collect::<Option<_>>()?;
296        let stem = |name: &str, suffix: &str| name.strip_suffix(suffix).map(str::to_owned);
297        match parts.as_slice() {
298            ["secrets.toml"] => Some(Self::Secrets),
299            ["clients.toml"] => Some(Self::Clients),
300            ["settings.toml"] => Some(Self::Settings),
301            ["sources.toml"] => Some(Self::Sources),
302            ["catalogs.toml"] => Some(Self::Catalogs),
303            ["servers", name] => stem(name, ".toml").map(|id| Self::Server { id }),
304            ["skill-meta", name] => stem(name, ".toml").map(|id| Self::SkillMeta { id }),
305            ["projects", id, "project.toml"] => Some(Self::Project {
306                id: (*id).to_owned(),
307                local: false,
308            }),
309            ["projects", id, "project.local.toml"] => Some(Self::Project {
310                id: (*id).to_owned(),
311                local: true,
312            }),
313            ["machines", name] => match stem(name, ".applied.toml") {
314                Some(machine_id) => Some(Self::Applied { machine_id }),
315                None => stem(name, ".toml").map(|machine_id| Self::Machine { machine_id }),
316            },
317            _ => None,
318        }
319    }
320}
321
322/// A parsed store file of any kind.
323#[derive(Debug, Clone)]
324pub enum StoreDocument {
325    /// Boxed: a server is several times larger than the other kinds.
326    Server(Box<TomlDocument<Server>>),
327    Secrets(TomlDocument<SecretCatalog>),
328    Clients(TomlDocument<ClientPrefsFile>),
329    Settings(TomlDocument<Settings>),
330    Sources(TomlDocument<SourcesFile>),
331    Catalogs(TomlDocument<CatalogsFile>),
332    SkillMeta(TomlDocument<SkillMeta>),
333    Project(TomlDocument<ProjectManifest>),
334    Machine(TomlDocument<MachineOverlay>),
335    Applied(TomlDocument<AppliedRecord>),
336}
337
338impl StoreDocument {
339    /// Parses `text` as the kind of `file`.
340    pub fn parse(file: &StoreFile, text: &str) -> Result<Self, Diagnostic> {
341        Ok(match file {
342            StoreFile::Server { .. } => Self::Server(Box::new(TomlDocument::parse(text)?)),
343            StoreFile::Secrets => Self::Secrets(TomlDocument::parse(text)?),
344            StoreFile::Clients => Self::Clients(TomlDocument::parse(text)?),
345            StoreFile::Settings => Self::Settings(TomlDocument::parse(text)?),
346            StoreFile::Sources => Self::Sources(TomlDocument::parse(text)?),
347            StoreFile::Catalogs => Self::Catalogs(TomlDocument::parse(text)?),
348            StoreFile::SkillMeta { .. } => Self::SkillMeta(TomlDocument::parse(text)?),
349            StoreFile::Project { .. } => Self::Project(TomlDocument::parse(text)?),
350            StoreFile::Machine { .. } => Self::Machine(TomlDocument::parse(text)?),
351            StoreFile::Applied { .. } => Self::Applied(TomlDocument::parse(text)?),
352        })
353    }
354
355    /// Validates against the rules for `file`. `shared_project_id` is the id
356    /// of the sibling `project.toml`, when there is one; it is only read for
357    /// `project.local.toml`.
358    pub fn validate(&self, file: &StoreFile, shared_project_id: Option<&str>) -> Diagnostics {
359        let name = |file: &StoreFile| match file {
360            StoreFile::Server { id }
361            | StoreFile::SkillMeta { id }
362            | StoreFile::Project { id, .. } => Some(id.clone()),
363            StoreFile::Machine { machine_id } | StoreFile::Applied { machine_id } => {
364                Some(machine_id.clone())
365            }
366            StoreFile::Secrets
367            | StoreFile::Clients
368            | StoreFile::Settings
369            | StoreFile::Sources
370            | StoreFile::Catalogs => None,
371        };
372        let name = name(file);
373        let name = name.as_deref();
374        match self {
375            Self::Server(doc) => doc.value().validate(name),
376            Self::Secrets(doc) => doc.value().validate(),
377            Self::Clients(doc) => doc.value().validate(),
378            Self::Settings(doc) => doc.value().validate(),
379            Self::Sources(doc) => doc.value().validate(),
380            Self::Catalogs(doc) => doc.value().validate(),
381            Self::SkillMeta(doc) => doc.value().validate(name),
382            Self::Project(doc) => {
383                let local = matches!(file, StoreFile::Project { local: true, .. });
384                let layer = if local {
385                    ManifestLayer::Local {
386                        shared_id: shared_project_id,
387                    }
388                } else {
389                    ManifestLayer::Shared
390                };
391                doc.value().validate(layer, name)
392            }
393            Self::Machine(doc) => doc.value().validate(name),
394            Self::Applied(doc) => doc.value().validate(name),
395        }
396    }
397
398    /// Serializes back to text, keeping comments, formatting and unknown keys.
399    pub fn to_text(&self) -> Result<String, CoreError> {
400        match self {
401            Self::Server(doc) => doc.to_text(),
402            Self::Secrets(doc) => doc.to_text(),
403            Self::Clients(doc) => doc.to_text(),
404            Self::Settings(doc) => doc.to_text(),
405            Self::Sources(doc) => doc.to_text(),
406            Self::Catalogs(doc) => doc.to_text(),
407            Self::SkillMeta(doc) => doc.to_text(),
408            Self::Project(doc) => doc.to_text(),
409            Self::Machine(doc) => doc.to_text(),
410            Self::Applied(doc) => doc.to_text(),
411        }
412    }
413}
414
415/// Parses and validates one store file. A parse failure is the only
416/// diagnostic when the text does not load.
417pub fn validate_store_file(
418    file: &StoreFile,
419    text: &str,
420    shared_project_id: Option<&str>,
421) -> Diagnostics {
422    match StoreDocument::parse(file, text) {
423        Ok(doc) => doc.validate(file, shared_project_id),
424        Err(diagnostic) => {
425            let mut diagnostics = Diagnostics::new();
426            diagnostics.push(diagnostic);
427            diagnostics
428        }
429    }
430}