Skip to main content

opcua_kit/client/
snapshot.rs

1use std::collections::BTreeSet;
2
3use super::{
4    Client, MAX_NODES_PER_READ, NAMESPACE_ARRAY, ReadError, ReadMetadata, ReadSession,
5    SERVER_ARRAY, Sample, definition::decode_data_type, sample::Quality, ua,
6};
7use crate::{
8    NodeId,
9    commissioning::{
10        Contract, Error, Evidence, SignalObservation, SignalRequirement, Snapshot,
11        SnapshotCollector,
12    },
13};
14
15/// Native snapshot acquisition failed before a complete validated document was available.
16#[derive(Debug, thiserror::Error)]
17#[non_exhaustive]
18pub enum SnapshotReadError {
19    /// The reviewed user differs from the authenticated session user.
20    #[error("snapshot contract principal differs from the authenticated session")]
21    Principal,
22    /// The contract selects a different server application from the pinned client.
23    #[error("snapshot contract ApplicationUri differs from the pinned server")]
24    ServerIdentity,
25    /// A selected signal aliases a standard node whose Value is required for session bootstrap.
26    #[error("snapshot signals[{index}] selects a reserved session bootstrap node")]
27    BootstrapNode {
28        /// Zero-based index in the supplied contract.
29        index: usize,
30    },
31    /// Session identity, namespace discovery or acquisition of the read guard failed.
32    #[error("could not prepare the snapshot session: {0}")]
33    Session(#[source] ReadError),
34    /// A server service or structural metadata check failed for this request.
35    #[error("snapshot signals[{index}]: {source}")]
36    Signal {
37        /// Zero-based index in the supplied contract.
38        index: usize,
39        /// Operation or decoding error.
40        #[source]
41        source: ReadError,
42    },
43    /// Including this row would exceed the aggregate document limit.
44    #[error("snapshot signals[{index}]: compact snapshot and newline exceed 4 MiB")]
45    OutputLimit {
46        /// Zero-based index of the first row that did not fit.
47        index: usize,
48    },
49    /// The completed capture or its scope envelope failed document validation.
50    #[error("invalid snapshot evidence: {0}")]
51    Evidence(#[source] Error),
52}
53
54fn evidence<T>(sample: Sample<T>) -> Evidence<T> {
55    Evidence {
56        status: sample.status,
57        value: sample.value,
58    }
59}
60
61fn protected_signals<'a>(
62    contract: &'a Contract,
63    server_uri: &str,
64    principal: &str,
65) -> Result<BTreeSet<&'a NodeId>, SnapshotReadError> {
66    if contract.principal() != principal {
67        return Err(SnapshotReadError::Principal);
68    }
69    if contract.application_uri() != server_uri {
70        return Err(SnapshotReadError::ServerIdentity);
71    }
72    contract.validate_capture_nodes()?;
73    Ok(contract.signals().iter().map(|s| &s.node).collect())
74}
75
76impl Contract {
77    /// Check that live acquisition will not read application evidence from reserved session bootstrap nodes.
78    /// This can be used before connecting or as part of offline preparation.
79    pub fn validate_capture_nodes(&self) -> Result<(), SnapshotReadError> {
80        for (index, signal) in self.signals().iter().enumerate() {
81            let node = &signal.node;
82            if node.namespace() == "http://opcfoundation.org/UA/"
83                && node
84                    .identifier()
85                    .strip_prefix("i=")
86                    .and_then(|id| id.parse::<u32>().ok())
87                    .is_some_and(|id| {
88                        matches!(id, SERVER_ARRAY | NAMESPACE_ARRAY | MAX_NODES_PER_READ)
89                    })
90            {
91                return Err(SnapshotReadError::BootstrapNode { index });
92            }
93        }
94        Ok(())
95    }
96}
97
98impl Client {
99    /// Observe only the commissioned declarations and requested standard unit properties.
100    /// The snapshot preserves the contract order and actual operation status, including a
101    /// Good status without a value. A missing namespace yields a row with just the identity.
102    /// The compact document plus newline is bounded at 4 MiB before appending each row.
103    /// Service-response decoding occurs before this application-level output check.
104    /// ServerArray, NamespaceArray and MaxNodesPerRead are reserved session bootstrap nodes.
105    /// Selecting one in the contract fails before the client reads any of those Values.
106    ///
107    /// ```
108    /// # async fn inspect(client: &opcua_kit::Client, contract: &opcua_kit::commissioning::Contract)
109    /// # -> Result<(), Box<dyn std::error::Error>> {
110    /// let snapshot = client.read_snapshot(contract).await?;
111    /// let report = opcua_kit::commissioning::assess(contract, &snapshot)?;
112    /// println!("{:?}", report.decision);
113    /// # Ok(()) }
114    /// ```
115    pub async fn read_snapshot(&self, contract: &Contract) -> Result<Snapshot, SnapshotReadError> {
116        let protected = protected_signals(contract, &self.server_uri, &self.principal)?;
117        let mut output = SnapshotCollector::new(contract).map_err(SnapshotReadError::Evidence)?;
118        let (mut session, metadata) = self
119            .read_session()
120            .await
121            .map_err(SnapshotReadError::Session)?;
122        for (index, signal) in contract.signals().iter().enumerate() {
123            let row = self
124                .snapshot_signal(&mut session, metadata, signal, &protected)
125                .await
126                .map_err(|source| SnapshotReadError::Signal { index, source })?;
127            output
128                .push(row)
129                .map_err(|_| SnapshotReadError::OutputLimit { index })?;
130        }
131        self.check_channel().map_err(SnapshotReadError::Session)?;
132        drop(session);
133        output.finish(contract).map_err(SnapshotReadError::Evidence)
134    }
135
136    async fn snapshot_signal(
137        &self,
138        session: &mut ReadSession,
139        metadata: &ReadMetadata,
140        signal: &SignalRequirement,
141        protected: &BTreeSet<&NodeId>,
142    ) -> Result<SignalObservation, ReadError> {
143        let mut row = SignalObservation::new(signal.name.clone(), signal.node.clone());
144        if !metadata
145            .namespaces
146            .by_uri
147            .contains_key(signal.node.namespace())
148        {
149            return Ok(row);
150        }
151        let quality = Quality::GoodSeverity;
152        let data_type = if signal.value_rank.is_some() {
153            let definition = self
154                .definition_locked(session, metadata, &signal.node, quality)
155                .await?;
156            row.value_rank = Some(evidence(definition.value_rank?));
157            definition.data_type?
158        } else {
159            let wire = metadata.namespaces.wire_node(&signal.node, 0)?;
160            let raw = self
161                .one_attribute(session, wire, ua::AttributeId::DataType)
162                .await?;
163            decode_data_type(&metadata.namespaces, &raw, quality)?
164        };
165        row.data_type = Some(evidence(data_type));
166        if signal.engineering_units.is_some() {
167            let unit = self
168                .units_locked(
169                    session,
170                    &metadata.namespaces,
171                    &signal.node,
172                    quality,
173                    |property| !protected.contains(property),
174                )
175                .await?;
176            row.engineering_units = Some(evidence(unit.sample));
177        }
178        Ok(row)
179    }
180}
181
182#[cfg(test)]
183mod tests {
184    use super::*;
185    use crate::commissioning::{MAX_DOCUMENT_BYTES, Unit, parse_contract};
186
187    #[test]
188    fn reject_bootstrap_aliases_in_any_position_before_preparing_session() {
189        let base = parse_contract(include_bytes!("../../fixtures/meter/contract.json")).unwrap();
190        for id in ["i=002254", "i=002255", "i=11705"] {
191            let mut a = base.signals()[0].clone();
192            a.node = NodeId::new("urn:vendor", id).unwrap();
193            let mut b = a.clone();
194            b.name = "bootstrap".into();
195            b.node = NodeId::new("http://opcfoundation.org/UA/", id).unwrap();
196            let new = |rows| Contract::new("site", "urn:server", "anonymous", rows).unwrap();
197            let c = new(vec![a.clone()]);
198            assert!(
199                protected_signals(&c, "urn:server", "anonymous")
200                    .unwrap()
201                    .contains(&a.node)
202            );
203            let c = new(vec![a, b]);
204            assert!(matches!(
205                protected_signals(&c, "urn:server", "anonymous"),
206                Err(SnapshotReadError::BootstrapNode { index: 1 })
207            ));
208            assert!(matches!(
209                protected_signals(&c, "urn:other", "anonymous"),
210                Err(SnapshotReadError::ServerIdentity)
211            ));
212        }
213    }
214
215    #[test]
216    fn rows_just_fit_or_fail_including_escaped_text_separator_and_newline() {
217        let fixture = parse_contract(include_bytes!("../../fixtures/meter/contract.json")).unwrap();
218        let mut other = fixture.signals()[0].clone();
219        other.name = "other".into();
220        other.node = NodeId::new("urn:site", "s=Other").unwrap();
221        let c = Contract::new(
222            "site",
223            "urn:server",
224            "anonymous",
225            vec![fixture.signals()[0].clone(), other],
226        )
227        .unwrap();
228        let row = |i: usize, suffix: usize| {
229            let required = &c.signals()[i];
230            let mut row = SignalObservation::new(required.name.clone(), required.node.clone());
231            row.data_type = Some(Evidence {
232                status: 0,
233                value: Some(required.data_type.clone()),
234            });
235            row.value_rank = Some(Evidence {
236                status: 0,
237                value: Some(-1),
238            });
239            row.engineering_units = Some(Evidence {
240                status: 0,
241                value: Some(Unit {
242                    namespace_uri: format!("urn:unit:\"温{}", "x".repeat(suffix)),
243                    unit_id: 1,
244                }),
245            });
246            row
247        };
248        let baseline = Snapshot::new(
249            c.device(),
250            c.application_uri(),
251            c.principal(),
252            vec![row(0, 0), row(1, 0)],
253        )
254        .unwrap();
255        let room = MAX_DOCUMENT_BYTES - 1 - serde_json::to_vec(&baseline).unwrap().len();
256        let mut output = SnapshotCollector::new(&c).unwrap();
257        output.push(row(0, 0)).unwrap();
258        output.push(row(1, room)).unwrap();
259        let exact = output.finish(&c).unwrap();
260        assert_eq!(
261            serde_json::to_vec(&exact).unwrap().len() + 1,
262            MAX_DOCUMENT_BYTES
263        );
264        let mut output = SnapshotCollector::new(&c).unwrap();
265        output.push(row(0, 0)).unwrap();
266        assert!(output.push(row(1, room + 1)).is_err());
267    }
268}