Skip to main content

stackless_core/def/
parse.rs

1//! `stackless.toml` text → [`StackDef`].
2
3use serde::Deserialize;
4
5use super::error::DefError;
6use super::model::StackDef;
7
8impl StackDef {
9    fn normalize(mut self) -> Result<Self, DefError> {
10        for (name, mut job) in std::mem::take(&mut self.jobs) {
11            job.kind = super::model::WorkloadKind::Job;
12            if self.services.insert(name.clone(), job).is_some() {
13                return Err(DefError::Schema {
14                    message: format!("workload and job share the name {name:?}"),
15                });
16            }
17        }
18        for (name, workload) in &self.services {
19            if let Some(health) = &workload.health {
20                health.validate(name)?;
21            }
22            if workload.kind == super::model::WorkloadKind::Service && workload.health.is_none() {
23                return Err(DefError::Schema {
24                    message: format!("services.{name}.health is required for a service"),
25                });
26            }
27        }
28        Ok(self)
29    }
30
31    /// Parse definition text. Syntax errors and schema mismatches are
32    /// distinct codes: an agent fixes them differently.
33    pub fn parse(text: &str) -> Result<Self, DefError> {
34        match toml::from_str::<Self>(text) {
35            Ok(def) => def.normalize(),
36            Err(err) => Err(map_toml_error(err.to_string())),
37        }
38    }
39
40    /// Parse a definition snapshotted into an instance record.
41    ///
42    /// Older snapshots may still contain `[datastores.*]`. Strip that
43    /// section (fresh files still reject it via [`Self::parse`]) but
44    /// keep the datastore names and `${datastores.*.url}` interpolations
45    /// so resume can resolve URLs from journaled provision checkpoints.
46    pub fn parse_snapshot(text: &str) -> Result<Self, DefError> {
47        let mut value: toml::Value = match toml::from_str(text) {
48            Ok(value) => value,
49            Err(err) => return Err(map_toml_error(err.to_string())),
50        };
51        let legacy_datastores = value
52            .as_table()
53            .and_then(|table| table.get("datastores"))
54            .and_then(|section| section.as_table())
55            .map(|section| section.keys().cloned().collect())
56            .unwrap_or_default();
57        if let Some(table) = value.as_table_mut() {
58            table.remove("datastores");
59        }
60        match StackDef::deserialize(value) {
61            Ok(mut def) => {
62                def.legacy_datastores = legacy_datastores;
63                def.normalize()
64            }
65            Err(err) => Err(map_toml_error(err.to_string())),
66        }
67    }
68}
69
70fn map_toml_error(message: String) -> DefError {
71    // `stack.name` is a DnsName: invalid values fail at serde, not
72    // later in validate. Keep the stable `def.validate.name_invalid`
73    // code agents already key on.
74    if let Some(name) = dns_name_parse_failure(&message) {
75        return DefError::NameInvalid {
76            kind: "stack",
77            name,
78        };
79    }
80    // toml reports schema mismatches (unknown/missing fields,
81    // wrong types) through the same error type as syntax
82    // failures; a span into valid TOML with a serde message is
83    // a schema problem.
84    if message.contains("wanted string or table")
85        || message.contains("unknown field")
86        || message.contains("missing field")
87        || message.contains("invalid type")
88        || message.contains("unknown variant")
89        || message.contains("duplicate field")
90    {
91        DefError::Schema { message }
92    } else {
93        DefError::Syntax { message }
94    }
95}
96
97fn dns_name_parse_failure(message: &str) -> Option<String> {
98    // serde custom: `invalid DNS name "Bad_Name": must be DNS-safe …`
99    let rest = message.split("invalid DNS name ").nth(1)?;
100    let name = rest.strip_prefix('"')?.split('"').next()?;
101    Some(name.to_owned())
102}