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 crate::codec::MAX_FRAME_SIZE;
22use std::cmp;
23
24/// Configuration for the multiplexer.
25#[derive(Debug, Clone)]
26pub struct MplexConfig {
27    /// Maximum number of simultaneously used substreams.
28    pub(crate) max_substreams: usize,
29    /// Maximum number of frames buffered per substream.
30    pub(crate) max_buffer_len: usize,
31    /// Behaviour when the buffer size limit is reached for a substream.
32    pub(crate) max_buffer_behaviour: MaxBufferBehaviour,
33    /// When sending data, split it into frames whose maximum size is this value
34    /// (max 1MByte, as per the Mplex spec).
35    pub(crate) split_send_size: usize,
36}
37
38impl MplexConfig {
39    /// Builds the default configuration.
40    pub fn new() -> MplexConfig {
41        Default::default()
42    }
43
44    /// Sets the maximum number of simultaneously used substreams.
45    ///
46    /// A substream is used as long as it has not been dropped,
47    /// even if it may already be closed or reset at the protocol
48    /// level (in which case it may still have buffered data that
49    /// can be read before the `StreamMuxer` API signals EOF).
50    ///
51    /// When the limit is reached, opening of outbound substreams
52    /// is delayed until another substream is dropped, whereas new
53    /// inbound substreams are immediately answered with a `Reset`.
54    /// If the number of inbound substreams that need to be reset
55    /// accumulates too quickly (judged by internal bounds), the
56    /// connection is closed with an error due to the misbehaved
57    /// remote.
58    pub fn set_max_num_streams(&mut self, max: usize) -> &mut Self {
59        self.max_substreams = max;
60        self
61    }
62
63    /// Sets the maximum number of frames buffered per substream.
64    ///
65    /// A limit is necessary in order to avoid DoS attacks.
66    pub fn set_max_buffer_size(&mut self, max: usize) -> &mut Self {
67        self.max_buffer_len = max;
68        self
69    }
70
71    /// Sets the behaviour when the maximum buffer size is reached
72    /// for a substream.
73    ///
74    /// See the documentation of [`MaxBufferBehaviour`].
75    pub fn set_max_buffer_behaviour(&mut self, behaviour: MaxBufferBehaviour) -> &mut Self {
76        self.max_buffer_behaviour = behaviour;
77        self
78    }
79
80    /// Sets the frame size used when sending data. Capped at 1Mbyte as per the
81    /// Mplex spec.
82    pub fn set_split_send_size(&mut self, size: usize) -> &mut Self {
83        let size = cmp::min(size, MAX_FRAME_SIZE);
84        self.split_send_size = size;
85        self
86    }
87}
88
89/// Behaviour when the maximum length of the buffer is reached.
90#[derive(Debug, Copy, Clone, PartialEq, Eq)]
91pub enum MaxBufferBehaviour {
92    /// Reset the substream whose frame buffer overflowed.
93    ///
94    /// > **Note**: If more than [`MplexConfig::set_max_buffer_size()`] frames
95    /// > are received in succession for a substream in the context of
96    /// > trying to read data from a different substream, the former substream
97    /// > may be reset before application code had a chance to read from the
98    /// > buffer. The max. buffer size needs to be sized appropriately when
99    /// > using this option to balance maximum resource usage and the
100    /// > probability of premature termination of a substream.
101    ResetStream,
102    /// No new message can be read from the underlying connection from any
103    /// substream as long as the buffer for a single substream is full,
104    /// i.e. application code is expected to read from the full buffer.
105    ///
106    /// > **Note**: To avoid blocking without making progress, application
107    /// > tasks should ensure that, when woken, always try to read (i.e.
108    /// > make progress) from every substream on which data is expected.
109    /// > This is imperative in general, as a woken task never knows for
110    /// > which substream it has been woken, but failure to do so with
111    /// > [`MaxBufferBehaviour::Block`] in particular may lead to stalled
112    /// > execution or spinning of a task without progress.
113    Block,
114}
115
116impl Default for MplexConfig {
117    fn default() -> MplexConfig {
118        MplexConfig {
119            max_substreams: 128,
120            max_buffer_len: 32,
121            max_buffer_behaviour: MaxBufferBehaviour::Block,
122            split_send_size: 8 * 1024,
123        }
124    }
125}