Skip to main content

open_net/api/ws/
client.rs

1use super::{ClientId, ConnectOptions, JournalOptions, Session, WebSocketClientConfig};
2use crate::module::ws_client::ws_client_inner::WSClientInner;
3use crate::{network::NetworkConfig, LogType, Result};
4use std::{fmt, sync::Arc};
5
6/// Shared entry point for WebSocket clients, used to create sessions, query configuration, and close the client.
7///
8/// # Example
9///
10/// ```no_run
11/// use open_net::{
12///     network::{NetworkConfig, TlsConfig},
13///     tls::CryptoProvider,
14///     ws::WebSocketClient,
15///     OpenNet, Result,
16/// };
17/// use std::sync::Arc;
18///
19/// # async fn example() -> Result<()> {
20/// // Choose and add a rustls 0.23 provider in the application crate.
21/// let provider: Arc<CryptoProvider> =
22///     Arc::new(rustls_openssl::default_provider());
23/// let network = NetworkConfig::default()
24///     .with_tls(TlsConfig::default().with_crypto_provider(provider));
25/// let net = OpenNet::new_with_network_config(network)?;
26/// let client: WebSocketClient = net.create_ws_client("market-feed").await?;
27/// println!("Client id: {}", client.id());
28/// client.shutdown().await?;
29/// net.destroy_ws_client("market-feed").await?;
30/// # Ok(())
31/// # }
32/// ```
33#[derive(Clone)]
34pub struct WebSocketClient {
35    /// Configuration, session management, and shutdown state common to all client clones.
36    pub(crate) inner: Arc<WSClientInner>,
37}
38impl WebSocketClient {
39    pub(crate) fn from_inner(inner: Arc<WSClientInner>) -> Self {
40        Self { inner }
41    }
42
43    /// Returns the identity of the current WebSocket client instance.
44    ///
45    /// # Use cases
46    ///
47    /// When an application maintains multiple server connections, it can use this
48    /// identifier in logs, metrics, and session indexes alongside
49    /// [`Session::client_id`] and the `client_id` field in connection events.
50    /// The identifier is allocated within the current process. All clones of a
51    /// client share it, and creating a session or reconnecting does not change it.
52    /// It is not a server-assigned user ID and must not be used as a persistent
53    /// business key across process restarts.
54    ///
55    /// # Example
56    ///
57    /// ```
58    /// use open_net::ws::WebSocketClient;
59    ///
60    /// fn log_client(client: &WebSocketClient) {
61    ///     let worker_client = client.clone();
62    ///     println!(
63    ///         "Preparing to process business messages from clients {} and {}",
64    ///         client.id(),
65    ///         worker_client.id(),
66    ///     );
67    /// }
68    /// ```
69    pub fn id(&self) -> ClientId {
70        self.inner.id()
71    }
72
73    /// Borrows the WebSocket configuration determined when the client was created.
74    ///
75    /// # Use cases
76    ///
77    /// Use this snapshot when diagnosing queue backpressure, message-size
78    /// limits, heartbeat behavior, or shutdown timing. It can also be cloned as
79    /// the starting point for another client configuration.
80    /// The returned reference is read-only, and the configuration remains fixed
81    /// for the client's lifetime, including reconnects. Changing a clone does
82    /// not affect this client. The target address, handshake headers, and
83    /// reconnect policy are supplied by [`ConnectOptions`] for each session.
84    ///
85    /// # Example
86    ///
87    /// ```
88    /// use open_net::ws::{WebSocketClient, WebSocketClientConfig};
89    ///
90    /// fn config_for_another_client(client: &WebSocketClient) -> WebSocketClientConfig {
91    ///     let current = client.config();
92    ///     println!(
93    ///         "Normal sending queue can hold up to {} messages",
94    ///         current.queues.normal.max_items
95    ///     );
96    ///
97    ///     // Pass the adjusted configuration to OpenNet::create_ws_client_with_config.
98    ///     let mut next = current.clone();
99    ///     next.queues.normal.max_items = 2048;
100    ///     next
101    /// }
102    /// ```
103    pub fn config(&self) -> &WebSocketClientConfig {
104        self.inner.config()
105    }
106
107    /// Borrows the actual proxy, TLS, and network state policies adopted by the current client.
108    ///
109    /// # Use cases
110    ///
111    /// Use this snapshot to determine which policy a client uses when the engine
112    /// has a default configuration and the client may have an override. It can
113    /// be cloned and adjusted for another client. The returned value is either
114    /// the inherited engine configuration or the complete per-client replacement.
115    /// All sessions and reconnects use this immutable policy; it describes the
116    /// configured behavior, not whether the live network is currently reachable.
117    ///
118    /// # Example
119    ///
120    /// ```
121    /// use open_net::network::{NetworkConfig, ProxyConfig};
122    /// use open_net::ws::WebSocketClient;
123    ///
124    /// fn direct_config_for_another_client(client: &WebSocketClient) -> NetworkConfig {
125    ///     let current = client.network_config();
126    ///     println!(
127    ///         "Network status policy: {:?}",
128    ///         current.network_status_policy()
129    ///     );
130    ///
131    ///     // Keep current TLS and network state policies, only change to direct for new clients.
132    ///     // Pass the return value to OpenNet::create_ws_client_with_network_config.
133    ///     current.clone().with_proxy(ProxyConfig::direct())
134    /// }
135    /// ```
136    pub fn network_config(&self) -> &NetworkConfig {
137        self.inner.network_config()
138    }
139
140    /// Create a session and wait for the session to establish a usable WebSocket connection before returning.
141    ///
142    /// # Use cases
143    ///
144    /// Use this method when startup must establish a connection before the
145    /// application sends subscriptions or other business messages. `options`
146    /// may be a `ws://` or `wss://` address or a [`ConnectOptions`] value that
147    /// sets authentication headers, timeouts, receive options, and reconnect policy.
148    /// Use [`Self::start_session`] when the session must be available before the
149    /// connection completes, when the attempt may be cancelled, or when a full
150    /// connection journal is required.
151    ///
152    /// This is equivalent to `start_session(options, None)` followed by
153    /// [`Session::wait_connected`], so it does not create an independent
154    /// connection journal. The default policy may retry an initial failure, and
155    /// `connect_timeout` bounds the total wait for the first connection; one
156    /// failed handshake therefore need not fail immediately. Later
157    /// disconnections continue to follow the session's reconnect policy, and a
158    /// successful return does not guarantee that the connection remains usable.
159    ///
160    /// Hold the returned [`Session`] for as long as the session is needed:
161    /// dropping it requests session cancellation even if a client or sender
162    /// clone remains. Cancelling the future returned by this method also drops
163    /// its internally created session and requests cancellation; cleanup may
164    /// continue in the background.
165    ///
166    /// # Errors
167    ///
168    /// Errors during session creation are the same as [`Self::start_session`].
169    /// If the session times out while connecting, encounters a non-retryable
170    /// handshake error, exhausts its retry budget, or is shut down while this
171    /// method waits, the corresponding error is returned.
172    ///
173    /// # Example
174    ///
175    /// ```no_run
176    /// use open_net::{
177    ///     network::{NetworkConfig, TlsConfig},
178    ///     tls::CryptoProvider,
179    ///     ws::ConnectOptions,
180    ///     OpenNet, Result,
181    /// };
182    /// use std::sync::Arc;
183    /// use std::time::Duration;
184    ///
185    /// # async fn example() -> Result<()> {
186    /// let provider: Arc<CryptoProvider> =
187    ///     Arc::new(rustls_openssl::default_provider());
188    /// let net = OpenNet::new_with_network_config(
189    ///     NetworkConfig::default()
190    ///         .with_tls(TlsConfig::default().with_crypto_provider(provider)),
191    /// )?;
192    /// let client = net.create_ws_client("market-feed").await?;
193    /// let mut options = ConnectOptions::new("wss://example.com/stream");
194    /// options.connect_timeout = Some(Duration::from_secs(15));
195    ///
196    /// let session = client.connect(options).await?;
197    /// // The connection has succeeded; keep holding the session while the
198    /// // subscription is active.
199    /// session
200    ///     .sender()
201    ///     .send(r#"{"op":"subscribe","topic":"prices"}"#)
202    ///     .await?;
203    ///
204    /// // Close the session when the work is complete; the client can create
205    /// // another session afterward.
206    /// session.close().await?;
207    /// net.destroy_ws_client("market-feed").await?;
208    /// # Ok(())
209    /// # }
210    /// ```
211    pub async fn connect(&self, options: impl Into<ConnectOptions>) -> Result<Session> {
212        let options = options.into();
213        crate::log_s!(LogType::WSC; "connect", "options", format!("{:?}", options));
214        let session = self.start_session(options, None).await?;
215        session.wait_connected().await?;
216        Ok(session)
217    }
218
219    /// Submit the connection task and return after the background work task receives the session without waiting for the handshake to succeed.
220    ///
221    /// # Use cases
222    ///
223    /// Use this method to display a connecting state immediately, provide a
224    /// cancel action, install state monitoring, or record the first handshake
225    /// and later reconnect attempts. After it returns, use
226    /// [`Session::watch_state`] to observe state, [`Session::cancel`] to request
227    /// cancellation, or [`Session::wait_connected`] to await a usable connection.
228    /// A successful return means only that the session was admitted; subsequent
229    /// connection attempts may still fail.
230    ///
231    /// # Parameters and lifecycle
232    ///
233    /// - `options`: Target address or complete connection configuration. The
234    ///   connection process follows its timeout and reconnect policies. A
235    ///   message inbox is created by default; use [`Session::take_messages`]
236    ///   to receive messages that arrive early.
237    /// - `journal`: With `Some`, creates a bounded connection journal before the
238    ///   first attempt. Retrieve it with [`Session::take_journal`] and consume
239    ///   it continuously; a full journal can block later connection attempts.
240    ///   With `None`, no journal is created, but state observation and the
241    ///   history-limited [`Session::subscribe_events`] stream remain available.
242    ///
243    /// Each client (including all clones) can only have one outstanding session at a time.
244    /// Each client, including all clones, can have only one outstanding session.
245    /// To change the target, first call [`Session::close`] on the old session and
246    /// wait for completion. If using `cancel`, also wait for [`Session::closed`].
247    /// The returned session owns the lifecycle and must remain held; retaining
248    /// only a sender or receiver does not prevent cancellation when the owner is dropped.
249    ///
250    /// # Errors
251    ///
252    /// Returns [`crate::error::ErrorKind::InvalidConfig`] for invalid options,
253    /// [`crate::error::ErrorKind::SessionAlreadyExists`] when another session
254    /// is still active, and [`crate::error::ErrorKind::Closed`] after client
255    /// shutdown has been requested. Resource exhaustion, a command wait that
256    /// exceeds the initial connection budget, or engine shutdown may also fail
257    /// admission. Connection errors after this method returns are reported by
258    /// the session's wait and observation interfaces.
259    ///
260    /// # Example
261    ///
262    /// ```no_run
263    /// use open_net::{ws::{JournalOptions, WebSocketClient}, Result};
264    ///
265    /// async fn connect_with_journal(client: &WebSocketClient) -> Result<()> {
266    ///     let mut session = client.start_session(
267    ///         "wss://example.com/stream",
268    ///         Some(JournalOptions::default()),
269    ///     ).await?;
270    ///
271    ///     let journal = session.take_journal().ok_or_else(|| {
272    ///         open_net::NetError::from(open_net::error::ErrorKind::InvalidConfig)
273    ///     })?;
274    ///     // The callback continues to consume logs; keep the subscription handle alive to avoid log accumulation while waiting for a connection.
275    ///     let _journal_subscription = journal.into_callback(|_, event| {
276    ///         match event {
277    ///             Ok(event) => println!("Session {}: {:?}", event.session_id, event.kind),
278    ///             Err(error) => eprintln!("Failed to receive connection log: {error:?}"),
279    ///         }
280    ///     })?;
281    ///
282    ///     let connection = session.wait_connected().await?;
283    ///     println!("Physical connection {} is ready", connection.connection_id);
284    ///     session.sender().send("hello").await?;
285    ///     session.close().await?;
286    ///     Ok(())
287    /// }
288    /// ```
289    pub async fn start_session(
290        &self,
291        options: impl Into<ConnectOptions>,
292        journal: Option<JournalOptions>,
293    ) -> Result<Session> {
294        let options = options.into();
295        crate::log_s!(LogType::WSC; "start_session", "options|journal", format!("{:?}", options), format!("{:?}", journal));
296        self.inner.start_session(options, journal).await
297    }
298
299    /// Determine whether the client has received a shutdown request.
300    ///
301    /// # Use cases
302    ///
303    /// Use this check before scheduling work during application shutdown or
304    /// while reusing a client handle. The state is shared by all clones and is
305    /// permanent once `true`; an ordinary disconnect, automatic reconnect, or
306    /// end of one session does not set it.
307    ///
308    /// Returning `true` does not mean that the background cleanup has been completed; call [`Self::shutdown`] when you need to wait for completion.
309    /// `true` does not mean that cleanup has finished; call [`Self::shutdown`]
310    /// when completion must be awaited. `false` does not mean that a usable
311    /// connection exists, and another task may request shutdown immediately,
312    /// so connection and send errors must still be handled after this check.
313    ///
314    /// # Example
315    ///
316    /// ```
317    /// use open_net::ws::WebSocketClient;
318    ///
319    /// fn show_client_lifecycle(client: &WebSocketClient) {
320    ///     if client.is_shutdown() {
321    ///         println!("Client {} is shutting down or has been shut down, stopping scheduling new tasks", client.id());
322    ///     } else {
323    ///         println!("Client {} has not been closed; the connection status needs to be queried from Session", client.id());
324    ///     }
325    /// }
326    /// ```
327    pub fn is_shutdown(&self) -> bool {
328        self.inner.is_shutdown()
329    }
330
331    /// Close the client permanently and wait for the background work tasks to finish cleaning up.
332    ///
333    /// # Use cases
334    ///
335    /// Use this method when the application exits, logs an account out, or will
336    /// no longer use the client. It stops connection and reconnect attempts,
337    /// ends the current session, and cleans up queues, pending requests, and
338    /// client-level subscriptions. All clones observe the shutdown, and no new
339    /// session can be created after completion. To close only the current
340    /// session while retaining the client, use [`Session::close`].
341    ///
342    /// This operation is idempotent and may be called concurrently; calls made
343    /// after cleanup completes return success immediately.
344    /// Closing does not guarantee that all queued messages have been written out, nor does it guarantee that the server has processed previously sent data.
345    /// If the application needs delivery or business confirmation, wait for the
346    /// relevant receipt or response before calling this method.
347    /// After the shutdown request is issued, the client will not resume operation even if the wait is canceled.
348    ///
349    /// This method does not remove the client name registration in the engine; if you still need to release the registration and reuse the name,
350    /// Calling [`crate::OpenNet::destroy_ws_client`] also closes the client.
351    ///
352    /// # Errors
353    ///
354    /// Returns [`crate::error::ErrorKind::EngineDropped`] if the background
355    /// command channel exits before cleanup is reported complete.
356    ///
357    /// # Example
358    ///
359    /// ```no_run
360    /// use open_net::{ws::WebSocketClient, Result};
361    ///
362    /// async fn stop_background_client(client: &WebSocketClient) -> Result<()> {
363    ///     let worker_client = client.clone();
364    ///     // Complete the business sending and response waiting that need to be reserved before calling.
365    ///     client.shutdown().await?;
366    ///     println!("Worker shutdown requested: {}", worker_client.is_shutdown());
367    ///
368    ///     // Multiple components can also be cleaned separately; here they will be returned successfully.
369    ///     worker_client.shutdown().await?;
370    ///     Ok(())
371    /// }
372    /// ```
373    pub async fn shutdown(&self) -> Result<()> {
374        crate::log_s!(LogType::WSC; "shutdown");
375        self.inner.shutdown().await
376    }
377}
378impl fmt::Debug for WebSocketClient {
379    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
380        f.debug_struct("WebSocketClient")
381            .field("id", &self.id())
382            .field("shutdown", &self.is_shutdown())
383            .finish()
384    }
385}