iroh/endpoint/
quic.rs

1//! Exporting and encapsulating structs from noq
2//!
3//! Co-locates all iroh-noq exports.
4//!
5//! There are some structs that we use in particular ways, where we would like
6//! to limit or expand how those structs are used in iroh. By encapsulating them
7//! we can ensure the functionality needed to make iroh work.
8
9#[cfg(feature = "qlog")]
10use std::path::Path;
11use std::{sync::Arc, time::Duration};
12
13/// `noq` types that are used in the public iroh API.
14// Each type is notated with the iroh type or noq type that uses it.
15pub use noq::{
16    AcceptBi,             // iroh::endpoint::Connection
17    AcceptUni,            // iroh::endpoint::Connection
18    AckFrequencyConfig,   // iroh::endpoint::quic::QuicTransportConfig
19    Closed,               // iroh::endpoint::WeakConnectionHandle
20    ClosedStream,         // iroh::protocol::AcceptError, noq::RecvStream, noq::SendStream
21    ConnectionError,      // iroh::endpoint::ConnectError
22    ConnectionStats,      // iroh::endpoint::Connection
23    Dir,                  // noq::StreamId
24    IdleTimeout,          // iroh::endpoint::quic::QuicTransportConfig
25    MtuDiscoveryConfig,   // iroh::endpoint::quic::QuicTransportConfig
26    OpenBi,               // iroh::endpoint::Connection
27    OpenUni,              // iroh::endpoint::Connection
28    PathStats,            // iroh::socket::remote_map::remote_state::PathInfo
29    ReadDatagram,         // iroh::endpoint::Connection
30    ReadError,            // noq::RecvStream
31    ReadExactError,       // noq::RecvStream
32    ReadManyDatagrams,    // iroh::endpoint::Connection
33    ReadToEndError,       // noq::RecvStream
34    RecvStream,           // noq::AcceptBi, noq::AcceptUni, noq::OpenBi, noq::OpenUni
35    ResetError,           // noq::RecvStream
36    SendDatagram,         // iroh::endpoint::Connection
37    SendDatagramError,    // iroh::endpoint::Connection
38    SendStream,           // noq::AcceptBi, noq::OpenUni
39    Side,                 // iroh::endpoint::Connection, noq::StreamId,
40    StoppedError,         // noq::SendStream
41    StreamId,             // noq::RecvStream
42    UnorderedRecvStream,  // noq::RecvStream
43    VarInt,               // various
44    VarIntBoundsExceeded, // noq::VarInt, noq::IdleTimeout
45    WriteError,           // noq::SendStream
46};
47#[cfg(feature = "qlog")]
48pub use noq::{QlogConfig, QlogFactory, QlogFileFactory};
49// `noq_proto` types that are used in the public iroh API.
50// Each type is notated with the iroh type or noq type that uses it.
51pub use noq_proto::{
52    ApplicationClose,                 // noq::ConnectionError
53    Chunk,                            // noq::RecvStream
54    ConnectError as QuicConnectError, // iroh::endpoint::ConnectWithOptsError
55    ConnectionClose,                  // noq::ConnectionError
56    DecryptedInitial,                 // iroh::endpoint::connection::Incoming
57    FrameStats,                       // noq::ConnectionStats
58    FrameType,                        // noq_proto::TransportError
59    IncomingAlpns,                    // iroh::endpoint::DecryptedInitial
60    PathId,                           // noq_proto::crypto::PacketKey
61    RttEstimator,                     // noq_proto::congestion::Controller
62    TimeSource,                       // iroh::endpoint::quic::ServerConfig
63    TokenLog,                         // noq::ValidationTokenConfig
64    TokenReuseError,                  // noq::TokenLog
65    TransportError,                   // noq::ConnectionError
66    TransportErrorCode,               // noq_proto::TransportError
67    UdpStats,                         // noq::ConnectionStats
68    ValidationTokenConfig,            // iroh::endpoint::quic::::ServerConfig
69    congestion::{
70        Controller,        // iroh::endpoint::Connection
71        ControllerFactory, // iroh::endpoint::quic::QuicTransportConfig
72        ControllerMetrics, // noq_proto::congestion::Controller
73    },
74    crypto::{
75        CryptoError,               // noq_proto::crypto::CryptoError, noq_proto::crypto::PacketKey
76        ExportKeyingMaterialError, // iroh::endpoint::Connection
77        HandshakeTokenKey,         // iroh::endpoint::quic::ServerConfig
78        HeaderKey,                 // noq_proto::crypto::Keys
79        Keys,                      // noq_proto::crypto::Session
80        PacketKey,                 // noq_proto::crypto::Keys
81        UnsupportedVersion,        // noq_proto::ConnectError
82    },
83    transport_parameters::TransportParameters, // noq_proto::crypot::ServerConfig
84};
85use tracing::warn;
86
87use crate::socket::{
88    HEARTBEAT_INTERVAL, MAX_MULTIPATH_PATHS, MAX_QNT_ADDRESSES, PATH_MAX_IDLE_TIMEOUT,
89};
90
91/// Builder for a [`QuicTransportConfig`].
92#[derive(Debug, Clone)]
93pub struct QuicTransportConfigBuilder(noq::TransportConfig);
94
95/// Parameters governing the core QUIC state machine
96///
97/// Default values should be suitable for most internet applications. Applications protocols which
98/// forbid remotely-initiated streams should set `max_concurrent_bidi_streams` and
99/// `max_concurrent_uni_streams` to zero.
100///
101/// In some cases, performance or resource requirements can be improved by tuning these values to
102/// suit a particular application and/or network connection. In particular, data window sizes can be
103/// tuned for a particular expected round trip time, link capacity, and memory availability. Tuning
104/// for higher bandwidths and latencies increases worst-case memory consumption, but does not impair
105/// performance at lower bandwidths and latencies. The default configuration is tuned for a 100Mbps
106/// link with a 100ms round trip time.
107///
108/// Use the [`QuicTransportConfigBuilder`] to customize these tunable fields.
109///
110/// In iroh, the config has some specific default values that make iroh's holepunching work
111/// well with QUIC multipath. Adjusting those settings may cause suboptimal usage.
112///
113/// Look at the following methods for more details:
114/// - [`QuicTransportConfigBuilder::default_path_keep_alive_interval`]
115/// - [`QuicTransportConfigBuilder::default_path_max_idle_timeout`]
116/// - [`QuicTransportConfigBuilder::max_concurrent_multipath_paths`]
117/// - [`QuicTransportConfigBuilder::max_remote_nat_traversal_addresses`]
118///
119/// # Examples
120/// ```
121/// use std::time::Duration;
122///
123/// use iroh::endpoint::QuicTransportConfig;
124///
125/// let _cfg = QuicTransportConfig::builder()
126///     .send_observed_address_reports(true)
127///     .build();
128/// ```
129#[derive(Debug, Clone)]
130pub struct QuicTransportConfig(Arc<noq::TransportConfig>);
131
132impl QuicTransportConfig {
133    /// Returns a default [`QuicTransportConfigBuilder`] that allows customizing
134    /// a [`QuicTransportConfig`].
135    pub fn builder() -> QuicTransportConfigBuilder {
136        QuicTransportConfigBuilder::new()
137    }
138}
139
140impl Default for QuicTransportConfig {
141    fn default() -> Self {
142        QuicTransportConfigBuilder::new().build()
143    }
144}
145
146impl QuicTransportConfig {
147    pub(crate) fn to_inner_arc(&self) -> Arc<noq::TransportConfig> {
148        self.0.clone()
149    }
150}
151
152impl QuicTransportConfigBuilder {
153    /// Creates a default [`QuicTransportConfigBuilder`].
154    fn new() -> Self {
155        let mut cfg = noq::TransportConfig::default();
156        // Override some transport config settings.
157        cfg.keep_alive_interval(Some(HEARTBEAT_INTERVAL));
158        cfg.default_path_keep_alive_interval(Some(HEARTBEAT_INTERVAL));
159        cfg.default_path_max_idle_timeout(Some(PATH_MAX_IDLE_TIMEOUT));
160        cfg.max_concurrent_multipath_paths(MAX_MULTIPATH_PATHS);
161        cfg.max_remote_nat_traversal_addresses(MAX_QNT_ADDRESSES);
162        cfg.server_handshake_migration(true);
163        Self(cfg)
164    }
165
166    /// Builds a [`QuicTransportConfig`] from the builder.
167    pub fn build(self) -> QuicTransportConfig {
168        QuicTransportConfig(Arc::new(self.0))
169    }
170
171    /// Maximum number of incoming bidirectional streams that may be open concurrently.
172    ///
173    /// Must be nonzero for the peer to open any bidirectional streams.
174    ///
175    /// Worst-case memory use is directly proportional to `max_concurrent_bidi_streams *
176    /// stream_receive_window`, with an upper bound proportional to `receive_window`.
177    pub fn max_concurrent_bidi_streams(mut self, value: VarInt) -> Self {
178        self.0.max_concurrent_bidi_streams(value);
179        self
180    }
181
182    /// Variant of `max_concurrent_bidi_streams` affecting unidirectional streams.
183    pub fn max_concurrent_uni_streams(mut self, value: VarInt) -> Self {
184        self.0.max_concurrent_uni_streams(value);
185        self
186    }
187
188    /// Maximum duration of inactivity to accept before timing out the connection.
189    ///
190    /// The true idle timeout is the minimum of this and the peer's own max idle timeout. `None`
191    /// represents an infinite timeout. Defaults to 30 seconds.
192    ///
193    /// **WARNING**: If a peer or its network path malfunctions or acts maliciously, an infinite
194    /// idle timeout can result in permanently hung futures!
195    ///
196    /// ```
197    /// # use std::{convert::TryInto, time::Duration};
198    /// # use iroh::endpoint::{QuicTransportConfig, VarInt, VarIntBoundsExceeded};
199    /// # fn main() -> Result<(), VarIntBoundsExceeded> {
200    /// let mut builder = QuicTransportConfig::builder()
201    ///     // Set the idle timeout as `VarInt`-encoded milliseconds
202    ///     .max_idle_timeout(Some(VarInt::from_u32(10_000).into()));
203    ///
204    /// // Set the idle timeout as a `Duration`
205    /// builder = builder.max_idle_timeout(Some(Duration::from_secs(10).try_into()?));
206    ///
207    /// let _cfg = builder.build();
208    ///
209    /// # Ok(())
210    /// # }
211    /// ```
212    pub fn max_idle_timeout(mut self, value: Option<IdleTimeout>) -> Self {
213        self.0.max_idle_timeout(value);
214        self
215    }
216
217    /// Maximum number of bytes the peer may transmit without acknowledgement on any one stream
218    /// before becoming blocked.
219    ///
220    /// This should be set to at least the expected connection latency multiplied by the maximum
221    /// desired throughput. Setting this smaller than `receive_window` helps ensure that a single
222    /// stream doesn't monopolize receive buffers, which may otherwise occur if the application
223    /// chooses not to read from a large stream for a time while still requiring data on other
224    /// streams.
225    pub fn stream_receive_window(mut self, value: VarInt) -> Self {
226        self.0.stream_receive_window(value);
227        self
228    }
229
230    /// Maximum number of bytes the peer may transmit across all streams of a connection before
231    /// becoming blocked.
232    ///
233    /// This should be set to at least the expected connection latency multiplied by the maximum
234    /// desired throughput. Larger values can be useful to allow maximum throughput within a
235    /// stream while another is blocked.
236    pub fn receive_window(mut self, value: VarInt) -> Self {
237        self.0.receive_window(value);
238        self
239    }
240
241    /// Maximum number of bytes to transmit to a peer without acknowledgment.
242    ///
243    /// Provides an upper bound on memory when communicating with peers that issue large amounts of
244    /// flow control credit. Endpoints that wish to handle large numbers of connections robustly
245    /// should take care to set this low enough to guarantee memory exhaustion does not occur if
246    /// every connection uses the entire window.
247    pub fn send_window(mut self, value: u64) -> Self {
248        self.0.send_window(value);
249        self
250    }
251
252    /// Whether to implement fair queuing for send streams having the same priority.
253    ///
254    /// When enabled, connections schedule data from outgoing streams having the same priority in a
255    /// round-robin fashion. When disabled, streams are scheduled in the order they are written to.
256    ///
257    /// Note that this only affects streams with the same priority. Higher priority streams always
258    /// take precedence over lower priority streams.
259    ///
260    /// Disabling fairness can reduce fragmentation and protocol overhead for workloads that use
261    /// many small streams.
262    pub fn send_fairness(mut self, value: bool) -> Self {
263        self.0.send_fairness(value);
264        self
265    }
266
267    /// Maximum reordering in packet number space before FACK style loss detection considers a
268    /// packet lost. Should not be less than 3, per RFC5681.
269    pub fn packet_threshold(mut self, value: u32) -> Self {
270        self.0.packet_threshold(value);
271        self
272    }
273
274    /// Maximum reordering in time space before time based loss detection considers a packet lost,
275    /// as a factor of RTT.
276    pub fn time_threshold(mut self, value: f32) -> Self {
277        self.0.time_threshold(value);
278        self
279    }
280
281    /// The RTT used before an RTT sample is taken.
282    pub fn initial_rtt(mut self, value: Duration) -> Self {
283        self.0.initial_rtt(value);
284        self
285    }
286
287    /// The initial value to be used as the maximum UDP payload size before running MTU discovery
288    /// (see [`QuicTransportConfigBuilder::mtu_discovery_config`]).
289    ///
290    /// Must be at least 1200, which is the default, and known to be safe for typical internet
291    /// applications. Larger values are more efficient, but increase the risk of packet loss due to
292    /// exceeding the network path's IP MTU. If the provided value is higher than what the network
293    /// path actually supports, packet loss will eventually trigger black hole detection and bring
294    /// it down to [`QuicTransportConfigBuilder::min_mtu`].
295    pub fn initial_mtu(mut self, value: u16) -> Self {
296        self.0.initial_mtu(value);
297        self
298    }
299
300    /// The maximum UDP payload size guaranteed to be supported by the network.
301    ///
302    /// Must be at least 1200, which is the default, and lower than or equal to
303    /// [`QuicTransportConfigBuilder::initial_mtu`].
304    ///
305    /// Real-world MTUs can vary according to ISP, VPN, and properties of intermediate network links
306    /// outside of either endpoint's control. Extreme care should be used when raising this value
307    /// outside of private networks where these factors are fully controlled. If the provided value
308    /// is higher than what the network path actually supports, the result will be unpredictable and
309    /// catastrophic packet loss, without a possibility of repair. Prefer
310    /// [`QuicTransportConfigBuilder::initial_mtu`] together with
311    /// [`QuicTransportConfigBuilder::mtu_discovery_config`] to set a maximum UDP payload size that robustly
312    /// adapts to the network.
313    pub fn min_mtu(mut self, value: u16) -> Self {
314        self.0.min_mtu(value);
315        self
316    }
317
318    /// Specifies the MTU discovery config (see [`MtuDiscoveryConfig`] for details).
319    ///
320    /// Enabled by default.
321    pub fn mtu_discovery_config(mut self, value: Option<MtuDiscoveryConfig>) -> Self {
322        self.0.mtu_discovery_config(value);
323        self
324    }
325
326    /// Pad UDP datagrams carrying application data to current maximum UDP payload size.
327    ///
328    /// Disabled by default. UDP datagrams containing loss probes are exempt from padding.
329    ///
330    /// Enabling this helps mitigate traffic analysis by network observers, but it increases
331    /// bandwidth usage. Without this mitigation precise plain text size of application datagrams as
332    /// well as the total size of stream write bursts can be inferred by observers under certain
333    /// conditions. This analysis requires either an uncongested connection or application datagrams
334    /// too large to be coalesced.
335    pub fn pad_to_mtu(mut self, value: bool) -> Self {
336        self.0.pad_to_mtu(value);
337        self
338    }
339
340    /// Specifies the ACK frequency config (see [`AckFrequencyConfig`] for details).
341    ///
342    /// The provided configuration will be ignored if the peer does not support the acknowledgement
343    /// frequency QUIC extension.
344    ///
345    /// Defaults to `None`, which disables controlling the peer's acknowledgement frequency. Even
346    /// if set to `None`, the local side still supports the acknowledgement frequency QUIC
347    /// extension and may use it in other ways.
348    pub fn ack_frequency_config(mut self, value: Option<AckFrequencyConfig>) -> Self {
349        self.0.ack_frequency_config(value);
350        self
351    }
352
353    /// Number of consecutive PTOs after which network is considered to be experiencing persistent congestion.
354    pub fn persistent_congestion_threshold(mut self, value: u32) -> Self {
355        self.0.persistent_congestion_threshold(value);
356        self
357    }
358
359    /// Period of inactivity before sending a keep-alive packet.
360    ///
361    /// Keep-alive packets prevent an inactive but otherwise healthy connection from timing
362    /// out. They are important to keep NAT bindings alive and firewalls open.
363    ///
364    /// The default is 5s, please be careful when modifying this as it may affect connection
365    /// stability. Must be set lower than the idle_timeout of both peers to be effective.
366    pub fn keep_alive_interval(mut self, value: Duration) -> Self {
367        self.0.keep_alive_interval(Some(value));
368        self
369    }
370
371    /// Maximum quantity of out-of-order crypto layer data to buffer.
372    pub fn crypto_buffer_size(mut self, value: usize) -> Self {
373        self.0.crypto_buffer_size(value);
374        self
375    }
376
377    /// Whether the implementation is permitted to set the spin bit on this connection.
378    ///
379    /// This allows passive observers to easily judge the round trip time of a connection, which can
380    /// be useful for network administration but sacrifices a small amount of privacy.
381    pub fn allow_spin(mut self, value: bool) -> Self {
382        self.0.allow_spin(value);
383        self
384    }
385
386    /// Maximum number of incoming application datagram bytes to buffer, or None to disable
387    /// incoming datagrams.
388    ///
389    /// The peer is forbidden to send single datagrams larger than this size. If the aggregate size
390    /// of all datagrams that have been received from the peer but not consumed by the application
391    /// exceeds this value, old datagrams are dropped until it is no longer exceeded.
392    pub fn datagram_receive_buffer_size(mut self, value: Option<usize>) -> Self {
393        self.0.datagram_receive_buffer_size(value);
394        self
395    }
396
397    /// Maximum number of outgoing application datagram bytes to buffer.
398    ///
399    /// While datagrams are sent ASAP, it is possible for an application to generate data faster
400    /// than the link, or even the underlying hardware, can transmit them. This limits the amount of
401    /// memory that may be consumed in that case. When the send buffer is full and a new datagram is
402    /// sent, older datagrams are dropped until sufficient space is available.
403    pub fn datagram_send_buffer_size(mut self, value: usize) -> Self {
404        self.0.datagram_send_buffer_size(value);
405        self
406    }
407
408    /// How to construct new `congestion::Controller`s.
409    ///
410    /// Typically the refcounted configuration of a `congestion::Controller`,
411    /// e.g. a `congestion::NewRenoConfig`.
412    ///
413    /// # Example
414    /// ```
415    /// # use iroh::endpoint::QuicTransportConfig; use noq_proto::congestion; use std::sync::Arc;
416    /// let config = QuicTransportConfig::builder()
417    ///     .congestion_controller_factory(Arc::new(congestion::NewRenoConfig::default()))
418    ///     .build();
419    /// ```
420    pub fn congestion_controller_factory(
421        mut self,
422        factory: Arc<dyn ControllerFactory + Send + Sync + 'static>,
423    ) -> Self {
424        self.0.congestion_controller_factory(factory);
425        self
426    }
427
428    /// Whether to use "Generic Segmentation Offload" to accelerate transmits, when supported by the
429    /// environment.
430    ///
431    /// Defaults to `true`.
432    ///
433    /// GSO dramatically reduces CPU consumption when sending large numbers of packets with the same
434    /// headers, such as when transmitting bulk data on a connection. However, it is not supported
435    /// by all network interface drivers or packet inspection tools. `noq-udp` will attempt to
436    /// disable GSO automatically when unavailable, but this can lead to spurious packet loss at
437    /// startup, temporarily degrading performance.
438    pub fn enable_segmentation_offload(mut self, enabled: bool) -> Self {
439        self.0.enable_segmentation_offload(enabled);
440        self
441    }
442
443    /// Whether to send observed address reports to peers.
444    ///
445    /// This will aid peers in inferring their reachable address, which in most NATd networks
446    /// will not be easily available to them.
447    pub fn send_observed_address_reports(mut self, enabled: bool) -> Self {
448        self.0.send_observed_address_reports(enabled);
449        self
450    }
451
452    /// Whether to receive observed address reports from other peers.
453    ///
454    /// Peers with the address discovery extension enabled that are willing to provide observed
455    /// address reports will do so if this transport parameter is set. In general, observed address
456    /// reports cannot be trusted. This, however, can aid the current endpoint in inferring its
457    /// reachable address, which in most NATd networks will not be easily available.
458    pub fn receive_observed_address_reports(mut self, enabled: bool) -> Self {
459        self.0.receive_observed_address_reports(enabled);
460        self
461    }
462
463    /// Enables the Multipath Extension for QUIC.
464    ///
465    /// Setting this to any nonzero value will enable the Multipath Extension for QUIC,
466    /// <https://datatracker.ietf.org/doc/draft-ietf-quic-multipath/>.
467    ///
468    /// The value provided specifies the number maximum number of paths this endpoint may open
469    /// concurrently when multipath is negotiated. For any path to be opened, the remote must
470    /// enable multipath as well.
471    ///
472    /// Note: this method will ignore values less than the recommended 13 and will log a warning.
473    pub fn max_concurrent_multipath_paths(mut self, max_concurrent: u32) -> Self {
474        if max_concurrent < MAX_MULTIPATH_PATHS + 1 {
475            warn!(
476                "QuicTransportConfig::max_concurrent_multipath_paths must be at minimum {}, ignoring user supplied value",
477                MAX_MULTIPATH_PATHS + 1
478            );
479            return self;
480        }
481        self.0.max_concurrent_multipath_paths(max_concurrent);
482        self
483    }
484
485    /// Sets a default per-path maximum idle timeout.
486    ///
487    /// If the path is idle for this long the path will be abandoned. Bear in mind this will
488    /// interact with the [`QuicTransportConfigBuilder::max_idle_timeout`], if the last path is
489    /// abandoned the entire connection will be closed.
490    ///
491    /// Note: values higher than `PATH_MAX_IDLE_TIMEOUT` (15 seconds) are clamped and a warning is logged.
492    pub fn default_path_max_idle_timeout(mut self, timeout: Duration) -> Self {
493        if timeout > PATH_MAX_IDLE_TIMEOUT {
494            warn!(
495                "QuicTransportConfig::default_path_max_idle must be at most {:?}, clamping",
496                PATH_MAX_IDLE_TIMEOUT
497            );
498            self.0
499                .default_path_max_idle_timeout(Some(PATH_MAX_IDLE_TIMEOUT));
500            return self;
501        }
502        self.0.default_path_max_idle_timeout(Some(timeout));
503        self
504    }
505
506    /// Sets a default per-path keep alive interval.
507    ///
508    /// Note that this does not interact with the connection-wide
509    /// [`QuicTransportConfigBuilder::keep_alive_interval`].  This setting will keep this path active,
510    /// [`QuicTransportConfigBuilder::keep_alive_interval`] will keep the connection active, with no
511    /// control over which path is used for this.
512    ///
513    /// Note: this method will ignore values higher than the recommended 5 seconds and will log a warning.
514    pub fn default_path_keep_alive_interval(mut self, interval: Duration) -> Self {
515        if interval > HEARTBEAT_INTERVAL {
516            warn!(
517                "QuicTransportConfig::default_path_keep_alive must be at most {:?}, ignoring user supplied value",
518                HEARTBEAT_INTERVAL
519            );
520            return self;
521        }
522        self.0.default_path_keep_alive_interval(Some(interval));
523        self
524    }
525
526    /// Sets the maximum number of nat traversal addresses this endpoint allows the remote to
527    /// advertise.
528    ///
529    /// Setting this to any nonzero value will enable Iroh's holepunching, loosely based in the Nat
530    /// Traversal Extension for QUIC, see
531    /// <https://www.ietf.org/archive/id/draft-seemann-quic-nat-traversal-02.html>
532    ///
533    /// This implementation expects the multipath extension to be enabled as well. If not yet
534    /// enabled via [`Self::max_concurrent_multipath_paths`], a default value of
535    /// 8 will be used.
536    ///
537    /// Note: this method will ignore values less than the recommended 8 and will log a warning.
538    pub fn max_remote_nat_traversal_addresses(mut self, max_addresses: u8) -> Self {
539        if max_addresses < MAX_MULTIPATH_PATHS as u8 {
540            warn!(
541                "QuicTransportConfig::max_remote_nat_traversal_addresses must be at least {}, ignoring user supplied value",
542                MAX_MULTIPATH_PATHS
543            );
544            return self;
545        }
546        self.0.max_remote_nat_traversal_addresses(max_addresses);
547        self
548    }
549
550    /// Configures qlog capturing by setting a [`QlogFactory`].
551    ///
552    /// This assigns a [`QlogFactory`] that produces qlog capture configurations for
553    /// individual connections.
554    #[cfg(feature = "qlog")]
555    pub fn qlog_factory(mut self, factory: Arc<dyn QlogFactory>) -> Self {
556        self.0.qlog_factory(factory);
557        self
558    }
559
560    /// Configures qlog capturing through the `QLOGDIR` environment variable.
561    ///
562    /// This uses [`QlogFileFactory::from_env`] to create a factory to write qlog traces
563    /// into the directory set through the `QLOGDIR` environment variable.
564    ///
565    /// If `QLOGDIR` is not set, no traces will be written. If `QLOGDIR` is set to a path
566    /// that does not exist, it will be created.
567    ///
568    /// The files will be prefixed with `prefix`.
569    #[cfg(feature = "qlog")]
570    pub fn qlog_from_env(mut self, prefix: &str) -> Self {
571        self.0.qlog_from_env(prefix);
572        self
573    }
574
575    /// Configures qlog capturing into a directory.
576    ///
577    /// This uses [`QlogFileFactory`] to create a factory to write qlog traces into
578    /// the specified directory.  The files will be prefixed with `prefix`.
579    #[cfg(feature = "qlog")]
580    pub fn qlog_from_path(mut self, path: impl AsRef<Path>, prefix: &str) -> Self {
581        self.0.qlog_from_path(path, prefix);
582        self
583    }
584}
585
586/// A builder for a [`ServerConfig`].
587#[derive(Debug, Clone)]
588pub struct ServerConfigBuilder {
589    inner: noq::ServerConfig,
590    transport: QuicTransportConfig,
591}
592
593/// Parameters governing incoming connections
594///
595/// Default values should be suitable for most internet applications.
596///
597/// Use a [`ServerConfigBuilder`] to adjust the default values.
598///
599/// To create a [`ServerConfig`] compatible with your [`Endpoint`] identity, use the [`Endpoint::create_server_config_builder`] method.
600///
601/// [`Endpoint`]: crate::Endpoint
602/// [`Endpoint::create_server_config_builder`]: crate::Endpoint::create_server_config_builder
603// Note: used in `iroh::endpoint::connection::Incoming::accept_with`
604// This is new-typed since `noq::ServerConfig` takes a `TransportConfig`, which we new-type as a `QuicTransportConfig`
605#[derive(Debug, Clone)]
606pub struct ServerConfig(Arc<noq::ServerConfig>);
607
608impl ServerConfig {
609    pub(crate) fn to_inner_arc(&self) -> Arc<noq::ServerConfig> {
610        self.0.clone()
611    }
612}
613
614impl ServerConfigBuilder {
615    /// Build a [`ServerConfig`] from a [`ServerConfigBuilder`].
616    pub fn build(self) -> ServerConfig {
617        ServerConfig(Arc::new(self.inner))
618    }
619
620    pub(crate) fn new(inner: noq::ServerConfig, transport: QuicTransportConfig) -> Self {
621        Self { inner, transport }
622    }
623
624    /// Sets a custom [`QuicTransportConfig`].
625    pub fn set_transport_config(mut self, transport: QuicTransportConfig) -> Self {
626        self.inner.transport_config(transport.to_inner_arc());
627        self.transport = transport;
628        self
629    }
630
631    /// Sets a custom [`ValidationTokenConfig`].
632    pub fn set_validation_token_config(mut self, validation_token: ValidationTokenConfig) -> Self {
633        self.inner.validation_token_config(validation_token);
634        self
635    }
636
637    /// Private key used to authenticate data included in handshake tokens
638    pub fn set_token_key(mut self, value: Arc<dyn HandshakeTokenKey>) -> Self {
639        self.inner.token_key(value);
640        self
641    }
642
643    /// Duration after a retry token was issued for which it's considered valid
644    ///
645    /// Defaults to 15 seconds.
646    pub fn set_retry_token_lifetime(mut self, value: Duration) -> Self {
647        self.inner.retry_token_lifetime(value);
648        self
649    }
650
651    /// Maximum number of [`Incoming`] to allow to exist at a time.
652    ///
653    /// An [`Incoming`] comes into existence when an incoming connection attempt
654    /// is received and stops existing when the application either accepts it or otherwise disposes
655    /// of it. While this limit is reached, new incoming connection attempts are immediately
656    /// refused. Larger values have greater worst-case memory consumption, but accommodate greater
657    /// application latency in handling incoming connection attempts.
658    ///
659    /// The default value is set to 65536. With a typical Ethernet MTU of 1500 bytes, this limits
660    /// memory consumption from this to under 100 MiB--a generous amount that still prevents memory
661    /// exhaustion in most contexts.
662    ///
663    /// [`Incoming`]: crate::endpoint::Incoming
664    pub fn set_max_incoming(mut self, max_incoming: usize) -> Self {
665        self.inner.max_incoming(max_incoming);
666        self
667    }
668
669    /// Maximum number of received bytes to buffer for each [`Incoming`].
670    ///
671    /// An [`Incoming`] comes into existence when an incoming connection attempt
672    /// is received and stops existing when the application either accepts it or otherwise disposes
673    /// of it. This limit governs only packets received within that period, and does not include
674    /// the first packet. Packets received in excess of this limit are dropped, which may cause
675    /// 0-RTT or handshake data to have to be retransmitted.
676    ///
677    /// The default value is set to 10 MiB--an amount such that in most situations a client would
678    /// not transmit that much 0-RTT data faster than the server handles the corresponding
679    /// [`Incoming`].
680    ///
681    /// [`Incoming`]: crate::endpoint::Incoming
682    pub fn set_incoming_buffer_size(mut self, incoming_buffer_size: u64) -> Self {
683        self.inner.incoming_buffer_size(incoming_buffer_size);
684        self
685    }
686
687    /// Maximum number of received bytes to buffer for all [`Incoming`]
688    /// collectively.
689    ///
690    /// An [`Incoming`] comes into existence when an incoming connection attempt
691    /// is received and stops existing when the application either accepts it or otherwise disposes
692    /// of it. This limit governs only packets received within that period, and does not include
693    /// the first packet. Packets received in excess of this limit are dropped, which may cause
694    /// 0-RTT or handshake data to have to be retransmitted.
695    ///
696    /// The default value is set to 100 MiB--a generous amount that still prevents memory
697    /// exhaustion in most contexts.
698    ///
699    /// [`Incoming`]: crate::endpoint::Incoming
700    pub fn set_incoming_buffer_size_total(mut self, incoming_buffer_size_total: u64) -> Self {
701        self.inner
702            .incoming_buffer_size_total(incoming_buffer_size_total);
703        self
704    }
705
706    /// Object to get current [`SystemTime`].
707    ///
708    /// This exists to allow system time to be mocked in tests, or wherever else desired.
709    ///
710    /// Defaults to [`noq::StdSystemTime`], which simply calls [`SystemTime::now()`](std::time::SystemTime::now).
711    ///
712    /// [`SystemTime`]: std::time::SystemTime
713    pub fn set_time_source(mut self, time_source: Arc<dyn TimeSource>) -> Self {
714        self.inner.time_source(time_source);
715        self
716    }
717}