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; "create_ws_client_with_network_config", "thread_name|config", thread_name, format!("{config:?}"));
243 let result: Result<WebSocketClient, NetError> = async {
244 let thread_name = thread_name.trim();
245 if thread_name.is_empty() {
246 return Err(NetError::from(crate::error::ErrorKind::InvalidInput));
247 }
248 self.inner
249 .create_ws_client(thread_name.to_string(), config, Some(network_config))
250 .await
251 }
252 .await;
253 result.inspect_err(|error| {
254 crate::log_e!(LogType::WSC; "create_ws_client_with_network_config", "error|error_kind", format!("{error:?}"), format!("{:?}", error.kind()));
255 })
256 }
257
258 #[cfg(feature = "ws-client")]
259 /// Returns a shared handle to an existing WebSocket client.
260 pub fn get_ws_client(&self, thread_name: &str) -> Result<WebSocketClient, NetError> {
261 crate::log_t!(LogType::WSC; "get_ws_client", "thread_name", thread_name);
262 let result: Result<WebSocketClient, NetError> = (|| {
263 if thread_name.trim().is_empty() {
264 return Err(NetError::from(crate::error::ErrorKind::InvalidInput));
265 }
266 self.inner.get_ws_client(thread_name.trim())
267 })();
268 result.inspect_err(|error| {
269 crate::log_e!(LogType::WSC; "get_ws_client", "error|error_kind", format!("{error:?}"), format!("{:?}", error.kind()));
270 })
271 }
272
273 #[cfg(feature = "ws-client")]
274 /// Permanently destroys a named WebSocket client after its worker exits.
275 ///
276 /// This future can be awaited without a caller Tokio runtime, including via
277 /// `futures::executor::block_on`. The SDK owns the worker join. Cancelling
278 /// the wait does not cancel cleanup or release the name before worker exit.
279 /// A concurrent destroy returns [`crate::error::ErrorKind::ConnectionClosing`];
280 /// an absent name returns [`crate::error::ErrorKind::ClientNotFound`]. Use
281 /// [`Self::destroy_ws_client_if_exists`] for repeated, idempotent cleanup.
282 pub async fn destroy_ws_client(&self, thread_name: &str) -> Result<(), NetError> {
283 crate::log_t!(LogType::WSC; "destroy_ws_client", "thread_name", thread_name);
284 let result: Result<(), NetError> = async {
285 if thread_name.trim().is_empty() {
286 return Err(NetError::from(crate::error::ErrorKind::InvalidInput));
287 }
288 self.inner.destroy_ws_client(thread_name.trim()).await
289 }
290 .await;
291 result.inspect_err(|error| {
292 crate::log_e!(LogType::WSC; "destroy_ws_client", "error|error_kind", format!("{error:?}"), format!("{:?}", error.kind()));
293 })
294 }
295
296 /// Permanently destroys a named WebSocket client when it exists.
297 ///
298 /// Missing names are treated as success, so this method can be used from
299 /// repeated or best-effort cleanup paths. If creation or destruction is
300 /// already in progress, it waits for that lifecycle operation and then
301 /// completes the requested cleanup.
302 /// Like [`Self::destroy_ws_client`], this does not require a caller Tokio
303 /// runtime and accepted cleanup continues if its waiter is cancelled.
304 #[cfg(feature = "ws-client")]
305 pub async fn destroy_ws_client_if_exists(&self, thread_name: &str) -> Result<(), NetError> {
306 crate::log_t!(LogType::WSC; "destroy_ws_client_if_exists", "thread_name", thread_name);
307 let result: Result<(), NetError> = async {
308 let thread_name = thread_name.trim();
309 if thread_name.is_empty() || thread_name.contains('\0') {
310 return Err(NetError::from(crate::error::ErrorKind::InvalidInput));
311 }
312 self.inner.destroy_ws_client_if_exists(thread_name).await
313 }
314 .await;
315 result.inspect_err(|error| {
316 crate::log_e!(LogType::WSC; "destroy_ws_client_if_exists", "error|error_kind", format!("{error:?}"), format!("{:?}", error.kind()));
317 })
318 }
319}
320
321#[cfg(feature = "net-status")]
322impl OpenNet {
323 /// Export this engine's cached network state for an explicitly configured
324 /// standalone HTTP client. Reading the context never starts monitoring.
325 /// The context remains bound to this engine and becomes Closed on engine drop.
326 pub fn network_status_context(&self) -> crate::net_status::NetworkStatusContext {
327 self.inner.network_status.context()
328 }
329
330 /// Creates a network-status client; call `start().await` to begin monitoring.
331 ///
332 /// Names are trimmed and must be unique within an engine. Requires the
333 /// `net-status` feature, also enabled by `http-client` and `ws-client`.
334 ///
335 /// ```no_run
336 /// use open_net::{NetError, OpenNet};
337 /// #[cfg(feature = "ws-client")]
338 /// use open_net::network::{NetworkConfig, TlsConfig};
339 /// #[cfg(feature = "ws-client")]
340 /// use std::sync::Arc;
341 /// # async fn example() -> Result<(), NetError> {
342 /// #[cfg(feature = "ws-client")]
343 /// let net = OpenNet::new_with_network_config(
344 /// NetworkConfig::default().with_tls(
345 /// TlsConfig::default().with_crypto_provider(Arc::new(
346 /// rustls_openssl::default_provider(),
347 /// )),
348 /// ),
349 /// )?;
350 /// #[cfg(not(feature = "ws-client"))]
351 /// let net = OpenNet::new()?;
352 /// let client = net.create_net_status_client("network-status").await?;
353 /// client.start().await?;
354 /// let snapshot = client.snapshot()?;
355 /// let status = snapshot.reachability;
356 /// let ip_stack = snapshot.ip_stack;
357 /// net.destroy_net_status_client("network-status").await?;
358 /// # Ok(())
359 /// # }
360 /// ```
361 pub async fn create_net_status_client(
362 &self,
363 thread_name: &str,
364 ) -> Result<NetStatusClient, NetError> {
365 let thread_name = thread_name.trim();
366 crate::log_s!(LogType::Engine; "create_net_status_client", "thread_name", thread_name);
367 if thread_name.is_empty() {
368 return Err(NetError::from(crate::error::ErrorKind::InvalidInput));
369 }
370 self.inner.create_net_status_client(thread_name)
371 }
372
373 /// Returns a shared handle to a named network-status client.
374 pub fn get_net_status_client(&self, thread_name: &str) -> Result<NetStatusClient, NetError> {
375 let thread_name = thread_name.trim();
376 if thread_name.is_empty() {
377 return Err(NetError::from(crate::error::ErrorKind::InvalidInput));
378 }
379 self.inner.get_net_status_client(thread_name)
380 }
381
382 /// Permanently stops a client, waits for monitoring to exit, and releases its name.
383 ///
384 /// Cancelling the wait does not cancel submitted destruction; the name remains
385 /// reserved until cleanup completes. Use `NetStatusClient::stop` to pause instead.
386 pub async fn destroy_net_status_client(&self, thread_name: &str) -> Result<(), NetError> {
387 let thread_name = thread_name.trim();
388 crate::log_s!(LogType::Engine; "destroy_net_status_client", "thread_name", thread_name);
389 if thread_name.is_empty() {
390 return Err(NetError::from(crate::error::ErrorKind::InvalidInput));
391 }
392 self.inner.destroy_net_status_client(thread_name).await
393 }
394}
395
396impl OpenNet {
397 /// Register a lazy HTTP client with fixed configuration and its own shutdown boundary.
398 ///
399 /// Names share the existing HTTP registry and must be nonblank and contain
400 /// no NUL. Registration validates configuration without constructing HTTP
401 /// workers. Clone the returned handle to share initialization and shutdown;
402 /// declaring an already reserved name returns `ClientAlreadyExists`.
403 #[cfg(feature = "http-client")]
404 pub fn managed_http(
405 &self,
406 name: &str,
407 config: HttpClientConfig,
408 ) -> Result<crate::api::http::ManagedHttpClient, NetError> {
409 let name = name.trim();
410 if name.is_empty() || name.contains('\0') {
411 return Err(NetError::from(crate::error::ErrorKind::InvalidInput));
412 }
413 self.inner.managed_http(name.to_owned(), config)
414 }
415
416 #[cfg(feature = "http-client")]
417 /// Creates an HTTP client with the supplied configuration.
418 pub async fn create_http_client_with_config(
419 &self,
420 thread_name: &str,
421 config: HttpClientConfig,
422 ) -> Result<HttpClient, NetError> {
423 crate::log_t!(LogType::HTTP; "create_http_client_with_config", "thread_name|config", thread_name, format!("{:?}", config));
424 let result: Result<HttpClient, NetError> = async {
425 let thread_name = thread_name.trim();
426 if thread_name.is_empty() || thread_name.contains('\0') {
427 return Err(NetError::from(crate::error::ErrorKind::InvalidInput));
428 }
429 self.inner
430 .create_http_client(thread_name.to_string(), config)
431 .await
432 }
433 .await;
434 result.inspect_err(|error| {
435 crate::log_e!(LogType::HTTP; "create_http_client_with_config", "error|error_kind", format!("{error:?}"), format!("{:?}", error.kind()));
436 })
437 }
438
439 #[cfg(feature = "http-client")]
440 /// Returns a shared handle to an existing HTTP client.
441 pub fn get_http_client(&self, thread_name: &str) -> Result<HttpClient, NetError> {
442 crate::log_t!(LogType::HTTP; "get_http_client", "thread_name", thread_name);
443 let name = thread_name.trim();
444 if name.is_empty() {
445 return Err(NetError::from(crate::error::ErrorKind::InvalidInput));
446 }
447 self.inner.get_http_client(name)
448 }
449
450 #[cfg(feature = "http-client")]
451 /// Permanently destroys a named HTTP client after its worker exits.
452 pub async fn destroy_http_client(&self, thread_name: &str) -> Result<(), NetError> {
453 crate::log_t!(LogType::HTTP; "destroy_http_client", "thread_name", thread_name);
454 let name = thread_name.trim();
455 if name.is_empty() {
456 return Err(NetError::from(crate::error::ErrorKind::InvalidInput));
457 }
458 self.inner.destroy_http_client(name).await
459 }
460}