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