Skip to main content

hopr_transport_mixer/
config.rs

1use std::time::Duration;
2
3pub const HOPR_MIXER_MINIMUM_DEFAULT_DELAY_IN_MS: u64 = 0;
4pub const HOPR_MIXER_DEFAULT_DELAY_RANGE_IN_MS: u64 = 20;
5pub const HOPR_MIXER_DELAY_METRIC_WINDOW: u64 = 100;
6pub const HOPR_MIXER_CAPACITY: usize = 20_000;
7
8#[cfg(feature = "serde")]
9fn default_metric_delay_window() -> u64 {
10    HOPR_MIXER_DELAY_METRIC_WINDOW
11}
12
13/// Mixer configuration.
14#[derive(Debug, Clone, Copy, Eq, PartialEq, smart_default::SmartDefault)]
15#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
16pub struct MixerConfig {
17    /// The minimum delay introduced during mixing.
18    #[default(Duration::from_millis(HOPR_MIXER_MINIMUM_DEFAULT_DELAY_IN_MS))]
19    #[cfg_attr(feature = "serde", serde(with = "humantime_serde"))]
20    pub min_delay: Duration,
21    /// The range from the minimum delay to the maximum possible delay.
22    #[default(Duration::from_millis(HOPR_MIXER_DEFAULT_DELAY_RANGE_IN_MS))]
23    #[cfg_attr(feature = "serde", serde(with = "humantime_serde"))]
24    pub delay_range: Duration,
25    /// The capacity of the preallocated mixer buffer.
26    ///
27    /// It is possible to insert more items past the capacity, triggering
28    /// a possible buffer reallocation.
29    #[default(HOPR_MIXER_CAPACITY)]
30    pub capacity: usize,
31    #[default(HOPR_MIXER_DELAY_METRIC_WINDOW)]
32    #[cfg_attr(feature = "serde", serde(skip_serializing, default = "default_metric_delay_window"))]
33    pub metric_delay_window: u64,
34}
35
36impl MixerConfig {
37    /// Get a random delay duration from the specified minimum and maximum delay available
38    /// inside the configuration.
39    pub fn random_delay(&self) -> Duration {
40        let max_delay = self.min_delay.saturating_add(self.delay_range);
41
42        let random_delay = if max_delay.as_millis() == 0 {
43            max_delay.as_millis() as u64
44        } else {
45            hopr_types::crypto_random::random_integer(
46                self.min_delay.as_millis() as u64,
47                Some(max_delay.as_millis() as u64),
48            )
49        };
50
51        Duration::from_millis(random_delay)
52    }
53}