Skip to main content

brep_plm/
catalog.rs

1//! The catalog rules: how a category's schema is inherited, what shape the
2//! tree may take, and whether a value fits an attribute.
3//!
4//! Pure functions over the category list, so the store can call them INSIDE
5//! its locked write — the one place a rule cannot be raced past.
6//!
7//! # The rules
8//!
9//! * A category's **effective schema** is its ancestors' attributes, root
10//!   first, then its own.
11//! * A child may ADD attributes but never redefine one an ancestor defines.
12//!   [`check_tree`] enforces that in both directions: a parent cannot gain a
13//!   key a descendant already has, either.
14//! * The tree has no cycles, and every parent exists.
15//! * A value is checked against its attribute's type when it is WRITTEN.
16//!   Whether the set is COMPLETE — every required key present — is checked
17//!   only at release ([`release_problems`]), because a draft may be unfinished.
18
19use std::collections::BTreeSet;
20
21use serde::Serialize;
22use serde_json::Value;
23
24use crate::model::{AttributeDef, AttributeKind, Category, Part};
25use crate::Error;
26
27/// The deepest a chain of categories may go. Deep enough for any real
28/// catalog; small enough that a walk over a corrupted file stops.
29pub const MAX_DEPTH: usize = 32;
30
31/// The category `id`, compared without regard to ASCII case.
32pub fn find<'a>(categories: &'a [Category], id: &str) -> Option<&'a Category> {
33    let id = id.trim();
34    if id.is_empty() {
35        return None;
36    }
37    categories.iter().find(|c| c.id.eq_ignore_ascii_case(id))
38}
39
40/// `id` and its ancestors, ROOT FIRST. Refuses a missing parent and a cycle.
41pub fn chain<'a>(categories: &'a [Category], id: &str) -> Result<Vec<&'a Category>, Error> {
42    let mut out: Vec<&Category> = Vec::new();
43    let mut current = id.to_string();
44    loop {
45        let category = find(categories, &current).ok_or_else(|| {
46            if out.is_empty() {
47                Error::not_found(format!("category '{current}'"))
48            } else {
49                Error::conflict(format!(
50                    "category '{}' names a parent '{current}' that does not exist",
51                    out.last().expect("not empty").id
52                ))
53            }
54        })?;
55        if out.iter().any(|seen| seen.id == category.id) {
56            return Err(Error::conflict(format!(
57                "category '{}' would be its own ancestor",
58                category.id
59            )));
60        }
61        if out.len() >= MAX_DEPTH {
62            return Err(Error::conflict(format!(
63                "categories nest at most {MAX_DEPTH} deep"
64            )));
65        }
66        out.push(category);
67        if category.parent.trim().is_empty() {
68            break;
69        }
70        current = category.parent.clone();
71    }
72    out.reverse();
73    Ok(out)
74}
75
76/// One attribute of an effective schema, and which category defines it.
77#[derive(Debug, Clone, Serialize)]
78pub struct Effective {
79    #[serde(flatten)]
80    pub def: AttributeDef,
81    /// The id of the category that defines it — the category itself or an
82    /// ancestor.
83    pub from: String,
84}
85
86/// Every attribute a part in `id` can carry, ancestors' first.
87pub fn schema(categories: &[Category], id: &str) -> Result<Vec<Effective>, Error> {
88    Ok(chain(categories, id)?
89        .into_iter()
90        .flat_map(|category| {
91            category.attributes.iter().map(move |def| Effective {
92                def: def.clone(),
93                from: category.id.clone(),
94            })
95        })
96        .collect())
97}
98
99/// `id` and every category beneath it, as lower-case ids.
100pub fn descendants(categories: &[Category], id: &str) -> BTreeSet<String> {
101    let mut out = BTreeSet::new();
102    let Some(root) = find(categories, id) else {
103        return out;
104    };
105    let mut frontier = vec![root.id.to_ascii_lowercase()];
106    while let Some(next) = frontier.pop() {
107        if !out.insert(next.clone()) {
108            continue; // a cycle in a hand-edited file; stop, don't loop
109        }
110        for child in categories.iter().filter(|c| c.parent.eq_ignore_ascii_case(&next)) {
111            frontier.push(child.id.to_ascii_lowercase());
112        }
113    }
114    out
115}
116
117/// "Fasteners / Screws" — the names from the root down to `id`.
118pub fn path_name(categories: &[Category], id: &str) -> String {
119    match chain(categories, id) {
120        Ok(chain) => chain.iter().map(|c| c.name.as_str()).collect::<Vec<_>>().join(" / "),
121        Err(_) => String::new(),
122    }
123}
124
125/// Whether a key is one a category may define: lower-case letters, digits,
126/// `_` and `-`, starting with a letter.
127fn usable_key(key: &str) -> bool {
128    key.chars().next().is_some_and(|c| c.is_ascii_lowercase())
129        && key
130            .chars()
131            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-')
132}
133
134/// A category id follows the part-type id rule: letters, digits, `-`, `_`,
135/// stored lower-case.
136pub fn normalize_id(id: &str) -> Result<String, Error> {
137    let id = id.trim().to_ascii_lowercase();
138    if id.is_empty() || !id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
139        return Err(Error::bad_request(
140            "a category id is letters, digits, '-' and '_'",
141        ));
142    }
143    Ok(id)
144}
145
146/// Tidy and check one category's OWN attribute list: keys lower-case and
147/// unique, every attribute named, every enum with at least one distinct value.
148pub fn check_definitions(defs: Vec<AttributeDef>) -> Result<Vec<AttributeDef>, Error> {
149    let mut out: Vec<AttributeDef> = Vec::with_capacity(defs.len());
150    for mut def in defs {
151        def.key = def.key.trim().to_ascii_lowercase();
152        if matches!(def.key.as_str(), "has_geometry" | "has_thumbnail") {
153            return Err(Error::bad_request(format!("{} is a built-in read-only attribute", def.key)));
154        }
155        if !usable_key(&def.key) {
156            return Err(Error::bad_request(format!(
157                "'{}' is not a usable attribute key — start with a letter; then letters, digits, '_' and '-'",
158                def.key
159            )));
160        }
161        def.name = def.name.trim().to_string();
162        if def.name.is_empty() {
163            def.name = def.key.clone();
164        }
165        if out.iter().any(|d| d.key == def.key) {
166            return Err(Error::bad_request(format!("attribute '{}' is defined twice", def.key)));
167        }
168        match &mut def.kind {
169            AttributeKind::Number { unit } => *unit = unit.trim().to_string(),
170            AttributeKind::Enum { values } => {
171                let mut tidy: Vec<String> = Vec::new();
172                for value in values.iter() {
173                    let value = value.trim();
174                    if value.is_empty() {
175                        continue;
176                    }
177                    if tidy.iter().any(|v| v.eq_ignore_ascii_case(value)) {
178                        return Err(Error::bad_request(format!(
179                            "attribute '{}' lists '{value}' twice",
180                            def.key
181                        )));
182                    }
183                    tidy.push(value.to_string());
184                }
185                if tidy.is_empty() {
186                    return Err(Error::bad_request(format!(
187                        "attribute '{}' is a list of values and needs at least one",
188                        def.key
189                    )));
190                }
191                *values = tidy;
192            }
193            AttributeKind::Text | AttributeKind::Bool => {}
194        }
195        out.push(def);
196    }
197    Ok(out)
198}
199
200/// Check the WHOLE tree after a change: every parent exists, no cycle, no
201/// category deeper than [`MAX_DEPTH`], and no attribute key defined twice
202/// along any root-to-leaf chain. Checking every chain is what makes the
203/// no-override rule hold in both directions — a child cannot redefine its
204/// parent's key, and a parent cannot gain a key a child already defines.
205pub fn check_tree(categories: &[Category]) -> Result<(), Error> {
206    for category in categories {
207        let chain = chain(categories, &category.id)?;
208        let mut owner: Vec<(&str, &str)> = Vec::new();
209        for link in &chain {
210            for def in &link.attributes {
211                if let Some((_, first)) = owner.iter().find(|(key, _)| *key == def.key) {
212                    return Err(Error::conflict(format!(
213                        "attribute '{}' is defined by '{first}' and again by '{}' — a category inherits its parent's attributes and cannot redefine one",
214                        def.key, link.id
215                    )));
216                }
217                owner.push((&def.key, &link.id));
218            }
219        }
220    }
221    Ok(())
222}
223
224/// Check `value` against `def` and return what to store: `None` to clear the
225/// attribute (a JSON `null` or an empty string), else the value in its
226/// canonical form. The browser sends form text, so a number may arrive as
227/// `"12.5"` and a flag as `"true"`; an enum value matches without regard to
228/// case and is stored in the spelling the schema lists.
229pub fn check_value(def: &AttributeDef, value: &Value) -> Result<Option<Value>, String> {
230    if value.is_null() || value.as_str().is_some_and(|s| s.trim().is_empty()) {
231        return Ok(None);
232    }
233    match &def.kind {
234        AttributeKind::Text => match value {
235            Value::String(text) => Ok(Some(Value::String(text.trim().to_string()))),
236            other => Err(format!("{} takes text, not {other}", def.name)),
237        },
238        AttributeKind::Number { .. } => {
239            let number = match value {
240                Value::Number(n) => n.as_f64(),
241                Value::String(text) => text.trim().parse::<f64>().ok(),
242                _ => None,
243            };
244            match number.filter(|n| n.is_finite()) {
245                // Keep integers integral: 12 is stored as 12, not 12.0.
246                Some(n) if n.fract() == 0.0 && n.abs() < 9.0e15 => Ok(Some(Value::from(n as i64))),
247                Some(n) => Ok(serde_json::Number::from_f64(n).map(Value::Number)),
248                None => Err(format!("{} takes a number, not {value}", def.name)),
249            }
250        }
251        AttributeKind::Bool => match value {
252            Value::Bool(b) => Ok(Some(Value::Bool(*b))),
253            Value::String(text) => match text.trim().to_ascii_lowercase().as_str() {
254                "true" | "yes" => Ok(Some(Value::Bool(true))),
255                "false" | "no" => Ok(Some(Value::Bool(false))),
256                _ => Err(format!("{} takes yes or no, not {value}", def.name)),
257            },
258            other => Err(format!("{} takes yes or no, not {other}", def.name)),
259        },
260        AttributeKind::Enum { values } => {
261            let text = value.as_str().map(str::trim).unwrap_or_default();
262            match values.iter().find(|v| v.eq_ignore_ascii_case(text)) {
263                Some(canonical) => Ok(Some(Value::String(canonical.clone()))),
264                None => Err(format!("{} is one of {}, not {value}", def.name, values.join(", "))),
265            }
266        }
267    }
268}
269
270/// Why `part` cannot release, as far as its catalog values go: every required
271/// attribute of its category has a value, and every value its category
272/// defines still fits (an administrator may have changed an attribute's type
273/// since it was written). An uncategorized part has no schema to check.
274pub fn release_problems(categories: &[Category], part: &Part) -> Vec<String> {
275    if part.category.is_empty() { return Vec::new(); }
276    let schema = match schema(categories, &part.category) {
277        Ok(schema) => schema,
278        Err(error) => return vec![error.to_string()],
279    };
280    let mut problems = Vec::new();
281    for Effective { def, .. } in &schema {
282        match part.attributes.get(&def.key) {
283            None => {
284                if def.required {
285                    problems.push(format!("{} is required", def.name));
286                }
287            }
288            Some(value) => match check_value(def, value) {
289                Ok(Some(_)) => {}
290                Ok(None) => {
291                    if def.required {
292                        problems.push(format!("{} is required", def.name));
293                    }
294                }
295                Err(message) => problems.push(message),
296            },
297        }
298    }
299    problems
300}
301
302/// Merge `changes` into a part's `values`, checking each written value against
303/// the effective schema of `category`. A `null` or empty value CLEARS its key
304/// and is always allowed — including a key the schema no longer defines,
305/// which is how an inert value left behind by a category move is removed.
306/// Setting any other key needs the part to be in a category that defines it.
307pub fn apply_values(
308    categories: &[Category],
309    category: &str,
310    values: &mut std::collections::BTreeMap<String, Value>,
311    changes: &serde_json::Map<String, Value>,
312) -> Result<(), Error> {
313    let schema = if category.is_empty() { Vec::new() } else { schema(categories, category)? };
314    for (key, value) in changes {
315        let key = key.trim().to_ascii_lowercase();
316        let clearing = value.is_null() || value.as_str().is_some_and(|s| s.trim().is_empty());
317        if clearing {
318            values.remove(&key);
319            continue;
320        }
321        let Some(Effective { def, .. }) = schema.iter().find(|e| e.def.key == key) else {
322            return Err(Error::bad_request(if schema.is_empty() && find(categories, category).is_none() {
323                format!("'{key}' cannot be set — choose a category for the part first")
324            } else {
325                format!(
326                    "'{key}' is not an attribute of category '{}'",
327                    path_name(categories, category)
328                )
329            }));
330        };
331        match check_value(def, value).map_err(Error::bad_request)? {
332            Some(stored) => {
333                values.insert(key, stored);
334            }
335            None => {
336                values.remove(&key);
337            }
338        }
339    }
340    Ok(())
341}
342
343/// Tags, trimmed, without empties, and without a repeat that differs only in
344/// case. The first spelling wins.
345pub fn tidy_tags(tags: impl IntoIterator<Item = String>) -> Vec<String> {
346    let mut out: Vec<String> = Vec::new();
347    for tag in tags {
348        let tag = tag.trim().to_string();
349        if !tag.is_empty() && !out.iter().any(|t| t.eq_ignore_ascii_case(&tag)) {
350            out.push(tag);
351        }
352    }
353    out
354}
355