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    /// Permanently close this engine's admission and request cancellation.
26    ///
27    /// Idempotent and safe inside SDK callbacks. It does not wait for callback,
28    /// provider, worker or runtime retirement. Use [`Self::shutdown`] from an
29    /// external control flow to confirm completion. The engine cannot reopen.
30    pub fn begin_shutdown(&self) {
31        self.inner.begin_shutdown(false);
32    }
33
34    /// Close this engine and wait for its running resources to exit.
35    ///
36    /// The first poll also calls [`Self::begin_shutdown`]. Concurrent/repeated
37    /// waiters share the result; cancelling a waiter never cancels cleanup.
38    /// No caller Tokio runtime is required. Success confirms retirement of
39    /// registered clients, their SDK callbacks/providers, network monitoring,
40    /// engine callback workers and runtime, even while public handles survive.
41    ///
42    /// Standalone HTTP workers, other engines, process-wide logging and the
43    /// process-wide retirement reaper are outside this boundary. A standalone
44    /// HTTP client using this engine's network context keeps its HTTP workers;
45    /// only its engine-owned observations retire. User-retained data is not freed.
46    /// Application tasks on an application-owned runtime remain its owner's duty.
47    ///
48    /// SDK callback/worker contexts are conservatively rejected on every poll
49    /// with `InvalidInput` (field `open_net.shutdown`, stage `Close`), including
50    /// cross-engine waits. Closing still starts; use `begin_shutdown` then return.
51    /// Indirect cross-thread waits cannot be detected. A callback/provider that
52    /// never returns can prevent completion; a caller timeout only ends its wait.
53    /// Errors do not certify that all resources have retired. Dropping the engine
54    /// still initiates automatic cleanup, but Drop itself is not a completion receipt.
55    pub async fn shutdown(&self) -> Result<(), NetError> {
56        self.inner.shutdown().await
57    }
58
59    /// Creates an engine with an immutable default network policy for WebSocket clients.
60    ///
61    /// Proxy and TLS settings are validated before any work starts. This
62    /// constructor currently applies only to WebSocket clients; use the
63    /// per-client network-config constructor to override defaults.
64    #[cfg(feature = "ws-client")]
65    pub fn new_with_network_config(
66        config: crate::network::NetworkConfig,
67    ) -> Result<Self, NetError> {
68        crate::log_s!(LogType::Engine; "OpenNet-new_with_network_config", "config", format!("{:?}", config));
69        Self::new_with_config(OpenNetConfig::default().with_network_config(config))
70    }
71
72    /// Creates an engine with default settings and queue capacities of 128.
73    ///
74    /// When the `ws-client` feature is enabled, the default WebSocket TLS
75    /// connector is compiled during this call. Supply a provider with
76    /// [`Self::new_with_network_config`] or install the application's process
77    /// provider before calling this constructor. The SDK never installs one.
78    pub fn new() -> Result<Self, NetError> {
79        crate::log_s!(LogType::Engine; "OpenNet-new");
80        Self::new_with_config(OpenNetConfig::default())
81    }
82
83    /// Creates an engine with the supplied runtime, queue capacities, and network policy.
84    ///
85    /// Validates configuration before creating channels or workers. Invalid
86    /// capacities, worker counts, or missing WebSocket TLS providers return
87    /// `InvalidConfig`; values remain fixed thereafter.
88    ///
89    /// ```no_run
90    /// use open_net::{config::OpenNetConfig, NetError, OpenNet};
91    /// #[cfg(feature = "ws-client")]
92    /// use open_net::network::{NetworkConfig, TlsConfig};
93    /// #[cfg(feature = "ws-client")]
94    /// use std::sync::Arc;
95    /// # fn example() -> Result<(), NetError> {
96    /// let config = OpenNetConfig::default()
97    ///     .with_async_queue_capacity(256)
98    ///     .with_sync_queue_capacity(128);
99    /// #[cfg(feature = "ws-client")]
100    /// let config = config.with_network_config(
101    ///     NetworkConfig::default().with_tls(
102    ///         TlsConfig::default().with_crypto_provider(Arc::new(
103    ///             rustls_openssl::default_provider(),
104    ///         )),
105    ///     ),
106    /// );
107    /// let net = OpenNet::new_with_config(config)?;
108    /// # Ok(())
109    /// # }
110    /// ```
111    pub fn new_with_config(config: OpenNetConfig) -> Result<Self, NetError> {
112        crate::log_s!(LogType::Engine; "OpenNet-new_with_config","config", format!("{:?}", config));
113        let result: Result<Self, NetError> = (|| {
114            Ok(Self {
115                inner: OpenNetInner::new_with_config(config)?,
116            })
117        })();
118        result.inspect_err(|error| {
119            crate::log_e!(LogType::Engine; "new_with_config", "error|error_kind", format!("{error:?}"), format!("{:?}", error.kind()));
120        })
121    }
122
123    /// Creates a WebSocket client with default parameters and waits for its worker to become ready.
124    ///
125    /// The returned client is disconnected; call `connect` or `start_session` to establish a session.
126    #[cfg(feature = "ws-client")]
127    pub async fn create_ws_client(&self, thread_name: &str) -> Result<WebSocketClient, NetError> {
128        crate::log_t!(LogType::WSC; "create_ws_client", "thread_name", thread_name);
129        let result: Result<WebSocketClient, NetError> = async {
130            self.create_ws_client_with_config(thread_name, WebSocketClientConfig::default())
131                .await
132        }
133        .await;
134        result.inspect_err(|error| {
135            crate::log_e!(LogType::WSC; "create_ws_client", "error|error_kind", format!("{error:?}"), format!("{:?}", error.kind()));
136        })
137    }
138
139    /// Creates a WebSocket client with the supplied parameters and engine network policy.
140    ///
141    /// Cancelling the wait does not cancel submitted creation; retrieve the
142    /// client later with `get_ws_client` and release it with `destroy_ws_client`.
143    #[cfg(feature = "ws-client")]
144    pub async fn create_ws_client_with_config(
145        &self,
146        thread_name: &str,
147        config: WebSocketClientConfig,
148    ) -> Result<WebSocketClient, NetError> {
149        crate::log_t!(LogType::WSC; "create_ws_client_with_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, None)
157                .await
158        }
159        .await;
160        result.inspect_err(|error| {
161            crate::log_e!(LogType::WSC; "create_ws_client_with_config", "error|error_kind", format!("{error:?}"), format!("{:?}", error.kind()));
162        })
163    }
164
165    /// Returns the named WebSocket client, creating it when the name is not
166    /// registered yet.
167    ///
168    /// The supplied configuration is used only when this call creates the
169    /// client. If another caller has already registered the name, this method
170    /// returns a clone of that client and keeps its original immutable
171    /// configuration. Concurrent callers wait for the same lifecycle
172    /// transition and do not receive `ClientAlreadyExists` for the same name.
173    #[cfg(feature = "ws-client")]
174    pub async fn get_or_create_ws_client_with_config(
175        &self,
176        thread_name: &str,
177        config: WebSocketClientConfig,
178    ) -> Result<WebSocketClient, NetError> {
179        crate::log_t!(LogType::WSC; "get_or_create_ws_client_with_config", "thread_name|config", thread_name, format!("{:?}", config));
180        let result: Result<WebSocketClient, NetError> = async {
181            let thread_name = thread_name.trim();
182            if thread_name.is_empty() || thread_name.contains('\0') {
183                return Err(NetError::from(crate::error::ErrorKind::InvalidInput));
184            }
185            self.inner
186                .get_or_create_ws_client(thread_name.to_string(), config)
187                .await
188        }
189        .await;
190        result.inspect_err(|error| {
191            crate::log_e!(LogType::WSC; "get_or_create_ws_client_with_config", "error|error_kind", format!("{error:?}"), format!("{:?}", error.kind()));
192        })
193    }
194
195    /// Creates a WebSocket client with an immutable per-client proxy and TLS policy.
196    ///
197    /// The supplied policy completely replaces engine defaults. `default()` selects
198    /// direct mode and WebPKI roots; connect, retry, and reconnect use this snapshot.
199    ///
200    /// Waits for the worker to become ready but does not connect. Dropping the
201    /// future does not cancel creation; retrieve and later destroy the client by name.
202    ///
203    /// ```no_run
204    /// use open_net::{
205    ///     network::{NetworkConfig, ProxyConfig, TlsConfig},
206    ///     tls::CryptoProvider,
207    ///     ws::WebSocketClientConfig,
208    ///     NetError, OpenNet,
209    /// };
210    /// use std::sync::Arc;
211    /// # async fn example() -> Result<(), NetError> {
212    /// let provider: Arc<CryptoProvider> =
213    ///     Arc::new(rustls_openssl::default_provider());
214    /// let defaults = NetworkConfig::default()
215    ///     .with_proxy(ProxyConfig::http_connect("http://127.0.0.1:8080", None)?)
216    ///     .with_tls(TlsConfig::default().with_crypto_provider(Arc::clone(&provider)));
217    /// let net = OpenNet::new_with_network_config(defaults.clone())?;
218    /// let inherited = net.create_ws_client("inherited").await?;
219    /// let direct = net.create_ws_client_with_network_config(
220    ///     "direct", WebSocketClientConfig::default(),
221    ///     NetworkConfig::default().with_tls(
222    ///         TlsConfig::default().with_crypto_provider(Arc::clone(&provider)),
223    ///     ),
224    /// ).await?;
225    /// let other = net.create_ws_client_with_network_config(
226    ///     "other", WebSocketClientConfig::default(),
227    ///     defaults.with_proxy(ProxyConfig::http_connect("http://127.0.0.1:8081", None)?),
228    /// ).await?;
229    /// net.destroy_ws_client("inherited").await?;
230    /// net.destroy_ws_client("direct").await?;
231    /// net.destroy_ws_client("other").await?;
232    /// # Ok(())
233    /// # }
234    /// ```
235    #[cfg(feature = "ws-client")]
236    pub async fn create_ws_client_with_network_config(
237        &self,
238        thread_name: &str,
239        config: WebSocketClientConfig,
240        network_config: crate::network::NetworkConfig,
241    ) -> Result<WebSocketClient, NetError> {
242        crate::log_t!(LogType::WSC; "ws.create_ws_client_with_network_config",
243            "thread_name|config_close_timeout|config_command_capacity|config_heartbeat_enabled|network_config_proxy_direct|network_config_proxy_authenticated|network_config_status_policy|network_config_tls_root_mode|network_config_tls_custom_root_count|network_config_tls_identity_present|network_config_tls_provider_present",
244            thread_name, config.close_timeout, config.queues.commands, config.heartbeat.is_some(),
245            network_config.proxy().is_direct(), network_config.proxy().is_authenticated(),
246            format!("{:?}", network_config.network_status_policy()), format!("{:?}", network_config.tls().root_mode()),
247            network_config.tls().custom_root_count(), network_config.tls().client_identity().is_some(),
248            network_config.tls().crypto_provider().is_some());
249        let result: Result<WebSocketClient, NetError> = async {
250            let thread_name = thread_name.trim();
251            if thread_name.is_empty() {
252                return Err(NetError::from(crate::error::ErrorKind::InvalidInput));
253            }
254            self.inner
255                .create_ws_client(thread_name.to_string(), config, Some(network_config))
256                .await
257        }
258        .await;
259        result.inspect_err(|error| {
260            crate::log_e!(LogType::WSC; "ws.create_ws_client_with_network_config", "error_kind|stage", format!("{:?}", error.kind()), format!("{:?}", error.context().stage));
261        })
262    }
263
264    #[cfg(feature = "ws-client")]
265    /// Returns a shared handle to an existing WebSocket client.
266    pub fn get_ws_client(&self, thread_name: &str) -> Result<WebSocketClient, NetError> {
267        crate::log_t!(LogType::WSC; "get_ws_client", "thread_name", thread_name);
268        let result: Result<WebSocketClient, NetError> = (|| {
269            if thread_name.trim().is_empty() {
270                return Err(NetError::from(crate::error::ErrorKind::InvalidInput));
271            }
272            self.inner.get_ws_client(thread_name.trim())
273        })();
274        result.inspect_err(|error| {
275            crate::log_e!(LogType::WSC; "get_ws_client", "error|error_kind", format!("{error:?}"), format!("{:?}", error.kind()));
276        })
277    }
278
279    #[cfg(feature = "ws-client")]
280    /// Permanently destroys a named WebSocket client after its worker exits.
281    ///
282    /// This future can be awaited without a caller Tokio runtime, including via
283    /// `futures::executor::block_on`. The SDK owns the worker join. Cancelling
284    /// the wait does not cancel cleanup or release the name before worker exit.
285    /// A concurrent destroy returns [`crate::error::ErrorKind::ConnectionClosing`];
286    /// an absent name returns [`crate::error::ErrorKind::ClientNotFound`]. Use
287    /// [`Self::destroy_ws_client_if_exists`] for repeated, idempotent cleanup.
288    pub async fn destroy_ws_client(&self, thread_name: &str) -> Result<(), NetError> {
289        crate::log_t!(LogType::WSC; "destroy_ws_client", "thread_name", thread_name);
290        let result: Result<(), NetError> = async {
291            if thread_name.trim().is_empty() {
292                return Err(NetError::from(crate::error::ErrorKind::InvalidInput));
293            }
294            self.inner.destroy_ws_client(thread_name.trim()).await
295        }
296        .await;
297        result.inspect_err(|error| {
298            crate::log_e!(LogType::WSC; "destroy_ws_client", "error|error_kind", format!("{error:?}"), format!("{:?}", error.kind()));
299        })
300    }
301
302    /// Permanently destroys a named WebSocket client when it exists.
303    ///
304    /// Missing names are treated as success, so this method can be used from
305    /// repeated or best-effort cleanup paths. If creation or destruction is
306    /// already in progress, it waits for that lifecycle operation and then
307    /// completes the requested cleanup.
308    /// Like [`Self::destroy_ws_client`], this does not require a caller Tokio
309    /// runtime and accepted cleanup continues if its waiter is cancelled.
310    #[cfg(feature = "ws-client")]
311    pub async fn destroy_ws_client_if_exists(&self, thread_name: &str) -> Result<(), NetError> {
312        crate::log_t!(LogType::WSC; "destroy_ws_client_if_exists", "thread_name", thread_name);
313        let result: Result<(), NetError> = async {
314            let thread_name = thread_name.trim();
315            if thread_name.is_empty() || thread_name.contains('\0') {
316                return Err(NetError::from(crate::error::ErrorKind::InvalidInput));
317            }
318            self.inner.destroy_ws_client_if_exists(thread_name).await
319        }
320        .await;
321        result.inspect_err(|error| {
322            crate::log_e!(LogType::WSC; "destroy_ws_client_if_exists", "error|error_kind", format!("{error:?}"), format!("{:?}", error.kind()));
323        })
324    }
325}
326
327#[cfg(feature = "net-status")]
328impl OpenNet {
329    /// Export this engine's cached network state for an explicitly configured
330    /// standalone HTTP client. Reading the context never starts monitoring.
331    /// The context remains bound to this engine and becomes Closed on engine drop.
332    pub fn network_status_context(&self) -> crate::net_status::NetworkStatusContext {
333        self.inner.network_status.context()
334    }
335
336    /// Creates a network-status client; call `start().await` to begin monitoring.
337    ///
338    /// Names are trimmed and must be unique within an engine. Requires the
339    /// `net-status` feature, also enabled by `http-client` and `ws-client`.
340    ///
341    /// ```no_run
342    /// use open_net::{NetError, OpenNet};
343    /// #[cfg(feature = "ws-client")]
344    /// use open_net::network::{NetworkConfig, TlsConfig};
345    /// #[cfg(feature = "ws-client")]
346    /// use std::sync::Arc;
347    /// # async fn example() -> Result<(), NetError> {
348    /// #[cfg(feature = "ws-client")]
349    /// let net = OpenNet::new_with_network_config(
350    ///     NetworkConfig::default().with_tls(
351    ///         TlsConfig::default().with_crypto_provider(Arc::new(
352    ///             rustls_openssl::default_provider(),
353    ///         )),
354    ///     ),
355    /// )?;
356    /// #[cfg(not(feature = "ws-client"))]
357    /// let net = OpenNet::new()?;
358    /// let client = net.create_net_status_client("network-status").await?;
359    /// client.start().await?;
360    /// let snapshot = client.snapshot()?;
361    /// let status = snapshot.reachability;
362    /// let ip_stack = snapshot.ip_stack;
363    /// net.destroy_net_status_client("network-status").await?;
364    /// # Ok(())
365    /// # }
366    /// ```
367    pub async fn create_net_status_client(
368        &self,
369        thread_name: &str,
370    ) -> Result<NetStatusClient, NetError> {
371        let thread_name = thread_name.trim();
372        crate::log_t!(LogType::Engine; "net_status.create_net_status_client", "thread_name", thread_name);
373        if thread_name.is_empty() {
374            return Err(NetError::from(crate::error::ErrorKind::InvalidInput));
375        }
376        self.inner.create_net_status_client(thread_name)
377    }
378
379    /// Returns a shared handle to a named network-status client.
380    pub fn get_net_status_client(&self, thread_name: &str) -> Result<NetStatusClient, NetError> {
381        let thread_name = thread_name.trim();
382        if thread_name.is_empty() {
383            return Err(NetError::from(crate::error::ErrorKind::InvalidInput));
384        }
385        self.inner.get_net_status_client(thread_name)
386    }
387
388    /// Permanently stops a client, waits for monitoring to exit, and releases its name.
389    ///
390    /// Cancelling the wait does not cancel submitted destruction; the name remains
391    /// reserved until cleanup completes. Use `NetStatusClient::stop` to pause instead.
392    pub async fn destroy_net_status_client(&self, thread_name: &str) -> Result<(), NetError> {
393        let thread_name = thread_name.trim();
394        crate::log_t!(LogType::Engine; "net_status.destroy_net_status_client", "thread_name", thread_name);
395        if thread_name.is_empty() {
396            return Err(NetError::from(crate::error::ErrorKind::InvalidInput));
397        }
398        self.inner.destroy_net_status_client(thread_name).await
399    }
400}
401
402impl OpenNet {
403    /// Register a lazy HTTP client with fixed configuration and its own shutdown boundary.
404    ///
405    /// Names share the existing HTTP registry and must be nonblank and contain
406    /// no NUL. Registration validates configuration without constructing HTTP
407    /// workers. Clone the returned handle to share initialization and shutdown;
408    /// declaring an already reserved name returns `ClientAlreadyExists`.
409    #[cfg(feature = "http-client")]
410    pub fn managed_http(
411        &self,
412        name: &str,
413        config: HttpClientConfig,
414    ) -> Result<crate::api::http::ManagedHttpClient, NetError> {
415        let name = name.trim();
416        if name.is_empty() || name.contains('\0') {
417            return Err(NetError::from(crate::error::ErrorKind::InvalidInput));
418        }
419        self.inner.managed_http(name.to_owned(), config)
420    }
421
422    #[cfg(feature = "http-client")]
423    /// Creates an HTTP client with the supplied configuration.
424    pub async fn create_http_client_with_config(
425        &self,
426        thread_name: &str,
427        config: HttpClientConfig,
428    ) -> Result<HttpClient, NetError> {
429        crate::log_t!(LogType::HTTP; "create_http_client_with_config", "thread_name|config", thread_name, format!("{:?}", config));
430        let result: Result<HttpClient, NetError> = async {
431            let thread_name = thread_name.trim();
432            if thread_name.is_empty() || thread_name.contains('\0') {
433                return Err(NetError::from(crate::error::ErrorKind::InvalidInput));
434            }
435            self.inner
436                .create_http_client(thread_name.to_string(), config)
437                .await
438        }
439        .await;
440        result.inspect_err(|error| {
441            crate::log_e!(LogType::HTTP; "create_http_client_with_config", "error|error_kind", format!("{error:?}"), format!("{:?}", error.kind()));
442        })
443    }
444
445    #[cfg(feature = "http-client")]
446    /// Returns a shared handle to an existing HTTP client.
447    pub fn get_http_client(&self, thread_name: &str) -> Result<HttpClient, NetError> {
448        crate::log_t!(LogType::HTTP; "get_http_client", "thread_name", thread_name);
449        let name = thread_name.trim();
450        if name.is_empty() {
451            return Err(NetError::from(crate::error::ErrorKind::InvalidInput));
452        }
453        self.inner.get_http_client(name)
454    }
455
456    #[cfg(feature = "http-client")]
457    /// Permanently destroys a named HTTP client after its worker exits.
458    pub async fn destroy_http_client(&self, thread_name: &str) -> Result<(), NetError> {
459        crate::log_t!(LogType::HTTP; "destroy_http_client", "thread_name", thread_name);
460        let name = thread_name.trim();
461        if name.is_empty() {
462            return Err(NetError::from(crate::error::ErrorKind::InvalidInput));
463        }
464        self.inner.destroy_http_client(name).await
465    }
466}