Skip to main content

opcua_kit/commissioning/
mod.rs

1//! Compare the declared metadata consumed by a gateway against scoped OPC UA observations.
2//!
3//! Parse a contract and a snapshot, then call [`assess`] to check the device on
4//! its first visit. When you have an earlier snapshot, [`compare`] also
5//! computes baseline outcomes. Both entry points validate device, server,
6//! principal and signal identity, and derive their decision from current
7//! evidence. Parsing and evaluation are independent of I/O.
8//! To author a contract from an existing snapshot, use [`draft_contract`]
9//! and review the resulting requirements against the gateway configuration.
10//!
11//! Each signal requires a DataType. Add `valueRank` to check its dimensionality,
12//! or `engineeringUnits` to check its unit by namespace URI and signed numeric
13//! identifier. For example, a signal can require
14//! `"engineeringUnits": {"namespaceUri":"http://www.opcfoundation.org/UA/units/un/cefact","unitId":4408652}`
15//! for degrees Celsius. Reports retain the raw evidence when a server returns an
16//! unidentified unit. Look for [`Outcome::Unverified`] in that case.
17//!
18//! ```
19//! use opcua_kit::commissioning::{assess, compare, parse_contract, parse_snapshot, Outcome};
20//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
21//! let contract = parse_contract(include_bytes!("../../fixtures/commissioning/contract.json"))?;
22//! let before = parse_snapshot(include_bytes!("../../fixtures/commissioning/before.json"))?;
23//! let inspection = assess(&contract, &before)?;
24//! assert_eq!(inspection.exit_code(), 0);
25//! assert!(!inspection.baseline_provided);
26//! assert!(inspection.findings.iter().all(|f| f.before_outcome.is_none()));
27//!
28//! let after = parse_snapshot(include_bytes!("../../fixtures/commissioning/after.json"))?;
29//! let report = compare(&contract, &before, &after)?;
30//! assert!(report.baseline_provided);
31//! assert_eq!(report.decision, Outcome::Mismatch);
32//! assert_eq!(report.counts.unverified, 1);
33//! # Ok(()) }
34//! # example().unwrap();
35//! ```
36//!
37//! ```
38//! use opcua_kit::commissioning::{compare, parse_contract, parse_snapshot, Error, Report};
39//!
40//! fn check(requirements: &[u8], baseline: &[u8], current: &[u8]) -> Result<Report, Error> {
41//!     let contract = parse_contract(requirements)?;
42//!     let before = parse_snapshot(baseline)?;
43//!     let after = parse_snapshot(current)?;
44//!     compare(&contract, &before, &after)
45//! }
46//! ```
47
48mod draft;
49#[cfg(feature = "cems")]
50pub mod meter;
51mod report;
52
53use std::{collections::BTreeSet, fmt, io};
54
55use serde::{Deserialize, Deserializer, Serialize, de::DeserializeOwned};
56
57use crate::{Severity, status_severity};
58
59pub use crate::NodeId;
60pub use draft::draft_contract;
61pub use report::{Attribute, AttributeValue, Counts, Finding, Outcome, Report, assess, compare};
62use {SignalObservation as Observed, SignalRequirement as Expected};
63
64/// Maximum encoded size of a contract or snapshot, in bytes.
65pub const MAX_DOCUMENT_BYTES: usize = 4 * 1024 * 1024;
66/// Maximum number of signal definitions or observations per document.
67pub const MAX_SIGNALS: usize = 1024;
68
69/// Invalid commissioning document or incompatible observation scope.
70#[derive(Clone, Debug)]
71pub struct Error(String);
72
73impl Error {
74    fn new(message: impl Into<String>) -> Self {
75        Self(message.into())
76    }
77
78    fn at(self, path: &str) -> Self {
79        Self(format!("{path}: {self}"))
80    }
81}
82
83impl fmt::Display for Error {
84    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85        f.write_str(&self.0)
86    }
87}
88
89impl std::error::Error for Error {}
90
91impl From<crate::NodeIdError> for Error {
92    fn from(error: crate::NodeIdError) -> Self {
93        Self::new(error.to_string())
94    }
95}
96
97#[derive(Debug, Serialize, Deserialize)]
98#[serde(rename_all = "camelCase", deny_unknown_fields)]
99struct Document<T> {
100    schema_version: u32,
101    device: String,
102    application_uri: String,
103    principal: String,
104    signals: Vec<T>,
105}
106
107/// Metadata a client requires from one named OPC UA node.
108/// Pass requirements to [`Contract::new`] for validation.
109#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
110#[serde(rename_all = "camelCase", deny_unknown_fields)]
111pub struct SignalRequirement {
112    /// Name used to correlate the signal with a commissioning observation.
113    pub name: String,
114    /// Node to inspect in the server's address space.
115    pub node: NodeId,
116    /// Required DataType attribute.
117    pub data_type: NodeId,
118    /// Optional OPC UA ValueRank, such as -1 for a scalar.
119    #[serde(
120        default,
121        skip_serializing_if = "Option::is_none",
122        deserialize_with = "present"
123    )]
124    pub value_rank: Option<i32>,
125    /// Optional unit identity required by the application.
126    #[serde(
127        default,
128        skip_serializing_if = "Option::is_none",
129        deserialize_with = "present"
130    )]
131    pub engineering_units: Option<Unit>,
132}
133
134impl SignalRequirement {
135    /// Require the named node to have the given DataType.
136    pub fn new(name: impl Into<String>, node: NodeId, data_type: NodeId) -> Self {
137        Self {
138            name: name.into(),
139            node,
140            data_type,
141            value_rank: None,
142            engineering_units: None,
143        }
144    }
145}
146
147/// The same programmatic unit identity used by the native client.
148pub use crate::EngineeringUnit as Unit;
149
150impl Unit {
151    fn validate(&self) -> Result<(), Error> {
152        if self.namespace_uri.chars().any(char::is_control) {
153            return Err(Error::new("namespaceUri contains control characters"));
154        }
155        Ok(())
156    }
157}
158
159/// Numeric operation status and the associated metadata when readable.
160#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
161#[serde(deny_unknown_fields, bound(deserialize = "T: Deserialize<'de>"))]
162pub struct Evidence<T> {
163    /// Full raw OPC UA StatusCode, including its subcode and flags.
164    pub status: u32,
165    /// Observed metadata when supplied with Good severity. An omitted value is unverified.
166    #[serde(
167        default,
168        skip_serializing_if = "Option::is_none",
169        deserialize_with = "present"
170    )]
171    pub value: Option<T>,
172}
173
174// A missing optional member and an explicitly null member have different meanings.
175// Deserialize a present member as T to retain that distinction.
176fn present<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
177where
178    D: Deserializer<'de>,
179    T: Deserialize<'de>,
180{
181    T::deserialize(deserializer).map(Some)
182}
183
184/// Attribute results for one named node. Missing attributes were not observed.
185#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
186#[serde(rename_all = "camelCase", deny_unknown_fields)]
187pub struct SignalObservation {
188    /// Name under which the application commissioned this signal.
189    pub name: String,
190    /// Node that supplied the observed attributes.
191    pub node: NodeId,
192    /// DataType read result, including the raw operation status.
193    #[serde(
194        default,
195        skip_serializing_if = "Option::is_none",
196        deserialize_with = "present"
197    )]
198    pub data_type: Option<Evidence<NodeId>>,
199    /// ValueRank read result.
200    #[serde(
201        default,
202        skip_serializing_if = "Option::is_none",
203        deserialize_with = "present"
204    )]
205    pub value_rank: Option<Evidence<i32>>,
206    /// EngineeringUnits read result.
207    #[serde(
208        default,
209        skip_serializing_if = "Option::is_none",
210        deserialize_with = "present"
211    )]
212    pub engineering_units: Option<Evidence<Unit>>,
213}
214
215impl SignalObservation {
216    /// Start an observation with no attribute results.
217    pub fn new(name: impl Into<String>, node: NodeId) -> Self {
218        Self {
219            name: name.into(),
220            node,
221            data_type: None,
222            value_rank: None,
223            engineering_units: None,
224        }
225    }
226}
227
228/// Validated, versioned requirements for one device, server and principal.
229#[derive(Debug, Serialize)]
230#[serde(transparent)]
231pub struct Contract(Document<SignalRequirement>);
232
233impl Contract {
234    /// Build a version 1 contract in memory using the same rules as [`parse_contract`].
235    ///
236    /// ```
237    /// use opcua_kit::commissioning::{Contract, NodeId, SignalRequirement};
238    /// # fn example() -> Result<(), opcua_kit::commissioning::Error> {
239    /// let node = NodeId::new("urn:plant:line-1", "s=PartsProduced")?;
240    /// let uint64 = NodeId::new("http://opcfoundation.org/UA/", "i=9")?;
241    /// let mut counter = SignalRequirement::new("PartsProduced", node, uint64);
242    /// counter.value_rank = Some(-1);
243    /// let contract = Contract::new("line-1", "urn:plant:server", "anonymous", vec![counter])?;
244    /// assert_eq!(contract.signals()[0].node.identifier(), "s=PartsProduced");
245    /// # Ok(()) }
246    /// # example().unwrap();
247    /// ```
248    pub fn new(
249        device: impl Into<String>,
250        application_uri: impl Into<String>,
251        principal: impl Into<String>,
252        signals: Vec<SignalRequirement>,
253    ) -> Result<Self, Error> {
254        validate_contract(Document::new(device, application_uri, principal, signals)?)
255    }
256
257    /// Device identifier chosen by the application.
258    pub fn device(&self) -> &str {
259        &self.0.device
260    }
261
262    /// Expected server ApplicationUri.
263    pub fn application_uri(&self) -> &str {
264        &self.0.application_uri
265    }
266
267    /// Principal under which the attributes are to be read.
268    pub fn principal(&self) -> &str {
269        &self.0.principal
270    }
271
272    /// Validated signal requirements in declaration order, with canonical node identifiers.
273    pub fn signals(&self) -> &[SignalRequirement] {
274        &self.0.signals
275    }
276
277    /// Number of distinct signals required by this contract.
278    pub fn signal_count(&self) -> usize {
279        self.0.signals.len()
280    }
281}
282
283/// Validated, versioned observations for one device, server and principal.
284#[derive(Debug, Serialize)]
285#[serde(transparent)]
286pub struct Snapshot(Document<SignalObservation>);
287
288impl Snapshot {
289    /// Build a version 1 snapshot in memory using the same rules as [`parse_snapshot`].
290    pub fn new(
291        device: impl Into<String>,
292        application_uri: impl Into<String>,
293        principal: impl Into<String>,
294        signals: Vec<SignalObservation>,
295    ) -> Result<Self, Error> {
296        validate_snapshot(Document::new(device, application_uri, principal, signals)?)
297    }
298
299    /// Device identifier associated with the observations.
300    pub fn device(&self) -> &str {
301        &self.0.device
302    }
303
304    /// ApplicationUri of the observed server.
305    pub fn application_uri(&self) -> &str {
306        &self.0.application_uri
307    }
308
309    /// Principal under which the attributes were observed.
310    pub fn principal(&self) -> &str {
311        &self.0.principal
312    }
313
314    /// Validated observations in declaration order, with canonical node identifiers.
315    pub fn signals(&self) -> &[SignalObservation] {
316        &self.0.signals
317    }
318}
319
320// Native capture owns at most one uncharged candidate row while it grows the snapshot.
321// The empty envelope includes both brackets. Each subsequent row adds one comma.
322#[cfg(feature = "client")]
323pub(crate) struct SnapshotCollector {
324    document: Document<SignalObservation>,
325    budget: ByteBudget,
326}
327
328#[cfg(feature = "client")]
329impl SnapshotCollector {
330    pub(crate) fn new(contract: &Contract) -> Result<Self, Error> {
331        let document = Document {
332            schema_version: 1,
333            device: contract.device().to_owned(),
334            application_uri: contract.application_uri().to_owned(),
335            principal: contract.principal().to_owned(),
336            signals: Vec::with_capacity(contract.signal_count()),
337        };
338        let mut budget = ByteBudget(MAX_DOCUMENT_BYTES - 1);
339        serde_json::to_writer(&mut budget, &document).map_err(|e| Error::new(e.to_string()))?;
340        Ok(Self { document, budget })
341    }
342
343    pub(crate) fn push(&mut self, row: SignalObservation) -> Result<(), Error> {
344        use io::Write;
345        if !self.document.signals.is_empty() {
346            self.budget
347                .write_all(b",")
348                .map_err(|e| Error::new(e.to_string()))?;
349        }
350        serde_json::to_writer(&mut self.budget, &row).map_err(|e| Error::new(e.to_string()))?;
351        self.document.signals.push(row);
352        Ok(())
353    }
354
355    pub(crate) fn finish(self, contract: &Contract) -> Result<Snapshot, Error> {
356        let snapshot = validate_snapshot(self.document)?;
357        contract.validate_capture(&snapshot)?;
358        Ok(snapshot)
359    }
360}
361
362// Count exact compact JSON bytes, including escapes, without allocating a wire document.
363struct ByteBudget(usize);
364
365impl io::Write for ByteBudget {
366    fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
367        self.0 = self
368            .0
369            .checked_sub(bytes.len())
370            .ok_or_else(|| io::Error::other("document exceeds 4 MiB"))?;
371        Ok(bytes.len())
372    }
373
374    fn flush(&mut self) -> io::Result<()> {
375        Ok(())
376    }
377}
378
379impl<T: Serialize> Document<T> {
380    fn new(
381        device: impl Into<String>,
382        application_uri: impl Into<String>,
383        principal: impl Into<String>,
384        signals: Vec<T>,
385    ) -> Result<Self, Error> {
386        let doc = Self {
387            schema_version: 1,
388            device: device.into(),
389            application_uri: application_uri.into(),
390            principal: principal.into(),
391            signals,
392        };
393        validate_header(&doc)?;
394        serde_json::to_writer(ByteBudget(MAX_DOCUMENT_BYTES), &doc)
395            .map_err(|error| Error::new(error.to_string()))?;
396        Ok(doc)
397    }
398}
399
400fn parse<T: DeserializeOwned>(bytes: &[u8]) -> Result<Document<T>, Error> {
401    if bytes.len() > MAX_DOCUMENT_BYTES {
402        return Err(Error::new("document exceeds 4 MiB"));
403    }
404    let doc: Document<T> = serde_json::from_slice(bytes).map_err(|error| {
405        // serde can quote fields from untrusted JSON. Keep diagnostics single-line
406        // and bounded even for unknown field names.
407        let message: String = error
408            .to_string()
409            .chars()
410            .take(180)
411            .flat_map(char::escape_debug)
412            .collect();
413        Error::new(format!(
414            "invalid JSON at line {}, column {}: {message}",
415            error.line(),
416            error.column()
417        ))
418    })?;
419    validate_header(&doc)?;
420    Ok(doc)
421}
422
423fn validate_header<T>(doc: &Document<T>) -> Result<(), Error> {
424    if doc.schema_version != 1 {
425        return Err(Error::new("unsupported schemaVersion (expected 1)"));
426    }
427    for (path, value) in [
428        ("device", &doc.device),
429        ("applicationUri", &doc.application_uri),
430        ("principal", &doc.principal),
431    ] {
432        validate_label(value).map_err(|e| e.at(path))?;
433    }
434    if doc.signals.len() > MAX_SIGNALS {
435        return Err(Error::new("signals exceeds 1024 entries"));
436    }
437    Ok(())
438}
439
440fn validate_label(label: &str) -> Result<(), Error> {
441    if label.trim().is_empty() || label.chars().any(char::is_control) {
442        return Err(Error::new(
443            "expected nonempty text without control characters",
444        ));
445    }
446    Ok(())
447}
448
449fn validate_rank(rank: i32) -> Result<(), Error> {
450    if rank < -3 {
451        return Err(Error::new("ValueRank must be -3 or greater"));
452    }
453    Ok(())
454}
455
456fn unique<'a>(items: impl Iterator<Item = (&'a str, &'a NodeId)>) -> Result<(), Error> {
457    let mut names = BTreeSet::new();
458    let mut nodes = BTreeSet::new();
459    for (i, (name, node)) in items.enumerate() {
460        if !names.insert(name) {
461            return Err(Error::new(format!(
462                "signals[{i}].name duplicates another signal name"
463            )));
464        }
465        if !nodes.insert(node) {
466            return Err(Error::new(format!(
467                "signals[{i}].node duplicates another node identity"
468            )));
469        }
470    }
471    Ok(())
472}
473
474/// Parse a contract from UTF-8 JSON, normalizing typed IDs and checking all bounds.
475pub fn parse_contract(bytes: &[u8]) -> Result<Contract, Error> {
476    validate_contract(parse(bytes)?)
477}
478
479fn validate_contract(doc: Document<SignalRequirement>) -> Result<Contract, Error> {
480    if doc.signals.is_empty() {
481        return Err(Error::new("contract must specify at least one signal"));
482    }
483    for (i, s) in doc.signals.iter().enumerate() {
484        validate_label(&s.name).map_err(|e| e.at(&format!("signals[{i}].name")))?;
485        if let Some(rank) = s.value_rank {
486            validate_rank(rank).map_err(|e| e.at(&format!("signals[{i}].valueRank")))?;
487        }
488        if let Some(unit) = &s.engineering_units {
489            let path = format!("signals[{i}].engineeringUnits");
490            unit.validate().map_err(|e| e.at(&path))?;
491            if !unit.is_identified() {
492                return Err(
493                    Error::new("expected nonempty namespaceUri and unitId other than -1").at(&path),
494                );
495            }
496        }
497    }
498    unique(doc.signals.iter().map(|s| (s.name.as_str(), &s.node)))?;
499    Ok(Contract(doc))
500}
501
502fn validate_observation<T>(
503    evidence: &Evidence<T>,
504    validate: impl FnOnce(&T) -> Result<(), Error>,
505) -> Result<(), Error> {
506    let good = status_severity(evidence.status) == Severity::Good;
507    let result = match (good, evidence.value.as_ref()) {
508        (true, Some(value)) => validate(value),
509        (_, None) => Ok(()),
510        (false, Some(_)) => Err(Error::new("non-Good status requires omitting the value")),
511    };
512    result.map_err(|e| Error::new(format!("{e} (status 0x{:08X})", evidence.status)))
513}
514
515// Decode the DataType identifier after its surrounding evidence so an invalid
516// identifier can be reported with the operand index and the original status.
517#[derive(Deserialize)]
518#[serde(rename_all = "camelCase", deny_unknown_fields)]
519struct WireObservation {
520    name: String,
521    node: NodeId,
522    #[serde(default, deserialize_with = "present")]
523    data_type: Option<Evidence<crate::identity::WireNode>>,
524    #[serde(default, deserialize_with = "present")]
525    value_rank: Option<Evidence<i32>>,
526    #[serde(default, deserialize_with = "present")]
527    engineering_units: Option<Evidence<Unit>>,
528}
529
530impl WireObservation {
531    fn into_observation(self, index: usize) -> Result<SignalObservation, Error> {
532        let data_type = self
533            .data_type
534            .map(|evidence| -> Result<_, Error> {
535                let value = evidence
536                    .value
537                    .map(NodeId::try_from)
538                    .transpose()
539                    .map_err(|err| {
540                        Error::new(format!(
541                            "signals[{index}].dataType: {err} (status 0x{:08X})",
542                            evidence.status
543                        ))
544                    })?;
545                Ok(Evidence {
546                    status: evidence.status,
547                    value,
548                })
549            })
550            .transpose()?;
551        Ok(SignalObservation {
552            name: self.name,
553            node: self.node,
554            data_type,
555            value_rank: self.value_rank,
556            engineering_units: self.engineering_units,
557        })
558    }
559}
560
561/// Parse snapshot JSON, verifying the status/value invariants of each observation.
562pub fn parse_snapshot(bytes: &[u8]) -> Result<Snapshot, Error> {
563    let doc: Document<WireObservation> = parse(bytes)?;
564    let signals = doc
565        .signals
566        .into_iter()
567        .enumerate()
568        .map(|(index, row)| row.into_observation(index))
569        .collect::<Result<_, _>>()?;
570    validate_snapshot(Document {
571        schema_version: doc.schema_version,
572        device: doc.device,
573        application_uri: doc.application_uri,
574        principal: doc.principal,
575        signals,
576    })
577}
578
579fn validate_snapshot(doc: Document<SignalObservation>) -> Result<Snapshot, Error> {
580    for (i, s) in doc.signals.iter().enumerate() {
581        validate_label(&s.name).map_err(|e| e.at(&format!("signals[{i}].name")))?;
582        if let Some(evidence) = &s.data_type {
583            validate_observation(evidence, |_| Ok(()))
584                .map_err(|e| e.at(&format!("signals[{i}].dataType")))?;
585        }
586        if let Some(evidence) = &s.value_rank {
587            validate_observation(evidence, |n| validate_rank(*n))
588                .map_err(|e| e.at(&format!("signals[{i}].valueRank")))?;
589        }
590        if let Some(evidence) = &s.engineering_units {
591            validate_observation(evidence, |unit| unit.validate())
592                .map_err(|e| e.at(&format!("signals[{i}].engineeringUnits")))?;
593        }
594    }
595    unique(doc.signals.iter().map(|s| (s.name.as_str(), &s.node)))?;
596    Ok(Snapshot(doc))
597}