Skip to main content

open_net/api/
open_net_config.rs

1#[cfg(feature = "ws-client")]
2use crate::api::network_config::NetworkConfig;
3use crate::error::NetError;
4use tokio::sync::Semaphore;
5
6/// Internal runtime, queue capacities, and default network policy used when
7/// constructing [`crate::OpenNet`]. Queue capacities count pending tasks, not
8/// bytes or concurrency, default to 128, must be in
9/// `1..=tokio::sync::Semaphore::MAX_PERMITS`, and are fixed after engine
10/// creation. [`crate::OpenNet::new_with_config`] validates them before creating
11/// channels or workers and reports invalid values as
12/// [`crate::error::ErrorKind::InvalidConfig`].
13#[cfg_attr(
14    feature = "ws-client",
15    doc = "
16When `ws-client` is enabled, configure a provider in the nested
17[`NetworkConfig`](crate::network::NetworkConfig) before constructing [`crate::OpenNet`],
18unless the host application has already installed a process-wide rustls provider."
19)]
20#[derive(Clone, Debug)]
21pub struct OpenNetConfig {
22    pub(crate) runtime_worker_threads: Option<usize>,
23    pub(crate) async_queue_capacity: usize,
24    pub(crate) sync_queue_capacity: usize,
25    #[cfg(feature = "ws-client")]
26    pub(crate) network_config: NetworkConfig,
27}
28
29impl Default for OpenNetConfig {
30    fn default() -> Self {
31        Self {
32            runtime_worker_threads: None,
33            async_queue_capacity: 128,
34            sync_queue_capacity: 128,
35            #[cfg(feature = "ws-client")]
36            network_config: NetworkConfig::default(),
37        }
38    }
39}
40
41impl OpenNetConfig {
42    /// Sets the management runtime worker count (`1..=256`). If omitted, Tokio
43    /// defaults apply, including the `TOKIO_WORKER_THREADS` environment
44    /// variable. The explicit value is validated before creation and does not
45    /// cap per-client I/O, callback, management, or blocking threads.
46    ///
47    /// ```no_run
48    /// use open_net::{NetError, OpenNet, OpenNetConfig};
49    ///
50    /// #[cfg(feature = "ws-client")]
51    /// use open_net::network::{NetworkConfig, TlsConfig};
52    /// #[cfg(feature = "ws-client")]
53    /// use std::sync::Arc;
54    /// # fn example() -> Result<(), NetError> {
55    /// let config = OpenNetConfig::default().with_runtime_worker_threads(2);
56    /// #[cfg(feature = "ws-client")]
57    /// let config = config.with_network_config(
58    ///     NetworkConfig::default().with_tls(
59    ///         TlsConfig::default().with_crypto_provider(Arc::new(
60    ///             rustls_openssl::default_provider(),
61    ///         )),
62    ///     ),
63    /// );
64    /// let net = OpenNet::new_with_config(config)?;
65    /// # Ok(())
66    /// # }
67    /// ```
68    pub fn with_runtime_worker_threads(mut self, threads: usize) -> Self {
69        self.runtime_worker_threads = Some(threads);
70        self
71    }
72
73    /// Sets the asynchronous submission queue capacity (default: 128).
74    /// The value is validated during engine creation and must be within the
75    /// semaphore-supported range.
76    pub fn with_async_queue_capacity(mut self, capacity: usize) -> Self {
77        self.async_queue_capacity = capacity;
78        self
79    }
80
81    /// Sets the synchronous-call queue capacity (default: 128). Synchronous
82    /// means the caller waits for a result; the underlying channel is still
83    /// MPSC. The value is validated during engine creation and must be within
84    /// the semaphore-supported range.
85    pub fn with_sync_queue_capacity(mut self, capacity: usize) -> Self {
86        self.sync_queue_capacity = capacity;
87        self
88    }
89
90    /// Sets the default WebSocket network policy; clients may override it at creation.
91    #[cfg(feature = "ws-client")]
92    pub fn with_network_config(mut self, config: NetworkConfig) -> Self {
93        self.network_config = config;
94        self
95    }
96
97    /// Returns the configured management-runtime worker count, if explicitly set.
98    pub fn runtime_worker_threads(&self) -> Option<usize> {
99        self.runtime_worker_threads
100    }
101
102    /// Returns the bounded asynchronous submission queue capacity.
103    pub fn async_queue_capacity(&self) -> usize {
104        self.async_queue_capacity
105    }
106
107    /// Returns the bounded synchronous submission queue capacity.
108    pub fn sync_queue_capacity(&self) -> usize {
109        self.sync_queue_capacity
110    }
111
112    #[cfg(feature = "ws-client")]
113    /// Returns the default WebSocket network policy used for new clients.
114    pub fn network_config(&self) -> &NetworkConfig {
115        &self.network_config
116    }
117
118    /// Validates runtime worker, queue, and nested network configuration limits.
119    pub fn validate(&self) -> Result<(), NetError> {
120        if self.runtime_worker_threads.is_some_and(|threads| {
121            threads == 0 || threads > crate::common::common_engine::MAX_RUNTIME_WORKER_THREADS
122        }) {
123            return Err(NetError::config(
124                "runtime_worker_threads",
125                "must be between 1 and 256",
126            ));
127        }
128        for (field, capacity) in [
129            ("async_queue_capacity", self.async_queue_capacity),
130            ("sync_queue_capacity", self.sync_queue_capacity),
131        ] {
132            if capacity == 0 || capacity > Semaphore::MAX_PERMITS {
133                return Err(NetError::config(
134                    field,
135                    "must be between 1 and Semaphore::MAX_PERMITS",
136                ));
137            }
138        }
139        #[cfg(feature = "ws-client")]
140        self.network_config.validate()?;
141        Ok(())
142    }
143}
144
145#[cfg(all(test, feature = "ws-client"))]
146mod validation_tests {
147    use super::*;
148    use crate::network::RootCertificateMode;
149
150    #[test]
151    fn engine_validation_includes_nested_network_configuration() -> Result<(), NetError> {
152        let mut network = NetworkConfig::default();
153        network.tls.root_mode = RootCertificateMode::Replace;
154        let config = OpenNetConfig::default().with_network_config(network);
155        if !matches!(config.validate(), Err(ref __classified_error_0) if matches!(__classified_error_0.kind(), crate::error::ErrorKind::InvalidConfig))
156        {
157            return Err(NetError::from(crate::error::ErrorKind::Internal));
158        }
159        Ok(())
160    }
161}