Skip to main content

cimmodel/
schema_source.rs

1//! Where a family's class table comes from.
2//!
3//! By default it is the table `cimgen` generated. With the `dynamic-schema`
4//! feature, an ENTSO-E RDFS directory can supply it instead, so a new profile
5//! version is a data load rather than a recompile.
6//!
7//! Resolution order, highest first:
8//!
9//! 1. [`load_from`] — an explicit call, for libraries and tests
10//! 2. `CIMOXIDE_PROFILES` — for the CLI, the servers and the Python bindings.
11//!    It lists directories, separated as in `PATH`, searched for profile files
12//!    that declare themselves a family's vocabulary
13//!    ([`cimschema::profile_file::Pool`]); a family it holds none of keeps its
14//!    generated table
15//! 3. the generated table
16//!
17//! A directory that is missing or fails to parse falls back to the generated
18//! table **with a warning**. Silently serving a stale schema because a path had
19//! a typo is the worst outcome available here.
20
21use crate::base::Schema;
22
23/// Resolve the schema for a family.
24///
25/// `generated` is the table `cimgen` emitted, used unless something overrides it.
26pub fn resolve(family: &'static str, generated: &'static Schema) -> &'static Schema {
27    #[cfg(feature = "dynamic-schema")]
28    {
29        dynamic::resolve(family, generated)
30    }
31    #[cfg(not(feature = "dynamic-schema"))]
32    {
33        let _ = family;
34        generated
35    }
36}
37
38#[cfg(feature = "dynamic-schema")]
39pub use dynamic::{
40    PROFILES_ENV, SchemaError, family_of_dir, load_from, load_pool_table, load_table,
41};
42
43#[cfg(feature = "dynamic-schema")]
44mod dynamic {
45    use std::collections::HashMap;
46    use std::path::{Path, PathBuf};
47    use std::sync::atomic::{AtomicBool, Ordering};
48    use std::sync::{Mutex, OnceLock};
49
50    use cimschema::family::{self, Family};
51    use cimschema::model::{CimAttribute, CimSpecification};
52
53    use crate::base::{AttrDef, AttrKind, ClassDef, EnumDef, EnumValueDef, Schema};
54
55    pub use cimschema::profile_file::PROFILES_ENV;
56    use cimschema::profile_file::{Pool, Role};
57
58    #[derive(Debug)]
59    pub enum SchemaError {
60        /// The registry was already built, so this load would have been ignored.
61        TooLate,
62        /// A table was already loaded for this family.
63        AlreadyLoaded,
64        /// No family with this id.
65        UnknownFamily(String),
66        Parse(String),
67    }
68
69    impl std::fmt::Display for SchemaError {
70        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71            match self {
72                Self::TooLate => write!(
73                    f,
74                    "the type registry is already built; load the schema before decoding"
75                ),
76                Self::AlreadyLoaded => write!(f, "a schema is already loaded for this family"),
77                Self::UnknownFamily(id) => write!(f, "unknown family: {id}"),
78                Self::Parse(e) => write!(f, "{e}"),
79            }
80        }
81    }
82
83    impl std::error::Error for SchemaError {}
84
85    fn explicit() -> &'static Mutex<HashMap<&'static str, &'static Schema>> {
86        static E: OnceLock<Mutex<HashMap<&'static str, &'static Schema>>> = OnceLock::new();
87        E.get_or_init(|| Mutex::new(HashMap::new()))
88    }
89
90    /// Set once `resolve` has run, so a late [`load_from`] can report that it
91    /// would have had no effect instead of silently doing nothing.
92    static RESOLVED: AtomicBool = AtomicBool::new(false);
93
94    /// Load a family's class table from a directory of RDFS vocabularies.
95    ///
96    /// Takes precedence over `CIMOXIDE_PROFILES`. Must be called before the
97    /// first decode: the registry is memoized, so afterwards this returns
98    /// [`SchemaError::TooLate`] rather than being quietly ignored.
99    pub fn load_from(family_id: &str, dir: &Path) -> Result<(), SchemaError> {
100        let family = family::by_id(family_id)
101            .ok_or_else(|| SchemaError::UnknownFamily(family_id.to_string()))?;
102        if RESOLVED.load(Ordering::SeqCst) {
103            return Err(SchemaError::TooLate);
104        }
105        let classes = load_table(family.id, dir)?;
106        let mut map = explicit().lock().unwrap();
107        if map.contains_key(family.id) {
108            return Err(SchemaError::AlreadyLoaded);
109        }
110        map.insert(family.id, classes);
111        Ok(())
112    }
113
114    pub(super) fn resolve(family_id: &'static str, generated: &'static Schema) -> &'static Schema {
115        RESOLVED.store(true, Ordering::SeqCst);
116
117        if let Some(classes) = explicit().lock().unwrap().get(family_id) {
118            return classes;
119        }
120
121        let Some(pool) = Pool::from_env() else {
122            return generated;
123        };
124        let Some(family) = family::by_id(family_id) else {
125            return generated;
126        };
127        let files = pool.files(family, Role::Vocabulary);
128        if files.is_empty() {
129            return generated;
130        }
131        match load_files(family, &files) {
132            Ok(classes) => classes,
133            Err(e) => {
134                eprintln!(
135                    "warning: {PROFILES_ENV} set but the {family_id} schema could not be \
136                     loaded ({e}); falling back to the generated class table"
137                );
138                generated
139            }
140        }
141    }
142
143    /// Which family's vocabularies an RDFS directory holds, by what the files
144    /// declare (see [`cimschema::profile_file`]): `None` when it holds neither
145    /// family's, or both.
146    pub fn family_of_dir(dir: &Path) -> Option<&'static Family> {
147        match cimschema::profile_file::families_in(dir, cimschema::profile_file::Role::Vocabulary)
148            .as_slice()
149        {
150            [family] => Some(family),
151            _ => None,
152        }
153    }
154
155    /// The files in `dir` that declare themselves `family`'s vocabulary.
156    fn vocabulary(dir: &Path, family: &Family) -> Vec<PathBuf> {
157        cimschema::profile_file::in_dir(dir, family, cimschema::profile_file::Role::Vocabulary)
158    }
159
160    /// Build a family's class table from RDFS without installing it.
161    ///
162    /// Useful for inspecting what a schema directory would produce, and for
163    /// checking it against the generated table.
164    pub fn load_table(family_id: &str, dir: &Path) -> Result<&'static Schema, SchemaError> {
165        let family = family::by_id(family_id)
166            .ok_or_else(|| SchemaError::UnknownFamily(family_id.to_string()))?;
167        load_family(family, dir)
168    }
169
170    fn load_family(family: &'static Family, dir: &Path) -> Result<&'static Schema, SchemaError> {
171        // The files that declare themselves the family's, so a directory
172        // holding both families' vocabularies serves each its own.
173        let files = vocabulary(dir, family);
174        if files.is_empty() {
175            return Err(SchemaError::Parse(format!(
176                "no {} vocabulary in {}",
177                family.id,
178                dir.display()
179            )));
180        }
181        load_files(family, &files)
182    }
183
184    /// Build a family's class table from the files a [`Pool`] found, without
185    /// installing it: what `CIMOXIDE_PROFILES` would load.
186    pub fn load_pool_table(family_id: &str, pool: &Pool) -> Result<&'static Schema, SchemaError> {
187        let family = family::by_id(family_id)
188            .ok_or_else(|| SchemaError::UnknownFamily(family_id.to_string()))?;
189        load_files(family, &pool.files(family, Role::Vocabulary))
190    }
191
192    fn load_files(
193        family: &'static Family,
194        files: &[PathBuf],
195    ) -> Result<&'static Schema, SchemaError> {
196        if files.is_empty() {
197            return Err(SchemaError::Parse(format!("no {} vocabulary", family.id)));
198        }
199        let spec = cimschema::import::import_schema_paths(files, family, false)
200            .map_err(|e| SchemaError::Parse(e.to_string()))?;
201        Ok(build(&spec))
202    }
203
204    /// Interns schema strings so they satisfy the `&'static` signatures the
205    /// element trait and registry require. Bounded by schema size and leaked
206    /// once per process.
207    #[derive(Default)]
208    struct Interner {
209        seen: HashMap<String, &'static str>,
210    }
211
212    impl Interner {
213        fn intern(&mut self, s: &str) -> &'static str {
214            if let Some(v) = self.seen.get(s) {
215                return v;
216            }
217            let leaked: &'static str = Box::leak(s.to_string().into_boxed_str());
218            self.seen.insert(s.to_string(), leaked);
219            leaked
220        }
221
222        fn intern_all(&mut self, items: &[String]) -> &'static [&'static str] {
223            let v: Vec<&'static str> = items.iter().map(|s| self.intern(s)).collect();
224            Vec::leak(v)
225        }
226    }
227
228    // Classification, ranges, datatypes and namespaces come from
229    // `cimschema::table`, which `cimgen::generator::classes_gen` calls too; the
230    // `runtime_table_matches_generated` tests check the rendering on top.
231    fn attr_kind(a: &CimAttribute) -> AttrKind {
232        match cimschema::table::attr_kind(a) {
233            cimschema::table::Kind::Literal => AttrKind::Literal,
234            cimschema::table::Kind::Association => AttrKind::Association,
235            cimschema::table::Kind::Enum => AttrKind::Enum,
236        }
237    }
238
239    fn build(spec: &CimSpecification) -> &'static Schema {
240        // Sorted key order, because the index in this vector is the class id
241        // that `super_class` refers to.
242        let mut ids: Vec<&String> = spec.types.keys().collect();
243        ids.sort();
244        let index_of: HashMap<&str, usize> = ids
245            .iter()
246            .enumerate()
247            .map(|(i, id)| (id.as_str(), i))
248            .collect();
249
250        let mut interner = Interner::default();
251        let mut out: Vec<ClassDef> = Vec::with_capacity(ids.len());
252
253        for id in &ids {
254            let t = &spec.types[*id];
255            let attrs: Vec<AttrDef> = t
256                .attributes
257                .iter()
258                .map(|a| AttrDef {
259                    id: interner.intern(&a.id),
260                    ns: interner.intern(&a.namespace),
261                    kind: attr_kind(a),
262                    range: interner.intern(cimschema::table::attr_range(a)),
263                    is_list: a.is_list,
264                    used: a.is_association_used,
265                    xsd: cimschema::table::xsd_type(a),
266                    value_ns: interner.intern(cimschema::table::value_namespace(spec, a)),
267                    origins: interner.intern_all(&a.origins),
268                    comment: interner.intern(&a.comment),
269                })
270                .collect();
271
272            let qualified = format!("{}{}", spec.family.type_prefix, t.id);
273            out.push(ClassDef {
274                ns: interner.intern(&t.namespace),
275                local: interner.intern(&t.id),
276                qualified: interner.intern(&qualified),
277                super_class: index_of.get(t.super_type.as_str()).copied(),
278                concrete: !t.concrete_in.is_empty(),
279                attrs: Vec::leak(attrs),
280                origins: interner.intern_all(&t.origins),
281                comment: interner.intern(&t.comment),
282            });
283        }
284
285        let pairs = |interner: &mut Interner,
286                     v: Vec<(&str, &str)>|
287         -> &'static [(&'static str, &'static str)] {
288            Vec::leak(
289                v.into_iter()
290                    .map(|(a, b)| (interner.intern(a), interner.intern(b)))
291                    .collect(),
292            )
293        };
294        let profiles = pairs(&mut interner, cimschema::table::profile_uris(spec));
295        let namespaces = pairs(&mut interner, cimschema::table::namespaces(spec));
296        let enums: Vec<EnumDef> = cimschema::table::enums(spec)
297            .into_iter()
298            .map(|e| EnumDef {
299                ns: interner.intern(&e.namespace),
300                local: interner.intern(&e.id),
301                comment: interner.intern(&e.comment),
302                values: Vec::leak(
303                    e.values
304                        .iter()
305                        .map(|v| EnumValueDef {
306                            id: interner.intern(&v.id),
307                            comment: interner.intern(&v.comment),
308                        })
309                        .collect(),
310                ),
311            })
312            .collect();
313        Box::leak(Box::new(Schema {
314            classes: Vec::leak(out),
315            profiles,
316            namespaces,
317            enums: Vec::leak(enums),
318        }))
319    }
320}