Skip to main content

opcua_kit/client/
recovery.rs

1//! Fresh, pinned sessions for long-running polling hosts.
2
3use tokio::task::JoinHandle;
4
5use super::{
6    CertificateRollover, Client, ConnectError, ConnectionConfig, ConnectionOptions, ReadError,
7    UserIdentity,
8};
9
10/// Relationship between the returned polling session and previous acquisitions.
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub enum SessionState {
13    /// First authenticated session returned by this owner.
14    Initial,
15    /// The previously returned session is still usable.
16    Continuing,
17    /// A fresh authenticated session has replaced an interrupted one. Data may be missing.
18    Reconnected,
19}
20
21/// One session lease. A new generation has a newly validated namespace table and read limit.
22pub struct RecoveredSession<'a> {
23    /// The ordinary pinned client. All read, subscription and commissioning APIs retain their semantics.
24    pub client: &'a Client,
25    /// Monotonically increasing successful session number, starting at one.
26    pub generation: u64,
27    /// Whether polling continues on the previous session or starts a fresh generation.
28    pub state: SessionState,
29}
30
31/// A fresh session could not be authenticated and prepared. The caller chooses when to retry.
32#[derive(Debug, thiserror::Error)]
33#[non_exhaustive]
34pub enum RecoveryError {
35    /// Local validation, pinned-channel authentication or session activation failed.
36    #[error(transparent)]
37    Connect(#[from] ConnectError),
38    /// The server identity, namespace array or read limits could not be established.
39    #[error("could not initialize fresh read-session metadata: {0}")]
40    Bootstrap(#[source] ReadError),
41    /// No Tokio runtime is available to drive the handshake.
42    #[error("session recovery needs a running Tokio runtime")]
43    NoRuntime,
44    /// A connection worker terminated unexpectedly.
45    #[error("session recovery worker did not complete")]
46    Worker(#[from] tokio::task::JoinError),
47    /// All session generation numbers have been used.
48    #[error("read-session generation exhausted")]
49    GenerationExhausted,
50}
51
52/// Reuses a pinned client until a channel change or failed/cancelled read retires its session.
53/// Each call to [`Self::session`] starts at most one connection attempt with the original endpoint,
54/// credentials, identity, policy and timeout. Schedule further attempts and backoff in the host.
55/// A lost read remains visible to the caller. A fresh generation does not replay observations.
56///
57/// ```
58/// use opcua_kit::{NodeId, client::{RecoveringClient, SessionState}};
59///
60/// async fn poll(owner: &mut RecoveringClient<'_>, node: &NodeId) -> Result<(), Box<dyn std::error::Error>> {
61///     let session = owner.session().await?;
62///     if session.state == SessionState::Reconnected {
63///         eprintln!("coverage gap before generation {}", session.generation);
64///     }
65///     let sample = session.client.read_scalar::<u64>(node).await?;
66///     println!("status={:#010x} register={:?}", sample.status, sample.value);
67///     Ok(())
68/// }
69/// ```
70pub struct RecoveringClient<'a> {
71    config: ConnectionConfig<'a>,
72    options: ConnectionOptions<'a>,
73    rollover: Option<CertificateRollover<'a>>,
74    current: Option<Client>,
75    connecting: Option<JoinHandle<Result<Client, RecoveryError>>>,
76    generation: u64,
77}
78
79fn session_health(client: &mut Client) -> Result<(), ReadError> {
80    client.check_channel()?;
81    if client.reads.get_mut().interrupted || !client.inner.is_alive() {
82        return Err(ReadError::SessionInterrupted);
83    }
84    Ok(())
85}
86
87impl<'a> RecoveringClient<'a> {
88    /// Bind the peer and credentials used for every generation. Network I/O begins at `session()`.
89    pub fn new(config: ConnectionConfig<'a>, options: ConnectionOptions<'a>) -> Self {
90        Self {
91            config,
92            options,
93            rollover: None,
94            current: None,
95            connecting: None,
96            generation: 0,
97        }
98    }
99
100    /// Apply the same bounded two-leaf trust policy to each fresh handshake.
101    pub fn new_with_rollover(
102        config: ConnectionConfig<'a>,
103        options: ConnectionOptions<'a>,
104        rollover: CertificateRollover<'a>,
105    ) -> Self {
106        let mut owner = Self::new(config, options);
107        owner.rollover = Some(rollover);
108        owner
109    }
110
111    /// Acquire an authenticated session. The blocking handshake runs on a worker. Dropping this
112    /// future leaves any pending attempt with the owner so its next call joins the same attempt.
113    ///
114    /// Check the generation before using results or recreating monitored items. The session lease
115    /// reflects known channel and read failures; the socket can still fail during any operation.
116    pub async fn session(&mut self) -> Result<RecoveredSession<'_>, RecoveryError> {
117        let reusable = self
118            .current
119            .as_mut()
120            .is_some_and(|c| session_health(c).is_ok());
121        let state = if reusable {
122            SessionState::Continuing
123        } else {
124            let next = self
125                .generation
126                .checked_add(1)
127                .ok_or(RecoveryError::GenerationExhausted)?;
128            if self.connecting.is_none() {
129                self.connecting = Some(self.start_connection()?);
130            }
131            let result = self
132                .connecting
133                .as_mut()
134                .expect("connection attempt installed")
135                .await;
136            self.connecting = None;
137            let mut client = result??;
138            // The original awaiter may have cancelled long before this caller joined the task.
139            if let Err(source) = session_health(&mut client) {
140                client.disconnect().await;
141                return Err(RecoveryError::Bootstrap(source));
142            }
143            self.current = Some(client);
144            self.generation = next;
145            if next == 1 {
146                SessionState::Initial
147            } else {
148                SessionState::Reconnected
149            }
150        };
151        Ok(RecoveredSession {
152            client: self.current.as_ref().expect("session prepared"),
153            generation: self.generation,
154            state,
155        })
156    }
157
158    /// Transfer a newly prepared session to a protocol service that owns its entire lifecycle.
159    pub(super) async fn into_client(mut self) -> Result<Client, RecoveryError> {
160        self.session().await?;
161        Ok(self.current.take().expect("session was prepared"))
162    }
163
164    fn start_connection(
165        &mut self,
166    ) -> Result<JoinHandle<Result<Client, RecoveryError>>, RecoveryError> {
167        let runtime =
168            tokio::runtime::Handle::try_current().map_err(|_| RecoveryError::NoRuntime)?;
169        let config = self.config;
170        config.validate_input_lengths()?;
171        self.options.user_identity.validate()?;
172        // Borrow for the owner's lifetime; make bounded, temporary owned copies only while
173        // a 'static blocking worker needs them. No user-supplied configuration is logged.
174        let endpoint = config.endpoint.to_owned();
175        let server_uri = config.server_application_uri.to_owned();
176        let server_cert = config.server_certificate_der.to_owned();
177        let rollover = self
178            .rollover
179            .map(|r| {
180                r.validate_length()?;
181                Ok::<_, ConnectError>((r.replacement_der.to_vec(), r.original_valid_until))
182            })
183            .transpose()?;
184        let client_uri = config.client_application_uri.to_owned();
185        let client_cert = config.client_certificate_der.to_owned();
186        let client_key = config.client_private_key_der.to_owned();
187        let timeout = config.timeout;
188        let policy = self.options.security_policy;
189        let login = match self.options.user_identity {
190            UserIdentity::Anonymous => None,
191            UserIdentity::Username { username, password } => {
192                Some((username.to_owned(), password.to_owned()))
193            }
194        };
195        let retired = self.current.take();
196        Ok(runtime.spawn(async move {
197            let client = tokio::task::spawn_blocking(move || {
198                // An interrupted session driver's destructor can join its worker thread.
199                drop(retired);
200                let identity = match &login {
201                    None => UserIdentity::Anonymous,
202                    Some((username, password)) => UserIdentity::Username { username, password },
203                };
204                Client::connect_pinned(
205                    ConnectionConfig {
206                        endpoint: &endpoint,
207                        server_application_uri: &server_uri,
208                        server_certificate_der: &server_cert,
209                        client_application_uri: &client_uri,
210                        client_certificate_der: &client_cert,
211                        client_private_key_der: &client_key,
212                        timeout,
213                    },
214                    ConnectionOptions {
215                        security_policy: policy,
216                        user_identity: identity,
217                    },
218                    rollover
219                        .as_ref()
220                        .map(|(cert, deadline)| CertificateRollover {
221                            replacement_der: cert,
222                            original_valid_until: *deadline,
223                        }),
224                )
225            })
226            .await??;
227            let initialized = client.read_session().await.map(|_| ());
228            if let Err(source) = initialized {
229                client.disconnect().await;
230                return Err(RecoveryError::Bootstrap(source));
231            }
232            Ok(client)
233        }))
234    }
235
236    /// Complete any pending attempt and gracefully disconnect its session.
237    pub async fn disconnect(mut self) {
238        if let Some(handle) = self.connecting.take()
239            && let Ok(Ok(client)) = handle.await
240        {
241            client.disconnect().await;
242        }
243        if let Some(client) = self.current.take() {
244            client.disconnect().await;
245        }
246    }
247}
248
249impl Drop for RecoveringClient<'_> {
250    fn drop(&mut self) {
251        if let Some(handle) = &self.connecting {
252            // A synchronous handshake already running on the worker ends at its transport timeout.
253            handle.abort();
254        }
255    }
256}