Skip to main content

open_net/api/
open_net.rs

1#[cfg(feature = "http-client")]
2use crate::api::http::http_client::HttpClient;
3#[cfg(feature = "http-client")]
4use crate::api::http::http_config::HttpClientConfig;
5use crate::api::open_net_config::OpenNetConfig;
6use crate::common::log::log_def::LogType;
7use crate::error::NetError;
8use crate::inner::net_impl::OpenNetInner;
9#[cfg(feature = "net-status")]
10use crate::net_status::NetStatusClient;
11#[cfg(feature = "ws-client")]
12use crate::ws::WebSocketClient;
13#[cfg(feature = "ws-client")]
14use crate::ws::WebSocketClientConfig;
15
16/// Top-level networking engine that owns runtime workers and named client instances.
17///
18/// Cloneable client handles remain valid until their named client is destroyed or the engine is dropped.
19pub struct OpenNet {
20    #[allow(dead_code)]
21    pub(crate) inner: OpenNetInner,
22}
23
24impl OpenNet {
25    /// Creates an engine with an immutable default network policy for WebSocket clients.
26    ///
27    /// Proxy and TLS settings are validated before any work starts. This
28    /// constructor currently applies only to WebSocket clients; use the
29    /// per-client network-config constructor to override defaults.
30    #[cfg(feature = "ws-client")]
31    pub fn new_with_network_config(
32        config: crate::network::NetworkConfig,
33    ) -> Result<Self, NetError> {
34        crate::log_s!(LogType::Engine; "OpenNet-new_with_network_config", "config", format!("{:?}", config));
35        Self::new_with_config(OpenNetConfig::default().with_network_config(config))
36    }
37
38    /// Creates an engine with default settings and queue capacities of 128.
39    pub fn new() -> Result<Self, NetError> {
40        crate::log_s!(LogType::Engine; "OpenNet-new");
41        Self::new_with_config(OpenNetConfig::default())
42    }
43
44    /// Creates an engine with the supplied runtime, queue capacities, and network policy.
45    ///
46    /// Validates configuration before creating channels or workers. Invalid
47    /// capacities or worker counts return `InvalidConfig`; values remain fixed thereafter.
48    ///
49    /// ```no_run
50    /// use open_net::{config::OpenNetConfig, NetError, OpenNet};
51    /// # fn example() -> Result<(), NetError> {
52    /// let net = OpenNet::new_with_config(
53    ///     OpenNetConfig::default()
54    ///         .with_async_queue_capacity(256)
55    ///         .with_sync_queue_capacity(128),
56    /// )?;
57    /// # Ok(())
58    /// # }
59    /// ```
60    pub fn new_with_config(config: OpenNetConfig) -> Result<Self, NetError> {
61        crate::log_s!(LogType::Engine; "OpenNet-new_with_config","config", format!("{:?}", config));
62        let result: Result<Self, NetError> = (|| {
63            Ok(Self {
64                inner: OpenNetInner::new_with_config(config)?,
65            })
66        })();
67        result.inspect_err(|error| {
68            crate::log_e!(LogType::Engine; "new_with_config", "error|error_kind", format!("{error:?}"), format!("{:?}", error.kind()));
69        })
70    }
71
72    /// Creates a WebSocket client with default parameters and waits for its worker to become ready.
73    ///
74    /// The returned client is disconnected; call `connect` or `start_session` to establish a session.
75    #[cfg(feature = "ws-client")]
76    pub async fn create_ws_client(&self, thread_name: &str) -> Result<WebSocketClient, NetError> {
77        crate::log_t!(LogType::WSC; "create_ws_client", "thread_name", thread_name);
78        let result: Result<WebSocketClient, NetError> = async {
79            self.create_ws_client_with_config(thread_name, WebSocketClientConfig::default())
80                .await
81        }
82        .await;
83        result.inspect_err(|error| {
84            crate::log_e!(LogType::WSC; "create_ws_client", "error|error_kind", format!("{error:?}"), format!("{:?}", error.kind()));
85        })
86    }
87
88    /// Creates a WebSocket client with the supplied parameters and engine network policy.
89    ///
90    /// Cancelling the wait does not cancel submitted creation; retrieve the
91    /// client later with `get_ws_client` and release it with `destroy_ws_client`.
92    #[cfg(feature = "ws-client")]
93    pub async fn create_ws_client_with_config(
94        &self,
95        thread_name: &str,
96        config: WebSocketClientConfig,
97    ) -> Result<WebSocketClient, NetError> {
98        crate::log_t!(LogType::WSC; "create_ws_client_with_config", "thread_name|config", thread_name, format!("{:?}", config));
99        let result: Result<WebSocketClient, NetError> = async {
100            let thread_name = thread_name.trim();
101            if thread_name.is_empty() {
102                return Err(NetError::from(crate::error::ErrorKind::InvalidInput));
103            }
104            self.inner
105                .create_ws_client(thread_name.to_string(), config, None)
106                .await
107        }
108        .await;
109        result.inspect_err(|error| {
110            crate::log_e!(LogType::WSC; "create_ws_client_with_config", "error|error_kind", format!("{error:?}"), format!("{:?}", error.kind()));
111        })
112    }
113
114    /// Creates a WebSocket client with an immutable per-client proxy and TLS policy.
115    ///
116    /// The supplied policy completely replaces engine defaults. `default()` selects
117    /// direct mode and WebPKI roots; connect, retry, and reconnect use this snapshot.
118    ///
119    /// Waits for the worker to become ready but does not connect. Dropping the
120    /// future does not cancel creation; retrieve and later destroy the client by name.
121    ///
122    /// ```no_run
123    /// use open_net::{network::{NetworkConfig, ProxyConfig}, ws::WebSocketClientConfig, NetError, OpenNet};
124    /// # async fn example() -> Result<(), NetError> {
125    /// let defaults = NetworkConfig::default()
126    ///     .with_proxy(ProxyConfig::http_connect("http://127.0.0.1:8080", None)?);
127    /// let net = OpenNet::new_with_network_config(defaults.clone())?;
128    /// let inherited = net.create_ws_client("inherited").await?;
129    /// let direct = net.create_ws_client_with_network_config(
130    ///     "direct", WebSocketClientConfig::default(), NetworkConfig::default(),
131    /// ).await?;
132    /// let other = net.create_ws_client_with_network_config(
133    ///     "other", WebSocketClientConfig::default(),
134    ///     defaults.with_proxy(ProxyConfig::http_connect("http://127.0.0.1:8081", None)?),
135    /// ).await?;
136    /// net.destroy_ws_client("inherited").await?;
137    /// net.destroy_ws_client("direct").await?;
138    /// net.destroy_ws_client("other").await?;
139    /// # Ok(())
140    /// # }
141    /// ```
142    #[cfg(feature = "ws-client")]
143    pub async fn create_ws_client_with_network_config(
144        &self,
145        thread_name: &str,
146        config: WebSocketClientConfig,
147        network_config: crate::network::NetworkConfig,
148    ) -> Result<WebSocketClient, NetError> {
149        crate::log_t!(LogType::WSC; "create_ws_client_with_network_config", "thread_name|config", thread_name, format!("{config:?}"));
150        let result: Result<WebSocketClient, NetError> = async {
151            let thread_name = thread_name.trim();
152            if thread_name.is_empty() {
153                return Err(NetError::from(crate::error::ErrorKind::InvalidInput));
154            }
155            self.inner
156                .create_ws_client(thread_name.to_string(), config, Some(network_config))
157                .await
158        }
159        .await;
160        result.inspect_err(|error| {
161            crate::log_e!(LogType::WSC; "create_ws_client_with_network_config", "error|error_kind", format!("{error:?}"), format!("{:?}", error.kind()));
162        })
163    }
164
165    #[cfg(feature = "ws-client")]
166    /// Returns a shared handle to an existing WebSocket client.
167    pub fn get_ws_client(&self, thread_name: &str) -> Result<WebSocketClient, NetError> {
168        crate::log_t!(LogType::WSC; "get_ws_client", "thread_name", thread_name);
169        let result: Result<WebSocketClient, NetError> = (|| {
170            if thread_name.trim().is_empty() {
171                return Err(NetError::from(crate::error::ErrorKind::InvalidInput));
172            }
173            self.inner.get_ws_client(thread_name.trim())
174        })();
175        result.inspect_err(|error| {
176            crate::log_e!(LogType::WSC; "get_ws_client", "error|error_kind", format!("{error:?}"), format!("{:?}", error.kind()));
177        })
178    }
179
180    #[cfg(feature = "ws-client")]
181    /// Permanently destroys a named WebSocket client after its worker exits.
182    pub async fn destroy_ws_client(&self, thread_name: &str) -> Result<(), NetError> {
183        crate::log_t!(LogType::WSC; "destroy_ws_client", "thread_name", thread_name);
184        let result: Result<(), NetError> = async {
185            if thread_name.trim().is_empty() {
186                return Err(NetError::from(crate::error::ErrorKind::InvalidInput));
187            }
188            self.inner.destroy_ws_client(thread_name.trim()).await
189        }
190        .await;
191        result.inspect_err(|error| {
192            crate::log_e!(LogType::WSC; "destroy_ws_client", "error|error_kind", format!("{error:?}"), format!("{:?}", error.kind()));
193        })
194    }
195}
196
197#[cfg(feature = "net-status")]
198impl OpenNet {
199    /// Export this engine's cached network state for an explicitly configured
200    /// standalone HTTP client. Reading the context never starts monitoring.
201    /// The context remains bound to this engine and becomes Closed on engine drop.
202    pub fn network_status_context(&self) -> crate::net_status::NetworkStatusContext {
203        self.inner.network_status.context()
204    }
205
206    /// Creates a network-status client; call `start().await` to begin monitoring.
207    ///
208    /// Names are trimmed and must be unique within an engine. Requires the
209    /// `net-status` feature, also enabled by `http-client` and `ws-client`.
210    ///
211    /// ```no_run
212    /// use open_net::{NetError, OpenNet};
213    /// # async fn example() -> Result<(), NetError> {
214    /// let net = OpenNet::new()?;
215    /// let client = net.create_net_status_client("network-status").await?;
216    /// client.start().await?;
217    /// let snapshot = client.snapshot()?;
218    /// let status = snapshot.reachability;
219    /// let ip_stack = snapshot.ip_stack;
220    /// net.destroy_net_status_client("network-status").await?;
221    /// # Ok(())
222    /// # }
223    /// ```
224    pub async fn create_net_status_client(
225        &self,
226        thread_name: &str,
227    ) -> Result<NetStatusClient, NetError> {
228        let thread_name = thread_name.trim();
229        crate::log_s!(LogType::Engine; "create_net_status_client", "thread_name", thread_name);
230        if thread_name.is_empty() {
231            return Err(NetError::from(crate::error::ErrorKind::InvalidInput));
232        }
233        self.inner.create_net_status_client(thread_name)
234    }
235
236    /// Returns a shared handle to a named network-status client.
237    pub fn get_net_status_client(&self, thread_name: &str) -> Result<NetStatusClient, NetError> {
238        let thread_name = thread_name.trim();
239        if thread_name.is_empty() {
240            return Err(NetError::from(crate::error::ErrorKind::InvalidInput));
241        }
242        self.inner.get_net_status_client(thread_name)
243    }
244
245    /// Permanently stops a client, waits for monitoring to exit, and releases its name.
246    ///
247    /// Cancelling the wait does not cancel submitted destruction; the name remains
248    /// reserved until cleanup completes. Use `NetStatusClient::stop` to pause instead.
249    pub async fn destroy_net_status_client(&self, thread_name: &str) -> Result<(), NetError> {
250        let thread_name = thread_name.trim();
251        crate::log_s!(LogType::Engine; "destroy_net_status_client", "thread_name", thread_name);
252        if thread_name.is_empty() {
253            return Err(NetError::from(crate::error::ErrorKind::InvalidInput));
254        }
255        self.inner.destroy_net_status_client(thread_name).await
256    }
257}
258
259impl OpenNet {
260    #[cfg(feature = "http-client")]
261    /// Creates an HTTP client with the supplied configuration.
262    pub async fn create_http_client_with_config(
263        &self,
264        thread_name: &str,
265        config: HttpClientConfig,
266    ) -> Result<HttpClient, NetError> {
267        crate::log_t!(LogType::HTTP; "create_http_client_with_config", "thread_name|config", thread_name, format!("{:?}", config));
268        let result: Result<HttpClient, NetError> = async {
269            let thread_name = thread_name.trim();
270            if thread_name.is_empty() || thread_name.contains('\0') {
271                return Err(NetError::from(crate::error::ErrorKind::InvalidInput));
272            }
273            self.inner
274                .create_http_client(thread_name.to_string(), config)
275                .await
276        }
277        .await;
278        result.inspect_err(|error| {
279            crate::log_e!(LogType::HTTP; "create_http_client_with_config", "error|error_kind", format!("{error:?}"), format!("{:?}", error.kind()));
280        })
281    }
282
283    #[cfg(feature = "http-client")]
284    /// Returns a shared handle to an existing HTTP client.
285    pub fn get_http_client(&self, thread_name: &str) -> Result<HttpClient, NetError> {
286        crate::log_t!(LogType::HTTP; "get_http_client", "thread_name", thread_name);
287        let name = thread_name.trim();
288        if name.is_empty() {
289            return Err(NetError::from(crate::error::ErrorKind::InvalidInput));
290        }
291        self.inner.get_http_client(name)
292    }
293
294    #[cfg(feature = "http-client")]
295    /// Permanently destroys a named HTTP client after its worker exits.
296    pub async fn destroy_http_client(&self, thread_name: &str) -> Result<(), NetError> {
297        crate::log_t!(LogType::HTTP; "destroy_http_client", "thread_name", thread_name);
298        let name = thread_name.trim();
299        if name.is_empty() {
300            return Err(NetError::from(crate::error::ErrorKind::InvalidInput));
301        }
302        self.inner.destroy_http_client(name).await
303    }
304}