Skip to main content

opcua_kit/client/
mod.rs

1//! Discover endpoints and browse, read or monitor nodes over a pinned OPC UA session.
2//!
3//! Reuse one [`Client`] across polling cycles. Node identifiers retain their
4//! namespace URI when a server reassigns numeric indexes. Check each result's status and wire type
5//! before using a value. Raw reads preserve the source and server timestamps,
6//! including their optional 10 ps increments. Use the commissioning API to assess a signal’s declared metadata.
7
8mod array;
9pub use array::ArrayValue;
10mod browse;
11#[cfg(feature = "control")]
12mod conditions;
13mod connection;
14#[cfg(feature = "control")]
15pub use conditions::{ConditionComment, ConditionError};
16#[cfg(feature = "control")]
17mod control;
18#[cfg(feature = "control")]
19pub use control::{CallOutcome, Control, ControlError};
20mod definition;
21mod events;
22pub use events::{EventError, EventField, Events, PublishError, Sequenced, SequencedDataChanges};
23mod history;
24pub use history::{HistoricalRead, HistoryError};
25mod wire;
26pub use crate::discovery::{EndpointInfo, EndpointToken, discover_endpoints};
27#[cfg(feature = "cems")]
28mod meter;
29mod recovery;
30mod sample;
31#[cfg(feature = "commissioning")]
32mod snapshot;
33mod subscription;
34mod units;
35pub use crate::EngineeringUnit;
36pub use crate::ua;
37pub use browse::{BrowseEntry, BrowseError, BrowseName};
38pub use connection::{
39    CertificateRollover, Client, ConnectError, ConnectionConfig, ConnectionOptions, SecurityPolicy,
40    UserIdentity,
41};
42pub use definition::{ReadAttribute, ReadOperand, VariableDefinition};
43#[cfg(feature = "cems")]
44pub use meter::MeterReadError;
45pub use recovery::{RecoveredSession, RecoveringClient, RecoveryError, SessionState};
46pub use sample::{FixedScalar, Sample, SampleTimestamp, Scalar, TimestampError};
47#[cfg(feature = "commissioning")]
48pub use snapshot::SnapshotReadError;
49pub use subscription::{
50    DataChange, DataChanges, MAX_MONITORED_NODES, MonitoredDataChanges, MonitoredNode,
51    SubscriptionError,
52};
53pub use ua::DataValue;
54pub use units::{EngineeringUnitEvidence, UnitStage};
55
56use std::{collections::BTreeMap, sync::Arc};
57
58use crate::NodeId;
59
60/// Maximum number of attribute operands in one logical client read.
61pub const MAX_READ_NODES: usize = 1024;
62const MAX_NAMESPACE_BYTES: usize = 4 * 1024 * 1024;
63const SERVER_ARRAY: u32 = 2254;
64const NAMESPACE_ARRAY: u32 = 2255;
65const MAX_NODES_PER_READ: u32 = 11705;
66
67/// A service, identity, or scalar-decoding error. Each successful result carries its node status.
68#[derive(Debug, thiserror::Error)]
69#[non_exhaustive]
70pub enum ReadError {
71    /// The Value is a scalar or an array of a different built-in type.
72    #[error("expected an array of the requested OPC UA element type")]
73    ArrayTypeMismatch,
74    /// Invalid dimensions or array size exceeds the client limits.
75    #[error("invalid array shape or array exceeds 65536 elements or 16 dimensions")]
76    InvalidArray,
77    /// Batch exceeds the client read limit.
78    #[error("a read accepts at most {MAX_READ_NODES} attribute operands")]
79    TooManyNodes,
80    /// Cannot use this connection's mapping after a channel change.
81    #[error("the secure channel changed; reconnect and retry the read")]
82    ChannelChanged,
83    /// A previous service request failed or its future was cancelled after dispatch.
84    #[error("the previous read was interrupted; open a fresh session")]
85    SessionInterrupted,
86    /// The authenticated server reported a different application identity.
87    #[error("the server application URI differs from the configured identity")]
88    ServerIdentity,
89    /// The server did not supply usable, unambiguous namespace metadata.
90    #[error("unusable server or namespace array")]
91    InvalidServerMetadata,
92    /// The server advertised a read limit with the wrong type or rank.
93    #[error("MaxNodesPerRead must be a scalar UInt32")]
94    InvalidReadLimit,
95    /// A returned DataType identifier is invalid or its namespace is absent from the session.
96    #[error("declared DataType is not a valid node in this session's namespace table")]
97    InvalidDataType,
98    /// The server supplied an Int32 outside the OPC UA ValueRank range.
99    #[error("ValueRank must be -3 or greater")]
100    InvalidValueRank,
101    /// The property lookup was incomplete, ambiguous, remote, or inconsistent.
102    #[error(
103        "EngineeringUnits must resolve completely to one distinct local Variable through HasProperty"
104    )]
105    InvalidUnitReference,
106    /// A resolved unit property would read a signal protected by the capture contract.
107    #[error("EngineeringUnits aliases a contracted signal")]
108    UnitAliasesSignal,
109    /// A property declaration or a Good property value does not match scalar EUInformation.
110    #[error(
111        "EngineeringUnits must declare and contain scalar EUInformation with a valid namespace URI"
112    )]
113    InvalidUnitProperty,
114    /// The selected namespace is absent in the session.
115    #[error("namespace for operand at index {index} is absent from this session")]
116    UnknownNamespace {
117        /// Position in the caller's slice.
118        index: usize,
119    },
120    /// A present Good value has a different OPC UA type or is an array.
121    #[error("expected an OPC UA {expected} scalar")]
122    ScalarTypeMismatch {
123        /// OPC UA built-in type name corresponding to the requested Rust type.
124        expected: &'static str,
125    },
126    /// DateTime cannot be represented in the supported Rust calendar range.
127    #[error("OPC UA DateTime is outside the Rust calendar range")]
128    DateTimeRange,
129    /// The underlying OPC UA service failed.
130    #[error("OPC UA service failed: {0}")]
131    Service(#[from] ua::StatusCode),
132}
133
134fn string(value: &ua::Variant) -> Option<&str> {
135    if let ua::Variant::String(text) = value {
136        text.value().as_deref()
137    } else {
138        None
139    }
140}
141
142fn strings(value: &DataValue) -> Result<&[ua::Variant], ReadError> {
143    if value
144        .status
145        .is_some_and(|status| status != ua::StatusCode::Good)
146    {
147        return Err(ReadError::InvalidServerMetadata);
148    }
149    match value.value.as_ref() {
150        Some(ua::Variant::Array(array))
151            if array.value_type == ua::VariantScalarTypeId::String
152                && array.dimensions.is_none() =>
153        {
154            Ok(&array.values)
155        }
156        _ => Err(ReadError::InvalidServerMetadata),
157    }
158}
159
160struct Namespaces {
161    by_uri: BTreeMap<Arc<str>, u16>,
162    by_index: Vec<Arc<str>>,
163}
164
165impl Namespaces {
166    fn wire_node(&self, node: &NodeId, index: usize) -> Result<ua::NodeId, ReadError> {
167        let ns = self
168            .by_uri
169            .get(node.namespace())
170            .ok_or(ReadError::UnknownNamespace { index })?;
171        // Preserve string identifiers literally, including semicolons, '=' and percent signs.
172        if let Some(text) = node.identifier().strip_prefix("s=") {
173            Ok(ua::NodeId::new(*ns, text))
174        } else {
175            format!("ns={ns};{}", node.identifier())
176                .parse()
177                .map_err(|_| ReadError::InvalidDataType)
178        }
179    }
180}
181
182fn namespace_map(table: &[ua::Variant]) -> Result<Namespaces, ReadError> {
183    if table.len() > usize::from(u16::MAX) + 1
184        || table.first().and_then(string) != Some("http://opcfoundation.org/UA/")
185    {
186        return Err(ReadError::InvalidServerMetadata);
187    }
188    let mut remaining = MAX_NAMESPACE_BYTES;
189    let mut by_uri = BTreeMap::new();
190    let mut by_index = Vec::with_capacity(table.len());
191    for (i, entry) in table.iter().enumerate() {
192        let index = u16::try_from(i).map_err(|_| ReadError::InvalidServerMetadata)?;
193        let uri = string(entry)
194            .filter(|s| !s.trim().is_empty() && !s.chars().any(char::is_control))
195            .ok_or(ReadError::InvalidServerMetadata)?;
196        remaining = remaining
197            .checked_sub(uri.len())
198            .ok_or(ReadError::InvalidServerMetadata)?;
199        let uri: Arc<str> = uri.into();
200        if by_uri.insert(Arc::clone(&uri), index).is_some() {
201            return Err(ReadError::InvalidServerMetadata);
202        }
203        by_index.push(uri);
204    }
205    Ok(Namespaces { by_uri, by_index })
206}
207
208fn read_limit(value: &DataValue) -> Result<usize, ReadError> {
209    // Optional in Part 5 §6.3.11. A singleton is safe without a usable advertisement.
210    if value.status.is_some_and(|status| !status.is_good()) {
211        return Ok(1);
212    }
213    let limit = match value.value.as_ref() {
214        None | Some(ua::Variant::Empty) => return Ok(1),
215        Some(ua::Variant::UInt32(n)) => *n,
216        _ => return Err(ReadError::InvalidReadLimit),
217    };
218    Ok(usize::try_from(limit)
219        .unwrap_or(usize::MAX)
220        .clamp(1, MAX_READ_NODES))
221}
222
223struct ReadMetadata {
224    namespaces: Namespaces,
225    max_nodes_per_read: usize,
226}
227
228// A cancelled request may still be in flight. Retire its namespace mapping
229// before allowing a new operation to use the session.
230#[derive(Default)]
231struct ReadSession {
232    interrupted: bool,
233}
234
235impl ReadSession {
236    async fn request<T>(
237        &mut self,
238        operation: impl Future<Output = Result<T, ReadError>>,
239    ) -> Result<T, ReadError> {
240        if self.interrupted {
241            return Err(ReadError::SessionInterrupted);
242        }
243        self.interrupted = true;
244        let result = operation.await?;
245        self.interrupted = false;
246        Ok(result)
247    }
248}
249
250impl Client {
251    fn check_channel(&self) -> Result<(), ReadError> {
252        if self.initial_channel() {
253            Ok(())
254        } else {
255            Err(ReadError::ChannelChanged)
256        }
257    }
258
259    async fn read_wire(
260        &self,
261        session: &mut ReadSession,
262        operands: &[(ua::NodeId, ua::AttributeId)],
263    ) -> Result<Vec<DataValue>, ReadError> {
264        let request = ua::ReadRequest {
265            nodes_to_read: Some(
266                operands
267                    .iter()
268                    .map(|(node, attribute)| ua::ReadValueId {
269                        node_id: node.clone(),
270                        attribute_id: *attribute as u32,
271                        ..Default::default()
272                    })
273                    .collect(),
274            ),
275            timestamps_to_return: ua::TimestampsToReturn::Both,
276            ..Default::default()
277        };
278        let response = self.guarded(session, self.inner.request(request)).await?;
279        let values = response.results.unwrap_or_default();
280        if values.len() != operands.len() {
281            session.interrupted = true;
282            return Err(ReadError::InvalidServerMetadata);
283        }
284        Ok(values)
285    }
286
287    async fn guarded<T>(
288        &self,
289        session: &mut ReadSession,
290        operation: impl Future<Output = Result<T, ua::StatusCode>>,
291    ) -> Result<T, ReadError> {
292        self.check_channel()?;
293        let result = session.request(async { Ok(operation.await?) }).await?;
294        self.check_channel()?;
295        Ok(result)
296    }
297
298    async fn one_attribute(
299        &self,
300        session: &mut ReadSession,
301        node: ua::NodeId,
302        attribute: ua::AttributeId,
303    ) -> Result<DataValue, ReadError> {
304        self.read_wire(session, &[(node, attribute)])
305            .await?
306            .pop()
307            .ok_or(ReadError::InvalidServerMetadata)
308    }
309
310    async fn read_metadata_value(
311        &self,
312        session: &mut ReadSession,
313        id: u32,
314    ) -> Result<DataValue, ReadError> {
315        self.one_attribute(session, ua::NodeId::new(0, id), ua::AttributeId::Value)
316            .await
317    }
318
319    async fn load_metadata(&self, session: &mut ReadSession) -> Result<ReadMetadata, ReadError> {
320        // The server may accept only one operand, including during discovery.
321        let servers = self.read_metadata_value(session, SERVER_ARRAY).await?;
322        if strings(&servers)?.first().and_then(string) != Some(self.server_uri.as_str()) {
323            return Err(ReadError::ServerIdentity);
324        }
325        let namespaces = self.read_metadata_value(session, NAMESPACE_ARRAY).await?;
326        let namespaces = namespace_map(strings(&namespaces)?)?;
327        let capability = self
328            .read_metadata_value(session, MAX_NODES_PER_READ)
329            .await?;
330        Ok(ReadMetadata {
331            namespaces,
332            max_nodes_per_read: read_limit(&capability)?,
333        })
334    }
335
336    /// Read a single Value attribute, including its raw status and both clock fields.
337    pub async fn read(&self, node: &NodeId) -> Result<DataValue, ReadError> {
338        self.read_many(std::slice::from_ref(node))
339            .await?
340            .pop()
341            .ok_or(ReadError::InvalidServerMetadata)
342    }
343
344    /// Read an exact OPC UA scalar as its native Rust type, preserving node status and clocks.
345    pub async fn read_scalar<T: Scalar>(&self, node: &NodeId) -> Result<Sample<T>, ReadError> {
346        Sample::from_raw(&self.read(node).await?)
347    }
348
349    /// Read a batch as one Rust scalar type. Results follow input order, including duplicates.
350    /// A scalar-decoding error affects only its entry. A node with Bad or Uncertain
351    /// status yields a sample with its status and an absent value. A service or
352    /// namespace error fails the entire batch.
353    pub async fn read_scalars<T: Scalar>(
354        &self,
355        nodes: &[NodeId],
356    ) -> Result<Vec<Result<Sample<T>, ReadError>>, ReadError> {
357        self.read_batch(nodes.iter().map(ReadOperand::value), |raw| {
358            Sample::from_raw(&raw)
359        })
360        .await
361    }
362
363    /// Read up to [`MAX_READ_NODES`] Value attributes in order, including repeated nodes.
364    /// The client splits requests at the session's advertised MaxNodesPerRead and
365    /// uses singleton requests when the limit is unavailable or zero. Each request
366    /// can observe a different instant. A failed service returns no partial batch.
367    /// An empty slice succeeds without contacting the server.
368    pub async fn read_many(&self, nodes: &[NodeId]) -> Result<Vec<DataValue>, ReadError> {
369        self.read_batch(nodes.iter().map(ReadOperand::value), std::convert::identity)
370            .await
371    }
372
373    // Project each response before requesting the next chunk. A numeric poll only
374    // retains its samples and item errors, even if a misconfigured node is an array.
375    async fn read_batch<'a, T>(
376        &self,
377        requested: impl ExactSizeIterator<Item = ReadOperand<'a>>,
378        project: impl FnMut(DataValue) -> T,
379    ) -> Result<Vec<T>, ReadError> {
380        let count = requested.len();
381        if count > MAX_READ_NODES {
382            return Err(ReadError::TooManyNodes);
383        }
384        if count == 0 {
385            return Ok(Vec::new());
386        }
387        let (mut session, metadata) = self.read_session().await?;
388        self.read_locked(&mut session, metadata, requested, project)
389            .await
390    }
391
392    async fn read_locked<'a, T>(
393        &self,
394        session: &mut ReadSession,
395        metadata: &ReadMetadata,
396        requested: impl ExactSizeIterator<Item = ReadOperand<'a>>,
397        mut project: impl FnMut(DataValue) -> T,
398    ) -> Result<Vec<T>, ReadError> {
399        let mut operands = Vec::with_capacity(requested.len());
400        for (index, ReadOperand { node, attribute }) in requested.enumerate() {
401            let wire = metadata.namespaces.wire_node(node, index)?;
402            operands.push((wire, attribute));
403        }
404        let mut values = Vec::with_capacity(operands.len());
405        for chunk in operands.chunks(metadata.max_nodes_per_read) {
406            let response = self.read_wire(session, chunk).await?;
407            values.extend(response.into_iter().map(&mut project));
408        }
409        Ok(values)
410    }
411
412    async fn read_session(
413        &self,
414    ) -> Result<(tokio::sync::MutexGuard<'_, ReadSession>, &ReadMetadata), ReadError> {
415        let mut session = self.reads.lock().await;
416        if session.interrupted {
417            return Err(ReadError::SessionInterrupted);
418        }
419        self.check_channel()?;
420        let metadata = self
421            .metadata
422            .get_or_try_init(|| self.load_metadata(&mut session))
423            .await?;
424        Ok((session, metadata))
425    }
426}
427
428#[cfg(test)]
429mod tests {
430    use super::*;
431
432    #[test]
433    fn max_nodes_per_read_is_a_positive_bounded_uint32_or_a_safe_fallback() {
434        for (advertised, expected) in [(0, 1), (1, 1), (2, 2), (1024, 1024), (u32::MAX, 1024)] {
435            let value = ua::DataValue::value_only(ua::Variant::UInt32(advertised));
436            assert_eq!(read_limit(&value).unwrap(), expected);
437        }
438        assert_eq!(read_limit(&ua::DataValue::default()).unwrap(), 1);
439        let qualified = ua::DataValue {
440            status: Some(ua::StatusCode::GoodClamped),
441            ..ua::DataValue::value_only(ua::Variant::UInt32(3))
442        };
443        assert_eq!(read_limit(&qualified).unwrap(), 3);
444        let wrong_type = ua::DataValue::value_only(ua::Variant::UInt64(2));
445        for status in [
446            ua::StatusCode::BadNodeIdUnknown,
447            ua::StatusCode::BadUserAccessDenied,
448            ua::StatusCode::UncertainLastUsableValue,
449        ] {
450            let unavailable = ua::DataValue {
451                status: Some(status),
452                ..wrong_type.clone()
453            };
454            assert_eq!(read_limit(&unavailable).unwrap(), 1);
455        }
456        assert!(matches!(
457            read_limit(&wrong_type),
458            Err(ReadError::InvalidReadLimit)
459        ));
460        let array = ua::DataValue::value_only(ua::Variant::from(vec![2u32]));
461        assert!(matches!(
462            read_limit(&array),
463            Err(ReadError::InvalidReadLimit)
464        ));
465    }
466
467    #[test]
468    fn interrupted_service_requests_retire_the_namespace_mapping() {
469        use std::future::{pending, ready};
470        use std::task::{Context, Poll, Waker};
471
472        let mut session = ReadSession::default();
473        let mut cx = Context::from_waker(Waker::noop());
474        let mut request = Box::pin(session.request(pending::<Result<(), ReadError>>()));
475        assert!(request.as_mut().poll(&mut cx).is_pending());
476        drop(request);
477        assert!(matches!(
478            Box::pin(session.request(ready(Ok(()))))
479                .as_mut()
480                .poll(&mut cx),
481            Poll::Ready(Err(ReadError::SessionInterrupted))
482        ));
483
484        let mut session = ReadSession::default();
485        let expired = ReadError::Service(ua::StatusCode::BadSessionIdInvalid);
486        assert!(matches!(
487            Box::pin(session.request(ready(Err::<(), _>(expired))))
488                .as_mut()
489                .poll(&mut cx),
490            Poll::Ready(Err(ReadError::Service(_)))
491        ));
492        assert!(session.interrupted);
493    }
494
495    // A URI must identify one usable entry within the session limit.
496    #[test]
497    fn namespace_table_requires_unique_usable_uris_and_a_bounded_size() {
498        let standard = "http://opcfoundation.org/UA/";
499        let table = |uris: &[&str]| {
500            uris.iter()
501                .map(|uri| ua::Variant::String((*uri).into()))
502                .collect::<Vec<_>>()
503        };
504        for uris in [
505            vec![],
506            vec!["urn:other"],
507            vec![standard, standard],
508            vec![standard, ""],
509            vec![standard, "  "],
510            vec![standard, "urn:bad\nuri"],
511        ] {
512            assert!(matches!(
513                namespace_map(&table(&uris)),
514                Err(ReadError::InvalidServerMetadata)
515            ));
516        }
517        let mut last = "a".repeat(MAX_NAMESPACE_BYTES - standard.len());
518        assert_eq!(
519            namespace_map(&table(&[standard, &last])).unwrap().by_uri[last.as_str()],
520            1
521        );
522        last.push('a');
523        assert!(matches!(
524            namespace_map(&table(&[standard, &last])),
525            Err(ReadError::InvalidServerMetadata)
526        ));
527    }
528}