1use std::path::PathBuf;
4use std::time::Duration;
5
6use crate::error::{NetworkError, Result};
7use crate::protocol::{ALPN, NetworkId, SchemaId};
8use crate::rendezvous::RendezvousConfig;
9
10pub const DEFAULT_MAX_MESSAGE_SIZE: usize = 256 * 1024;
12pub const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
14pub const DEFAULT_EVENT_CHANNEL_CAPACITY: usize = 1024;
16pub const DEFAULT_MAX_CONCURRENT_STREAMS_PER_PEER: usize = 64;
18
19#[derive(Debug, Clone)]
23pub struct NetworkConfig {
24 pub data_dir: PathBuf,
26 pub network_id: NetworkId,
28 pub schema_id: SchemaId,
30 pub max_message_size: usize,
32 pub request_timeout: Duration,
34 pub event_channel_capacity: usize,
36 pub max_concurrent_streams_per_peer: usize,
38 pub rendezvous: Option<RendezvousConfig>,
41 pub stream_protocols: Vec<Vec<u8>>,
44 pub schema_independent_stream_protocols: Vec<Vec<u8>>,
47}
48
49impl NetworkConfig {
50 pub fn builder() -> NetworkConfigBuilder {
52 NetworkConfigBuilder::default()
53 }
54}
55
56#[derive(Debug, Default, Clone)]
61pub struct NetworkConfigBuilder {
62 data_dir: Option<PathBuf>,
63 network_id: Option<NetworkId>,
64 schema_id: Option<SchemaId>,
65 max_message_size: Option<usize>,
66 request_timeout: Option<Duration>,
67 event_channel_capacity: Option<usize>,
68 max_concurrent_streams_per_peer: Option<usize>,
69 rendezvous: Option<RendezvousConfig>,
70 stream_protocols: Vec<Vec<u8>>,
71 schema_independent_stream_protocols: Vec<Vec<u8>>,
72}
73
74impl NetworkConfigBuilder {
75 pub fn data_dir(mut self, dir: impl Into<PathBuf>) -> Self {
77 self.data_dir = Some(dir.into());
78 self
79 }
80
81 pub fn network_id(mut self, network_id: NetworkId) -> Self {
83 self.network_id = Some(network_id);
84 self
85 }
86
87 pub fn schema_id(mut self, schema_id: SchemaId) -> Self {
89 self.schema_id = Some(schema_id);
90 self
91 }
92
93 pub fn max_message_size(mut self, size: usize) -> Self {
95 self.max_message_size = Some(size);
96 self
97 }
98
99 pub fn request_timeout(mut self, timeout: Duration) -> Self {
101 self.request_timeout = Some(timeout);
102 self
103 }
104
105 pub fn event_channel_capacity(mut self, capacity: usize) -> Self {
107 self.event_channel_capacity = Some(capacity);
108 self
109 }
110
111 pub fn max_concurrent_streams_per_peer(mut self, limit: usize) -> Self {
113 self.max_concurrent_streams_per_peer = Some(limit);
114 self
115 }
116
117 pub fn rendezvous(mut self, rendezvous: RendezvousConfig) -> Self {
119 self.rendezvous = Some(rendezvous);
120 self
121 }
122
123 pub fn stream_protocol(mut self, alpn: impl Into<Vec<u8>>) -> Self {
127 self.stream_protocols.push(alpn.into());
128 self
129 }
130
131 pub fn schema_independent_stream_protocol(mut self, alpn: impl Into<Vec<u8>>) -> Self {
138 self.schema_independent_stream_protocols.push(alpn.into());
139 self
140 }
141
142 pub fn build(self) -> Result<NetworkConfig> {
144 let data_dir = self
145 .data_dir
146 .ok_or_else(|| NetworkError::InvalidConfig("data_dir is required".into()))?;
147 let network_id = self
148 .network_id
149 .ok_or_else(|| NetworkError::InvalidConfig("network_id is required".into()))?;
150 let schema_id = self
151 .schema_id
152 .ok_or_else(|| NetworkError::InvalidConfig("schema_id is required".into()))?;
153
154 if data_dir.as_os_str().is_empty() {
155 return Err(NetworkError::InvalidConfig(
156 "data_dir must not be empty".into(),
157 ));
158 }
159
160 let max_message_size = self.max_message_size.unwrap_or(DEFAULT_MAX_MESSAGE_SIZE);
161 if max_message_size == 0 {
162 return Err(NetworkError::InvalidConfig(
163 "max_message_size must be greater than zero".into(),
164 ));
165 }
166 if max_message_size > u32::MAX as usize {
167 return Err(NetworkError::InvalidConfig(
168 "max_message_size must fit into a 32-bit length prefix".into(),
169 ));
170 }
171
172 let request_timeout = self.request_timeout.unwrap_or(DEFAULT_REQUEST_TIMEOUT);
173 if request_timeout.is_zero() {
174 return Err(NetworkError::InvalidConfig(
175 "request_timeout must be greater than zero".into(),
176 ));
177 }
178
179 let event_channel_capacity = self
180 .event_channel_capacity
181 .unwrap_or(DEFAULT_EVENT_CHANNEL_CAPACITY);
182 if event_channel_capacity == 0 {
183 return Err(NetworkError::InvalidConfig(
184 "event_channel_capacity must be greater than zero".into(),
185 ));
186 }
187
188 let max_concurrent_streams_per_peer = self
189 .max_concurrent_streams_per_peer
190 .unwrap_or(DEFAULT_MAX_CONCURRENT_STREAMS_PER_PEER);
191 if max_concurrent_streams_per_peer == 0 {
192 return Err(NetworkError::InvalidConfig(
193 "max_concurrent_streams_per_peer must be greater than zero".into(),
194 ));
195 }
196
197 if let Some(rendezvous) = &self.rendezvous {
198 if rendezvous.interval.is_zero() {
199 return Err(NetworkError::InvalidConfig(
200 "rendezvous interval must be greater than zero".into(),
201 ));
202 }
203 if rendezvous.entry_ttl.is_zero() {
204 return Err(NetworkError::InvalidConfig(
205 "rendezvous entry_ttl must be greater than zero".into(),
206 ));
207 }
208 }
209
210 for (index, alpn) in self.stream_protocols.iter().enumerate() {
211 if alpn.is_empty() {
212 return Err(NetworkError::InvalidConfig(
213 "stream protocol ALPN must not be empty".into(),
214 ));
215 }
216 if alpn.as_slice() == ALPN {
217 return Err(NetworkError::InvalidConfig(
218 "stream protocol ALPN must differ from the engine ALPN".into(),
219 ));
220 }
221 if self.stream_protocols[..index].contains(alpn) {
222 return Err(NetworkError::InvalidConfig(format!(
223 "duplicate stream protocol ALPN: {}",
224 String::from_utf8_lossy(alpn)
225 )));
226 }
227 }
228 for (index, alpn) in self.schema_independent_stream_protocols.iter().enumerate() {
229 if alpn.is_empty() {
230 return Err(NetworkError::InvalidConfig(
231 "schema-independent stream protocol ALPN must not be empty".into(),
232 ));
233 }
234 if alpn.as_slice() == ALPN {
235 return Err(NetworkError::InvalidConfig(
236 "schema-independent stream protocol ALPN must differ from the engine ALPN"
237 .into(),
238 ));
239 }
240 if self.schema_independent_stream_protocols[..index].contains(alpn)
241 || self.stream_protocols.contains(alpn)
242 {
243 return Err(NetworkError::InvalidConfig(format!(
244 "duplicate stream protocol ALPN: {}",
245 String::from_utf8_lossy(alpn)
246 )));
247 }
248 }
249
250 Ok(NetworkConfig {
251 data_dir,
252 network_id,
253 schema_id,
254 max_message_size,
255 request_timeout,
256 event_channel_capacity,
257 max_concurrent_streams_per_peer,
258 rendezvous: self.rendezvous,
259 stream_protocols: self.stream_protocols,
260 schema_independent_stream_protocols: self.schema_independent_stream_protocols,
261 })
262 }
263}
264
265#[cfg(test)]
266mod tests {
267 use super::*;
268
269 fn base_builder() -> NetworkConfigBuilder {
270 NetworkConfig::builder()
271 .data_dir("./some-dir")
272 .network_id(NetworkId::from_name("test-network"))
273 .schema_id(SchemaId::from_name("test-schema"))
274 }
275
276 #[test]
277 fn builder_applies_defaults() {
278 let config = base_builder().build().expect("valid config");
279 assert_eq!(config.max_message_size, DEFAULT_MAX_MESSAGE_SIZE);
280 assert_eq!(config.request_timeout, DEFAULT_REQUEST_TIMEOUT);
281 assert_eq!(
282 config.event_channel_capacity,
283 DEFAULT_EVENT_CHANNEL_CAPACITY
284 );
285 assert_eq!(
286 config.max_concurrent_streams_per_peer,
287 DEFAULT_MAX_CONCURRENT_STREAMS_PER_PEER
288 );
289 }
290
291 #[test]
292 fn builder_rejects_missing_required_fields() {
293 assert!(NetworkConfig::builder().build().is_err());
294 assert!(
295 NetworkConfig::builder()
296 .data_dir("./dir")
297 .network_id(NetworkId::from_name("n"))
298 .build()
299 .is_err()
300 );
301 }
302
303 #[test]
304 fn builder_rejects_invalid_values() {
305 assert!(base_builder().max_message_size(0).build().is_err());
306 assert!(
307 base_builder()
308 .request_timeout(Duration::ZERO)
309 .build()
310 .is_err()
311 );
312 assert!(base_builder().event_channel_capacity(0).build().is_err());
313 assert!(
314 base_builder()
315 .max_concurrent_streams_per_peer(0)
316 .build()
317 .is_err()
318 );
319 }
320
321 #[test]
322 fn rendezvous_is_disabled_by_default_and_validated_when_set() {
323 let config = base_builder().build().expect("valid config");
324 assert!(config.rendezvous.is_none());
325
326 let config = base_builder()
327 .rendezvous(RendezvousConfig::default())
328 .build()
329 .expect("valid config");
330 assert!(config.rendezvous.is_some());
331
332 let zero_interval = RendezvousConfig {
333 interval: Duration::ZERO,
334 ..RendezvousConfig::default()
335 };
336 assert!(base_builder().rendezvous(zero_interval).build().is_err());
337
338 let zero_ttl = RendezvousConfig {
339 entry_ttl: Duration::ZERO,
340 ..RendezvousConfig::default()
341 };
342 assert!(base_builder().rendezvous(zero_ttl).build().is_err());
343 }
344
345 #[test]
346 fn stream_protocols_are_validated() {
347 let config = base_builder().build().expect("valid config");
348 assert!(config.stream_protocols.is_empty());
349
350 let config = base_builder()
351 .stream_protocol("my-app/blob/1")
352 .stream_protocol("my-app/other/1")
353 .build()
354 .expect("valid config");
355 assert_eq!(config.stream_protocols.len(), 2);
356
357 assert!(base_builder().stream_protocol("").build().is_err());
358 assert!(base_builder().stream_protocol(ALPN).build().is_err());
359 assert!(
360 base_builder()
361 .stream_protocol("dup/1")
362 .stream_protocol("dup/1")
363 .build()
364 .is_err()
365 );
366 assert!(
367 base_builder()
368 .stream_protocol("dup/1")
369 .schema_independent_stream_protocol("dup/1")
370 .build()
371 .is_err()
372 );
373
374 let config = base_builder()
375 .schema_independent_stream_protocol("furumi/capabilities/1")
376 .build()
377 .expect("valid schema-independent stream protocol");
378 assert_eq!(
379 config.schema_independent_stream_protocols,
380 vec![b"furumi/capabilities/1".to_vec()]
381 );
382 }
383}