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