Skip to main content

opcua_kit/commissioning/
report.rs

1use std::collections::BTreeMap;
2
3use serde::Serialize;
4
5use super::{Contract, Error, Evidence, Expected, NodeId, Observed, Snapshot, Unit};
6
7/// Result of a required check, also used for the overall decision.
8#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
9#[serde(rename_all = "lowercase")]
10pub enum Outcome {
11    /// The current observation satisfies the expectation.
12    Matched,
13    /// The current observation contradicts the expectation.
14    Mismatch,
15    /// The current observation is missing, has non-Good status or lacks unit identity.
16    Unverified,
17}
18
19/// OPC UA attribute or property evaluated by a commissioning check.
20#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
21pub enum Attribute {
22    /// Declared DataType NodeId.
23    DataType,
24    /// Declared ValueRank integer.
25    ValueRank,
26    /// EngineeringUnits property of the signal.
27    EngineeringUnits,
28}
29
30/// Expected or observed metadata in a finding.
31#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
32#[serde(untagged)]
33pub enum AttributeValue {
34    /// Namespace-qualified DataType identity.
35    DataType(NodeId),
36    /// Exact OPC UA ValueRank.
37    ValueRank(i32),
38    /// Namespace-qualified identity in an EngineeringUnits property.
39    EngineeringUnits(Unit),
40}
41
42/// Comparison of one named signal's required attribute.
43#[derive(Debug, Serialize)]
44#[serde(rename_all = "camelCase")]
45pub struct Finding {
46    /// Contract's signal name.
47    pub name: String,
48    /// Stable namespace-qualified signal identifier.
49    pub node: NodeId,
50    /// Attribute the operator required.
51    pub attribute: Attribute,
52    /// Requirement taken from the contract.
53    pub expected: AttributeValue,
54    /// Baseline evidence, if captured.
55    pub before: Option<Evidence<AttributeValue>>,
56    /// Current evidence, if captured.
57    pub after: Option<Evidence<AttributeValue>>,
58    /// Decision for this attribute in the supplied baseline. A first inspection
59    /// has no baseline decision. Missing evidence in a supplied baseline yields
60    /// `Some(Outcome::Unverified)`.
61    pub before_outcome: Option<Outcome>,
62    /// Decision for this attribute against the current observation.
63    pub outcome: Outcome,
64}
65
66/// Number of required attributes in each outcome.
67#[derive(Debug, Default, Eq, PartialEq, Serialize)]
68pub struct Counts {
69    /// Current observations that satisfy the contract.
70    pub matched: usize,
71    /// Confirmed current differences.
72    pub mismatch: usize,
73    /// Current observations with insufficient evidence.
74    pub unverified: usize,
75}
76
77/// A self-contained decision for one logical device, server and principal.
78#[derive(Debug, Serialize)]
79#[serde(rename_all = "camelCase")]
80pub struct Report {
81    /// Report format version (2). Contracts and snapshots use format 1.
82    pub schema_version: u32,
83    /// Whether the caller supplied an earlier snapshot for comparison.
84    pub baseline_provided: bool,
85    /// Logical device label.
86    pub device: String,
87    /// Expected server application identity.
88    pub application_uri: String,
89    /// Principal used for the supplied observations.
90    pub principal: String,
91    /// Overall decision, with confirmed mismatches taking precedence.
92    pub decision: Outcome,
93    /// True when every required current attribute could be evaluated.
94    pub complete: bool,
95    /// Number of required attributes by outcome.
96    pub counts: Counts,
97    /// Sorted by signal name, then DataType, ValueRank and EngineeringUnits.
98    pub findings: Vec<Finding>,
99}
100
101impl Report {
102    /// CLI-compatible exit status. Invalid input is a separate [`Error`].
103    pub fn exit_code(&self) -> u8 {
104        match self.decision {
105            Outcome::Matched => 0,
106            Outcome::Mismatch => 2,
107            Outcome::Unverified => 3,
108        }
109    }
110}
111
112fn index<'a>(
113    contract: &Contract,
114    definitions: &BTreeMap<&str, &Expected>,
115    snapshot: &'a Snapshot,
116) -> Result<BTreeMap<&'a str, &'a Observed>, Error> {
117    let c = &contract.0;
118    let s = &snapshot.0;
119    for (field, expected, observed) in [
120        ("device", &c.device, &s.device),
121        ("applicationUri", &c.application_uri, &s.application_uri),
122        ("principal", &c.principal, &s.principal),
123    ] {
124        if expected != observed {
125            return Err(Error::new(format!("{field} differs from the contract")));
126        }
127    }
128    let mut index = BTreeMap::new();
129    for (i, row) in s.signals.iter().enumerate() {
130        let definition = definitions
131            .get(row.name.as_str())
132            .ok_or_else(|| Error::new(format!("signals[{i}].name is absent from the contract")))?;
133        if definition.node != row.node {
134            return Err(Error::new(format!(
135                "signals[{i}].node differs from the contract mapping"
136            )));
137        }
138        index.insert(row.name.as_str(), row);
139    }
140    Ok(index)
141}
142
143impl<T: Clone> Evidence<T> {
144    fn mapped(&self, f: impl FnOnce(T) -> AttributeValue) -> Evidence<AttributeValue> {
145        Evidence {
146            status: self.status,
147            value: self.value.clone().map(f),
148        }
149    }
150}
151
152fn evidence(row: Option<&&Observed>, attribute: Attribute) -> Option<Evidence<AttributeValue>> {
153    let signal = row?;
154    match attribute {
155        Attribute::DataType => signal
156            .data_type
157            .as_ref()
158            .map(|e| e.mapped(AttributeValue::DataType)),
159        Attribute::ValueRank => signal
160            .value_rank
161            .as_ref()
162            .map(|e| e.mapped(AttributeValue::ValueRank)),
163        Attribute::EngineeringUnits => signal
164            .engineering_units
165            .as_ref()
166            .map(|e| e.mapped(AttributeValue::EngineeringUnits)),
167    }
168}
169
170/// Assess the current snapshot against the contract at the first inspection.
171/// Missing observations yield unverified findings. The report contains current
172/// evidence and leaves all baseline evidence and baseline outcomes empty.
173pub fn assess(contract: &Contract, snapshot: &Snapshot) -> Result<Report, Error> {
174    evaluate(contract, None, snapshot)
175}
176
177/// Compare two validated snapshots against the contract. Missing observations are
178/// valid partial evidence. Snapshot rows with an unknown name or a changed NodeId
179/// are invalid. Only current evidence determines the gate decision.
180pub fn compare(contract: &Contract, before: &Snapshot, after: &Snapshot) -> Result<Report, Error> {
181    evaluate(contract, Some(before), after)
182}
183
184fn evaluate(
185    contract: &Contract,
186    baseline: Option<&Snapshot>,
187    snapshot: &Snapshot,
188) -> Result<Report, Error> {
189    let definitions: BTreeMap<_, _> = contract
190        .0
191        .signals
192        .iter()
193        .map(|s| (s.name.as_str(), s))
194        .collect();
195    let before = baseline
196        .map(|s| index(contract, &definitions, s))
197        .transpose()
198        .map_err(|e| e.at("before"))?;
199    let after = index(contract, &definitions, snapshot).map_err(|e| e.at("snapshot"))?;
200    let mut counts = Counts::default();
201    let mut findings = Vec::new();
202    for (name, signal) in definitions {
203        let prior_row = before.as_ref().and_then(|rows| rows.get(name));
204        let current_row = after.get(name);
205        let datatype = (
206            Attribute::DataType,
207            AttributeValue::DataType(signal.data_type.clone()),
208        );
209        let rank = signal
210            .value_rank
211            .map(|v| (Attribute::ValueRank, AttributeValue::ValueRank(v)));
212        let units = signal.engineering_units.clone().map(|unit| {
213            (
214                Attribute::EngineeringUnits,
215                AttributeValue::EngineeringUnits(unit),
216            )
217        });
218        for (attribute, expected) in std::iter::once(datatype).chain(rank).chain(units) {
219            let previous = evidence(prior_row, attribute);
220            let current = evidence(current_row, attribute);
221            let classify = |e: &Option<Evidence<AttributeValue>>| match e
222                .as_ref()
223                .and_then(|r| r.value.as_ref())
224            {
225                Some(AttributeValue::EngineeringUnits(unit)) if !unit.is_identified() => {
226                    Outcome::Unverified
227                }
228                Some(value) if *value == expected => Outcome::Matched,
229                Some(_) => Outcome::Mismatch,
230                None => Outcome::Unverified,
231            };
232            let outcome = classify(&current);
233            let before_outcome = baseline.map(|_| classify(&previous));
234            match outcome {
235                Outcome::Matched => counts.matched += 1,
236                Outcome::Mismatch => counts.mismatch += 1,
237                Outcome::Unverified => counts.unverified += 1,
238            }
239            findings.push(Finding {
240                name: name.to_owned(),
241                node: signal.node.clone(),
242                attribute,
243                expected,
244                before: previous,
245                before_outcome,
246                after: current,
247                outcome,
248            });
249        }
250    }
251    let decision = if counts.mismatch > 0 {
252        Outcome::Mismatch
253    } else if counts.unverified > 0 {
254        Outcome::Unverified
255    } else {
256        Outcome::Matched
257    };
258    Ok(Report {
259        schema_version: 2,
260        baseline_provided: baseline.is_some(),
261        device: contract.0.device.clone(),
262        application_uri: contract.0.application_uri.clone(),
263        principal: contract.0.principal.clone(),
264        complete: counts.unverified == 0,
265        counts,
266        decision,
267        findings,
268    })
269}
270
271impl Contract {
272    /// Check that the collector accounted for every signal under the requested identities.
273    /// A row without evidence records an unresolved namespace. When a node
274    /// resolves, each requested attribute needs a result, including non-Good statuses.
275    ///
276    /// Use this before publishing a new capture. Offline [`compare`] also accepts
277    /// partial snapshots so previously collected evidence can still be assessed.
278    pub fn validate_capture(&self, snapshot: &Snapshot) -> Result<(), Error> {
279        let definitions = self
280            .0
281            .signals
282            .iter()
283            .map(|s| (s.name.as_str(), s))
284            .collect();
285        let observed = index(self, &definitions, snapshot)?;
286        if observed.len() != self.0.signals.len() {
287            return Err(Error::new(
288                "capture is missing one or more requested signals",
289            ));
290        }
291        for (i, expected) in self.0.signals.iter().enumerate() {
292            let signal = observed[expected.name.as_str()];
293            if signal.data_type.is_none()
294                && signal.value_rank.is_none()
295                && signal.engineering_units.is_none()
296            {
297                continue;
298            }
299            if signal.data_type.is_none() {
300                return Err(Error::new(format!(
301                    "capture is missing DataType for contract signals[{i}]"
302                )));
303            }
304            if signal.value_rank.is_some() != expected.value_rank.is_some() {
305                return Err(Error::new(format!(
306                    "capture ValueRank coverage differs from contract signals[{i}]"
307                )));
308            }
309            if signal.engineering_units.is_some() != expected.engineering_units.is_some() {
310                return Err(Error::new(format!(
311                    "capture EngineeringUnits coverage differs from contract signals[{i}]"
312                )));
313            }
314        }
315        Ok(())
316    }
317}