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