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