Skip to main content

opcua_kit/client/
subscription.rs

1use std::{
2    collections::BTreeMap,
3    sync::{
4        Arc, Mutex, OnceLock,
5        atomic::{AtomicBool, Ordering},
6    },
7    time::Duration,
8};
9
10use super::events::wire;
11use tokio::sync::{SemaphorePermit, mpsc};
12
13use super::{Client, DataValue, ReadError, ua};
14use crate::NodeId;
15
16/// Maximum number of requested Value attributes in one subscription.
17pub const MAX_MONITORED_NODES: usize = 32;
18const CAPACITY: usize = 32;
19const MAX_VALUE_BYTES: usize = 128 * 1024;
20const MIN_INTERVAL: Duration = Duration::from_millis(10);
21const MAX_WAIT: Duration = Duration::from_secs(60);
22
23/// Setup or reception of an authenticated sampled Value notification failed.
24#[derive(Debug, thiserror::Error)]
25#[non_exhaustive]
26pub enum SubscriptionError {
27    /// Transport, namespace, or original pinned session is unavailable.
28    #[error(transparent)]
29    Session(#[from] ReadError),
30    /// Requested sample/publish interval is outside 10 milliseconds to 60 seconds.
31    #[error("subscription interval must be between 10 milliseconds and 60 seconds")]
32    InvalidInterval,
33    /// Wait must be positive and at most one minute.
34    #[error("notification wait must be positive and at most 60 seconds")]
35    InvalidWait,
36    /// One subscription takes between one and 32 nodes.
37    #[error("a subscription requires 1 to {MAX_MONITORED_NODES} nodes")]
38    ItemCount,
39    /// The peer rejected an individual monitored item during setup.
40    #[error("monitored item {index} was rejected: {source}")]
41    ItemRejected {
42        /// Zero-based position in the supplied list.
43        index: usize,
44        /// Original OPC UA status for the item.
45        #[source]
46        source: ua::StatusCode,
47    },
48    /// Eight active subscriptions already exist on this client.
49    #[error("client already has eight active subscriptions")]
50    Limit,
51    /// Server did not supply usable revised intervals and a queue of 2–32 entries.
52    #[error("unusable revised subscription or monitored item parameters")]
53    InvalidRevision,
54    /// The peer supplied an unusable sampling interval or queue for this member.
55    #[error("unusable revised parameters for monitored item {index}")]
56    ItemRevision {
57        /// Zero-based position in the supplied list.
58        index: usize,
59    },
60    /// The bounded notification queue filled. Create a fresh subscription.
61    #[error("local notification buffer overflowed; resynchronize the value")]
62    LocalOverflow,
63    /// A notification's Variant exceeded 128 KiB of UA binary data or could not be measured.
64    #[error(
65        "notification Variant exceeds the supported 128 KiB limit or has no valid binary encoding"
66    )]
67    ValueLimit,
68    /// A group member's Variant exceeded the supported binary size or could not be measured.
69    #[error("notification for item {index} exceeds 128 KiB or has no valid binary encoding")]
70    ItemValueLimit {
71        /// Zero-based position in the supplied list.
72        index: usize,
73    },
74    /// The peer indicated its monitored item queue overflowed; includes the full raw status.
75    #[error("server notification queue overflowed (status 0x{0:08X}); resynchronize the value")]
76    ServerOverflow(u32),
77    /// A group member reported its server-side queue overflow.
78    #[error(
79        "server queue overflowed for item {index} (status 0x{status:08X}); resynchronize the group"
80    )]
81    ItemOverflow {
82        /// Zero-based position in the supplied list.
83        index: usize,
84        /// Full OPC UA StatusCode.
85        status: u32,
86    },
87    /// A Publish response skipped or repeated a sequence number.
88    #[error("data-change sequence gap: expected {expected}, got {actual}")]
89    SequenceGap {
90        /// Next sequence expected on this subscription.
91        expected: u32,
92        /// Sequence returned by the server.
93        actual: u32,
94    },
95    /// No notification arrived within this caller-selected wait. The handle remains usable.
96    #[error("timed out waiting for a data change")]
97    Timeout,
98    /// The monitored item or client stopped delivering, or a terminal error was already reported.
99    #[error("data-change subscription ended; resynchronize on a fresh session")]
100    Ended,
101}
102
103#[derive(Default)]
104struct Loss {
105    local: AtomicBool,
106    gap: OnceLock<(u32, u32)>,
107    server: OnceLock<(usize, u32)>,
108    closed: AtomicBool,
109    value_limit: OnceLock<usize>,
110}
111
112impl Loss {
113    fn check(&self) -> Result<(), SubscriptionError> {
114        if let Some(&(expected, actual)) = self.gap.get() {
115            return Err(SubscriptionError::SequenceGap { expected, actual });
116        }
117        if let Some(&(index, status)) = self.server.get() {
118            return Err(SubscriptionError::ItemOverflow { index, status });
119        }
120        if let Some(&index) = self.value_limit.get() {
121            return Err(SubscriptionError::ItemValueLimit { index });
122        }
123        if self.local.load(Ordering::Acquire) {
124            return Err(SubscriptionError::LocalOverflow);
125        }
126        if self.closed.load(Ordering::Acquire) {
127            return Err(SubscriptionError::Ended);
128        }
129        Ok(())
130    }
131
132    fn deliver(&self, tx: &mpsc::Sender<Option<DataChange>>, index: usize, value: &DataValue) {
133        if self.check().is_err() {
134            return;
135        }
136        let status = value.status.unwrap_or_default().bits();
137        // StatusCode InfoType=DataValue (bits 10–11) and Overflow (bit 7).
138        let message = if status & 0x0000_0c80 == 0x0000_0480 {
139            let _ = self.server.set((index, status));
140            None
141        } else if value.value.as_ref().is_some_and(|variant| {
142            super::wire::variant_size(variant).is_none_or(|bytes| bytes > MAX_VALUE_BYTES)
143        }) {
144            let _ = self.value_limit.set(index);
145            None
146        } else {
147            Some(DataChange {
148                index,
149                value: value.clone(),
150            })
151        };
152        if let Err(mpsc::error::TrySendError::Full(_)) = tx.try_send(message) {
153            self.local.store(true, Ordering::Release);
154        }
155    }
156}
157
158/// Source position and unmodified OPC UA DataValue for one notification.
159#[derive(Debug)]
160pub struct DataChange {
161    /// Index into [`MonitoredDataChanges::items`] in the original request order.
162    pub index: usize,
163    /// Original status, clocks and Variant emitted by the peer.
164    pub value: DataValue,
165}
166
167/// Stable identity and revised monitoring parameters for one group member.
168#[derive(Debug)]
169pub struct MonitoredNode {
170    /// Namespace URI and identifier supplied by the application.
171    pub node: NodeId,
172    /// Server-revised sampling interval.
173    pub sampling_interval: Duration,
174    /// Server-revised monitored item queue capacity.
175    pub queue_size: u32,
176}
177
178/// One OPC UA subscription monitoring multiple Value attributes on the original session.
179/// Drop requests deletion of all items and the subscription. A loss on any item ends the group.
180/// Use a dedicated sequenced stream when you need retransmission or per-message provenance.
181pub struct MonitoredDataChanges<'a> {
182    client: &'a Client,
183    receiver: mpsc::Receiver<Option<DataChange>>,
184    pending: Option<DataChange>,
185    loss: Arc<Loss>,
186    ended: bool,
187    items: Vec<MonitoredNode>,
188    publishing: Duration,
189    _registration: Registration,
190    _permit: SemaphorePermit<'a>,
191}
192
193/// Single-node convenience handle returned by [`Client::subscribe`].
194pub struct DataChanges<'a>(MonitoredDataChanges<'a>);
195
196/// Publish responses can carry notifications for any subscription on the session.
197#[derive(Clone, Default)]
198pub(super) struct PublishGroups(Arc<Mutex<GroupState>>);
199
200#[derive(Default)]
201struct GroupState {
202    routes: BTreeMap<u32, Route>,
203    running: bool,
204    changes: u64,
205}
206
207struct Route {
208    sender: mpsc::Sender<Option<DataChange>>,
209    loss: Arc<Loss>,
210    count: usize,
211    expected: u32,
212    timeout_ms: u32,
213}
214
215impl Route {
216    fn end(&self) {
217        self.loss.closed.store(true, Ordering::Release);
218        let _ = self.sender.try_send(None);
219    }
220
221    fn receive(&mut self, message: &ua::NotificationMessage) {
222        let notes = message.notification_data.as_deref().unwrap_or_default();
223        if self.expected != message.sequence_number {
224            let _ = self.loss.gap.set((self.expected, message.sequence_number));
225            self.end();
226            return;
227        }
228        if notes.is_empty() {
229            return;
230        }
231        self.expected = self.expected.wrapping_add(1).max(1);
232        let mut changes = Vec::new();
233        if notes.len() > CAPACITY {
234            self.end();
235            return;
236        }
237        for note in notes {
238            let Some(data) = note.inner_as::<ua::DataChangeNotification>() else {
239                self.end();
240                return;
241            };
242            let items = data.monitored_items.as_deref().unwrap_or_default();
243            if items.is_empty() || items.len() > CAPACITY - changes.len() {
244                self.end();
245                return;
246            }
247            for item in items {
248                let Some(index) = item
249                    .client_handle
250                    .checked_sub(1)
251                    .map(|n| n as usize)
252                    .filter(|&n| n < self.count)
253                else {
254                    self.end();
255                    return;
256                };
257                changes.push((index, &item.value));
258            }
259        }
260        for (index, data) in changes {
261            self.loss.deliver(&self.sender, index, data);
262        }
263    }
264}
265
266struct Registration {
267    groups: PublishGroups,
268    id: u32,
269    session: Arc<super::connection::Session>,
270    runtime: tokio::runtime::Handle,
271}
272
273impl Drop for Registration {
274    fn drop(&mut self) {
275        let mut state = self.groups.0.lock().expect("publish routes");
276        state.routes.remove(&self.id);
277        state.changes = state.changes.wrapping_add(1);
278        drop(state);
279        let session = self.session.clone();
280        let id = self.id;
281        self.runtime.spawn(async move {
282            let _ = session
283                .request(ua::DeleteSubscriptionsRequest {
284                    subscription_ids: Some(vec![id]),
285                    ..Default::default()
286                })
287                .await;
288        });
289    }
290}
291
292impl GroupState {
293    fn stop(&mut self) {
294        for route in self.routes.values() {
295            route.end();
296        }
297        self.running = false;
298    }
299}
300
301impl PublishGroups {
302    fn register(
303        &self,
304        session: &Arc<super::connection::Session>,
305        id: u32,
306        route: Route,
307    ) -> Result<Registration, SubscriptionError> {
308        let mut state = self.0.lock().expect("publish routes");
309        if state.routes.contains_key(&id) {
310            return Err(SubscriptionError::InvalidRevision);
311        }
312        state.routes.insert(id, route);
313        state.changes = state.changes.wrapping_add(1);
314        if !state.running {
315            state.running = true;
316            tokio::spawn(self.clone().run(session.clone()));
317        }
318        Ok(Registration {
319            groups: self.clone(),
320            id,
321            session: session.clone(),
322            runtime: tokio::runtime::Handle::current(),
323        })
324    }
325
326    async fn run(self, session: Arc<super::connection::Session>) {
327        let mut ack = None;
328        loop {
329            let (timeout, changes) = {
330                let mut state = self.0.lock().expect("publish routes");
331                let Some(timeout) = state.routes.values().map(|r| r.timeout_ms).max() else {
332                    state.running = false;
333                    return;
334                };
335                (timeout, state.changes)
336            };
337            let sent: Option<ua::SubscriptionAcknowledgement> = ack.take();
338            let req = wire::publish(sent.iter().cloned().collect(), timeout);
339            let result = session.request(req).await;
340            let mut state = self.0.lock().expect("publish routes");
341            match result {
342                Ok(reply) => {
343                    let statuses = reply.results.as_deref().unwrap_or_default();
344                    if statuses.len() != usize::from(sent.is_some()) {
345                        state.stop();
346                        return;
347                    }
348                    if let Some(ack) = sent
349                        && !statuses[0].is_good()
350                        && let Some(route) = state.routes.get(&ack.subscription_id)
351                    {
352                        route.end();
353                    }
354                    if let Some(route) = state.routes.get_mut(&reply.subscription_id) {
355                        let seq = reply.notification_message.sequence_number;
356                        let available = reply
357                            .available_sequence_numbers
358                            .as_deref()
359                            .unwrap_or_default();
360                        if available.len() > 4096 {
361                            route.end();
362                            continue;
363                        }
364                        route.receive(&reply.notification_message);
365                        if reply
366                            .notification_message
367                            .notification_data
368                            .as_ref()
369                            .is_some_and(|n| !n.is_empty())
370                            && available.contains(&seq)
371                        {
372                            ack = Some(ua::SubscriptionAcknowledgement {
373                                subscription_id: reply.subscription_id,
374                                sequence_number: seq,
375                            });
376                        }
377                    }
378                }
379                Err(ua::StatusCode::BadNoSubscription) if changes != state.changes => continue,
380                Err(_) => {
381                    state.stop();
382                    return;
383                }
384            }
385        }
386    }
387}
388
389impl Client {
390    /// Subscribe to sampled data changes for one selected Value. The supplied interval
391    /// applies to sampling and publishing (10 ms to 60 s); inspect the revised intervals
392    /// on the returned handle. Up to eight handles can be active per client.
393    pub async fn subscribe(
394        &self,
395        node: &NodeId,
396        interval: Duration,
397    ) -> Result<DataChanges<'_>, SubscriptionError> {
398        self.subscribe_many(std::slice::from_ref(node), interval)
399            .await
400            .map(DataChanges)
401            .map_err(|error| match error {
402                SubscriptionError::ItemRejected { source, .. } => ReadError::Service(source).into(),
403                SubscriptionError::ItemRevision { .. } => SubscriptionError::InvalidRevision,
404                other => other,
405            })
406    }
407
408    /// Monitor 1–32 nodes in one subscription. Each result refers to the corresponding
409    /// input index, including repeated nodes. All namespaces are resolved before creation.
410    /// An item rejection fails the entire setup and releases any accepted siblings.
411    /// A timeout leaves the subscription usable. After a terminal loss, resynchronize all
412    /// values and create a fresh subscription. The shared local queue holds 32 notifications.
413    ///
414    /// ```
415    /// # use std::time::Duration;
416    /// # use opcua_kit::{Client, NodeId, SubscriptionError};
417    /// # async fn observe(client: &Client, pressure: NodeId, fan: NodeId) -> Result<(), SubscriptionError> {
418    /// let mut changes = client.subscribe_many(&[pressure, fan], Duration::from_millis(250)).await?;
419    /// let change = changes.next(Duration::from_secs(5)).await?;
420    /// let source = &changes.items()[change.index].node;
421    /// println!("{}: {:?}", source.identifier(), change.value);
422    /// # Ok(()) }
423    /// ```
424    pub async fn subscribe_many(
425        &self,
426        nodes: &[NodeId],
427        interval: Duration,
428    ) -> Result<MonitoredDataChanges<'_>, SubscriptionError> {
429        if !(1..=MAX_MONITORED_NODES).contains(&nodes.len()) {
430            return Err(SubscriptionError::ItemCount);
431        }
432        if !(MIN_INTERVAL..=MAX_WAIT).contains(&interval) {
433            return Err(SubscriptionError::InvalidInterval);
434        }
435        let permit = self
436            .subscriptions
437            .try_acquire()
438            .map_err(|_| SubscriptionError::Limit)?;
439        let (mut session, metadata) = self.read_session().await?;
440        let wire_nodes = nodes
441            .iter()
442            .enumerate()
443            .map(|(index, node)| metadata.namespaces.wire_node(node, index))
444            .collect::<Result<Vec<_>, _>>()?;
445        let sub = wire::create_subscription(self, &mut session, interval).await?;
446        let (sender, receiver) = mpsc::channel(CAPACITY);
447        let loss = Arc::new(Loss::default());
448        let registration = self.publish_groups.register(
449            &self.inner,
450            sub.id,
451            Route {
452                sender,
453                loss: loss.clone(),
454                expected: 1,
455                count: nodes.len(),
456                timeout_ms: sub.timeout_ms,
457            },
458        )?;
459        let requests = wire_nodes
460            .into_iter()
461            .enumerate()
462            .map(|(i, node)| wire::item(node, 13, (i + 1) as u32, interval, Default::default()))
463            .collect();
464        let results = wire::create_items(self, &mut session, sub.id, requests).await?;
465        let items = match wire::revisions(nodes, &results) {
466            Ok(items) => items,
467            Err(error) => {
468                let accepted: Vec<_> = results
469                    .iter()
470                    .filter(|r| r.status_code.is_good() && r.monitored_item_id != 0)
471                    .map(|r| r.monitored_item_id)
472                    .collect();
473                if !accepted.is_empty() {
474                    let cleanup = ua::DeleteMonitoredItemsRequest {
475                        subscription_id: sub.id,
476                        monitored_item_ids: Some(accepted),
477                        ..Default::default()
478                    };
479                    let _ = self
480                        .guarded(&mut session, self.inner.request(cleanup))
481                        .await;
482                }
483                return Err(error);
484            }
485        };
486        Ok(MonitoredDataChanges {
487            client: self,
488            receiver,
489            pending: None,
490            loss,
491            ended: false,
492            items,
493            publishing: sub.interval,
494            _registration: registration,
495            _permit: permit,
496        })
497    }
498}
499
500impl DataChanges<'_> {
501    /// Revised interval at which the server samples the variable.
502    pub const fn sampling_interval(&self) -> Duration {
503        self.0.items.as_slice()[0].sampling_interval
504    }
505    /// Revised interval at which the server checks for publishable notifications.
506    pub const fn publishing_interval(&self) -> Duration {
507        self.0.publishing_interval()
508    }
509    /// Revised monitored item queue size at the peer.
510    pub const fn server_queue_size(&self) -> u32 {
511        self.0.items.as_slice()[0].queue_size
512    }
513
514    /// Wait for one DataValue. A timeout is retryable, and cancellation preserves a dequeued value.
515    pub async fn next(&mut self, wait: Duration) -> Result<DataValue, SubscriptionError> {
516        match self.0.next(wait).await {
517            Ok(change) => Ok(change.value),
518            Err(SubscriptionError::ItemValueLimit { .. }) => Err(SubscriptionError::ValueLimit),
519            Err(SubscriptionError::ItemOverflow { status, .. }) => {
520                Err(SubscriptionError::ServerOverflow(status))
521            }
522            Err(other) => Err(other),
523        }
524    }
525}
526
527impl MonitoredDataChanges<'_> {
528    /// Monitored identities and revised parameters in original input order.
529    pub fn items(&self) -> &[MonitoredNode] {
530        &self.items
531    }
532    /// Revised interval shared by this subscription.
533    pub const fn publishing_interval(&self) -> Duration {
534        self.publishing
535    }
536
537    fn healthy(&self) -> Result<(), SubscriptionError> {
538        self.client.check_channel()?;
539        if !self.client.inner.is_alive() {
540            return Err(SubscriptionError::Ended);
541        }
542        if self
543            .client
544            .reads
545            .try_lock()
546            .is_ok_and(|session| session.interrupted)
547        {
548            return Err(ReadError::SessionInterrupted.into());
549        }
550        self.loss.check()
551    }
552
553    async fn receive(&mut self) -> Result<DataChange, SubscriptionError> {
554        self.healthy()?;
555        if self.pending.is_none() {
556            self.pending = self.receiver.recv().await.ok_or(SubscriptionError::Ended)?;
557            self.loss.check()?;
558        }
559        // Keep the dequeued value in self across this await; cancelling next cannot
560        // silently consume a value. Serialize delivery with retiring a service session.
561        let guard = self.client.reads.lock().await;
562        if guard.interrupted {
563            return Err(ReadError::SessionInterrupted.into());
564        }
565        self.healthy()?;
566        Ok(self.pending.take().expect("received notification"))
567    }
568
569    /// Wait for one indexed DataValue, including its status and original clocks. A timeout is
570    /// retryable. An overflow, invalidated session or closed subscription terminates delivery.
571    /// A cancelled wait retains any notification dequeued before cancellation.
572    pub async fn next(&mut self, wait: Duration) -> Result<DataChange, SubscriptionError> {
573        if self.ended {
574            return Err(SubscriptionError::Ended);
575        }
576        if wait.is_zero() || wait > MAX_WAIT {
577            return Err(SubscriptionError::InvalidWait);
578        }
579        let result = match tokio::time::timeout(wait, self.receive()).await {
580            Ok(result) => result,
581            Err(_) => match self.healthy() {
582                Ok(()) => return Err(SubscriptionError::Timeout),
583                Err(error) => Err(error),
584            },
585        };
586        if result.is_err() {
587            self.ended = true;
588        }
589        result
590    }
591}
592
593#[cfg(test)]
594mod tests {
595    use super::*;
596
597    #[test]
598    fn count_and_binary_size_bounds_report_loss_without_delivering_an_oversized_payload() {
599        let bytes = |count| ua::DataValue::from(ua::Variant::ByteString(vec![0x5a; count].into()));
600        let (tx, mut rx) = mpsc::channel(1);
601        let loss = Loss::default();
602        loss.deliver(&tx, 0, &bytes(MAX_VALUE_BYTES - 5));
603        assert!(loss.check().is_ok());
604        assert!(rx.try_recv().unwrap().is_some());
605        loss.deliver(&tx, 0, &bytes(MAX_VALUE_BYTES - 4));
606        assert!(matches!(
607            loss.check(),
608            Err(SubscriptionError::ItemValueLimit { index: 0 })
609        ));
610        assert!(rx.try_recv().unwrap().is_none());
611        let loss = Loss::default();
612        loss.deliver(&tx, 0, &bytes(0));
613        loss.deliver(&tx, 0, &bytes(0));
614        assert!(matches!(
615            loss.check(),
616            Err(SubscriptionError::LocalOverflow)
617        ));
618    }
619
620    #[test]
621    fn removed_member_ends_the_group_while_another_sender_is_alive() {
622        let (sender, mut rx) = mpsc::channel(2);
623        let loss = Arc::new(Loss::default());
624        let route = Route {
625            sender: sender.clone(),
626            loss: loss.clone(),
627            count: 2,
628            expected: 1,
629            timeout_ms: 1000,
630        };
631        route.end();
632        assert!(rx.try_recv().unwrap().is_none());
633        assert!(matches!(loss.check(), Err(SubscriptionError::Ended)));
634        loss.deliver(&sender, 0, &ua::DataValue::default());
635        assert!(matches!(
636            rx.try_recv(),
637            Err(mpsc::error::TryRecvError::Empty)
638        ));
639    }
640
641    #[test]
642    fn keepalive_and_notifications_advance_only_their_subscription_sequence() {
643        let (sender, mut rx) = mpsc::channel(2);
644        let loss = Arc::new(Loss::default());
645        let mut route = Route {
646            sender,
647            loss: loss.clone(),
648            count: 2,
649            expected: u32::MAX,
650            timeout_ms: 1000,
651        };
652        let mut message = ua::NotificationMessage {
653            sequence_number: u32::MAX,
654            ..Default::default()
655        };
656        route.receive(&message);
657        assert_eq!(route.expected, u32::MAX);
658        assert!(rx.try_recv().is_err());
659        message.notification_data =
660            Some(vec![ua::ExtensionObject::new(ua::DataChangeNotification {
661                monitored_items: Some(vec![ua::MonitoredItemNotification {
662                    client_handle: 2,
663                    value: ua::DataValue::from(17u32),
664                }]),
665                ..Default::default()
666            })]);
667        route.receive(&message);
668        let change = rx.try_recv().unwrap().unwrap();
669        assert_eq!(change.index, 1);
670        assert_eq!(change.value.value, Some(ua::Variant::UInt32(17)));
671        assert_eq!(route.expected, 1);
672        route.receive(&message);
673        assert!(matches!(
674            loss.check(),
675            Err(SubscriptionError::SequenceGap {
676                expected: 1,
677                actual: u32::MAX
678            })
679        ));
680        assert!(rx.try_recv().unwrap().is_none());
681    }
682
683    #[test]
684    fn overflow_only_applies_to_the_data_value_info_type() {
685        for (status, overflow) in [(0x80, false), (0x480, true), (0x4090_4480, true)] {
686            let (tx, mut rx) = mpsc::channel(1);
687            let loss = Loss::default();
688            let raw = ua::DataValue {
689                status: Some(ua::StatusCode::from(status)),
690                ..Default::default()
691            };
692            loss.deliver(&tx, 7, &raw);
693            assert_eq!(
694                matches!(loss.check(), Err(SubscriptionError::ItemOverflow { index: 7, status: code }) if code == status),
695                overflow
696            );
697            assert_eq!(rx.try_recv().unwrap().is_none(), overflow);
698        }
699    }
700}