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