opcua-kit 0.1.0

Embeddable OPC UA client, server and UADP library for Rust applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! Ordered event notifications and Publish acknowledgement on a dedicated pinned session.
mod publish;
mod sequenced_data;
pub use sequenced_data::SequencedDataChanges;
pub(super) mod wire;
use super::ua;
use super::{
    BrowseName, CertificateRollover, Client, ConnectionConfig, ConnectionOptions, ReadError,
    RecoveringClient, RecoveryError, SubscriptionError,
};
use crate::NodeId;
pub use publish::Sequenced;
use std::time::Duration;

/// One select clause. The type identifies the event declaring the field. An empty
/// path selects the NodeId attribute of the event instance (for example ConditionId).
#[derive(Debug, Clone)]
pub struct EventField {
    /// Stable event type NodeId, such as BaseEventType (i=2041).
    pub type_definition: NodeId,
    /// Relative qualified field names. Up to eight components.
    pub path: Vec<BrowseName>,
}

impl EventField {
    /// Select the reported ConditionId (the NodeId attribute of ConditionType, empty browse path).
    /// For an instance outside the standard namespace, normalize the returned NodeId with
    /// [`Events::stable_node`] before using it on another session.
    pub fn condition_id() -> Self {
        Self {
            type_definition: NodeId::new("http://opcfoundation.org/UA/", "i=2782")
                .expect("standard node"),
            path: Vec::new(),
        }
    }

    /// Select one field of BaseEventType, such as EventId, Time, Message or Severity.
    pub fn base(name: &str) -> Result<Self, super::BrowseError> {
        let namespace = "http://opcfoundation.org/UA/";
        Ok(Self {
            type_definition: NodeId::new(namespace, "i=2041").expect("standard node"),
            path: vec![BrowseName::new(namespace, name)?],
        })
    }
}

#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
/// Dedicated Publish stream setup, delivery and retransmission failures.
pub enum PublishError {
    #[error(transparent)]
    /// Failed to establish a dedicated pinned session.
    Connect(#[from] RecoveryError),
    #[error("subscription service status 0x{0:08X}")]
    /// The server rejected the monitored item, event field, acknowledgement or subscription.
    Status(u32),
    #[error("subscription sequence cannot be recovered: expected {expected}, got {actual}")]
    /// A skipped message was unavailable, exceeded the recovery window, or the sequence was repeated.
    SequenceGap {
        /// Expected nonzero Publish sequence number.
        expected: u32,
        /// Observed sequence number.
        actual: u32,
    },
    #[error(transparent)]
    /// Channel, namespace or service failure.
    Session(#[from] ReadError),
    #[error(transparent)]
    /// Invalid interval/revision, wait timeout or loss of delivery.
    Subscription(#[from] SubscriptionError),
    #[error("select 1 to 32 event fields, each with up to eight valid browse names")]
    /// Invalid local selection.
    InvalidSelection,
    #[error("invalid or oversized OPC UA notification or subscription response")]
    /// The response has invalid shape, routing, or encoded size.
    InvalidNotification,
    #[error("the server reported an EventQueueOverflowEventType; resynchronize events")]
    /// The server reported lost events.
    ServerOverflow,
}

/// Error returned by an event stream and its condition operations.
pub type EventError = PublishError;

/// An event stream on a dedicated pinned session. Each notification contains the selected
/// Variants in caller order. Keep a pending Publish alive across cancelled or timed-out waits.
/// The server buffers events between calls; poll regularly within its subscription lifetime.
pub struct Events(publish::Stream<Vec<ua::Variant>>);

const OVERFLOW_EVENT: u32 = 3035;
const INTERNAL_FIELDS: [&str; 3] = ["EventType", "SourceNode", "SourceName"];
const MAX_WAIT: Duration = Duration::from_secs(60);

fn selected_values<'a>(
    mut fields: impl Iterator<Item = &'a ua::Variant> + Clone,
) -> Result<Vec<ua::Variant>, EventError> {
    let all = fields.clone();
    let Some(ua::Variant::NodeId(ty)) = fields.next() else {
        return Err(EventError::InvalidNotification);
    };
    if ty.is_null() {
        return Err(EventError::InvalidNotification);
    }
    if **ty == ua::NodeId::new(0, OVERFLOW_EVENT) {
        return Err(EventError::ServerOverflow);
    }
    // Part 5 §6.4.34 assigns this source to concrete overflow event subtypes.
    let server = match fields.next() {
        Some(ua::Variant::NodeId(node)) => **node == ua::NodeId::new(0, 2253),
        Some(ua::Variant::Empty) => false,
        _ => return Err(EventError::InvalidNotification),
    };
    match fields.next() {
        Some(ua::Variant::String(name))
            if server && name.as_ref() == "Internal/EventQueueOverflow" =>
        {
            return Err(EventError::ServerOverflow);
        }
        Some(ua::Variant::String(_) | ua::Variant::Empty) => (),
        _ => return Err(EventError::InvalidNotification),
    }
    let mut left = 128 * 1024usize;
    for field in all {
        let bytes = super::wire::variant_size(field).ok_or(EventError::InvalidNotification)?;
        left = left
            .checked_sub(bytes)
            .ok_or(EventError::InvalidNotification)?;
    }
    Ok(fields.cloned().collect())
}

impl Events {
    /// Translate a raw NodeId from an event delivered by this session to a URI-qualified identity.
    pub fn stable_node(&self, node: &ua::NodeId) -> Result<NodeId, EventError> {
        let metadata = self
            .0
            .client
            .as_ref()
            .and_then(|client| client.metadata.get())
            .ok_or(EventError::InvalidNotification)?;
        Ok(metadata.namespaces.stable_node(node)?)
    }

    #[cfg(feature = "control")]
    pub(super) fn condition_session(&self) -> Option<(&Client, u32)> {
        if self.0.ended {
            return None;
        }
        self.0
            .client
            .as_deref()
            .map(|client| (client, self.0.subscription))
    }

    /// Open a fresh authenticated session dedicated to one event notifier, and select 1–32
    /// ordered fields. Publishing interval: 10 ms to 60 s. Hidden EventType, SourceNode and
    /// SourceName fields recognize queue overflow notifications and concrete subtypes. The host can use a separate client for reads.
    pub async fn connect(
        config: ConnectionConfig<'_>,
        options: ConnectionOptions<'_>,
        notifier: &NodeId,
        fields: &[EventField],
        interval: Duration,
    ) -> Result<Self, EventError> {
        Self::open(
            RecoveringClient::new(config, options),
            notifier,
            fields,
            interval,
        )
        .await
    }

    /// Open an event session with an independently reviewed successor leaf and a deadline on
    /// the original leaf. Pin selection uses the same checks as [`Client::connect_with_rollover`].
    pub async fn connect_with_rollover(
        config: ConnectionConfig<'_>,
        options: ConnectionOptions<'_>,
        rollover: CertificateRollover<'_>,
        notifier: &NodeId,
        fields: &[EventField],
        interval: Duration,
    ) -> Result<Self, EventError> {
        Self::open(
            RecoveringClient::new_with_rollover(config, options, rollover),
            notifier,
            fields,
            interval,
        )
        .await
    }

    async fn open(
        owner: RecoveringClient<'_>,
        notifier: &NodeId,
        fields: &[EventField],
        interval: Duration,
    ) -> Result<Self, EventError> {
        if !(1..=32).contains(&fields.len())
            || fields
                .iter()
                .any(|f| f.path.len() > 8 || f.path.iter().any(|n| n.validate().is_err()))
        {
            return Err(EventError::InvalidSelection);
        }
        if !(Duration::from_millis(10)..=MAX_WAIT).contains(&interval) {
            return Err(SubscriptionError::InvalidInterval.into());
        }
        let client = owner.into_client().await?;
        let setup = Self::setup(&client, notifier, fields, interval).await;
        let (subscription, timeout_ms) = match setup {
            Ok(result) => result,
            Err(error) => {
                client.disconnect().await;
                return Err(error);
            }
        };
        Ok(Self(publish::Stream::new(
            client,
            subscription,
            timeout_ms,
            fields.len(),
            decode_events,
        )))
    }

    async fn setup(
        client: &Client,
        notifier: &NodeId,
        fields: &[EventField],
        interval: Duration,
    ) -> Result<(u32, u32), EventError> {
        let (mut session, metadata) = client.read_session().await?;
        let ns = &metadata.namespaces;
        let node = ns.wire_node(notifier, 0)?;
        let mut clauses: Vec<_> = INTERNAL_FIELDS
            .iter()
            .map(|&name| ua::SimpleAttributeOperand {
                type_definition_id: ua::NodeId::new(0, 2041),
                browse_path: Some(vec![ua::QualifiedName::new(0, name)]),
                attribute_id: 13,
                ..Default::default()
            })
            .collect();
        for (index, field) in fields.iter().enumerate() {
            let ty = ns.wire_node(&field.type_definition, index)?;
            let path = field
                .path
                .iter()
                .map(|name| {
                    let ns_index = ns
                        .by_uri
                        .get(name.namespace.as_str())
                        .ok_or(ReadError::UnknownNamespace { index })?;
                    Ok::<_, ReadError>(ua::QualifiedName::new(*ns_index, name.name.as_str()))
                })
                .collect::<Result<Vec<_>, _>>()?;
            clauses.push(ua::SimpleAttributeOperand {
                type_definition_id: ty,
                attribute_id: if path.is_empty() { 1 } else { 13 },
                browse_path: Some(path),
                ..Default::default()
            });
        }
        let count = clauses.len();
        let subscription = wire::create_subscription(client, &mut session, interval).await?;
        let filter = ua::ExtensionObject::new(ua::EventFilter {
            select_clauses: Some(clauses),
            ..Default::default()
        });
        let item = wire::item(node, 12, 1, Duration::ZERO, filter);
        let results = wire::create_items(client, &mut session, subscription.id, vec![item]).await?;
        let result = &results[0];
        if !result.status_code.is_good() {
            return Err(EventError::Status(result.status_code.bits()));
        }
        if result.monitored_item_id == 0 || !(1..=32).contains(&result.revised_queue_size) {
            return Err(SubscriptionError::InvalidRevision.into());
        }
        validate_filter(&result.filter_result, count)?;
        Ok((subscription.id, subscription.timeout_ms))
    }

    /// Wait for the next ordered event. Eligible retained messages are recovered via Republish.
    pub async fn next(&mut self, wait: Duration) -> Result<Vec<ua::Variant>, EventError> {
        Ok(self.next_with_sequence(wait).await?.value)
    }

    /// Return the Publish sequence and whether the event was recovered from the server's retransmission queue.
    pub async fn next_with_sequence(
        &mut self,
        wait: Duration,
    ) -> Result<Sequenced<Vec<ua::Variant>>, EventError> {
        self.0.next(wait).await
    }

    /// Cancel the outstanding request and close the dedicated subscription and session.
    pub async fn disconnect(self) {
        self.0.disconnect().await;
    }
}

fn validate_filter(filter: &ua::ExtensionObject, count: usize) -> Result<(), EventError> {
    if filter.is_null() {
        return Ok(());
    }
    let result = filter
        .inner_as::<ua::EventFilterResult>()
        .ok_or(EventError::InvalidNotification)?;
    let statuses = result.select_clause_results.as_deref().unwrap_or_default();
    if !statuses.is_empty() && statuses.len() != count {
        return Err(EventError::InvalidNotification);
    }
    if let Some(s) = statuses.iter().find(|s| !s.is_good()) {
        return Err(EventError::Status(s.bits()));
    }
    Ok(())
}

fn decode_events(
    note: &ua::ExtensionObject,
    count: usize,
    budget: &mut usize,
    events: &mut Vec<Vec<ua::Variant>>,
) -> Result<(), EventError> {
    let invalid = || EventError::InvalidNotification;
    let list = note
        .inner_as::<ua::EventNotificationList>()
        .ok_or_else(invalid)?;
    let rows = list.events.as_deref().unwrap_or_default();
    if rows.len() > 32 - events.len() {
        return Err(invalid());
    }
    for event in rows {
        let fields = event.event_fields.as_deref().unwrap_or_default();
        if event.client_handle != 1 || fields.len() != count + INTERNAL_FIELDS.len() {
            return Err(invalid());
        }
        let values = fields.iter();
        for value in values.clone() {
            *budget = budget
                .checked_sub(super::wire::variant_size(value).ok_or_else(invalid)?)
                .ok_or_else(invalid)?;
        }
        events.push(selected_values(values)?);
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn unexpected_filter_result_type_is_rejected() {
        assert!(validate_filter(&ua::ExtensionObject::default(), 1).is_ok());
        let other = ua::ExtensionObject::new(ua::EventFilter::default());
        assert!(matches!(
            validate_filter(&other, 1),
            Err(EventError::InvalidNotification)
        ));
    }

    #[test]
    fn concrete_overflow_uses_both_standard_source_fields() {
        let ty = ua::Variant::from(ua::NodeId::new(2, 2000));
        let server = ua::Variant::from(ua::NodeId::new(0, 2253));
        let other = ua::Variant::from(ua::NodeId::new(2, 2001));
        let name = ua::Variant::from("Internal/EventQueueOverflow");
        let absent = ua::Variant::Empty;
        assert!(matches!(
            selected_values([&ty, &server, &name].into_iter()),
            Err(EventError::ServerOverflow)
        ));
        assert!(
            selected_values([&ty, &other, &name].into_iter())
                .unwrap()
                .is_empty()
        );
        assert!(
            selected_values([&ty, &server, &absent].into_iter())
                .unwrap()
                .is_empty()
        );
        assert!(matches!(
            selected_values([&ty, &name, &server].into_iter()),
            Err(EventError::InvalidNotification)
        ));
    }

    #[test]
    fn event_type_and_exact_aggregate_budget_are_checked_before_copying_fields() {
        let ty = ua::Variant::from(ua::NodeId::new(0, 2041));
        let source = ua::Variant::from(ua::NodeId::new(0, 2253));
        let name = ua::Variant::from("Server");
        let hidden_bytes = [&ty, &source, &name]
            .iter()
            .map(|field| super::super::wire::variant_size(field).unwrap())
            .sum::<usize>();
        let capacity = 128 * 1024 - hidden_bytes - 5;
        let value = |size| ua::Variant::ByteString(vec![0; size].into());
        assert_eq!(
            selected_values([&ty, &source, &name, &value(capacity)].into_iter())
                .unwrap()
                .len(),
            1
        );
        assert!(matches!(
            selected_values([&ty, &source, &name, &value(capacity + 1)].into_iter()),
            Err(EventError::InvalidNotification)
        ));
        assert!(matches!(
            selected_values([&ua::Variant::from(ua::NodeId::new(0, 0))].into_iter()),
            Err(EventError::InvalidNotification)
        ));
        assert!(matches!(
            selected_values([&ua::Variant::from(ua::NodeId::new(0, 3035))].into_iter()),
            Err(EventError::ServerOverflow)
        ));
    }
}