opcua_kit/client/
recovery.rs1use tokio::task::JoinHandle;
4
5use super::{
6 CertificateRollover, Client, ConnectError, ConnectionConfig, ConnectionOptions, ReadError,
7 UserIdentity,
8};
9
10#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub enum SessionState {
13 Initial,
15 Continuing,
17 Reconnected,
19}
20
21pub struct RecoveredSession<'a> {
23 pub client: &'a Client,
25 pub generation: u64,
27 pub state: SessionState,
29}
30
31#[derive(Debug, thiserror::Error)]
33#[non_exhaustive]
34pub enum RecoveryError {
35 #[error(transparent)]
37 Connect(#[from] ConnectError),
38 #[error("could not initialize fresh read-session metadata: {0}")]
40 Bootstrap(#[source] ReadError),
41 #[error("session recovery needs a running Tokio runtime")]
43 NoRuntime,
44 #[error("session recovery worker did not complete")]
46 Worker(#[from] tokio::task::JoinError),
47 #[error("read-session generation exhausted")]
49 GenerationExhausted,
50}
51
52pub 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 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 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 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 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 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 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 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 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 handle.abort();
254 }
255 }
256}