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