Skip to main content

xtce_model/
db.rs

1//! The loaded telemetry database.
2
3use std::path::{Path, PathBuf};
4
5use crate::commands::MetaCommand;
6use crate::containers::{Container, Entry, SpaceSystem};
7use crate::error::XtceError;
8use crate::ids::{ContainerId, MetaCommandId, ParamId, SpaceSystemId, Span, TypeId};
9use crate::intern::{FxHashMap, Interner, NameId};
10use crate::lower::Lowering;
11use crate::types::{Parameter, ParameterType, TypeKind};
12use crate::xml::Dom;
13
14/// An XTCE construct that was modelled structurally but cannot be decoded.
15///
16/// Recording these instead of failing the load is what lets `xtce info` succeed on every
17/// real mission database while still telling the truth about coverage. The corresponding
18/// `XtceError::Unsupported` is raised by the decoder, at the point a value actually depends
19/// on the construct.
20#[derive(Clone, Debug)]
21pub struct Unsupported {
22    /// The element that is out of scope.
23    pub element: String,
24    /// Where it appeared in the document.
25    pub path: String,
26    /// Why it could not be modelled for decoding.
27    pub reason: &'static str,
28}
29
30/// A loaded XTCE telemetry database.
31///
32/// Every entity lives in a flat arena addressed by a typed index; see [`crate::ids`]. The
33/// database is immutable once built, and `Send + Sync`, so one instance can be shared by any
34/// number of decoding threads.
35pub struct XtceDb {
36    interner: Interner,
37    space_systems: Vec<SpaceSystem>,
38    types: Vec<ParameterType>,
39    parameters: Vec<Parameter>,
40    containers: Vec<Container>,
41    entries: Vec<Entry>,
42    root_containers: Vec<ContainerId>,
43    meta_commands: Vec<MetaCommand>,
44    /// Bytes behind every `EntryKind::FixedValue`, in one arena.
45    fixed_values: Vec<u8>,
46
47    type_by_qualified: FxHashMap<NameId, TypeId>,
48    type_by_leaf: FxHashMap<NameId, TypeId>,
49    param_by_qualified: FxHashMap<NameId, ParamId>,
50    param_by_leaf: FxHashMap<NameId, ParamId>,
51    container_by_qualified: FxHashMap<NameId, ContainerId>,
52    container_by_leaf: FxHashMap<NameId, ContainerId>,
53
54    unsupported: Vec<Unsupported>,
55    source: Option<PathBuf>,
56    xmlns: Option<String>,
57    skipped_sections: Vec<String>,
58}
59
60/// Everything [`Lowering`] produces, handed over in one struct to keep the constructor from
61/// growing a dozen positional parameters.
62pub(crate) struct Parts {
63    pub interner: Interner,
64    pub space_systems: Vec<SpaceSystem>,
65    pub types: Vec<ParameterType>,
66    pub parameters: Vec<Parameter>,
67    pub containers: Vec<Container>,
68    pub entries: Vec<Entry>,
69    pub root_containers: Vec<ContainerId>,
70    pub meta_commands: Vec<MetaCommand>,
71    pub fixed_values: Vec<u8>,
72    pub type_by_qualified: FxHashMap<NameId, TypeId>,
73    pub type_by_leaf: FxHashMap<NameId, TypeId>,
74    pub param_by_qualified: FxHashMap<NameId, ParamId>,
75    pub param_by_leaf: FxHashMap<NameId, ParamId>,
76    pub container_by_qualified: FxHashMap<NameId, ContainerId>,
77    pub container_by_leaf: FxHashMap<NameId, ContainerId>,
78    pub unsupported: Vec<Unsupported>,
79    pub xmlns: Option<String>,
80    pub skipped_sections: Vec<String>,
81}
82
83impl XtceDb {
84    pub(crate) fn assemble(parts: Parts) -> Self {
85        Self {
86            interner: parts.interner,
87            space_systems: parts.space_systems,
88            types: parts.types,
89            parameters: parts.parameters,
90            containers: parts.containers,
91            entries: parts.entries,
92            root_containers: parts.root_containers,
93            meta_commands: parts.meta_commands,
94            fixed_values: parts.fixed_values,
95            type_by_qualified: parts.type_by_qualified,
96            type_by_leaf: parts.type_by_leaf,
97            param_by_qualified: parts.param_by_qualified,
98            param_by_leaf: parts.param_by_leaf,
99            container_by_qualified: parts.container_by_qualified,
100            container_by_leaf: parts.container_by_leaf,
101            unsupported: parts.unsupported,
102            source: None,
103            xmlns: parts.xmlns,
104            skipped_sections: parts.skipped_sections,
105        }
106    }
107
108    /// Loads an XTCE document from disk.
109    ///
110    /// # Errors
111    ///
112    /// Returns [`XtceError::Io`] if the file cannot be read, and any [`XtceError`] the
113    /// parser or lowering pass produces.
114    pub fn from_path(path: impl AsRef<Path>) -> Result<Self, XtceError> {
115        let path = path.as_ref();
116        let text = std::fs::read_to_string(path).map_err(|source| XtceError::Io {
117            path: path.to_path_buf(),
118            source,
119        })?;
120        let mut db = Self::from_xml(&text)?;
121        db.source = Some(path.to_path_buf());
122        Ok(db)
123    }
124
125    /// Parses an XTCE document held in memory.
126    ///
127    /// # Errors
128    ///
129    /// Returns [`XtceError`] if the document is not well-formed XML, is not rooted at
130    /// `<SpaceSystem>`, contains an unresolvable reference, or defines cyclic container
131    /// inheritance.
132    pub fn from_xml(text: &str) -> Result<Self, XtceError> {
133        let dom = Dom::parse(text)?;
134        Lowering::new(&dom).run()
135    }
136
137    /// The file this database was loaded from, when it came from disk.
138    #[must_use]
139    pub fn source(&self) -> Option<&Path> {
140        self.source.as_deref()
141    }
142
143    /// The XML namespace declared on the root element, which identifies the XTCE version.
144    #[must_use]
145    pub fn xmlns(&self) -> Option<&str> {
146        self.xmlns.as_deref()
147    }
148
149    /// Document sections dropped during parsing because telemetry decoding never reads
150    /// them, such as `CommandMetaData`.
151    #[must_use]
152    pub fn skipped_sections(&self) -> &[String] {
153        &self.skipped_sections
154    }
155
156    /// Constructs that were modelled but cannot be decoded.
157    #[must_use]
158    pub fn unsupported(&self) -> &[Unsupported] {
159        &self.unsupported
160    }
161
162    /// The string interner backing every name in this database.
163    #[must_use]
164    pub fn interner(&self) -> &Interner {
165        &self.interner
166    }
167
168    /// Resolves an interned handle to its text.
169    #[must_use]
170    pub fn name(&self, id: NameId) -> &str {
171        self.interner.resolve(id)
172    }
173
174    /// All space systems, the root first.
175    #[must_use]
176    pub fn space_systems(&self) -> &[SpaceSystem] {
177        &self.space_systems
178    }
179
180    /// All parameter types, in document order.
181    #[must_use]
182    pub fn types(&self) -> &[ParameterType] {
183        &self.types
184    }
185
186    /// All parameters, in document order.
187    #[must_use]
188    pub fn parameters(&self) -> &[Parameter] {
189        &self.parameters
190    }
191
192    /// All containers, in document order.
193    #[must_use]
194    pub fn containers(&self) -> &[Container] {
195        &self.containers
196    }
197
198    /// The shared entry arena. Slice it with [`Container::entries`].
199    #[must_use]
200    pub fn entries(&self) -> &[Entry] {
201        &self.entries
202    }
203
204    /// Every telecommand the `<CommandMetaData>` section defines, in document order.
205    ///
206    /// Empty for a definition with no command half, which is most of them.
207    #[must_use]
208    pub fn meta_commands(&self) -> &[MetaCommand] {
209        &self.meta_commands
210    }
211
212    /// A telecommand by index.
213    #[must_use]
214    pub fn meta_command(&self, id: MetaCommandId) -> Option<&MetaCommand> {
215        self.meta_commands.get(id.index())
216    }
217
218    /// The bytes an `EntryKind::FixedValue` carries.
219    #[must_use]
220    pub fn fixed_value(&self, span: Span) -> &[u8] {
221        span.slice(&self.fixed_values)
222    }
223
224    /// Finds a telecommand by its name or by its qualified name.
225    #[must_use]
226    pub fn find_meta_command(&self, name: &str) -> Option<MetaCommandId> {
227        let wanted = self.interner.get(name)?;
228        self.meta_commands
229            .iter()
230            .position(|command| command.name == wanted || command.qualified_name == wanted)
231            .map(|index| MetaCommandId::new(u32::try_from(index).unwrap_or(u32::MAX)))
232    }
233
234    /// Containers that declare no `<BaseContainer>`, i.e. candidate decoding roots.
235    ///
236    /// Includes the roots of the command tree, which are containers like any other. See
237    /// [`Self::default_root_container`] for why the *default* root ignores them.
238    #[must_use]
239    pub fn root_containers(&self) -> &[ContainerId] {
240        &self.root_containers
241    }
242
243    /// A space system by index.
244    #[must_use]
245    pub fn space_system(&self, id: SpaceSystemId) -> Option<&SpaceSystem> {
246        self.space_systems.get(id.index())
247    }
248
249    /// A parameter by index.
250    #[must_use]
251    pub fn parameter(&self, id: ParamId) -> Option<&Parameter> {
252        self.parameters.get(id.index())
253    }
254
255    /// A parameter type by index.
256    #[must_use]
257    pub fn parameter_type(&self, id: TypeId) -> Option<&ParameterType> {
258        self.types.get(id.index())
259    }
260
261    /// A container by index.
262    #[must_use]
263    pub fn container(&self, id: ContainerId) -> Option<&Container> {
264        self.containers.get(id.index())
265    }
266
267    /// The entries of a container, as a slice of the shared arena.
268    #[must_use]
269    pub fn container_entries(&self, id: ContainerId) -> &[Entry] {
270        self.container(id)
271            .map_or(&[], |container| container.entries.slice(&self.entries))
272    }
273
274    /// The type of a parameter.
275    #[must_use]
276    pub fn type_of(&self, id: ParamId) -> Option<&ParameterType> {
277        self.parameter(id)
278            .and_then(|parameter| self.parameter_type(parameter.type_id))
279    }
280
281    /// Looks up a parameter by fully qualified name (`/Root/PKT_APID`) or, failing that, by
282    /// unqualified name.
283    #[must_use]
284    pub fn find_parameter(&self, name: &str) -> Option<ParamId> {
285        let id = self.interner.get(name)?;
286        self.param_by_qualified
287            .get(&id)
288            .or_else(|| self.param_by_leaf.get(&id))
289            .copied()
290    }
291
292    /// Looks up a container by fully qualified name or, failing that, by unqualified name.
293    #[must_use]
294    pub fn find_container(&self, name: &str) -> Option<ContainerId> {
295        let id = self.interner.get(name)?;
296        self.container_by_qualified
297            .get(&id)
298            .or_else(|| self.container_by_leaf.get(&id))
299            .copied()
300    }
301
302    /// Looks up a parameter type by fully qualified name or, failing that, by unqualified
303    /// name.
304    #[must_use]
305    pub fn find_type(&self, name: &str) -> Option<TypeId> {
306        let id = self.interner.get(name)?;
307        self.type_by_qualified
308            .get(&id)
309            .or_else(|| self.type_by_leaf.get(&id))
310            .copied()
311    }
312
313    /// The display label a boolean parameter type gives to `value`.
314    ///
315    /// XTCE calls booleans "a restricted form of enumeration", and this exposes the
316    /// `zeroStringValue` / `oneStringValue` labels. The decoder itself yields a plain
317    /// `bool`, matching the reference implementation.
318    #[must_use]
319    pub fn boolean_label(&self, id: TypeId, value: bool) -> Option<&str> {
320        let TypeKind::Boolean {
321            zero_label,
322            one_label,
323        } = self.parameter_type(id)?.kind
324        else {
325            return None;
326        };
327        let label = if value { one_label } else { zero_label }?;
328        Some(self.interner.resolve(label))
329    }
330
331    /// The container a decoder should start from when none is named.
332    ///
333    /// Prefers the conventional CCSDS root names, then falls back to the only base-less
334    /// container if the document has exactly one.
335    #[must_use]
336    pub fn default_root_container(&self) -> Option<ContainerId> {
337        for candidate in ["CCSDSPacket", "CCSDSTelemetryPacket"] {
338            if let Some(id) = self.find_container(candidate) {
339                return Some(id);
340            }
341        }
342        // Only telemetry. A command container with no `<BaseContainer>` is a root of the
343        // command tree, not a packet this would decode by default: a caller who wants one
344        // names it. Without this, adding a command half to a definition would take the
345        // default root away from the telemetry it already had.
346        let mut telemetry = self
347            .root_containers
348            .iter()
349            .filter(|id| self.container(**id).is_some_and(|c| !c.is_command));
350        match (telemetry.next(), telemetry.next()) {
351            (Some(only), None) => Some(*only),
352            _ => None,
353        }
354    }
355
356    /// Counts for reporting, computed on demand.
357    #[must_use]
358    pub fn stats(&self) -> Stats {
359        let decodable_types = self
360            .types
361            .iter()
362            .filter(|ty| !matches!(ty.kind, TypeKind::Unsupported { .. }))
363            .count();
364        Stats {
365            space_systems: self.space_systems.len(),
366            parameters: self.parameters.len(),
367            parameter_types: self.types.len(),
368            decodable_parameter_types: decodable_types,
369            containers: self.containers.len(),
370            abstract_containers: self.containers.iter().filter(|c| c.is_abstract).count(),
371            entries: self.entries.len(),
372            meta_commands: self.meta_commands.len(),
373            interned_names: self.interner.len(),
374            interned_bytes: self.interner.bytes(),
375            unsupported: self.unsupported.len(),
376        }
377    }
378}
379
380/// Summary counts for a loaded database.
381#[derive(Clone, Copy, Debug, PartialEq, Eq)]
382pub struct Stats {
383    /// Number of `SpaceSystem` nodes.
384    pub space_systems: usize,
385    /// Number of parameters.
386    pub parameters: usize,
387    /// Number of parameter types.
388    pub parameter_types: usize,
389    /// Parameter types this crate can decode.
390    pub decodable_parameter_types: usize,
391    /// Number of sequence containers.
392    pub containers: usize,
393    /// Containers marked `abstract="true"`.
394    pub abstract_containers: usize,
395    /// Total entries across all containers.
396    pub entries: usize,
397    /// Number of telecommands.
398    pub meta_commands: usize,
399    /// Distinct interned strings.
400    pub interned_names: usize,
401    /// Bytes of unique string data.
402    pub interned_bytes: usize,
403    /// Constructs modelled but not decodable.
404    pub unsupported: usize,
405}