Skip to main content

iroh_live_node/
preset.rs

1//! The endpoint preset for MoQ and its congestion controllers.
2//!
3//! [`MoqPreset`] is iroh's N0 preset with this crate's crypto provider and a
4//! QUIC transport tuned for MoQ.
5//! [`Congestion`] names the controllers to choose from.
6
7use std::{fmt, str::FromStr, sync::Arc};
8
9#[cfg(not(target_family = "wasm"))]
10use iroh::address_lookup::DnsAddressLookup;
11use iroh::{
12    address_lookup::{PkarrPublisher, PkarrResolver},
13    endpoint::{Builder, QuicTransportConfig, default_relay_mode, presets},
14};
15use n0_error::stack_error;
16use noq_proto::congestion::{Bbr3Config, ControllerFactory, CubicConfig, NewRenoConfig};
17
18/// The prefix of the qlog file names [`Congestion::transport_config`] writes.
19#[cfg(feature = "qlog")]
20const QLOG_PREFIX: &str = "iroh-live";
21
22/// iroh's N0 preset with BBR3 congestion control.
23///
24/// It sets what iroh's `presets::N0` sets: n0's pkarr publisher and resolver,
25/// its DNS address lookup and the default iroh relays. The crypto provider is
26/// [`crypto_provider`](crate::crypto_provider), the backend this crate's
27/// features select, where iroh's preset would pick one by iroh's own `tls-*`
28/// features.
29///
30/// Works anywhere iroh takes a preset:
31///
32/// ```no_run
33/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
34/// let endpoint = iroh::Endpoint::bind(iroh_live_node::MoqPreset).await?;
35/// # Ok(())
36/// # }
37/// ```
38///
39/// moq-net sends every subscriber the publisher's send-rate estimate,
40/// `cwnd / rtt`. A live publisher sends less than the link could take, and
41/// under CUBIC, iroh's default, its window grows until something is lost, so
42/// the estimate shows room to spare on a full link. BBR3 sizes the window from
43/// the delivery rate it measures, so the estimate tracks the link.
44///
45/// With the `qlog` feature, the endpoint writes a qlog trace of each
46/// connection into `QLOGDIR`, see [`Congestion::transport_config`].
47#[derive(Debug, Clone, Copy, Default)]
48pub struct MoqPreset;
49
50impl presets::Preset for MoqPreset {
51    fn apply(self, builder: Builder) -> Builder {
52        let mut builder = crate::MinimalPreset
53            .apply(builder)
54            .address_lookup(PkarrPublisher::n0_dns())
55            .address_lookup(PkarrResolver::n0_dns());
56        #[cfg(not(target_family = "wasm"))]
57        {
58            builder = builder.address_lookup(DnsAddressLookup::n0_dns());
59        }
60        builder
61            .relay_mode(default_relay_mode())
62            .transport_config(Congestion::default().transport_config())
63    }
64}
65
66/// A QUIC congestion controller.
67///
68/// [`MoqPreset`] binds an endpoint with [`Bbr3`](Self::Bbr3), which keeps
69/// moq-net's send-rate estimate on the link. The others are there to compare
70/// against. An endpoint uses one controller for every connection, and
71/// one dial can take another by setting
72/// [`transport_config`](Self::transport_config) in
73/// [`ConnectOptions::quic`](crate::ConnectOptions::quic).
74///
75/// It parses from its name in any case, and displays as that name.
76///
77/// ```
78/// use iroh_live_node::Congestion;
79///
80/// let congestion: Congestion = "cubic".parse().expect("a known controller");
81/// assert_eq!(congestion, Congestion::Cubic);
82/// assert_eq!(congestion.to_string(), "CUBIC");
83/// ```
84#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
85pub enum Congestion {
86    /// BBR3, which paces to the delivery rate it measures.
87    #[default]
88    Bbr3,
89    /// CUBIC, iroh's own default, which grows its window until a packet is lost.
90    Cubic,
91    /// NewReno, the classic loss-based controller.
92    NewReno,
93}
94
95impl Congestion {
96    /// Every controller, BBR3 first.
97    pub const ALL: [Self; 3] = [Self::Bbr3, Self::Cubic, Self::NewReno];
98
99    /// Returns the name it displays as and parses from.
100    #[must_use]
101    pub fn name(self) -> &'static str {
102        match self {
103            Self::Bbr3 => "BBR3",
104            Self::Cubic => "CUBIC",
105            Self::NewReno => "NewReno",
106        }
107    }
108
109    /// Returns a QUIC transport config with this controller and iroh's other defaults.
110    ///
111    /// Pass it to an endpoint builder's `transport_config`, or to one dial in
112    /// `iroh::endpoint::ConnectOptions`.
113    ///
114    /// With the `qlog` feature, the config writes a qlog trace of every
115    /// connection into the directory the `QLOGDIR` environment variable names.
116    /// This call reads `QLOGDIR` and creates the directory, so setting it
117    /// afterwards has no effect, and without it nothing is written.
118    ///
119    /// Each side writes one file per connection, named
120    /// `iroh-live-<unix ms>-<connection id>-<client|server>.qlog`. The
121    /// connection id is the client's first destination id, so both ends of a
122    /// connection name their file with the same id.
123    ///
124    /// The traces log every packet, so a file grows about as large as the
125    /// data its connection sends, and nothing rotates or caps them. They
126    /// also hold the peers' IP addresses. `QLOGDIR` is a shared name that
127    /// quiche, ngtcp2 and curl read too, so set it only while you diagnose.
128    #[must_use]
129    pub fn transport_config(self) -> QuicTransportConfig {
130        let builder = QuicTransportConfig::builder().congestion_controller_factory(self.factory());
131        #[cfg(feature = "qlog")]
132        let builder = builder.qlog_from_env(QLOG_PREFIX);
133        builder.build()
134    }
135
136    /// Returns the factory that builds this controller for each path.
137    fn factory(self) -> Arc<dyn ControllerFactory + Send + Sync + 'static> {
138        match self {
139            Self::Bbr3 => Arc::new(Bbr3Config::default()),
140            Self::Cubic => Arc::new(CubicConfig::default()),
141            Self::NewReno => Arc::new(NewRenoConfig::default()),
142        }
143    }
144}
145
146impl fmt::Display for Congestion {
147    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148        f.write_str(self.name())
149    }
150}
151
152impl FromStr for Congestion {
153    type Err = UnknownCongestion;
154
155    fn from_str(name: &str) -> Result<Self, Self::Err> {
156        Self::ALL
157            .into_iter()
158            .find(|congestion| congestion.name().eq_ignore_ascii_case(name))
159            .ok_or_else(|| UnknownCongestion(name.to_string()))
160    }
161}
162
163/// An error returned when a name is not that of a [`Congestion`] controller.
164#[stack_error(derive)]
165#[derive(Clone, PartialEq, Eq)]
166#[error("unknown congestion controller {_0:?}: expected BBR3, CUBIC, or NewReno (any case)")]
167pub struct UnknownCongestion(String);
168
169#[cfg(test)]
170mod tests {
171    use super::*;
172
173    #[test]
174    fn every_controller_parses_from_its_name() {
175        for congestion in Congestion::ALL {
176            assert_eq!(congestion.to_string().parse(), Ok(congestion));
177            assert_eq!(congestion.name().to_lowercase().parse(), Ok(congestion));
178        }
179        assert!("vegas".parse::<Congestion>().is_err());
180    }
181}