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 #[deprecated(
263 note = "Send fairness is now always enabled. Neither enabling nor disabling it has no effect."
264 )]
265 pub fn send_fairness(mut self, value: bool) -> Self {
266 #[allow(deprecated)]
267 self.0.send_fairness(value);
268 self
269 }
270
271 /// Maximum reordering in packet number space before FACK style loss detection considers a
272 /// packet lost. Should not be less than 3, per RFC5681.
273 pub fn packet_threshold(mut self, value: u32) -> Self {
274 self.0.packet_threshold(value);
275 self
276 }
277
278 /// Maximum reordering in time space before time based loss detection considers a packet lost,
279 /// as a factor of RTT.
280 pub fn time_threshold(mut self, value: f32) -> Self {
281 self.0.time_threshold(value);
282 self
283 }
284
285 /// The RTT used before an RTT sample is taken.
286 pub fn initial_rtt(mut self, value: Duration) -> Self {
287 self.0.initial_rtt(value);
288 self
289 }
290
291 /// The initial value to be used as the maximum UDP payload size before running MTU discovery
292 /// (see [`QuicTransportConfigBuilder::mtu_discovery_config`]).
293 ///
294 /// Must be at least 1200, which is the default, and known to be safe for typical internet
295 /// applications. Larger values are more efficient, but increase the risk of packet loss due to
296 /// exceeding the network path's IP MTU. If the provided value is higher than what the network
297 /// path actually supports, packet loss will eventually trigger black hole detection and bring
298 /// it down to [`QuicTransportConfigBuilder::min_mtu`].
299 pub fn initial_mtu(mut self, value: u16) -> Self {
300 self.0.initial_mtu(value);
301 self
302 }
303
304 /// The maximum UDP payload size guaranteed to be supported by the network.
305 ///
306 /// Must be at least 1200, which is the default, and lower than or equal to
307 /// [`QuicTransportConfigBuilder::initial_mtu`].
308 ///
309 /// Real-world MTUs can vary according to ISP, VPN, and properties of intermediate network links
310 /// outside of either endpoint's control. Extreme care should be used when raising this value
311 /// outside of private networks where these factors are fully controlled. If the provided value
312 /// is higher than what the network path actually supports, the result will be unpredictable and
313 /// catastrophic packet loss, without a possibility of repair. Prefer
314 /// [`QuicTransportConfigBuilder::initial_mtu`] together with
315 /// [`QuicTransportConfigBuilder::mtu_discovery_config`] to set a maximum UDP payload size that robustly
316 /// adapts to the network.
317 pub fn min_mtu(mut self, value: u16) -> Self {
318 self.0.min_mtu(value);
319 self
320 }
321
322 /// Specifies the MTU discovery config (see [`MtuDiscoveryConfig`] for details).
323 ///
324 /// Enabled by default.
325 pub fn mtu_discovery_config(mut self, value: Option<MtuDiscoveryConfig>) -> Self {
326 self.0.mtu_discovery_config(value);
327 self
328 }
329
330 /// Pad UDP datagrams carrying application data to current maximum UDP payload size.
331 ///
332 /// Disabled by default. UDP datagrams containing loss probes are exempt from padding.
333 ///
334 /// Enabling this helps mitigate traffic analysis by network observers, but it increases
335 /// bandwidth usage. Without this mitigation precise plain text size of application datagrams as
336 /// well as the total size of stream write bursts can be inferred by observers under certain
337 /// conditions. This analysis requires either an uncongested connection or application datagrams
338 /// too large to be coalesced.
339 pub fn pad_to_mtu(mut self, value: bool) -> Self {
340 self.0.pad_to_mtu(value);
341 self
342 }
343
344 /// Specifies the ACK frequency config (see [`AckFrequencyConfig`] for details).
345 ///
346 /// The provided configuration will be ignored if the peer does not support the acknowledgement
347 /// frequency QUIC extension.
348 ///
349 /// Defaults to `None`, which disables controlling the peer's acknowledgement frequency. Even
350 /// if set to `None`, the local side still supports the acknowledgement frequency QUIC
351 /// extension and may use it in other ways.
352 pub fn ack_frequency_config(mut self, value: Option<AckFrequencyConfig>) -> Self {
353 self.0.ack_frequency_config(value);
354 self
355 }
356
357 /// Number of consecutive PTOs after which network is considered to be experiencing persistent congestion.
358 pub fn persistent_congestion_threshold(mut self, value: u32) -> Self {
359 self.0.persistent_congestion_threshold(value);
360 self
361 }
362
363 /// Period of inactivity before sending a keep-alive packet.
364 ///
365 /// Keep-alive packets prevent an inactive but otherwise healthy connection from timing
366 /// out. They are important to keep NAT bindings alive and firewalls open.
367 ///
368 /// The default is 5s, please be careful when modifying this as it may affect connection
369 /// stability. Must be set lower than the idle_timeout of both peers to be effective.
370 pub fn keep_alive_interval(mut self, value: Duration) -> Self {
371 self.0.keep_alive_interval(Some(value));
372 self
373 }
374
375 /// Maximum quantity of out-of-order crypto layer data to buffer.
376 pub fn crypto_buffer_size(mut self, value: usize) -> Self {
377 self.0.crypto_buffer_size(value);
378 self
379 }
380
381 /// Whether the implementation is permitted to set the spin bit on this connection.
382 ///
383 /// This allows passive observers to easily judge the round trip time of a connection, which can
384 /// be useful for network administration but sacrifices a small amount of privacy.
385 pub fn allow_spin(mut self, value: bool) -> Self {
386 self.0.allow_spin(value);
387 self
388 }
389
390 /// Maximum number of incoming application datagram bytes to buffer, or None to disable
391 /// incoming datagrams.
392 ///
393 /// The peer is forbidden to send single datagrams larger than this size. If the aggregate size
394 /// of all datagrams that have been received from the peer but not consumed by the application
395 /// exceeds this value, old datagrams are dropped until it is no longer exceeded.
396 pub fn datagram_receive_buffer_size(mut self, value: Option<usize>) -> Self {
397 self.0.datagram_receive_buffer_size(value);
398 self
399 }
400
401 /// Maximum number of outgoing application datagram bytes to buffer.
402 ///
403 /// While datagrams are sent ASAP, it is possible for an application to generate data faster
404 /// than the link, or even the underlying hardware, can transmit them. This limits the amount of
405 /// memory that may be consumed in that case. When the send buffer is full and a new datagram is
406 /// sent, older datagrams are dropped until sufficient space is available.
407 pub fn datagram_send_buffer_size(mut self, value: usize) -> Self {
408 self.0.datagram_send_buffer_size(value);
409 self
410 }
411
412 /// How to construct new `congestion::Controller`s.
413 ///
414 /// Typically the refcounted configuration of a `congestion::Controller`,
415 /// e.g. a `congestion::NewRenoConfig`.
416 ///
417 /// # Example
418 /// ```
419 /// # use iroh::endpoint::QuicTransportConfig; use noq_proto::congestion; use std::sync::Arc;
420 /// let config = QuicTransportConfig::builder()
421 /// .congestion_controller_factory(Arc::new(congestion::NewRenoConfig::default()))
422 /// .build();
423 /// ```
424 pub fn congestion_controller_factory(
425 mut self,
426 factory: Arc<dyn ControllerFactory + Send + Sync + 'static>,
427 ) -> Self {
428 self.0.congestion_controller_factory(factory);
429 self
430 }
431
432 /// Whether to use "Generic Segmentation Offload" to accelerate transmits, when supported by the
433 /// environment.
434 ///
435 /// Defaults to `true`.
436 ///
437 /// GSO dramatically reduces CPU consumption when sending large numbers of packets with the same
438 /// headers, such as when transmitting bulk data on a connection. However, it is not supported
439 /// by all network interface drivers or packet inspection tools. `noq-udp` will attempt to
440 /// disable GSO automatically when unavailable, but this can lead to spurious packet loss at
441 /// startup, temporarily degrading performance.
442 pub fn enable_segmentation_offload(mut self, enabled: bool) -> Self {
443 self.0.enable_segmentation_offload(enabled);
444 self
445 }
446
447 /// Whether to send observed address reports to peers.
448 ///
449 /// This will aid peers in inferring their reachable address, which in most NATd networks
450 /// will not be easily available to them.
451 pub fn send_observed_address_reports(mut self, enabled: bool) -> Self {
452 self.0.send_observed_address_reports(enabled);
453 self
454 }
455
456 /// Whether to receive observed address reports from other peers.
457 ///
458 /// Peers with the address discovery extension enabled that are willing to provide observed
459 /// address reports will do so if this transport parameter is set. In general, observed address
460 /// reports cannot be trusted. This, however, can aid the current endpoint in inferring its
461 /// reachable address, which in most NATd networks will not be easily available.
462 pub fn receive_observed_address_reports(mut self, enabled: bool) -> Self {
463 self.0.receive_observed_address_reports(enabled);
464 self
465 }
466
467 /// Enables the Multipath Extension for QUIC.
468 ///
469 /// Setting this to any nonzero value will enable the Multipath Extension for QUIC,
470 /// <https://datatracker.ietf.org/doc/draft-ietf-quic-multipath/>.
471 ///
472 /// The value provided specifies the number maximum number of paths this endpoint may open
473 /// concurrently when multipath is negotiated. For any path to be opened, the remote must
474 /// enable multipath as well.
475 ///
476 /// Note: this method will ignore values less than the recommended 13 and will log a warning.
477 pub fn max_concurrent_multipath_paths(mut self, max_concurrent: u32) -> Self {
478 if max_concurrent < MAX_MULTIPATH_PATHS + 1 {
479 warn!(
480 "QuicTransportConfig::max_concurrent_multipath_paths must be at minimum {}, ignoring user supplied value",
481 MAX_MULTIPATH_PATHS + 1
482 );
483 return self;
484 }
485 self.0.max_concurrent_multipath_paths(max_concurrent);
486 self
487 }
488
489 /// Sets a default per-path maximum idle timeout.
490 ///
491 /// If the path is idle for this long the path will be abandoned. Bear in mind this will
492 /// interact with the [`QuicTransportConfigBuilder::max_idle_timeout`], if the last path is
493 /// abandoned the entire connection will be closed.
494 ///
495 /// Note: values higher than `PATH_MAX_IDLE_TIMEOUT` (15 seconds) are clamped and a warning is logged.
496 pub fn default_path_max_idle_timeout(mut self, timeout: Duration) -> Self {
497 if timeout > PATH_MAX_IDLE_TIMEOUT {
498 warn!(
499 "QuicTransportConfig::default_path_max_idle must be at most {:?}, clamping",
500 PATH_MAX_IDLE_TIMEOUT
501 );
502 self.0
503 .default_path_max_idle_timeout(Some(PATH_MAX_IDLE_TIMEOUT));
504 return self;
505 }
506 self.0.default_path_max_idle_timeout(Some(timeout));
507 self
508 }
509
510 /// Sets a default per-path keep alive interval.
511 ///
512 /// Note that this does not interact with the connection-wide
513 /// [`QuicTransportConfigBuilder::keep_alive_interval`]. This setting will keep this path active,
514 /// [`QuicTransportConfigBuilder::keep_alive_interval`] will keep the connection active, with no
515 /// control over which path is used for this.
516 ///
517 /// Note: this method will ignore values higher than the recommended 5 seconds and will log a warning.
518 pub fn default_path_keep_alive_interval(mut self, interval: Duration) -> Self {
519 if interval > HEARTBEAT_INTERVAL {
520 warn!(
521 "QuicTransportConfig::default_path_keep_alive must be at most {:?}, ignoring user supplied value",
522 HEARTBEAT_INTERVAL
523 );
524 return self;
525 }
526 self.0.default_path_keep_alive_interval(Some(interval));
527 self
528 }
529
530 /// Sets the maximum number of nat traversal addresses this endpoint allows the remote to
531 /// advertise.
532 ///
533 /// Setting this to any nonzero value will enable Iroh's holepunching, loosely based in the Nat
534 /// Traversal Extension for QUIC, see
535 /// <https://www.ietf.org/archive/id/draft-seemann-quic-nat-traversal-02.html>
536 ///
537 /// This implementation expects the multipath extension to be enabled as well. If not yet
538 /// enabled via [`Self::max_concurrent_multipath_paths`], a default value of
539 /// 8 will be used.
540 ///
541 /// Note: this method will ignore values less than the recommended 8 and will log a warning.
542 pub fn max_remote_nat_traversal_addresses(mut self, max_addresses: u8) -> Self {
543 if max_addresses < MAX_MULTIPATH_PATHS as u8 {
544 warn!(
545 "QuicTransportConfig::max_remote_nat_traversal_addresses must be at least {}, ignoring user supplied value",
546 MAX_MULTIPATH_PATHS
547 );
548 return self;
549 }
550 self.0.max_remote_nat_traversal_addresses(max_addresses);
551 self
552 }
553
554 /// Configures qlog capturing by setting a [`QlogFactory`].
555 ///
556 /// This assigns a [`QlogFactory`] that produces qlog capture configurations for
557 /// individual connections.
558 #[cfg(feature = "qlog")]
559 pub fn qlog_factory(mut self, factory: Arc<dyn QlogFactory>) -> Self {
560 self.0.qlog_factory(factory);
561 self
562 }
563
564 /// Configures qlog capturing through the `QLOGDIR` environment variable.
565 ///
566 /// This uses [`QlogFileFactory::from_env`] to create a factory to write qlog traces
567 /// into the directory set through the `QLOGDIR` environment variable.
568 ///
569 /// If `QLOGDIR` is not set, no traces will be written. If `QLOGDIR` is set to a path
570 /// that does not exist, it will be created.
571 ///
572 /// The files will be prefixed with `prefix`.
573 #[cfg(feature = "qlog")]
574 pub fn qlog_from_env(mut self, prefix: &str) -> Self {
575 self.0.qlog_from_env(prefix);
576 self
577 }
578
579 /// Configures qlog capturing into a directory.
580 ///
581 /// This uses [`QlogFileFactory`] to create a factory to write qlog traces into
582 /// the specified directory. The files will be prefixed with `prefix`.
583 #[cfg(feature = "qlog")]
584 pub fn qlog_from_path(mut self, path: impl AsRef<Path>, prefix: &str) -> Self {
585 self.0.qlog_from_path(path, prefix);
586 self
587 }
588}
589
590/// A builder for a [`ServerConfig`].
591#[derive(Debug, Clone)]
592pub struct ServerConfigBuilder {
593 inner: noq::ServerConfig,
594 transport: QuicTransportConfig,
595}
596
597/// Parameters governing incoming connections
598///
599/// Default values should be suitable for most internet applications.
600///
601/// Use a [`ServerConfigBuilder`] to adjust the default values.
602///
603/// To create a [`ServerConfig`] compatible with your [`Endpoint`] identity, use the [`Endpoint::create_server_config_builder`] method.
604///
605/// [`Endpoint`]: crate::Endpoint
606/// [`Endpoint::create_server_config_builder`]: crate::Endpoint::create_server_config_builder
607// Note: used in `iroh::endpoint::connection::Incoming::accept_with`
608// This is new-typed since `noq::ServerConfig` takes a `TransportConfig`, which we new-type as a `QuicTransportConfig`
609#[derive(Debug, Clone)]
610pub struct ServerConfig(Arc<noq::ServerConfig>);
611
612impl ServerConfig {
613 pub(crate) fn to_inner_arc(&self) -> Arc<noq::ServerConfig> {
614 self.0.clone()
615 }
616}
617
618impl ServerConfigBuilder {
619 /// Build a [`ServerConfig`] from a [`ServerConfigBuilder`].
620 pub fn build(self) -> ServerConfig {
621 ServerConfig(Arc::new(self.inner))
622 }
623
624 pub(crate) fn new(inner: noq::ServerConfig, transport: QuicTransportConfig) -> Self {
625 Self { inner, transport }
626 }
627
628 /// Sets a custom [`QuicTransportConfig`].
629 pub fn set_transport_config(mut self, transport: QuicTransportConfig) -> Self {
630 self.inner.transport_config(transport.to_inner_arc());
631 self.transport = transport;
632 self
633 }
634
635 /// Sets a custom [`ValidationTokenConfig`].
636 pub fn set_validation_token_config(mut self, validation_token: ValidationTokenConfig) -> Self {
637 self.inner.validation_token_config(validation_token);
638 self
639 }
640
641 /// Private key used to authenticate data included in handshake tokens
642 pub fn set_token_key(mut self, value: Arc<dyn HandshakeTokenKey>) -> Self {
643 self.inner.token_key(value);
644 self
645 }
646
647 /// Duration after a retry token was issued for which it's considered valid
648 ///
649 /// Defaults to 15 seconds.
650 pub fn set_retry_token_lifetime(mut self, value: Duration) -> Self {
651 self.inner.retry_token_lifetime(value);
652 self
653 }
654
655 /// Maximum number of [`Incoming`] to allow to exist at a time.
656 ///
657 /// An [`Incoming`] comes into existence when an incoming connection attempt
658 /// is received and stops existing when the application either accepts it or otherwise disposes
659 /// of it. While this limit is reached, new incoming connection attempts are immediately
660 /// refused. Larger values have greater worst-case memory consumption, but accommodate greater
661 /// application latency in handling incoming connection attempts.
662 ///
663 /// The default value is set to 65536. With a typical Ethernet MTU of 1500 bytes, this limits
664 /// memory consumption from this to under 100 MiB--a generous amount that still prevents memory
665 /// exhaustion in most contexts.
666 ///
667 /// [`Incoming`]: crate::endpoint::Incoming
668 pub fn set_max_incoming(mut self, max_incoming: usize) -> Self {
669 self.inner.max_incoming(max_incoming);
670 self
671 }
672
673 /// Maximum number of received bytes to buffer for each [`Incoming`].
674 ///
675 /// An [`Incoming`] comes into existence when an incoming connection attempt
676 /// is received and stops existing when the application either accepts it or otherwise disposes
677 /// of it. This limit governs only packets received within that period, and does not include
678 /// the first packet. Packets received in excess of this limit are dropped, which may cause
679 /// 0-RTT or handshake data to have to be retransmitted.
680 ///
681 /// The default value is set to 10 MiB--an amount such that in most situations a client would
682 /// not transmit that much 0-RTT data faster than the server handles the corresponding
683 /// [`Incoming`].
684 ///
685 /// [`Incoming`]: crate::endpoint::Incoming
686 pub fn set_incoming_buffer_size(mut self, incoming_buffer_size: u64) -> Self {
687 self.inner.incoming_buffer_size(incoming_buffer_size);
688 self
689 }
690
691 /// Maximum number of received bytes to buffer for all [`Incoming`]
692 /// collectively.
693 ///
694 /// An [`Incoming`] comes into existence when an incoming connection attempt
695 /// is received and stops existing when the application either accepts it or otherwise disposes
696 /// of it. This limit governs only packets received within that period, and does not include
697 /// the first packet. Packets received in excess of this limit are dropped, which may cause
698 /// 0-RTT or handshake data to have to be retransmitted.
699 ///
700 /// The default value is set to 100 MiB--a generous amount that still prevents memory
701 /// exhaustion in most contexts.
702 ///
703 /// [`Incoming`]: crate::endpoint::Incoming
704 pub fn set_incoming_buffer_size_total(mut self, incoming_buffer_size_total: u64) -> Self {
705 self.inner
706 .incoming_buffer_size_total(incoming_buffer_size_total);
707 self
708 }
709
710 /// Object to get current [`SystemTime`].
711 ///
712 /// This exists to allow system time to be mocked in tests, or wherever else desired.
713 ///
714 /// Defaults to [`noq::StdSystemTime`], which simply calls [`SystemTime::now()`](std::time::SystemTime::now).
715 ///
716 /// [`SystemTime`]: std::time::SystemTime
717 pub fn set_time_source(mut self, time_source: Arc<dyn TimeSource>) -> Self {
718 self.inner.time_source(time_source);
719 self
720 }
721}