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