libp2p_mplex/
config.rs

1// Copyright 2018 Parity Technologies (UK) Ltd.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the "Software"),
5// to deal in the Software without restriction, including without limitation
6// the rights to use, copy, modify, merge, publish, distribute, sublicense,
7// and/or sell copies of the Software, and to permit persons to whom the
8// Software is furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19// DEALINGS IN THE SOFTWARE.
20
21use std::cmp;
22
23use crate::codec::MAX_FRAME_SIZE;
24
25pub(crate) const DEFAULT_MPLEX_PROTOCOL_NAME: &str = "/mplex/6.7.0";
26
27/// Configuration for the multiplexer.
28#[derive(Debug, Clone)]
29pub struct MplexConfig {
30    /// Maximum number of simultaneously used substreams.
31    pub(crate) max_substreams: usize,
32    /// Maximum number of frames buffered per substream.
33    pub(crate) max_buffer_len: usize,
34    /// Behaviour when the buffer size limit is reached for a substream.
35    pub(crate) max_buffer_behaviour: MaxBufferBehaviour,
36    /// When sending data, split it into frames whose maximum size is this value
37    /// (max 1MByte, as per the Mplex spec).
38    pub(crate) split_send_size: usize,
39    /// Protocol name, defaults to b"/mplex/6.7.0"
40    pub(crate) protocol_name: &'static str,
41}
42
43impl MplexConfig {
44    /// Builds the default configuration.
45    pub fn new() -> MplexConfig {
46        Default::default()
47    }
48
49    /// Sets the maximum number of simultaneously used substreams.
50    ///
51    /// A substream is used as long as it has not been dropped,
52    /// even if it may already be closed or reset at the protocol
53    /// level (in which case it may still have buffered data that
54    /// can be read before the `StreamMuxer` API signals EOF).
55    ///
56    /// When the limit is reached, opening of outbound substreams
57    /// is delayed until another substream is dropped, whereas new
58    /// inbound substreams are immediately answered with a `Reset`.
59    /// If the number of inbound substreams that need to be reset
60    /// accumulates too quickly (judged by internal bounds), the
61    /// connection is closed with an error due to the misbehaved
62    /// remote.
63    pub fn set_max_num_streams(&mut self, max: usize) -> &mut Self {
64        self.max_substreams = max;
65        self
66    }
67
68    /// Sets the maximum number of frames buffered per substream.
69    ///
70    /// A limit is necessary in order to avoid DoS attacks.
71    pub fn set_max_buffer_size(&mut self, max: usize) -> &mut Self {
72        self.max_buffer_len = max;
73        self
74    }
75
76    /// Sets the behaviour when the maximum buffer size is reached
77    /// for a substream.
78    ///
79    /// See the documentation of [`MaxBufferBehaviour`].
80    pub fn set_max_buffer_behaviour(&mut self, behaviour: MaxBufferBehaviour) -> &mut Self {
81        self.max_buffer_behaviour = behaviour;
82        self
83    }
84
85    /// Sets the frame size used when sending data. Capped at 1Mbyte as per the
86    /// Mplex spec.
87    pub fn set_split_send_size(&mut self, size: usize) -> &mut Self {
88        let size = cmp::min(size, MAX_FRAME_SIZE);
89        self.split_send_size = size;
90        self
91    }
92
93    /// Set the protocol name.
94    ///
95    /// ```rust
96    /// use libp2p_mplex::MplexConfig;
97    /// let mut muxer_config = MplexConfig::new();
98    /// muxer_config.set_protocol_name("/mplex/6.7.0");
99    /// ```
100    pub fn set_protocol_name(&mut self, protocol_name: &'static str) -> &mut Self {
101        self.protocol_name = protocol_name;
102        self
103    }
104}
105
106/// Behaviour when the maximum length of the buffer is reached.
107#[derive(Debug, Copy, Clone, PartialEq, Eq)]
108pub enum MaxBufferBehaviour {
109    /// Reset the substream whose frame buffer overflowed.
110    ///
111    /// > **Note**: If more than [`MplexConfig::set_max_buffer_size()`] frames
112    /// > are received in succession for a substream in the context of
113    /// > trying to read data from a different substream, the former substream
114    /// > may be reset before application code had a chance to read from the
115    /// > buffer. The max. buffer size needs to be sized appropriately when
116    /// > using this option to balance maximum resource usage and the
117    /// > probability of premature termination of a substream.
118    ResetStream,
119    /// No new message can be read from the underlying connection from any
120    /// substream as long as the buffer for a single substream is full,
121    /// i.e. application code is expected to read from the full buffer.
122    ///
123    /// > **Note**: To avoid blocking without making progress, application
124    /// > tasks should ensure that, when woken, always try to read (i.e.
125    /// > make progress) from every substream on which data is expected.
126    /// > This is imperative in general, as a woken task never knows for
127    /// > which substream it has been woken, but failure to do so with
128    /// > [`MaxBufferBehaviour::Block`] in particular may lead to stalled
129    /// > execution or spinning of a task without progress.
130    Block,
131}
132
133impl Default for MplexConfig {
134    fn default() -> MplexConfig {
135        MplexConfig {
136            max_substreams: 128,
137            max_buffer_len: 32,
138            max_buffer_behaviour: MaxBufferBehaviour::Block,
139            split_send_size: 8 * 1024,
140            protocol_name: DEFAULT_MPLEX_PROTOCOL_NAME,
141        }
142    }
143}