Skip to main content

opcua_kit/client/
events.rs

1//! Ordered event notifications and Publish acknowledgement on a dedicated pinned session.
2mod publish;
3mod sequenced_data;
4pub use sequenced_data::SequencedDataChanges;
5pub(super) mod wire;
6use super::ua;
7use super::{
8    BrowseName, CertificateRollover, Client, ConnectionConfig, ConnectionOptions, ReadError,
9    RecoveringClient, RecoveryError, SubscriptionError,
10};
11use crate::NodeId;
12pub use publish::Sequenced;
13use std::time::Duration;
14
15/// One select clause. The type identifies the event declaring the field. An empty
16/// path selects the NodeId attribute of the event instance (for example ConditionId).
17#[derive(Debug, Clone)]
18pub struct EventField {
19    /// Stable event type NodeId, such as BaseEventType (i=2041).
20    pub type_definition: NodeId,
21    /// Relative qualified field names. Up to eight components.
22    pub path: Vec<BrowseName>,
23}
24
25impl EventField {
26    /// Select the reported ConditionId (the NodeId attribute of ConditionType, empty browse path).
27    /// For an instance outside the standard namespace, normalize the returned NodeId with
28    /// [`Events::stable_node`] before using it on another session.
29    pub fn condition_id() -> Self {
30        Self {
31            type_definition: NodeId::new("http://opcfoundation.org/UA/", "i=2782")
32                .expect("standard node"),
33            path: Vec::new(),
34        }
35    }
36
37    /// Select one field of BaseEventType, such as EventId, Time, Message or Severity.
38    pub fn base(name: &str) -> Result<Self, super::BrowseError> {
39        let namespace = "http://opcfoundation.org/UA/";
40        Ok(Self {
41            type_definition: NodeId::new(namespace, "i=2041").expect("standard node"),
42            path: vec![BrowseName::new(namespace, name)?],
43        })
44    }
45}
46
47#[derive(Debug, thiserror::Error)]
48#[non_exhaustive]
49/// Dedicated Publish stream setup, delivery and retransmission failures.
50pub enum PublishError {
51    #[error(transparent)]
52    /// Failed to establish a dedicated pinned session.
53    Connect(#[from] RecoveryError),
54    #[error("subscription service status 0x{0:08X}")]
55    /// The server rejected the monitored item, event field, acknowledgement or subscription.
56    Status(u32),
57    #[error("subscription sequence cannot be recovered: expected {expected}, got {actual}")]
58    /// A skipped message was unavailable, exceeded the recovery window, or the sequence was repeated.
59    SequenceGap {
60        /// Expected nonzero Publish sequence number.
61        expected: u32,
62        /// Observed sequence number.
63        actual: u32,
64    },
65    #[error(transparent)]
66    /// Channel, namespace or service failure.
67    Session(#[from] ReadError),
68    #[error(transparent)]
69    /// Invalid interval/revision, wait timeout or loss of delivery.
70    Subscription(#[from] SubscriptionError),
71    #[error("select 1 to 32 event fields, each with up to eight valid browse names")]
72    /// Invalid local selection.
73    InvalidSelection,
74    #[error("invalid or oversized OPC UA notification or subscription response")]
75    /// The response has invalid shape, routing, or encoded size.
76    InvalidNotification,
77    #[error("the server reported an EventQueueOverflowEventType; resynchronize events")]
78    /// The server reported lost events.
79    ServerOverflow,
80}
81
82/// Error returned by an event stream and its condition operations.
83pub type EventError = PublishError;
84
85/// An event stream on a dedicated pinned session. Each notification contains the selected
86/// Variants in caller order. Keep a pending Publish alive across cancelled or timed-out waits.
87/// The server buffers events between calls; poll regularly within its subscription lifetime.
88pub struct Events(publish::Stream<Vec<ua::Variant>>);
89
90const OVERFLOW_EVENT: u32 = 3035;
91const INTERNAL_FIELDS: [&str; 3] = ["EventType", "SourceNode", "SourceName"];
92const MAX_WAIT: Duration = Duration::from_secs(60);
93
94fn selected_values<'a>(
95    mut fields: impl Iterator<Item = &'a ua::Variant> + Clone,
96) -> Result<Vec<ua::Variant>, EventError> {
97    let all = fields.clone();
98    let Some(ua::Variant::NodeId(ty)) = fields.next() else {
99        return Err(EventError::InvalidNotification);
100    };
101    if ty.is_null() {
102        return Err(EventError::InvalidNotification);
103    }
104    if **ty == ua::NodeId::new(0, OVERFLOW_EVENT) {
105        return Err(EventError::ServerOverflow);
106    }
107    // Part 5 §6.4.34 assigns this source to concrete overflow event subtypes.
108    let server = match fields.next() {
109        Some(ua::Variant::NodeId(node)) => **node == ua::NodeId::new(0, 2253),
110        Some(ua::Variant::Empty) => false,
111        _ => return Err(EventError::InvalidNotification),
112    };
113    match fields.next() {
114        Some(ua::Variant::String(name))
115            if server && name.as_ref() == "Internal/EventQueueOverflow" =>
116        {
117            return Err(EventError::ServerOverflow);
118        }
119        Some(ua::Variant::String(_) | ua::Variant::Empty) => (),
120        _ => return Err(EventError::InvalidNotification),
121    }
122    let mut left = 128 * 1024usize;
123    for field in all {
124        let bytes = super::wire::variant_size(field).ok_or(EventError::InvalidNotification)?;
125        left = left
126            .checked_sub(bytes)
127            .ok_or(EventError::InvalidNotification)?;
128    }
129    Ok(fields.cloned().collect())
130}
131
132impl Events {
133    /// Translate a raw NodeId from an event delivered by this session to a URI-qualified identity.
134    pub fn stable_node(&self, node: &ua::NodeId) -> Result<NodeId, EventError> {
135        let metadata = self
136            .0
137            .client
138            .as_ref()
139            .and_then(|client| client.metadata.get())
140            .ok_or(EventError::InvalidNotification)?;
141        Ok(metadata.namespaces.stable_node(node)?)
142    }
143
144    #[cfg(feature = "control")]
145    pub(super) fn condition_session(&self) -> Option<(&Client, u32)> {
146        if self.0.ended {
147            return None;
148        }
149        self.0
150            .client
151            .as_deref()
152            .map(|client| (client, self.0.subscription))
153    }
154
155    /// Open a fresh authenticated session dedicated to one event notifier, and select 1–32
156    /// ordered fields. Publishing interval: 10 ms to 60 s. Hidden EventType, SourceNode and
157    /// SourceName fields recognize queue overflow notifications and concrete subtypes. The host can use a separate client for reads.
158    pub async fn connect(
159        config: ConnectionConfig<'_>,
160        options: ConnectionOptions<'_>,
161        notifier: &NodeId,
162        fields: &[EventField],
163        interval: Duration,
164    ) -> Result<Self, EventError> {
165        Self::open(
166            RecoveringClient::new(config, options),
167            notifier,
168            fields,
169            interval,
170        )
171        .await
172    }
173
174    /// Open an event session with an independently reviewed successor leaf and a deadline on
175    /// the original leaf. Pin selection uses the same checks as [`Client::connect_with_rollover`].
176    pub async fn connect_with_rollover(
177        config: ConnectionConfig<'_>,
178        options: ConnectionOptions<'_>,
179        rollover: CertificateRollover<'_>,
180        notifier: &NodeId,
181        fields: &[EventField],
182        interval: Duration,
183    ) -> Result<Self, EventError> {
184        Self::open(
185            RecoveringClient::new_with_rollover(config, options, rollover),
186            notifier,
187            fields,
188            interval,
189        )
190        .await
191    }
192
193    async fn open(
194        owner: RecoveringClient<'_>,
195        notifier: &NodeId,
196        fields: &[EventField],
197        interval: Duration,
198    ) -> Result<Self, EventError> {
199        if !(1..=32).contains(&fields.len())
200            || fields
201                .iter()
202                .any(|f| f.path.len() > 8 || f.path.iter().any(|n| n.validate().is_err()))
203        {
204            return Err(EventError::InvalidSelection);
205        }
206        if !(Duration::from_millis(10)..=MAX_WAIT).contains(&interval) {
207            return Err(SubscriptionError::InvalidInterval.into());
208        }
209        let client = owner.into_client().await?;
210        let setup = Self::setup(&client, notifier, fields, interval).await;
211        let (subscription, timeout_ms) = match setup {
212            Ok(result) => result,
213            Err(error) => {
214                client.disconnect().await;
215                return Err(error);
216            }
217        };
218        Ok(Self(publish::Stream::new(
219            client,
220            subscription,
221            timeout_ms,
222            fields.len(),
223            decode_events,
224        )))
225    }
226
227    async fn setup(
228        client: &Client,
229        notifier: &NodeId,
230        fields: &[EventField],
231        interval: Duration,
232    ) -> Result<(u32, u32), EventError> {
233        let (mut session, metadata) = client.read_session().await?;
234        let ns = &metadata.namespaces;
235        let node = ns.wire_node(notifier, 0)?;
236        let mut clauses: Vec<_> = INTERNAL_FIELDS
237            .iter()
238            .map(|&name| ua::SimpleAttributeOperand {
239                type_definition_id: ua::NodeId::new(0, 2041),
240                browse_path: Some(vec![ua::QualifiedName::new(0, name)]),
241                attribute_id: 13,
242                ..Default::default()
243            })
244            .collect();
245        for (index, field) in fields.iter().enumerate() {
246            let ty = ns.wire_node(&field.type_definition, index)?;
247            let path = field
248                .path
249                .iter()
250                .map(|name| {
251                    let ns_index = ns
252                        .by_uri
253                        .get(name.namespace.as_str())
254                        .ok_or(ReadError::UnknownNamespace { index })?;
255                    Ok::<_, ReadError>(ua::QualifiedName::new(*ns_index, name.name.as_str()))
256                })
257                .collect::<Result<Vec<_>, _>>()?;
258            clauses.push(ua::SimpleAttributeOperand {
259                type_definition_id: ty,
260                attribute_id: if path.is_empty() { 1 } else { 13 },
261                browse_path: Some(path),
262                ..Default::default()
263            });
264        }
265        let count = clauses.len();
266        let subscription = wire::create_subscription(client, &mut session, interval).await?;
267        let filter = ua::ExtensionObject::new(ua::EventFilter {
268            select_clauses: Some(clauses),
269            ..Default::default()
270        });
271        let item = wire::item(node, 12, 1, Duration::ZERO, filter);
272        let results = wire::create_items(client, &mut session, subscription.id, vec![item]).await?;
273        let result = &results[0];
274        if !result.status_code.is_good() {
275            return Err(EventError::Status(result.status_code.bits()));
276        }
277        if result.monitored_item_id == 0 || !(1..=32).contains(&result.revised_queue_size) {
278            return Err(SubscriptionError::InvalidRevision.into());
279        }
280        validate_filter(&result.filter_result, count)?;
281        Ok((subscription.id, subscription.timeout_ms))
282    }
283
284    /// Wait for the next ordered event. Eligible retained messages are recovered via Republish.
285    pub async fn next(&mut self, wait: Duration) -> Result<Vec<ua::Variant>, EventError> {
286        Ok(self.next_with_sequence(wait).await?.value)
287    }
288
289    /// Return the Publish sequence and whether the event was recovered from the server's retransmission queue.
290    pub async fn next_with_sequence(
291        &mut self,
292        wait: Duration,
293    ) -> Result<Sequenced<Vec<ua::Variant>>, EventError> {
294        self.0.next(wait).await
295    }
296
297    /// Cancel the outstanding request and close the dedicated subscription and session.
298    pub async fn disconnect(self) {
299        self.0.disconnect().await;
300    }
301}
302
303fn validate_filter(filter: &ua::ExtensionObject, count: usize) -> Result<(), EventError> {
304    if filter.is_null() {
305        return Ok(());
306    }
307    let result = filter
308        .inner_as::<ua::EventFilterResult>()
309        .ok_or(EventError::InvalidNotification)?;
310    let statuses = result.select_clause_results.as_deref().unwrap_or_default();
311    if !statuses.is_empty() && statuses.len() != count {
312        return Err(EventError::InvalidNotification);
313    }
314    if let Some(s) = statuses.iter().find(|s| !s.is_good()) {
315        return Err(EventError::Status(s.bits()));
316    }
317    Ok(())
318}
319
320fn decode_events(
321    note: &ua::ExtensionObject,
322    count: usize,
323    budget: &mut usize,
324    events: &mut Vec<Vec<ua::Variant>>,
325) -> Result<(), EventError> {
326    let invalid = || EventError::InvalidNotification;
327    let list = note
328        .inner_as::<ua::EventNotificationList>()
329        .ok_or_else(invalid)?;
330    let rows = list.events.as_deref().unwrap_or_default();
331    if rows.len() > 32 - events.len() {
332        return Err(invalid());
333    }
334    for event in rows {
335        let fields = event.event_fields.as_deref().unwrap_or_default();
336        if event.client_handle != 1 || fields.len() != count + INTERNAL_FIELDS.len() {
337            return Err(invalid());
338        }
339        let values = fields.iter();
340        for value in values.clone() {
341            *budget = budget
342                .checked_sub(super::wire::variant_size(value).ok_or_else(invalid)?)
343                .ok_or_else(invalid)?;
344        }
345        events.push(selected_values(values)?);
346    }
347    Ok(())
348}
349
350#[cfg(test)]
351mod tests {
352    use super::*;
353
354    #[test]
355    fn unexpected_filter_result_type_is_rejected() {
356        assert!(validate_filter(&ua::ExtensionObject::default(), 1).is_ok());
357        let other = ua::ExtensionObject::new(ua::EventFilter::default());
358        assert!(matches!(
359            validate_filter(&other, 1),
360            Err(EventError::InvalidNotification)
361        ));
362    }
363
364    #[test]
365    fn concrete_overflow_uses_both_standard_source_fields() {
366        let ty = ua::Variant::from(ua::NodeId::new(2, 2000));
367        let server = ua::Variant::from(ua::NodeId::new(0, 2253));
368        let other = ua::Variant::from(ua::NodeId::new(2, 2001));
369        let name = ua::Variant::from("Internal/EventQueueOverflow");
370        let absent = ua::Variant::Empty;
371        assert!(matches!(
372            selected_values([&ty, &server, &name].into_iter()),
373            Err(EventError::ServerOverflow)
374        ));
375        assert!(
376            selected_values([&ty, &other, &name].into_iter())
377                .unwrap()
378                .is_empty()
379        );
380        assert!(
381            selected_values([&ty, &server, &absent].into_iter())
382                .unwrap()
383                .is_empty()
384        );
385        assert!(matches!(
386            selected_values([&ty, &name, &server].into_iter()),
387            Err(EventError::InvalidNotification)
388        ));
389    }
390
391    #[test]
392    fn event_type_and_exact_aggregate_budget_are_checked_before_copying_fields() {
393        let ty = ua::Variant::from(ua::NodeId::new(0, 2041));
394        let source = ua::Variant::from(ua::NodeId::new(0, 2253));
395        let name = ua::Variant::from("Server");
396        let hidden_bytes = [&ty, &source, &name]
397            .iter()
398            .map(|field| super::super::wire::variant_size(field).unwrap())
399            .sum::<usize>();
400        let capacity = 128 * 1024 - hidden_bytes - 5;
401        let value = |size| ua::Variant::ByteString(vec![0; size].into());
402        assert_eq!(
403            selected_values([&ty, &source, &name, &value(capacity)].into_iter())
404                .unwrap()
405                .len(),
406            1
407        );
408        assert!(matches!(
409            selected_values([&ty, &source, &name, &value(capacity + 1)].into_iter()),
410            Err(EventError::InvalidNotification)
411        ));
412        assert!(matches!(
413            selected_values([&ua::Variant::from(ua::NodeId::new(0, 0))].into_iter()),
414            Err(EventError::InvalidNotification)
415        ));
416        assert!(matches!(
417            selected_values([&ua::Variant::from(ua::NodeId::new(0, 3035))].into_iter()),
418            Err(EventError::ServerOverflow)
419        ));
420    }
421}