xtce-model 0.1.1

XTCE telemetry metadata: streaming XML parser and arena-backed intermediate representation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//! The loaded telemetry database.

use std::path::{Path, PathBuf};

use crate::commands::MetaCommand;
use crate::containers::{Container, Entry, SpaceSystem};
use crate::error::XtceError;
use crate::ids::{ContainerId, MetaCommandId, ParamId, SpaceSystemId, Span, TypeId};
use crate::intern::{FxHashMap, Interner, NameId};
use crate::lower::Lowering;
use crate::types::{Parameter, ParameterType, TypeKind};
use crate::xml::Dom;

/// An XTCE construct that was modelled structurally but cannot be decoded.
///
/// Recording these instead of failing the load is what lets `xtce info` succeed on every
/// real mission database while still telling the truth about coverage. The corresponding
/// `XtceError::Unsupported` is raised by the decoder, at the point a value actually depends
/// on the construct.
#[derive(Clone, Debug)]
pub struct Unsupported {
    /// The element that is out of scope.
    pub element: String,
    /// Where it appeared in the document.
    pub path: String,
    /// Why it could not be modelled for decoding.
    pub reason: &'static str,
}

/// A loaded XTCE telemetry database.
///
/// Every entity lives in a flat arena addressed by a typed index; see [`crate::ids`]. The
/// database is immutable once built, and `Send + Sync`, so one instance can be shared by any
/// number of decoding threads.
pub struct XtceDb {
    interner: Interner,
    space_systems: Vec<SpaceSystem>,
    types: Vec<ParameterType>,
    parameters: Vec<Parameter>,
    containers: Vec<Container>,
    entries: Vec<Entry>,
    root_containers: Vec<ContainerId>,
    meta_commands: Vec<MetaCommand>,
    /// Bytes behind every `EntryKind::FixedValue`, in one arena.
    fixed_values: Vec<u8>,

    type_by_qualified: FxHashMap<NameId, TypeId>,
    type_by_leaf: FxHashMap<NameId, TypeId>,
    param_by_qualified: FxHashMap<NameId, ParamId>,
    param_by_leaf: FxHashMap<NameId, ParamId>,
    container_by_qualified: FxHashMap<NameId, ContainerId>,
    container_by_leaf: FxHashMap<NameId, ContainerId>,

    unsupported: Vec<Unsupported>,
    source: Option<PathBuf>,
    xmlns: Option<String>,
    skipped_sections: Vec<String>,
}

/// Everything [`Lowering`] produces, handed over in one struct to keep the constructor from
/// growing a dozen positional parameters.
pub(crate) struct Parts {
    pub interner: Interner,
    pub space_systems: Vec<SpaceSystem>,
    pub types: Vec<ParameterType>,
    pub parameters: Vec<Parameter>,
    pub containers: Vec<Container>,
    pub entries: Vec<Entry>,
    pub root_containers: Vec<ContainerId>,
    pub meta_commands: Vec<MetaCommand>,
    pub fixed_values: Vec<u8>,
    pub type_by_qualified: FxHashMap<NameId, TypeId>,
    pub type_by_leaf: FxHashMap<NameId, TypeId>,
    pub param_by_qualified: FxHashMap<NameId, ParamId>,
    pub param_by_leaf: FxHashMap<NameId, ParamId>,
    pub container_by_qualified: FxHashMap<NameId, ContainerId>,
    pub container_by_leaf: FxHashMap<NameId, ContainerId>,
    pub unsupported: Vec<Unsupported>,
    pub xmlns: Option<String>,
    pub skipped_sections: Vec<String>,
}

impl XtceDb {
    pub(crate) fn assemble(parts: Parts) -> Self {
        Self {
            interner: parts.interner,
            space_systems: parts.space_systems,
            types: parts.types,
            parameters: parts.parameters,
            containers: parts.containers,
            entries: parts.entries,
            root_containers: parts.root_containers,
            meta_commands: parts.meta_commands,
            fixed_values: parts.fixed_values,
            type_by_qualified: parts.type_by_qualified,
            type_by_leaf: parts.type_by_leaf,
            param_by_qualified: parts.param_by_qualified,
            param_by_leaf: parts.param_by_leaf,
            container_by_qualified: parts.container_by_qualified,
            container_by_leaf: parts.container_by_leaf,
            unsupported: parts.unsupported,
            source: None,
            xmlns: parts.xmlns,
            skipped_sections: parts.skipped_sections,
        }
    }

    /// Loads an XTCE document from disk.
    ///
    /// # Errors
    ///
    /// Returns [`XtceError::Io`] if the file cannot be read, and any [`XtceError`] the
    /// parser or lowering pass produces.
    pub fn from_path(path: impl AsRef<Path>) -> Result<Self, XtceError> {
        let path = path.as_ref();
        let text = std::fs::read_to_string(path).map_err(|source| XtceError::Io {
            path: path.to_path_buf(),
            source,
        })?;
        let mut db = Self::from_xml(&text)?;
        db.source = Some(path.to_path_buf());
        Ok(db)
    }

    /// Parses an XTCE document held in memory.
    ///
    /// # Errors
    ///
    /// Returns [`XtceError`] if the document is not well-formed XML, is not rooted at
    /// `<SpaceSystem>`, contains an unresolvable reference, or defines cyclic container
    /// inheritance.
    pub fn from_xml(text: &str) -> Result<Self, XtceError> {
        let dom = Dom::parse(text)?;
        Lowering::new(&dom).run()
    }

    /// The file this database was loaded from, when it came from disk.
    #[must_use]
    pub fn source(&self) -> Option<&Path> {
        self.source.as_deref()
    }

    /// The XML namespace declared on the root element, which identifies the XTCE version.
    #[must_use]
    pub fn xmlns(&self) -> Option<&str> {
        self.xmlns.as_deref()
    }

    /// Document sections dropped during parsing because telemetry decoding never reads
    /// them, such as `CommandMetaData`.
    #[must_use]
    pub fn skipped_sections(&self) -> &[String] {
        &self.skipped_sections
    }

    /// Constructs that were modelled but cannot be decoded.
    #[must_use]
    pub fn unsupported(&self) -> &[Unsupported] {
        &self.unsupported
    }

    /// The string interner backing every name in this database.
    #[must_use]
    pub fn interner(&self) -> &Interner {
        &self.interner
    }

    /// Resolves an interned handle to its text.
    #[must_use]
    pub fn name(&self, id: NameId) -> &str {
        self.interner.resolve(id)
    }

    /// All space systems, the root first.
    #[must_use]
    pub fn space_systems(&self) -> &[SpaceSystem] {
        &self.space_systems
    }

    /// All parameter types, in document order.
    #[must_use]
    pub fn types(&self) -> &[ParameterType] {
        &self.types
    }

    /// All parameters, in document order.
    #[must_use]
    pub fn parameters(&self) -> &[Parameter] {
        &self.parameters
    }

    /// All containers, in document order.
    #[must_use]
    pub fn containers(&self) -> &[Container] {
        &self.containers
    }

    /// The shared entry arena. Slice it with [`Container::entries`].
    #[must_use]
    pub fn entries(&self) -> &[Entry] {
        &self.entries
    }

    /// Every telecommand the `<CommandMetaData>` section defines, in document order.
    ///
    /// Empty for a definition with no command half, which is most of them.
    #[must_use]
    pub fn meta_commands(&self) -> &[MetaCommand] {
        &self.meta_commands
    }

    /// A telecommand by index.
    #[must_use]
    pub fn meta_command(&self, id: MetaCommandId) -> Option<&MetaCommand> {
        self.meta_commands.get(id.index())
    }

    /// The bytes an `EntryKind::FixedValue` carries.
    #[must_use]
    pub fn fixed_value(&self, span: Span) -> &[u8] {
        span.slice(&self.fixed_values)
    }

    /// Finds a telecommand by its name or by its qualified name.
    #[must_use]
    pub fn find_meta_command(&self, name: &str) -> Option<MetaCommandId> {
        let wanted = self.interner.get(name)?;
        self.meta_commands
            .iter()
            .position(|command| command.name == wanted || command.qualified_name == wanted)
            .map(|index| MetaCommandId::new(u32::try_from(index).unwrap_or(u32::MAX)))
    }

    /// Containers that declare no `<BaseContainer>`, i.e. candidate decoding roots.
    ///
    /// Includes the roots of the command tree, which are containers like any other. See
    /// [`Self::default_root_container`] for why the *default* root ignores them.
    #[must_use]
    pub fn root_containers(&self) -> &[ContainerId] {
        &self.root_containers
    }

    /// A space system by index.
    #[must_use]
    pub fn space_system(&self, id: SpaceSystemId) -> Option<&SpaceSystem> {
        self.space_systems.get(id.index())
    }

    /// A parameter by index.
    #[must_use]
    pub fn parameter(&self, id: ParamId) -> Option<&Parameter> {
        self.parameters.get(id.index())
    }

    /// A parameter type by index.
    #[must_use]
    pub fn parameter_type(&self, id: TypeId) -> Option<&ParameterType> {
        self.types.get(id.index())
    }

    /// A container by index.
    #[must_use]
    pub fn container(&self, id: ContainerId) -> Option<&Container> {
        self.containers.get(id.index())
    }

    /// The entries of a container, as a slice of the shared arena.
    #[must_use]
    pub fn container_entries(&self, id: ContainerId) -> &[Entry] {
        self.container(id)
            .map_or(&[], |container| container.entries.slice(&self.entries))
    }

    /// The type of a parameter.
    #[must_use]
    pub fn type_of(&self, id: ParamId) -> Option<&ParameterType> {
        self.parameter(id)
            .and_then(|parameter| self.parameter_type(parameter.type_id))
    }

    /// Looks up a parameter by fully qualified name (`/Root/PKT_APID`) or, failing that, by
    /// unqualified name.
    #[must_use]
    pub fn find_parameter(&self, name: &str) -> Option<ParamId> {
        let id = self.interner.get(name)?;
        self.param_by_qualified
            .get(&id)
            .or_else(|| self.param_by_leaf.get(&id))
            .copied()
    }

    /// Looks up a container by fully qualified name or, failing that, by unqualified name.
    #[must_use]
    pub fn find_container(&self, name: &str) -> Option<ContainerId> {
        let id = self.interner.get(name)?;
        self.container_by_qualified
            .get(&id)
            .or_else(|| self.container_by_leaf.get(&id))
            .copied()
    }

    /// Looks up a parameter type by fully qualified name or, failing that, by unqualified
    /// name.
    #[must_use]
    pub fn find_type(&self, name: &str) -> Option<TypeId> {
        let id = self.interner.get(name)?;
        self.type_by_qualified
            .get(&id)
            .or_else(|| self.type_by_leaf.get(&id))
            .copied()
    }

    /// The display label a boolean parameter type gives to `value`.
    ///
    /// XTCE calls booleans "a restricted form of enumeration", and this exposes the
    /// `zeroStringValue` / `oneStringValue` labels. The decoder itself yields a plain
    /// `bool`, matching the reference implementation.
    #[must_use]
    pub fn boolean_label(&self, id: TypeId, value: bool) -> Option<&str> {
        let TypeKind::Boolean {
            zero_label,
            one_label,
        } = self.parameter_type(id)?.kind
        else {
            return None;
        };
        let label = if value { one_label } else { zero_label }?;
        Some(self.interner.resolve(label))
    }

    /// The container a decoder should start from when none is named.
    ///
    /// Prefers the conventional CCSDS root names, then falls back to the only base-less
    /// container if the document has exactly one.
    #[must_use]
    pub fn default_root_container(&self) -> Option<ContainerId> {
        for candidate in ["CCSDSPacket", "CCSDSTelemetryPacket"] {
            if let Some(id) = self.find_container(candidate) {
                return Some(id);
            }
        }
        // Only telemetry. A command container with no `<BaseContainer>` is a root of the
        // command tree, not a packet this would decode by default: a caller who wants one
        // names it. Without this, adding a command half to a definition would take the
        // default root away from the telemetry it already had.
        let mut telemetry = self
            .root_containers
            .iter()
            .filter(|id| self.container(**id).is_some_and(|c| !c.is_command));
        match (telemetry.next(), telemetry.next()) {
            (Some(only), None) => Some(*only),
            _ => None,
        }
    }

    /// Counts for reporting, computed on demand.
    #[must_use]
    pub fn stats(&self) -> Stats {
        let decodable_types = self
            .types
            .iter()
            .filter(|ty| !matches!(ty.kind, TypeKind::Unsupported { .. }))
            .count();
        Stats {
            space_systems: self.space_systems.len(),
            parameters: self.parameters.len(),
            parameter_types: self.types.len(),
            decodable_parameter_types: decodable_types,
            containers: self.containers.len(),
            abstract_containers: self.containers.iter().filter(|c| c.is_abstract).count(),
            entries: self.entries.len(),
            meta_commands: self.meta_commands.len(),
            interned_names: self.interner.len(),
            interned_bytes: self.interner.bytes(),
            unsupported: self.unsupported.len(),
        }
    }
}

/// Summary counts for a loaded database.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Stats {
    /// Number of `SpaceSystem` nodes.
    pub space_systems: usize,
    /// Number of parameters.
    pub parameters: usize,
    /// Number of parameter types.
    pub parameter_types: usize,
    /// Parameter types this crate can decode.
    pub decodable_parameter_types: usize,
    /// Number of sequence containers.
    pub containers: usize,
    /// Containers marked `abstract="true"`.
    pub abstract_containers: usize,
    /// Total entries across all containers.
    pub entries: usize,
    /// Number of telecommands.
    pub meta_commands: usize,
    /// Distinct interned strings.
    pub interned_names: usize,
    /// Bytes of unique string data.
    pub interned_bytes: usize,
    /// Constructs modelled but not decodable.
    pub unsupported: usize,
}