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 #[cfg(feature = "quality-doctor")]
23 pub(crate) quality_doctor: crate::quality::QualityDoctorConfig,
24 pub(crate) runtime_worker_threads: Option<usize>,
25 pub(crate) async_queue_capacity: usize,
26 pub(crate) sync_queue_capacity: usize,
27 #[cfg(feature = "ws-client")]
28 pub(crate) network_config: NetworkConfig,
29}
30
31impl Default for OpenNetConfig {
32 fn default() -> Self {
33 Self {
34 #[cfg(feature = "quality-doctor")]
35 quality_doctor: crate::quality::QualityDoctorConfig::default(),
36 runtime_worker_threads: None,
37 async_queue_capacity: 128,
38 sync_queue_capacity: 128,
39 #[cfg(feature = "ws-client")]
40 network_config: NetworkConfig::default(),
41 }
42 }
43}
44
45impl OpenNetConfig {
46 /// Sets the passive diagnostic policy shared by this engine's managed clients.
47 ///
48 /// `config` supplies the mode, protocol selection, memory/retention limits,
49 /// Detailed sampling rates, and finding thresholds. The default is
50 /// [`crate::quality::QualityMode::Off`]. This builder stores the supplied value
51 /// without validation; [`Self::validate`] and engine construction validate it
52 /// and report invalid values as [`crate::error::ErrorKind::InvalidConfig`].
53 /// Call `config.validate()` directly when the detailed diagnostic validation
54 /// error is needed.
55 ///
56 /// Basic and Detailed remain dormant until an explicit
57 /// [`crate::OpenNet::quality_doctor`] call, or a `quality_doctor()` call on a
58 /// managed HTTP client, activates the shared collector. Configure and activate
59 /// before submitting operations: requests never initialize the diagnostic
60 /// store, and earlier observations are not reconstructed. Calling this builder
61 /// does not start diagnostic tasks, perform network probes, or alter request
62 /// deadlines and retry policies. The policy is fixed for the resulting engine.
63 #[cfg(feature = "quality-doctor")]
64 pub fn with_quality_doctor(mut self, config: crate::quality::QualityDoctorConfig) -> Self {
65 self.quality_doctor = config;
66 self
67 }
68
69 /// Sets the management runtime worker count (`1..=256`). If omitted, Tokio
70 /// defaults apply, including the `TOKIO_WORKER_THREADS` environment
71 /// variable. The explicit value is validated before creation and does not
72 /// cap per-client I/O, callback, management, or blocking threads.
73 ///
74 /// ```no_run
75 /// use open_net::{NetError, OpenNet, OpenNetConfig};
76 ///
77 /// #[cfg(feature = "ws-client")]
78 /// use open_net::network::{NetworkConfig, TlsConfig};
79 /// #[cfg(feature = "ws-client")]
80 /// use std::sync::Arc;
81 /// # fn example() -> Result<(), NetError> {
82 /// let config = OpenNetConfig::default().with_runtime_worker_threads(2);
83 /// #[cfg(feature = "ws-client")]
84 /// let config = config.with_network_config(
85 /// NetworkConfig::default().with_tls(
86 /// TlsConfig::default().with_crypto_provider(Arc::new(
87 /// rustls_openssl::default_provider(),
88 /// )),
89 /// ),
90 /// );
91 /// let net = OpenNet::new_with_config(config)?;
92 /// # Ok(())
93 /// # }
94 /// ```
95 pub fn with_runtime_worker_threads(mut self, threads: usize) -> Self {
96 self.runtime_worker_threads = Some(threads);
97 self
98 }
99
100 /// Sets the asynchronous submission queue capacity (default: 128).
101 /// The value is validated during engine creation and must be within the
102 /// semaphore-supported range.
103 pub fn with_async_queue_capacity(mut self, capacity: usize) -> Self {
104 self.async_queue_capacity = capacity;
105 self
106 }
107
108 /// Sets the synchronous-call queue capacity (default: 128). Synchronous
109 /// means the caller waits for a result; the underlying channel is still
110 /// MPSC. The value is validated during engine creation and must be within
111 /// the semaphore-supported range.
112 pub fn with_sync_queue_capacity(mut self, capacity: usize) -> Self {
113 self.sync_queue_capacity = capacity;
114 self
115 }
116
117 /// Sets the default WebSocket network policy; clients may override it at creation.
118 #[cfg(feature = "ws-client")]
119 pub fn with_network_config(mut self, config: NetworkConfig) -> Self {
120 self.network_config = config;
121 self
122 }
123
124 /// Returns the configured management-runtime worker count, if explicitly set.
125 pub fn runtime_worker_threads(&self) -> Option<usize> {
126 self.runtime_worker_threads
127 }
128
129 /// Returns the bounded asynchronous submission queue capacity.
130 pub fn async_queue_capacity(&self) -> usize {
131 self.async_queue_capacity
132 }
133
134 /// Returns the bounded synchronous submission queue capacity.
135 pub fn sync_queue_capacity(&self) -> usize {
136 self.sync_queue_capacity
137 }
138
139 #[cfg(feature = "ws-client")]
140 /// Returns the default WebSocket network policy used for new clients.
141 pub fn network_config(&self) -> &NetworkConfig {
142 &self.network_config
143 }
144
145 /// Validates runtime worker, queue, and nested network configuration limits.
146 pub fn validate(&self) -> Result<(), NetError> {
147 #[cfg(feature = "quality-doctor")]
148 self.quality_doctor
149 .validate()
150 .map_err(|_| NetError::config("quality_doctor", "invalid diagnostic configuration"))?;
151 if self.runtime_worker_threads.is_some_and(|threads| {
152 threads == 0 || threads > crate::common::common_engine::MAX_RUNTIME_WORKER_THREADS
153 }) {
154 return Err(NetError::config(
155 "runtime_worker_threads",
156 "must be between 1 and 256",
157 ));
158 }
159 for (field, capacity) in [
160 ("async_queue_capacity", self.async_queue_capacity),
161 ("sync_queue_capacity", self.sync_queue_capacity),
162 ] {
163 if capacity == 0 || capacity > Semaphore::MAX_PERMITS {
164 return Err(NetError::config(
165 field,
166 "must be between 1 and Semaphore::MAX_PERMITS",
167 ));
168 }
169 }
170 #[cfg(feature = "ws-client")]
171 self.network_config.validate()?;
172 Ok(())
173 }
174}
175
176#[cfg(all(test, feature = "ws-client"))]
177mod validation_tests {
178 use super::*;
179 use crate::network::RootCertificateMode;
180
181 #[test]
182 fn engine_validation_includes_nested_network_configuration() -> Result<(), NetError> {
183 let mut network = NetworkConfig::default();
184 network.tls.root_mode = RootCertificateMode::Replace;
185 let config = OpenNetConfig::default().with_network_config(network);
186 if !matches!(config.validate(), Err(ref __classified_error_0) if matches!(__classified_error_0.kind(), crate::error::ErrorKind::InvalidConfig))
187 {
188 return Err(NetError::from(crate::error::ErrorKind::Internal));
189 }
190 Ok(())
191 }
192}