Skip to main content

opcua_kit/client/
browse.rs

1use super::{
2    Client, Namespaces, ReadError, ReadSession, ua,
3    units::{MAX_PAGES, MAX_REFERENCES, Page, local_target, references},
4};
5use crate::NodeId;
6
7const MAX_PATH: usize = 16;
8const MAX_TEXT: usize = 4096;
9const MAX_RESULT_BYTES: usize = 1024 * 1024;
10
11/// A browse name qualified by its namespace URI. Names use case-sensitive exact matching.
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct BrowseName {
14    /// Namespace URI of the BrowseName, independent of the target NodeId namespace.
15    pub namespace: String,
16    /// Nonempty UTF-8 name.
17    pub name: String,
18}
19
20impl BrowseName {
21    /// Construct one path component. Each field accepts up to 4096 UTF-8 bytes.
22    pub fn new(namespace: impl Into<String>, name: impl Into<String>) -> Result<Self, BrowseError> {
23        let value = Self {
24            namespace: namespace.into(),
25            name: name.into(),
26        };
27        value.validate()?;
28        Ok(value)
29    }
30
31    pub(super) fn validate(&self) -> Result<(), BrowseError> {
32        if self.namespace.trim().is_empty()
33            || self.name.is_empty()
34            || [&self.namespace, &self.name]
35                .iter()
36                .any(|s| s.len() > MAX_TEXT || s.chars().any(char::is_control))
37        {
38            return Err(BrowseError::InvalidName);
39        }
40        Ok(())
41    }
42}
43
44/// One forward hierarchical reference. Browsing does not read its target Value.
45#[derive(Debug, Clone)]
46pub struct BrowseEntry {
47    /// Stable identity of the local target.
48    pub node: NodeId,
49    /// Namespace-qualified name used for relative navigation.
50    pub browse_name: BrowseName,
51    /// Actual reference subtype, such as HasComponent or HasProperty.
52    pub reference_type: NodeId,
53    /// Server-reported class of the target.
54    pub node_class: ua::NodeClass,
55}
56
57/// A local navigation request could not be completed unambiguously.
58#[derive(Debug, thiserror::Error)]
59#[non_exhaustive]
60pub enum BrowseError {
61    /// Transport or pinned session failure.
62    #[error(transparent)]
63    Session(ReadError),
64    /// One Browse or BrowseNext item had a nonzero status.
65    #[error("browse item status 0x{0:08X}")]
66    Status(u32),
67    /// Server returned an incomplete, remote or invalid reference.
68    #[error("invalid browse response or nonlocal reference")]
69    InvalidReference,
70    /// A name exceeds the byte limit, contains a control character, or is empty.
71    #[error("browse name and namespace must be nonempty and at most 4096 bytes without controls")]
72    InvalidName,
73    /// A listing or path exceeded a documented bound.
74    #[error("browse exceeded its reference, page, text or path limit")]
75    Limit,
76    /// No exact matching child at this zero-based path step.
77    #[error("no matching child for path component {0}")]
78    NotFound(usize),
79    /// More than one reference matched this zero-based path step.
80    #[error("ambiguous child at path component {0}")]
81    Ambiguous(usize),
82}
83
84impl From<ReadError> for BrowseError {
85    fn from(error: ReadError) -> Self {
86        match error {
87            ReadError::InvalidUnitReference | ReadError::InvalidDataType => Self::InvalidReference,
88            other => Self::Session(other),
89        }
90    }
91}
92
93fn entry(
94    namespaces: &Namespaces,
95    reference: &ua::ReferenceDescription,
96) -> Result<BrowseEntry, BrowseError> {
97    let valid_class = [
98        ua::NodeClass::Object,
99        ua::NodeClass::Variable,
100        ua::NodeClass::Method,
101        ua::NodeClass::ObjectType,
102        ua::NodeClass::VariableType,
103        ua::NodeClass::ReferenceType,
104        ua::NodeClass::DataType,
105        ua::NodeClass::View,
106    ]
107    .contains(&reference.node_class);
108    if !reference.is_forward || reference.reference_type_id.is_null() || !valid_class {
109        return Err(BrowseError::InvalidReference);
110    }
111    let qualified = &reference.browse_name;
112    let namespace = namespaces
113        .by_index
114        .get(usize::from(qualified.namespace_index))
115        .ok_or(BrowseError::InvalidReference)?;
116    let name = qualified
117        .name
118        .value()
119        .as_deref()
120        .ok_or(BrowseError::InvalidReference)?;
121    if namespace.len() > MAX_TEXT || name.len() > MAX_TEXT {
122        return Err(BrowseError::Limit);
123    }
124    let node = local_target(namespaces, &reference.node_id)?;
125    if node.namespace() == "http://opcfoundation.org/UA/" && node.identifier() == "i=0" {
126        return Err(BrowseError::InvalidReference);
127    }
128    Ok(BrowseEntry {
129        browse_name: BrowseName::new(namespace.as_ref(), name)?,
130        node,
131        reference_type: namespaces.stable_node(&reference.reference_type_id)?,
132        node_class: reference.node_class,
133    })
134}
135
136impl Client {
137    /// List all forward local hierarchical children of one node, including reference subtypes.
138    /// Output preserves server order. A listing is limited to 256 references, 256 pages,
139    /// and 1 MiB of retained identifier/name text. A failure discards the partial listing.
140    pub async fn browse_children(&self, node: &NodeId) -> Result<Vec<BrowseEntry>, BrowseError> {
141        let (mut session, metadata) = self.read_session().await?;
142        let mut pages = MAX_PAGES;
143        self.children_locked(&mut session, &metadata.namespaces, node, &mut pages)
144            .await
145    }
146
147    /// Follow 1–16 exact forward hierarchical browse names. Each step must match exactly
148    /// one child on this server. The complete path shares one 256-page budget.
149    pub async fn resolve_path(
150        &self,
151        start: &NodeId,
152        path: &[BrowseName],
153    ) -> Result<NodeId, BrowseError> {
154        if path.is_empty() || path.len() > MAX_PATH {
155            return Err(BrowseError::Limit);
156        }
157        for component in path {
158            component.validate()?;
159        }
160        let (mut session, metadata) = self.read_session().await?;
161        let mut node = start.clone();
162        let mut pages = MAX_PAGES;
163        for (index, component) in path.iter().enumerate() {
164            let children = self
165                .children_locked(&mut session, &metadata.namespaces, &node, &mut pages)
166                .await?;
167            let mut matching = children
168                .into_iter()
169                .filter(|child| &child.browse_name == component);
170            node = matching.next().ok_or(BrowseError::NotFound(index))?.node;
171            if matching.next().is_some() {
172                return Err(BrowseError::Ambiguous(index));
173            }
174        }
175        Ok(node)
176    }
177
178    async fn children_locked(
179        &self,
180        session: &mut ReadSession,
181        namespaces: &Namespaces,
182        node: &NodeId,
183        pages_left: &mut usize,
184    ) -> Result<Vec<BrowseEntry>, BrowseError> {
185        if *pages_left == 0 {
186            return Err(BrowseError::Limit);
187        }
188        let description = ua::BrowseDescription {
189            node_id: namespaces.wire_node(node, 0)?,
190            browse_direction: ua::BrowseDirection::Forward,
191            reference_type_id: ua::NodeId::new(0, 33u32),
192            include_subtypes: true,
193            result_mask: 0x0f,
194            node_class_mask: 0,
195        };
196        let request = ua::BrowseRequest {
197            requested_max_references_per_node: MAX_REFERENCES as u32,
198            nodes_to_browse: Some(vec![description]),
199            ..Default::default()
200        };
201        let mut page = Page::First(self.guarded(session, self.inner.request(request)).await?);
202        let mut children = Vec::new();
203        let mut bytes = MAX_RESULT_BYTES;
204        loop {
205            *pages_left -= 1;
206            let (result, point) = page.checked(session)?;
207            let inspected = (|| {
208                let status = result.status_code.bits();
209                if status != 0 {
210                    return Err(BrowseError::Status(status));
211                }
212                let batch = references(result)?;
213                if batch.len() > MAX_REFERENCES - children.len() {
214                    return Err(BrowseError::Limit);
215                }
216                for reference in batch {
217                    let child = entry(namespaces, reference)?;
218                    for field in [
219                        &child.browse_name.namespace,
220                        &child.browse_name.name,
221                        child.node.namespace(),
222                        child.node.identifier(),
223                        child.reference_type.namespace(),
224                        child.reference_type.identifier(),
225                    ] {
226                        bytes = bytes.checked_sub(field.len()).ok_or(BrowseError::Limit)?;
227                    }
228                    children.push(child);
229                }
230                Ok(())
231            })();
232            let Some(point) = point else {
233                inspected?;
234                return Ok(children);
235            };
236            if inspected.is_err() || *pages_left == 0 {
237                self.next_browse_page(session, point, true).await?;
238                inspected?;
239                return Err(BrowseError::Limit);
240            }
241            page = Page::Next(self.next_browse_page(session, point, false).await?);
242        }
243    }
244}