ant_quic/config/
transport.rs

1use std::{fmt, sync::Arc};
2
3use crate::{Duration, INITIAL_MTU, MAX_UDP_PAYLOAD, VarInt, VarIntBoundsExceeded, congestion};
4
5/// Parameters governing the core QUIC state machine
6///
7/// Default values should be suitable for most internet applications. Applications protocols which
8/// forbid remotely-initiated streams should set `max_concurrent_bidi_streams` and
9/// `max_concurrent_uni_streams` to zero.
10///
11/// In some cases, performance or resource requirements can be improved by tuning these values to
12/// suit a particular application and/or network connection. In particular, data window sizes can be
13/// tuned for a particular expected round trip time, link capacity, and memory availability. Tuning
14/// for higher bandwidths and latencies increases worst-case memory consumption, but does not impair
15/// performance at lower bandwidths and latencies. The default configuration is tuned for a 100Mbps
16/// link with a 100ms round trip time.
17#[derive(Clone)]
18pub struct TransportConfig {
19    pub(crate) max_concurrent_bidi_streams: VarInt,
20    pub(crate) max_concurrent_uni_streams: VarInt,
21    pub(crate) max_idle_timeout: Option<VarInt>,
22    pub(crate) stream_receive_window: VarInt,
23    pub(crate) receive_window: VarInt,
24    pub(crate) send_window: u64,
25    pub(crate) send_fairness: bool,
26
27    pub(crate) packet_threshold: u32,
28    pub(crate) time_threshold: f32,
29    pub(crate) initial_rtt: Duration,
30    pub(crate) initial_mtu: u16,
31    pub(crate) min_mtu: u16,
32    pub(crate) mtu_discovery_config: Option<MtuDiscoveryConfig>,
33    pub(crate) pad_to_mtu: bool,
34    pub(crate) ack_frequency_config: Option<AckFrequencyConfig>,
35
36    pub(crate) persistent_congestion_threshold: u32,
37    pub(crate) keep_alive_interval: Option<Duration>,
38    pub(crate) crypto_buffer_size: usize,
39    pub(crate) allow_spin: bool,
40    pub(crate) datagram_receive_buffer_size: Option<usize>,
41    pub(crate) datagram_send_buffer_size: usize,
42    #[cfg(test)]
43    pub(crate) deterministic_packet_numbers: bool,
44
45    pub(crate) congestion_controller_factory: Arc<dyn congestion::ControllerFactory + Send + Sync>,
46
47    pub(crate) enable_segmentation_offload: bool,
48    
49    /// NAT traversal configuration
50    pub(crate) nat_traversal_config: Option<crate::transport_parameters::NatTraversalConfig>,
51}
52
53impl TransportConfig {
54    /// Maximum number of incoming bidirectional streams that may be open concurrently
55    ///
56    /// Must be nonzero for the peer to open any bidirectional streams.
57    ///
58    /// Worst-case memory use is directly proportional to `max_concurrent_bidi_streams *
59    /// stream_receive_window`, with an upper bound proportional to `receive_window`.
60    pub fn max_concurrent_bidi_streams(&mut self, value: VarInt) -> &mut Self {
61        self.max_concurrent_bidi_streams = value;
62        self
63    }
64
65    /// Variant of `max_concurrent_bidi_streams` affecting unidirectional streams
66    pub fn max_concurrent_uni_streams(&mut self, value: VarInt) -> &mut Self {
67        self.max_concurrent_uni_streams = value;
68        self
69    }
70
71    /// Maximum duration of inactivity to accept before timing out the connection.
72    ///
73    /// The true idle timeout is the minimum of this and the peer's own max idle timeout. `None`
74    /// represents an infinite timeout. Defaults to 30 seconds.
75    ///
76    /// **WARNING**: If a peer or its network path malfunctions or acts maliciously, an infinite
77    /// idle timeout can result in permanently hung futures!
78    ///
79    /// ```
80    /// # use std::{convert::TryInto, time::Duration};
81    /// # use ant_quic::{TransportConfig, VarInt, VarIntBoundsExceeded};
82    /// # fn main() -> Result<(), VarIntBoundsExceeded> {
83    /// let mut config = TransportConfig::default();
84    ///
85    /// // Set the idle timeout as `VarInt`-encoded milliseconds
86    /// config.max_idle_timeout(Some(VarInt::from_u32(10_000).into()));
87    ///
88    /// // Set the idle timeout as a `Duration`
89    /// config.max_idle_timeout(Some(Duration::from_secs(10).try_into()?));
90    /// # Ok(())
91    /// # }
92    /// ```
93    pub fn max_idle_timeout(&mut self, value: Option<IdleTimeout>) -> &mut Self {
94        self.max_idle_timeout = value.map(|t| t.0);
95        self
96    }
97
98    /// Maximum number of bytes the peer may transmit without acknowledgement on any one stream
99    /// before becoming blocked.
100    ///
101    /// This should be set to at least the expected connection latency multiplied by the maximum
102    /// desired throughput. Setting this smaller than `receive_window` helps ensure that a single
103    /// stream doesn't monopolize receive buffers, which may otherwise occur if the application
104    /// chooses not to read from a large stream for a time while still requiring data on other
105    /// streams.
106    pub fn stream_receive_window(&mut self, value: VarInt) -> &mut Self {
107        self.stream_receive_window = value;
108        self
109    }
110
111    /// Maximum number of bytes the peer may transmit across all streams of a connection before
112    /// becoming blocked.
113    ///
114    /// This should be set to at least the expected connection latency multiplied by the maximum
115    /// desired throughput. Larger values can be useful to allow maximum throughput within a
116    /// stream while another is blocked.
117    pub fn receive_window(&mut self, value: VarInt) -> &mut Self {
118        self.receive_window = value;
119        self
120    }
121
122    /// Maximum number of bytes to transmit to a peer without acknowledgment
123    ///
124    /// Provides an upper bound on memory when communicating with peers that issue large amounts of
125    /// flow control credit. Endpoints that wish to handle large numbers of connections robustly
126    /// should take care to set this low enough to guarantee memory exhaustion does not occur if
127    /// every connection uses the entire window.
128    pub fn send_window(&mut self, value: u64) -> &mut Self {
129        self.send_window = value;
130        self
131    }
132
133    /// Whether to implement fair queuing for send streams having the same priority.
134    ///
135    /// When enabled, connections schedule data from outgoing streams having the same priority in a
136    /// round-robin fashion. When disabled, streams are scheduled in the order they are written to.
137    ///
138    /// Note that this only affects streams with the same priority. Higher priority streams always
139    /// take precedence over lower priority streams.
140    ///
141    /// Disabling fairness can reduce fragmentation and protocol overhead for workloads that use
142    /// many small streams.
143    pub fn send_fairness(&mut self, value: bool) -> &mut Self {
144        self.send_fairness = value;
145        self
146    }
147
148    /// Maximum reordering in packet number space before FACK style loss detection considers a
149    /// packet lost. Should not be less than 3, per RFC5681.
150    pub fn packet_threshold(&mut self, value: u32) -> &mut Self {
151        self.packet_threshold = value;
152        self
153    }
154
155    /// Maximum reordering in time space before time based loss detection considers a packet lost,
156    /// as a factor of RTT
157    pub fn time_threshold(&mut self, value: f32) -> &mut Self {
158        self.time_threshold = value;
159        self
160    }
161
162    /// The RTT used before an RTT sample is taken
163    pub fn initial_rtt(&mut self, value: Duration) -> &mut Self {
164        self.initial_rtt = value;
165        self
166    }
167
168    /// The initial value to be used as the maximum UDP payload size before running MTU discovery
169    /// (see [`TransportConfig::mtu_discovery_config`]).
170    ///
171    /// Must be at least 1200, which is the default, and known to be safe for typical internet
172    /// applications. Larger values are more efficient, but increase the risk of packet loss due to
173    /// exceeding the network path's IP MTU. If the provided value is higher than what the network
174    /// path actually supports, packet loss will eventually trigger black hole detection and bring
175    /// it down to [`TransportConfig::min_mtu`].
176    pub fn initial_mtu(&mut self, value: u16) -> &mut Self {
177        self.initial_mtu = value.max(INITIAL_MTU);
178        self
179    }
180
181    pub(crate) fn get_initial_mtu(&self) -> u16 {
182        self.initial_mtu.max(self.min_mtu)
183    }
184
185    /// The maximum UDP payload size guaranteed to be supported by the network.
186    ///
187    /// Must be at least 1200, which is the default, and lower than or equal to
188    /// [`TransportConfig::initial_mtu`].
189    ///
190    /// Real-world MTUs can vary according to ISP, VPN, and properties of intermediate network links
191    /// outside of either endpoint's control. Extreme care should be used when raising this value
192    /// outside of private networks where these factors are fully controlled. If the provided value
193    /// is higher than what the network path actually supports, the result will be unpredictable and
194    /// catastrophic packet loss, without a possibility of repair. Prefer
195    /// [`TransportConfig::initial_mtu`] together with
196    /// [`TransportConfig::mtu_discovery_config`] to set a maximum UDP payload size that robustly
197    /// adapts to the network.
198    pub fn min_mtu(&mut self, value: u16) -> &mut Self {
199        self.min_mtu = value.max(INITIAL_MTU);
200        self
201    }
202
203    /// Specifies the MTU discovery config (see [`MtuDiscoveryConfig`] for details).
204    ///
205    /// Enabled by default.
206    pub fn mtu_discovery_config(&mut self, value: Option<MtuDiscoveryConfig>) -> &mut Self {
207        self.mtu_discovery_config = value;
208        self
209    }
210
211    /// Pad UDP datagrams carrying application data to current maximum UDP payload size
212    ///
213    /// Disabled by default. UDP datagrams containing loss probes are exempt from padding.
214    ///
215    /// Enabling this helps mitigate traffic analysis by network observers, but it increases
216    /// bandwidth usage. Without this mitigation precise plain text size of application datagrams as
217    /// well as the total size of stream write bursts can be inferred by observers under certain
218    /// conditions. This analysis requires either an uncongested connection or application datagrams
219    /// too large to be coalesced.
220    pub fn pad_to_mtu(&mut self, value: bool) -> &mut Self {
221        self.pad_to_mtu = value;
222        self
223    }
224
225    /// Specifies the ACK frequency config (see [`AckFrequencyConfig`] for details)
226    ///
227    /// The provided configuration will be ignored if the peer does not support the acknowledgement
228    /// frequency QUIC extension.
229    ///
230    /// Defaults to `None`, which disables controlling the peer's acknowledgement frequency. Even
231    /// if set to `None`, the local side still supports the acknowledgement frequency QUIC
232    /// extension and may use it in other ways.
233    pub fn ack_frequency_config(&mut self, value: Option<AckFrequencyConfig>) -> &mut Self {
234        self.ack_frequency_config = value;
235        self
236    }
237
238    /// Number of consecutive PTOs after which network is considered to be experiencing persistent congestion.
239    pub fn persistent_congestion_threshold(&mut self, value: u32) -> &mut Self {
240        self.persistent_congestion_threshold = value;
241        self
242    }
243
244    /// Period of inactivity before sending a keep-alive packet
245    ///
246    /// Keep-alive packets prevent an inactive but otherwise healthy connection from timing out.
247    ///
248    /// `None` to disable, which is the default. Only one side of any given connection needs keep-alive
249    /// enabled for the connection to be preserved. Must be set lower than the idle_timeout of both
250    /// peers to be effective.
251    pub fn keep_alive_interval(&mut self, value: Option<Duration>) -> &mut Self {
252        self.keep_alive_interval = value;
253        self
254    }
255
256    /// Maximum quantity of out-of-order crypto layer data to buffer
257    pub fn crypto_buffer_size(&mut self, value: usize) -> &mut Self {
258        self.crypto_buffer_size = value;
259        self
260    }
261
262    /// Whether the implementation is permitted to set the spin bit on this connection
263    ///
264    /// This allows passive observers to easily judge the round trip time of a connection, which can
265    /// be useful for network administration but sacrifices a small amount of privacy.
266    pub fn allow_spin(&mut self, value: bool) -> &mut Self {
267        self.allow_spin = value;
268        self
269    }
270
271    /// Maximum number of incoming application datagram bytes to buffer, or None to disable
272    /// incoming datagrams
273    ///
274    /// The peer is forbidden to send single datagrams larger than this size. If the aggregate size
275    /// of all datagrams that have been received from the peer but not consumed by the application
276    /// exceeds this value, old datagrams are dropped until it is no longer exceeded.
277    pub fn datagram_receive_buffer_size(&mut self, value: Option<usize>) -> &mut Self {
278        self.datagram_receive_buffer_size = value;
279        self
280    }
281
282    /// Maximum number of outgoing application datagram bytes to buffer
283    ///
284    /// While datagrams are sent ASAP, it is possible for an application to generate data faster
285    /// than the link, or even the underlying hardware, can transmit them. This limits the amount of
286    /// memory that may be consumed in that case. When the send buffer is full and a new datagram is
287    /// sent, older datagrams are dropped until sufficient space is available.
288    pub fn datagram_send_buffer_size(&mut self, value: usize) -> &mut Self {
289        self.datagram_send_buffer_size = value;
290        self
291    }
292
293    /// Whether to force every packet number to be used
294    ///
295    /// By default, packet numbers are occasionally skipped to ensure peers aren't ACKing packets
296    /// before they see them.
297    #[cfg(test)]
298    pub(crate) fn deterministic_packet_numbers(&mut self, enabled: bool) -> &mut Self {
299        self.deterministic_packet_numbers = enabled;
300        self
301    }
302
303    /// How to construct new `congestion::Controller`s
304    ///
305    /// Typically the refcounted configuration of a `congestion::Controller`,
306    /// e.g. a `congestion::NewRenoConfig`.
307    ///
308    /// # Example
309    /// ```
310    /// # use std::sync::Arc;
311    /// use ant_quic::config::TransportConfig;
312    /// 
313    /// let mut config = TransportConfig::default();
314    /// // The default uses CubicConfig, but custom implementations can be provided
315    /// // by implementing the congestion::ControllerFactory trait
316    /// ```
317    pub fn congestion_controller_factory(
318        &mut self,
319        factory: Arc<dyn congestion::ControllerFactory + Send + Sync + 'static>,
320    ) -> &mut Self {
321        self.congestion_controller_factory = factory;
322        self
323    }
324
325    /// Whether to use "Generic Segmentation Offload" to accelerate transmits, when supported by the
326    /// environment
327    ///
328    /// Defaults to `true`.
329    ///
330    /// GSO dramatically reduces CPU consumption when sending large numbers of packets with the same
331    /// headers, such as when transmitting bulk data on a connection. However, it is not supported
332    /// by all network interface drivers or packet inspection tools. `quinn-udp` will attempt to
333    /// disable GSO automatically when unavailable, but this can lead to spurious packet loss at
334    /// startup, temporarily degrading performance.
335    pub fn enable_segmentation_offload(&mut self, enabled: bool) -> &mut Self {
336        self.enable_segmentation_offload = enabled;
337        self
338    }
339
340    /// Configure NAT traversal capabilities for this connection
341    ///
342    /// When enabled, this connection will support QUIC NAT traversal extensions including:
343    /// - Address candidate advertisement and validation
344    /// - Coordinated hole punching through bootstrap nodes
345    /// - Multi-path connectivity testing
346    /// - Automatic path migration for NAT rebinding
347    ///
348    /// This is required for P2P connections through NATs in Autonomi networks.
349    /// Pass `None` to disable NAT traversal or use the high-level NAT traversal API
350    /// to create appropriate configurations.
351    pub fn nat_traversal_config(&mut self, config: Option<crate::transport_parameters::NatTraversalConfig>) -> &mut Self {
352        self.nat_traversal_config = config;
353        self
354    }
355    
356    /// Enable NAT traversal with default client configuration
357    ///
358    /// This is a convenience method that enables NAT traversal with sensible defaults
359    /// for a client endpoint. Use `nat_traversal_config()` for more control.
360    pub fn enable_nat_traversal(&mut self, enabled: bool) -> &mut Self {
361        if enabled {
362            use crate::transport_parameters::{NatTraversalConfig, NatTraversalRole};
363            self.nat_traversal_config = Some(NatTraversalConfig {
364                role: NatTraversalRole::Client,
365                max_candidates: VarInt::from_u32(10),
366                coordination_timeout: VarInt::from_u32(5000), // 5 seconds
367                max_concurrent_attempts: VarInt::from_u32(3),
368                peer_id: None, // Will be set later when peer ID is determined
369            });
370        } else {
371            self.nat_traversal_config = None;
372        }
373        self
374    }
375}
376
377impl Default for TransportConfig {
378    fn default() -> Self {
379        const EXPECTED_RTT: u32 = 100; // ms
380        const MAX_STREAM_BANDWIDTH: u32 = 12500 * 1000; // bytes/s
381        // Window size needed to avoid pipeline
382        // stalls
383        const STREAM_RWND: u32 = MAX_STREAM_BANDWIDTH / 1000 * EXPECTED_RTT;
384
385        Self {
386            max_concurrent_bidi_streams: 100u32.into(),
387            max_concurrent_uni_streams: 100u32.into(),
388            // 30 second default recommended by RFC 9308 ยง 3.2
389            max_idle_timeout: Some(VarInt(30_000)),
390            stream_receive_window: STREAM_RWND.into(),
391            receive_window: VarInt::MAX,
392            send_window: (8 * STREAM_RWND).into(),
393            send_fairness: true,
394
395            packet_threshold: 3,
396            time_threshold: 9.0 / 8.0,
397            initial_rtt: Duration::from_millis(333), // per spec, intentionally distinct from EXPECTED_RTT
398            initial_mtu: INITIAL_MTU,
399            min_mtu: INITIAL_MTU,
400            mtu_discovery_config: Some(MtuDiscoveryConfig::default()),
401            pad_to_mtu: false,
402            ack_frequency_config: None,
403
404            persistent_congestion_threshold: 3,
405            keep_alive_interval: None,
406            crypto_buffer_size: 16 * 1024,
407            allow_spin: true,
408            datagram_receive_buffer_size: Some(STREAM_RWND as usize),
409            datagram_send_buffer_size: 1024 * 1024,
410            #[cfg(test)]
411            deterministic_packet_numbers: false,
412
413            congestion_controller_factory: Arc::new(congestion::CubicConfig::default()),
414
415            enable_segmentation_offload: true,
416            nat_traversal_config: None,
417        }
418    }
419}
420
421impl fmt::Debug for TransportConfig {
422    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
423        let Self {
424            max_concurrent_bidi_streams,
425            max_concurrent_uni_streams,
426            max_idle_timeout,
427            stream_receive_window,
428            receive_window,
429            send_window,
430            send_fairness,
431            packet_threshold,
432            time_threshold,
433            initial_rtt,
434            initial_mtu,
435            min_mtu,
436            mtu_discovery_config,
437            pad_to_mtu,
438            ack_frequency_config,
439            persistent_congestion_threshold,
440            keep_alive_interval,
441            crypto_buffer_size,
442            allow_spin,
443            datagram_receive_buffer_size,
444            datagram_send_buffer_size,
445            #[cfg(test)]
446                deterministic_packet_numbers: _,
447            congestion_controller_factory: _,
448            enable_segmentation_offload,
449            nat_traversal_config,
450        } = self;
451        fmt.debug_struct("TransportConfig")
452            .field("max_concurrent_bidi_streams", max_concurrent_bidi_streams)
453            .field("max_concurrent_uni_streams", max_concurrent_uni_streams)
454            .field("max_idle_timeout", max_idle_timeout)
455            .field("stream_receive_window", stream_receive_window)
456            .field("receive_window", receive_window)
457            .field("send_window", send_window)
458            .field("send_fairness", send_fairness)
459            .field("packet_threshold", packet_threshold)
460            .field("time_threshold", time_threshold)
461            .field("initial_rtt", initial_rtt)
462            .field("initial_mtu", initial_mtu)
463            .field("min_mtu", min_mtu)
464            .field("mtu_discovery_config", mtu_discovery_config)
465            .field("pad_to_mtu", pad_to_mtu)
466            .field("ack_frequency_config", ack_frequency_config)
467            .field(
468                "persistent_congestion_threshold",
469                persistent_congestion_threshold,
470            )
471            .field("keep_alive_interval", keep_alive_interval)
472            .field("crypto_buffer_size", crypto_buffer_size)
473            .field("allow_spin", allow_spin)
474            .field("datagram_receive_buffer_size", datagram_receive_buffer_size)
475            .field("datagram_send_buffer_size", datagram_send_buffer_size)
476            // congestion_controller_factory not debug
477            .field("enable_segmentation_offload", enable_segmentation_offload)
478            .field("nat_traversal_config", nat_traversal_config)
479            .finish_non_exhaustive()
480    }
481}
482
483/// Parameters for controlling the peer's acknowledgement frequency
484///
485/// The parameters provided in this config will be sent to the peer at the beginning of the
486/// connection, so it can take them into account when sending acknowledgements (see each parameter's
487/// description for details on how it influences acknowledgement frequency).
488///
489/// Quinn's implementation follows the fourth draft of the
490/// [QUIC Acknowledgement Frequency extension](https://datatracker.ietf.org/doc/html/draft-ietf-quic-ack-frequency-04).
491/// The defaults produce behavior slightly different than the behavior without this extension,
492/// because they change the way reordered packets are handled (see
493/// [`AckFrequencyConfig::reordering_threshold`] for details).
494#[derive(Clone, Debug)]
495pub struct AckFrequencyConfig {
496    pub(crate) ack_eliciting_threshold: VarInt,
497    pub(crate) max_ack_delay: Option<Duration>,
498    pub(crate) reordering_threshold: VarInt,
499}
500
501impl AckFrequencyConfig {
502    /// The ack-eliciting threshold we will request the peer to use
503    ///
504    /// This threshold represents the number of ack-eliciting packets an endpoint may receive
505    /// without immediately sending an ACK.
506    ///
507    /// The remote peer should send at least one ACK frame when more than this number of
508    /// ack-eliciting packets have been received. A value of 0 results in a receiver immediately
509    /// acknowledging every ack-eliciting packet.
510    ///
511    /// Defaults to 1, which sends ACK frames for every other ack-eliciting packet.
512    pub fn ack_eliciting_threshold(&mut self, value: VarInt) -> &mut Self {
513        self.ack_eliciting_threshold = value;
514        self
515    }
516
517    /// The `max_ack_delay` we will request the peer to use
518    ///
519    /// This parameter represents the maximum amount of time that an endpoint waits before sending
520    /// an ACK when the ack-eliciting threshold hasn't been reached.
521    ///
522    /// The effective `max_ack_delay` will be clamped to be at least the peer's `min_ack_delay`
523    /// transport parameter, and at most the greater of the current path RTT or 25ms.
524    ///
525    /// Defaults to `None`, in which case the peer's original `max_ack_delay` will be used, as
526    /// obtained from its transport parameters.
527    pub fn max_ack_delay(&mut self, value: Option<Duration>) -> &mut Self {
528        self.max_ack_delay = value;
529        self
530    }
531
532    /// The reordering threshold we will request the peer to use
533    ///
534    /// This threshold represents the amount of out-of-order packets that will trigger an endpoint
535    /// to send an ACK, without waiting for `ack_eliciting_threshold` to be exceeded or for
536    /// `max_ack_delay` to be elapsed.
537    ///
538    /// A value of 0 indicates out-of-order packets do not elicit an immediate ACK. A value of 1
539    /// immediately acknowledges any packets that are received out of order (this is also the
540    /// behavior when the extension is disabled).
541    ///
542    /// It is recommended to set this value to [`TransportConfig::packet_threshold`] minus one.
543    /// Since the default value for [`TransportConfig::packet_threshold`] is 3, this value defaults
544    /// to 2.
545    pub fn reordering_threshold(&mut self, value: VarInt) -> &mut Self {
546        self.reordering_threshold = value;
547        self
548    }
549}
550
551impl Default for AckFrequencyConfig {
552    fn default() -> Self {
553        Self {
554            ack_eliciting_threshold: VarInt(1),
555            max_ack_delay: None,
556            reordering_threshold: VarInt(2),
557        }
558    }
559}
560
561/// Parameters governing MTU discovery.
562///
563/// # The why of MTU discovery
564///
565/// By design, QUIC ensures during the handshake that the network path between the client and the
566/// server is able to transmit unfragmented UDP packets with a body of 1200 bytes. In other words,
567/// once the connection is established, we know that the network path's maximum transmission unit
568/// (MTU) is of at least 1200 bytes (plus IP and UDP headers). Because of this, a QUIC endpoint can
569/// split outgoing data in packets of 1200 bytes, with confidence that the network will be able to
570/// deliver them (if the endpoint were to send bigger packets, they could prove too big and end up
571/// being dropped).
572///
573/// There is, however, a significant overhead associated to sending a packet. If the same
574/// information can be sent in fewer packets, that results in higher throughput. The amount of
575/// packets that need to be sent is inversely proportional to the MTU: the higher the MTU, the
576/// bigger the packets that can be sent, and the fewer packets that are needed to transmit a given
577/// amount of bytes.
578///
579/// Most networks have an MTU higher than 1200. Through MTU discovery, endpoints can detect the
580/// path's MTU and, if it turns out to be higher, start sending bigger packets.
581///
582/// # MTU discovery internals
583///
584/// Quinn implements MTU discovery through DPLPMTUD (Datagram Packetization Layer Path MTU
585/// Discovery), described in [section 14.3 of RFC
586/// 9000](https://www.rfc-editor.org/rfc/rfc9000.html#section-14.3). This method consists of sending
587/// QUIC packets padded to a particular size (called PMTU probes), and waiting to see if the remote
588/// peer responds with an ACK. If an ACK is received, that means the probe arrived at the remote
589/// peer, which in turn means that the network path's MTU is of at least the packet's size. If the
590/// probe is lost, it is sent another 2 times before concluding that the MTU is lower than the
591/// packet's size.
592///
593/// MTU discovery runs on a schedule (e.g. every 600 seconds) specified through
594/// [`MtuDiscoveryConfig::interval`]. The first run happens right after the handshake, and
595/// subsequent discoveries are scheduled to run when the interval has elapsed, starting from the
596/// last time when MTU discovery completed.
597///
598/// Since the search space for MTUs is quite big (the smallest possible MTU is 1200, and the highest
599/// is 65527), Quinn performs a binary search to keep the number of probes as low as possible. The
600/// lower bound of the search is equal to [`TransportConfig::initial_mtu`] in the
601/// initial MTU discovery run, and is equal to the currently discovered MTU in subsequent runs. The
602/// upper bound is determined by the minimum of [`MtuDiscoveryConfig::upper_bound`] and the
603/// `max_udp_payload_size` transport parameter received from the peer during the handshake.
604///
605/// # Black hole detection
606///
607/// If, at some point, the network path no longer accepts packets of the detected size, packet loss
608/// will eventually trigger black hole detection and reset the detected MTU to 1200. In that case,
609/// MTU discovery will be triggered after [`MtuDiscoveryConfig::black_hole_cooldown`] (ignoring the
610/// timer that was set based on [`MtuDiscoveryConfig::interval`]).
611///
612/// # Interaction between peers
613///
614/// There is no guarantee that the MTU on the path between A and B is the same as the MTU of the
615/// path between B and A. Therefore, each peer in the connection needs to run MTU discovery
616/// independently in order to discover the path's MTU.
617#[derive(Clone, Debug)]
618pub struct MtuDiscoveryConfig {
619    pub(crate) interval: Duration,
620    pub(crate) upper_bound: u16,
621    pub(crate) minimum_change: u16,
622    pub(crate) black_hole_cooldown: Duration,
623}
624
625impl MtuDiscoveryConfig {
626    /// Specifies the time to wait after completing MTU discovery before starting a new MTU
627    /// discovery run.
628    ///
629    /// Defaults to 600 seconds, as recommended by [RFC
630    /// 8899](https://www.rfc-editor.org/rfc/rfc8899).
631    pub fn interval(&mut self, value: Duration) -> &mut Self {
632        self.interval = value;
633        self
634    }
635
636    /// Specifies the upper bound to the max UDP payload size that MTU discovery will search for.
637    ///
638    /// Defaults to 1452, to stay within Ethernet's MTU when using IPv4 and IPv6. The highest
639    /// allowed value is 65527, which corresponds to the maximum permitted UDP payload on IPv6.
640    ///
641    /// It is safe to use an arbitrarily high upper bound, regardless of the network path's MTU. The
642    /// only drawback is that MTU discovery might take more time to finish.
643    pub fn upper_bound(&mut self, value: u16) -> &mut Self {
644        self.upper_bound = value.min(MAX_UDP_PAYLOAD);
645        self
646    }
647
648    /// Specifies the amount of time that MTU discovery should wait after a black hole was detected
649    /// before running again. Defaults to one minute.
650    ///
651    /// Black hole detection can be spuriously triggered in case of congestion, so it makes sense to
652    /// try MTU discovery again after a short period of time.
653    pub fn black_hole_cooldown(&mut self, value: Duration) -> &mut Self {
654        self.black_hole_cooldown = value;
655        self
656    }
657
658    /// Specifies the minimum MTU change to stop the MTU discovery phase.
659    /// Defaults to 20.
660    pub fn minimum_change(&mut self, value: u16) -> &mut Self {
661        self.minimum_change = value;
662        self
663    }
664}
665
666impl Default for MtuDiscoveryConfig {
667    fn default() -> Self {
668        Self {
669            interval: Duration::from_secs(600),
670            upper_bound: 1452,
671            black_hole_cooldown: Duration::from_secs(60),
672            minimum_change: 20,
673        }
674    }
675}
676
677/// Maximum duration of inactivity to accept before timing out the connection
678///
679/// This wraps an underlying [`VarInt`], representing the duration in milliseconds. Values can be
680/// constructed by converting directly from `VarInt`, or using `TryFrom<Duration>`.
681///
682/// ```
683/// # use std::{convert::TryFrom, time::Duration};
684/// use ant_quic::config::IdleTimeout;
685/// use ant_quic::{VarIntBoundsExceeded, VarInt};
686/// # fn main() -> Result<(), VarIntBoundsExceeded> {
687/// // A `VarInt`-encoded value in milliseconds
688/// let timeout = IdleTimeout::from(VarInt::from_u32(10_000));
689///
690/// // Try to convert a `Duration` into a `VarInt`-encoded timeout
691/// let timeout = IdleTimeout::try_from(Duration::from_secs(10))?;
692/// # Ok(())
693/// # }
694/// ```
695#[derive(Default, Copy, Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
696pub struct IdleTimeout(VarInt);
697
698impl From<VarInt> for IdleTimeout {
699    fn from(inner: VarInt) -> Self {
700        Self(inner)
701    }
702}
703
704impl std::convert::TryFrom<Duration> for IdleTimeout {
705    type Error = VarIntBoundsExceeded;
706
707    fn try_from(timeout: Duration) -> Result<Self, Self::Error> {
708        let inner = VarInt::try_from(timeout.as_millis())?;
709        Ok(Self(inner))
710    }
711}
712
713impl fmt::Debug for IdleTimeout {
714    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
715        self.0.fmt(f)
716    }
717}