Skip to main content

federation_net/
config.rs

1//! Engine configuration.
2
3use std::path::PathBuf;
4use std::time::Duration;
5
6use crate::error::{NetworkError, Result};
7use crate::protocol::{ALPN, NetworkId, SchemaId};
8use crate::rendezvous::RendezvousConfig;
9
10/// Default maximum size of an encoded domain message (256 KiB).
11pub const DEFAULT_MAX_MESSAGE_SIZE: usize = 256 * 1024;
12/// Default timeout applied to handshakes and message round-trips.
13pub const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
14/// Default capacity of the event channel.
15pub const DEFAULT_EVENT_CHANNEL_CAPACITY: usize = 1024;
16/// Default limit of concurrently processed streams per peer.
17pub const DEFAULT_MAX_CONCURRENT_STREAMS_PER_PEER: usize = 64;
18
19/// Configuration for a [`crate::NetworkEngine`].
20///
21/// Use [`NetworkConfig::builder`] to construct a validated instance.
22#[derive(Debug, Clone)]
23pub struct NetworkConfig {
24    /// Directory where the persistent peer identity is stored.
25    pub data_dir: PathBuf,
26    /// Identifier of the network this peer participates in.
27    pub network_id: NetworkId,
28    /// Identifier of the domain message schema.
29    pub schema_id: SchemaId,
30    /// Maximum size in bytes of a single encoded domain message.
31    pub max_message_size: usize,
32    /// Timeout applied to handshakes and message round-trips.
33    pub request_timeout: Duration,
34    /// Capacity of the bounded event channel.
35    pub event_channel_capacity: usize,
36    /// Maximum number of concurrently processed streams per peer.
37    pub max_concurrent_streams_per_peer: usize,
38    /// Automatic peer discovery over the mainline DHT; `None` disables it and
39    /// peers are connected via tickets only.
40    pub rendezvous: Option<RendezvousConfig>,
41    /// Auxiliary ALPN protocols on which this peer accepts raw byte streams
42    /// (see [`crate::NetworkEngine::stream_acceptor`]).
43    pub stream_protocols: Vec<Vec<u8>>,
44    /// Auxiliary stream protocols whose handshake is independent of the
45    /// application schema. Intended for compatibility/capability discovery.
46    pub schema_independent_stream_protocols: Vec<Vec<u8>>,
47}
48
49impl NetworkConfig {
50    /// Returns a new [`NetworkConfigBuilder`].
51    pub fn builder() -> NetworkConfigBuilder {
52        NetworkConfigBuilder::default()
53    }
54}
55
56/// Builder for [`NetworkConfig`].
57///
58/// `data_dir`, `network_id` and `schema_id` are required; everything else has
59/// sensible defaults.
60#[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    /// Sets the directory where the persistent peer identity is stored.
76    pub fn data_dir(mut self, dir: impl Into<PathBuf>) -> Self {
77        self.data_dir = Some(dir.into());
78        self
79    }
80
81    /// Sets the network identifier.
82    pub fn network_id(mut self, network_id: NetworkId) -> Self {
83        self.network_id = Some(network_id);
84        self
85    }
86
87    /// Sets the schema identifier.
88    pub fn schema_id(mut self, schema_id: SchemaId) -> Self {
89        self.schema_id = Some(schema_id);
90        self
91    }
92
93    /// Sets the maximum size in bytes of a single encoded domain message.
94    pub fn max_message_size(mut self, size: usize) -> Self {
95        self.max_message_size = Some(size);
96        self
97    }
98
99    /// Sets the timeout applied to handshakes and message round-trips.
100    pub fn request_timeout(mut self, timeout: Duration) -> Self {
101        self.request_timeout = Some(timeout);
102        self
103    }
104
105    /// Sets the capacity of the bounded event channel.
106    pub fn event_channel_capacity(mut self, capacity: usize) -> Self {
107        self.event_channel_capacity = Some(capacity);
108        self
109    }
110
111    /// Sets the maximum number of concurrently processed streams per peer.
112    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    /// Enables automatic peer discovery over the mainline DHT.
118    pub fn rendezvous(mut self, rendezvous: RendezvousConfig) -> Self {
119        self.rendezvous = Some(rendezvous);
120        self
121    }
122
123    /// Declares an auxiliary ALPN protocol on which this peer accepts raw
124    /// byte streams (see [`crate::NetworkEngine::stream_acceptor`]). May be
125    /// called multiple times, once per protocol.
126    pub fn stream_protocol(mut self, alpn: impl Into<Vec<u8>>) -> Self {
127        self.stream_protocols.push(alpn.into());
128        self
129    }
130
131    /// Declares an auxiliary ALPN protocol that validates the network and
132    /// federation transport version, but deliberately does not require the
133    /// application schema id to match.
134    ///
135    /// This is suitable for bounded, self-versioned capability discovery
136    /// protocols that must remain reachable across schema upgrades.
137    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    /// Validates the configuration and builds a [`NetworkConfig`].
143    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}