iroh/socket/
transports.rs

1use std::{
2    fmt,
3    io::{self, IoSliceMut},
4    net::{IpAddr, Ipv6Addr, SocketAddr, SocketAddrV6},
5    num::NonZeroUsize,
6    pin::Pin,
7    sync::Arc,
8    task::{Context, Poll},
9};
10
11use bytes::Bytes;
12use iroh_base::{CustomAddr, EndpointId, RelayUrl, TransportAddr};
13use iroh_relay::RelayMap;
14use n0_watcher::Watcher;
15use relay::{RelayNetworkChangeSender, RelaySender};
16use tokio_util::sync::CancellationToken;
17use tracing::{debug, error, instrument, trace, warn};
18
19use super::{Socket, mapped_addrs::MultipathMappedAddr};
20use crate::{
21    endpoint::RelayStatus,
22    metrics::EndpointMetrics,
23    net_report::Report,
24    socket::mapped_addrs::{AddrMap, CustomMappedAddr},
25};
26
27pub(crate) mod custom;
28#[cfg(not(wasm_browser))]
29mod ip;
30mod relay;
31
32use custom::{CustomEndpoint, CustomSender, CustomTransport};
33
34#[cfg(not(wasm_browser))]
35pub(crate) use self::ip::Config as IpConfig;
36#[cfg(not(wasm_browser))]
37use self::ip::{IpNetworkChangeSender, IpTransports, IpTransportsSender};
38pub(crate) use self::relay::{
39    HomeRelayWatch, RelayActorConfig, RelayConnectionFailure, RelayConnectionState, RelayTransport,
40};
41
42/// How many times all transports may error on `poll_recv` before we give up.
43///
44/// Once all transports errored for this many times in a row, we give up and forward
45/// the error to noq, which will kill the endpoint driver then.
46const MAX_CONSECUTIVE_RECV_ERRORS: usize = 8;
47
48/// Manages the different underlying data transports that the socket can support.
49#[derive(Debug)]
50pub(crate) struct Transports {
51    #[cfg(not(wasm_browser))]
52    ip: IpTransports,
53    relay: Vec<RelayTransport>,
54    custom: Vec<Box<dyn CustomEndpoint>>,
55
56    poll_recv_counter: usize,
57    /// Cache for per-packet recv info, to speed up access
58    recv_infos: [RecvInfo; noq_udp::BATCH_SIZE],
59    consecutive_total_recv_failures: usize,
60}
61
62/// Combined watcher type for all ip transports
63type IpTransportsWatcher = n0_watcher::Join<SocketAddr, n0_watcher::Direct<SocketAddr>>;
64/// Combined watcher type for all custom transports
65type CustomTransportsWatcher =
66    n0_watcher::Join<Vec<CustomAddr>, n0_watcher::Direct<Vec<CustomAddr>>>;
67/// Combined watcher type for all relay transports
68type RelayTransportsWatcher = n0_watcher::Join<
69    Option<(RelayUrl, EndpointId)>,
70    n0_watcher::Map<n0_watcher::Direct<Option<RelayStatus>>, Option<(RelayUrl, EndpointId)>>,
71>;
72
73pub(super) type HomeRelayWatcher = n0_watcher::Map<
74    n0_watcher::Join<Option<RelayStatus>, n0_watcher::Direct<Option<RelayStatus>>>,
75    Vec<RelayStatus>,
76>;
77
78#[cfg(not(wasm_browser))]
79/// Combined watcher type for all transports, custom, relay and ip
80pub(crate) type LocalAddrsWatch = n0_watcher::Map<
81    n0_watcher::Tuple<
82        n0_watcher::Tuple<IpTransportsWatcher, CustomTransportsWatcher>,
83        RelayTransportsWatcher,
84    >,
85    Vec<Addr>,
86>;
87
88/// Type for watching relay and custom transports only, no ip
89#[cfg(wasm_browser)]
90pub(crate) type LocalAddrsWatch =
91    n0_watcher::Map<n0_watcher::Tuple<CustomTransportsWatcher, RelayTransportsWatcher>, Vec<Addr>>;
92
93/// Available transport configurations.
94#[derive(Debug, Clone)]
95#[non_exhaustive]
96pub(crate) enum TransportConfig {
97    /// IP based transport
98    #[cfg(not(wasm_browser))]
99    Ip {
100        /// The actual IP Config
101        config: ip::Config,
102        /// Was this added explicitly by the user.
103        is_user_defined: bool,
104    },
105    /// Relay transport
106    Relay {
107        /// The [`RelayMap`] used for this relay.
108        relay_map: RelayMap,
109        /// Was this added explicitly by the user.
110        is_user_defined: bool,
111    },
112    /// Custom transport factory.
113    #[cfg_attr(not(feature = "unstable-custom-transports"), allow(dead_code))]
114    Custom(Arc<dyn CustomTransport>),
115}
116
117impl TransportConfig {
118    /// Configures a default IPv4 transport, listening on `0.0.0.0:0`.
119    #[cfg(not(wasm_browser))]
120    pub(crate) fn default_ipv4() -> Self {
121        use std::net::Ipv4Addr;
122
123        use ipnet::Ipv4Net;
124
125        Self::Ip {
126            config: ip::Config::V4 {
127                ip_net: Ipv4Net::new(Ipv4Addr::UNSPECIFIED, 0).expect("checked"),
128                port: 0,
129                is_required: true,
130                is_default: false,
131            },
132            is_user_defined: false,
133        }
134    }
135
136    /// Configures a default IPv6 transport, listening on `[::]:0`.
137    #[cfg(not(wasm_browser))]
138    pub(crate) fn default_ipv6() -> Self {
139        use ipnet::Ipv6Net;
140
141        Self::Ip {
142            config: ip::Config::V6 {
143                ip_net: Ipv6Net::new(Ipv6Addr::UNSPECIFIED, 0).expect("checked"),
144                scope_id: 0,
145                port: 0,
146                is_required: false,
147                is_default: false,
148            },
149            is_user_defined: false,
150        }
151    }
152
153    /// Is this a default IPv4 configuration
154    #[cfg(not(wasm_browser))]
155    pub(crate) fn is_ipv4_default(&self) -> bool {
156        match self {
157            Self::Ip { config, .. } => config.is_default() && config.is_ipv4(),
158            _ => false,
159        }
160    }
161
162    /// Is this a default IPv6 configuration
163    #[cfg(not(wasm_browser))]
164    pub(crate) fn is_ipv6_default(&self) -> bool {
165        match self {
166            Self::Ip { config, .. } => config.is_default() && config.is_ipv6(),
167            _ => false,
168        }
169    }
170
171    /// Is this configuration set by the user.
172    pub(crate) fn is_user_defined(&self) -> bool {
173        match self {
174            #[cfg(not(wasm_browser))]
175            Self::Ip {
176                is_user_defined, ..
177            } => *is_user_defined,
178            Self::Relay {
179                is_user_defined, ..
180            } => *is_user_defined,
181            Self::Custom(_) => true,
182        }
183    }
184}
185
186impl Transports {
187    /// Binds the  transports.
188    pub(crate) fn bind(
189        configs: &[TransportConfig],
190        relay_actor_config: RelayActorConfig,
191        metrics: &EndpointMetrics,
192        shutdown_token: CancellationToken,
193    ) -> io::Result<Self> {
194        #[cfg(not(wasm_browser))]
195        let ip_configs = {
196            let mut ip_configs = Vec::new();
197
198            // user defined overrides defaults
199            let has_ipv4_default = configs
200                .iter()
201                .any(|t| t.is_ipv4_default() && t.is_user_defined());
202            let has_ipv6_default = configs
203                .iter()
204                .any(|t| t.is_ipv6_default() && t.is_user_defined());
205            for config in configs {
206                if let TransportConfig::Ip {
207                    config,
208                    is_user_defined,
209                } = config
210                {
211                    if !is_user_defined
212                        && (config.is_ipv4() && has_ipv4_default
213                            || config.is_ipv6() && has_ipv6_default)
214                    {
215                        continue;
216                    }
217                    ip_configs.push(*config);
218                }
219            }
220            ip_configs
221        };
222        #[cfg(not(wasm_browser))]
223        let ip = IpTransports::bind(ip_configs.into_iter(), metrics)?;
224
225        let relay = configs
226            .iter()
227            .filter(|t| matches!(t, TransportConfig::Relay { .. }))
228            .map(|_c| RelayTransport::new(relay_actor_config.clone(), shutdown_token.child_token()))
229            .collect();
230
231        let mut custom = Vec::new();
232        for config in configs.iter().filter_map(|t| {
233            if let TransportConfig::Custom(config) = t {
234                Some(config)
235            } else {
236                None
237            }
238        }) {
239            let transport = config.bind()?;
240            custom.push(transport);
241        }
242
243        Ok(Self {
244            #[cfg(not(wasm_browser))]
245            ip,
246            relay,
247            custom,
248            poll_recv_counter: Default::default(),
249            recv_infos: Default::default(),
250            consecutive_total_recv_failures: 0,
251        })
252    }
253
254    pub(crate) fn poll_recv(
255        &mut self,
256        cx: &mut Context,
257        bufs: &mut [io::IoSliceMut<'_>],
258        metas: &mut [noq_udp::RecvMeta],
259        sock: &Socket,
260    ) -> Poll<io::Result<usize>> {
261        assert_eq!(bufs.len(), metas.len(), "non matching bufs & metas");
262        assert!(bufs.len() <= noq_udp::BATCH_SIZE, "too many buffers");
263        if sock.is_closed() {
264            return Poll::Pending;
265        }
266
267        match self.inner_poll_recv(cx, bufs, metas)? {
268            Poll::Pending => Poll::Pending,
269            Poll::Ready(0) => Poll::Ready(Ok(0)),
270            Poll::Ready(n) => {
271                sock.process_datagrams(&mut bufs[..n], &mut metas[..n], &self.recv_infos[..n]);
272                Poll::Ready(Ok(n))
273            }
274        }
275    }
276
277    /// Tries to recv data, on all available transports.
278    fn inner_poll_recv(
279        &mut self,
280        cx: &mut Context,
281        bufs: &mut [IoSliceMut<'_>],
282        metas: &mut [noq_udp::RecvMeta],
283    ) -> Poll<io::Result<usize>> {
284        assert_eq!(bufs.len(), metas.len(), "non matching bufs & metas");
285
286        let mut total_polled = 0;
287        let mut total_errors = 0;
288        let mut return_ready = false;
289
290        macro_rules! poll_transport {
291            ($transport:expr) => {
292                total_polled += 1;
293                match $transport.poll_recv(cx, bufs, metas, &mut self.recv_infos) {
294                    Poll::Pending => {}
295                    Poll::Ready(Ok(0)) => {
296                        return_ready = true;
297                    }
298                    Poll::Ready(Ok(n)) => {
299                        // Once a transport has data ready, we return directly.
300                        self.consecutive_total_recv_failures = 0;
301                        return Poll::Ready(Ok(n));
302                    }
303                    Poll::Ready(Err(err)) => {
304                        // We don't set `has_poll_ready` to `true` here, because if we did,
305                        // a single always-failing transport would put us into a hot loop
306                        // where `poll_recv` would be called right away again and again even if
307                        // the non-failing transports are all pending.
308                        total_errors += 1;
309                        debug!(transport = %$transport, "recv error: {err:#}");
310                    }
311                }
312            };
313        }
314
315        // To improve fairness, every other call reverses the ordering of polling.
316        self.poll_recv_counter = self.poll_recv_counter.wrapping_add(1);
317        let counter = self.poll_recv_counter;
318        if counter.is_multiple_of(2) {
319            #[cfg(not(wasm_browser))]
320            for transport in self.ip.iter_mut() {
321                poll_transport!(transport);
322            }
323            for transport in self.relay.iter_mut() {
324                poll_transport!(transport);
325            }
326            for transport in self.custom.iter_mut() {
327                poll_transport!(transport);
328            }
329        } else {
330            for transport in self.custom.iter_mut().rev() {
331                poll_transport!(transport);
332            }
333            for transport in self.relay.iter_mut().rev() {
334                poll_transport!(transport);
335            }
336            #[cfg(not(wasm_browser))]
337            for transport in self.ip.iter_mut() {
338                poll_transport!(transport);
339            }
340        }
341
342        if total_polled == total_errors {
343            // All transports errored.
344            self.consecutive_total_recv_failures += 1;
345            debug!(
346                "All transports failed to receive ({} remaining)",
347                MAX_CONSECUTIVE_RECV_ERRORS.wrapping_sub(self.consecutive_total_recv_failures)
348            );
349            if self.consecutive_total_recv_failures >= MAX_CONSECUTIVE_RECV_ERRORS {
350                warn!("All transports failed to receive. QUIC endpoint will be shutdown.");
351                Poll::Ready(Err(io::Error::new(
352                    io::ErrorKind::NetworkDown,
353                    "All transports failed to receive",
354                )))
355            } else {
356                Poll::Ready(Ok(0))
357            }
358        } else {
359            // At least one transport is pending or returned Ok(0).
360            self.consecutive_total_recv_failures = 0;
361            if return_ready {
362                Poll::Ready(Ok(0))
363            } else {
364                Poll::Pending
365            }
366        }
367    }
368
369    /// Returns a list of all currently known local addresses.
370    ///
371    /// For IP based transports this is the [`SocketAddr`] of the socket,
372    /// for relay transports, this is the home relay.
373    pub(crate) fn local_addrs(&self) -> Vec<Addr> {
374        self.local_addrs_watch().get()
375    }
376
377    pub(super) fn home_relay_watch(&self) -> HomeRelayWatcher {
378        n0_watcher::Join::new(self.relay.iter().map(|t| t.my_relay_status()))
379            .map(|v| v.into_iter().flatten().collect())
380    }
381
382    #[cfg(not(wasm_browser))]
383    /// Watch for all currently known local addresses, including IP based transports.
384    pub(crate) fn local_addrs_watch(&self) -> LocalAddrsWatch {
385        let ips = n0_watcher::Join::new(self.ip.iter().map(|t| t.local_addr_watch()));
386        let relays = n0_watcher::Join::new(self.relay.iter().map(|t| t.local_addr_watch()));
387        let custom = n0_watcher::Join::new(self.custom.iter().map(|t| t.watch_local_addrs()));
388
389        ips.or(custom).or(relays).map(|((ips, custom), relays)| {
390            let ips = ips.into_iter().map(Addr::from);
391            let custom = custom.into_iter().flatten().map(Addr::from);
392            let relays = relays
393                .into_iter()
394                .flatten()
395                .map(|(relay_url, endpoint_id)| Addr::Relay(relay_url, endpoint_id));
396            ips.chain(custom).chain(relays).collect()
397        })
398    }
399
400    #[cfg(wasm_browser)]
401    /// Watch for all currently known local addresses, excluding IP based transports.
402    pub(crate) fn local_addrs_watch(&self) -> LocalAddrsWatch {
403        let relays = n0_watcher::Join::new(self.relay.iter().map(|t| t.local_addr_watch()));
404        let custom = n0_watcher::Join::new(self.custom.iter().map(|t| t.watch_local_addrs()));
405        custom.or(relays).map(|(custom, relays)| {
406            let custom = custom.into_iter().flatten().map(Addr::from);
407            let relays = relays
408                .into_iter()
409                .flatten()
410                .map(|(relay_url, endpoint_id)| Addr::Relay(relay_url, endpoint_id));
411            custom.chain(relays).collect()
412        })
413    }
414
415    /// Returns the bound addresses for IP based transports
416    #[cfg(not(wasm_browser))]
417    pub(crate) fn ip_bind_addrs(&self) -> Vec<SocketAddr> {
418        self.ip.iter().map(|t| t.bind_addr()).collect()
419    }
420
421    #[cfg(not(wasm_browser))]
422    pub(crate) fn max_transmit_segments(&self) -> NonZeroUsize {
423        let ip = self.ip.iter().map(|t| t.max_transmit_segments());
424        let custom = self.custom.iter().map(|t| t.max_transmit_segments());
425        ip.chain(custom).min().unwrap_or(NonZeroUsize::MIN)
426    }
427
428    #[cfg(wasm_browser)]
429    pub(crate) fn max_transmit_segments(&self) -> NonZeroUsize {
430        self.custom
431            .iter()
432            .map(|t| t.max_transmit_segments())
433            .min()
434            .unwrap_or(NonZeroUsize::MIN)
435    }
436
437    #[cfg(not(wasm_browser))]
438    pub(crate) fn max_receive_segments(&self) -> NonZeroUsize {
439        // `max_receive_segments` controls the size of the `RecvMeta` buffer
440        // that noq creates. Having buffers slightly bigger than necessary
441        // isn't terrible, and makes sure a single socket can read the maximum
442        // amount with a single poll. We considered adding these numbers instead,
443        // but we never get data from both sockets at the same time in `poll_recv`
444        // and it's impossible and unnecessary to be refactored that way.
445
446        let res = self.ip.iter().map(|t| t.max_receive_segments()).max();
447        res.unwrap_or(NonZeroUsize::MIN)
448    }
449
450    #[cfg(wasm_browser)]
451    pub(crate) fn max_receive_segments(&self) -> NonZeroUsize {
452        NonZeroUsize::MIN
453    }
454
455    #[cfg(not(wasm_browser))]
456    pub(crate) fn may_fragment(&self) -> bool {
457        self.ip.iter().any(|t| t.may_fragment())
458    }
459
460    #[cfg(wasm_browser)]
461    pub(crate) fn may_fragment(&self) -> bool {
462        false
463    }
464
465    pub(crate) fn create_sender(&self) -> TransportsSender {
466        #[cfg(not(wasm_browser))]
467        let ip = self.ip.create_sender();
468
469        let relay = self.relay.iter().map(|t| t.create_sender()).collect();
470        let custom = self.custom.iter().map(|t| t.create_sender()).collect();
471        let max_transmit_segments = self.max_transmit_segments();
472
473        TransportsSender {
474            #[cfg(not(wasm_browser))]
475            ip,
476            relay,
477            custom,
478            max_transmit_segments,
479        }
480    }
481
482    /// Handles potential changes to the underlying network conditions.
483    pub(crate) fn create_network_change_sender(&self) -> NetworkChangeSender {
484        NetworkChangeSender {
485            #[cfg(not(wasm_browser))]
486            ip: self
487                .ip
488                .iter()
489                .map(|t| t.create_network_change_sender())
490                .collect(),
491            relay: self
492                .relay
493                .iter()
494                .map(|t| t.create_network_change_sender())
495                .collect(),
496        }
497    }
498}
499
500#[derive(Debug)]
501pub(crate) struct NetworkChangeSender {
502    #[cfg(not(wasm_browser))]
503    ip: Vec<IpNetworkChangeSender>,
504    relay: Vec<RelayNetworkChangeSender>,
505}
506
507impl NetworkChangeSender {
508    pub(crate) fn on_network_change(&self, report: &Report) {
509        #[cfg(not(wasm_browser))]
510        for ip in &self.ip {
511            ip.on_network_change(report);
512        }
513
514        for relay in &self.relay {
515            relay.on_network_change(report);
516        }
517    }
518
519    /// Triggers an immediate relay connection health check after a network change.
520    ///
521    /// Uses RTT-based timeout for faster detection of broken connections.
522    pub(crate) fn check_relay_connection(&self) {
523        for relay in &self.relay {
524            relay.check_connection_after_network_change();
525        }
526    }
527
528    /// Rebinds underlying connections, if necessary.
529    pub(crate) fn rebind(&self) -> std::io::Result<()> {
530        let mut res = Ok(());
531
532        #[cfg(not(wasm_browser))]
533        for transport in &self.ip {
534            if let Err(err) = transport.rebind() {
535                warn!("failed to rebind {:?}", err);
536                res = Err(err);
537            }
538        }
539
540        for transport in &self.relay {
541            if let Err(err) = transport.rebind() {
542                warn!("failed to rebind {:?}", err);
543                res = Err(err);
544            }
545        }
546        res
547    }
548}
549
550/// An outgoing packet
551#[derive(Debug, Clone)]
552#[cfg_attr(not(feature = "unstable-custom-transports"), allow(unreachable_pub))]
553pub struct Transmit<'a> {
554    pub(crate) ecn: Option<noq_udp::EcnCodepoint>,
555    /// Packet contents
556    pub contents: &'a [u8],
557    /// Optional segment size for GSO
558    pub segment_size: Option<usize>,
559}
560
561impl<'a> Transmit<'a> {
562    fn datagram_count(&self) -> usize {
563        match self.segment_size {
564            None => 1,
565            Some(size) => self.contents.len().div_ceil(size),
566        }
567    }
568}
569
570/// An outgoing packet that can be sent across channels.
571#[derive(Debug, Clone)]
572pub(crate) struct OwnedTransmit {
573    pub(crate) ecn: Option<noq_udp::EcnCodepoint>,
574    pub(crate) contents: Bytes,
575    pub(crate) segment_size: Option<usize>,
576}
577
578impl From<&noq_udp::Transmit<'_>> for OwnedTransmit {
579    fn from(source: &noq_udp::Transmit<'_>) -> Self {
580        Self {
581            ecn: source.ecn,
582            contents: Bytes::copy_from_slice(source.contents),
583            segment_size: source.segment_size,
584        }
585    }
586}
587
588/// Transports address.
589#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
590pub enum Addr {
591    /// An IP address, should always be stored in its canonical form.
592    Ip(SocketAddr),
593    /// A relay address.
594    Relay(RelayUrl, EndpointId),
595    /// A custom transport address.
596    Custom(CustomAddr),
597}
598
599impl fmt::Debug for Addr {
600    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
601        match self {
602            Addr::Ip(addr) => write!(f, "Ip({addr})"),
603            Addr::Relay(url, node_id) => write!(f, "Relay({url}, {})", node_id.fmt_short()),
604            Addr::Custom(custom_addr) => write!(f, "Custom({custom_addr:?})"),
605        }
606    }
607}
608
609/// Per-packet recv data filled in by transports during [`poll_recv`][CustomEndpoint::poll_recv].
610///
611/// This carries the bits of [`noq_udp::RecvMeta`] that custom transports
612/// can't express through `RecvMeta` itself: the remote address as a
613/// [`CustomAddr`] and, optionally, the local custom address that received
614/// the packet. For IP transports the kernel populates `RecvMeta` directly;
615/// for relays the local URL is the remote's relay URL — so for them this
616/// struct is filled in only with the remote variant.
617///
618/// Custom transport authors construct values via [`RecvInfo::new`], which
619/// only accepts [`CustomAddr`].
620#[cfg_attr(not(feature = "unstable-custom-transports"), allow(unreachable_pub))]
621#[derive(Clone, Debug, Default)]
622pub struct RecvInfo {
623    remote: Addr,
624    local: Option<CustomAddr>,
625}
626
627impl RecvInfo {
628    /// Creates a [`RecvInfo`] from an internal [`Addr`], with no local custom
629    /// address. Used by IP and relay recv paths.
630    pub(crate) fn from_addr(remote: Addr) -> Self {
631        Self {
632            remote,
633            local: None,
634        }
635    }
636
637    pub(crate) fn remote(&self) -> &Addr {
638        &self.remote
639    }
640
641    pub(crate) fn local(&self) -> Option<&CustomAddr> {
642        self.local.as_ref()
643    }
644}
645
646#[cfg(feature = "unstable-custom-transports")]
647impl RecvInfo {
648    /// Creates a new [`RecvInfo`] for an incoming packet on a custom transport.
649    ///
650    /// `remote` is the remote custom address. `local` is the local custom
651    /// address that received this packet, if the transport can identify it;
652    /// pass `None` otherwise.
653    pub fn new(remote: CustomAddr, local: Option<CustomAddr>) -> Self {
654        Self {
655            remote: Addr::Custom(remote),
656            local,
657        }
658    }
659}
660
661impl Default for Addr {
662    fn default() -> Self {
663        Self::Ip(SocketAddr::V6(SocketAddrV6::new(
664            Ipv6Addr::UNSPECIFIED,
665            0,
666            0,
667            0,
668        )))
669    }
670}
671
672impl From<SocketAddr> for Addr {
673    fn from(value: SocketAddr) -> Self {
674        match value {
675            SocketAddr::V4(_) => Self::Ip(value),
676            SocketAddr::V6(addr) => {
677                Self::Ip(SocketAddr::new(addr.ip().to_canonical(), addr.port()))
678            }
679        }
680    }
681}
682
683impl From<&SocketAddr> for Addr {
684    fn from(value: &SocketAddr) -> Self {
685        match value {
686            SocketAddr::V4(_) => Self::Ip(*value),
687            SocketAddr::V6(addr) => {
688                Self::Ip(SocketAddr::new(addr.ip().to_canonical(), addr.port()))
689            }
690        }
691    }
692}
693
694impl From<CustomAddr> for Addr {
695    fn from(value: CustomAddr) -> Self {
696        Self::Custom(value)
697    }
698}
699
700impl From<(RelayUrl, EndpointId)> for Addr {
701    fn from(value: (RelayUrl, EndpointId)) -> Self {
702        Self::Relay(value.0, value.1)
703    }
704}
705
706impl From<Addr> for TransportAddr {
707    fn from(value: Addr) -> Self {
708        match value {
709            Addr::Ip(addr) => TransportAddr::Ip(addr),
710            Addr::Relay(url, _) => TransportAddr::Relay(url),
711            Addr::Custom(addr) => TransportAddr::Custom(addr),
712        }
713    }
714}
715
716impl Addr {
717    pub(crate) fn is_relay(&self) -> bool {
718        matches!(self, Self::Relay(..))
719    }
720
721    /// Returns `None` if not an `Ip`.
722    pub(crate) fn into_socket_addr(self) -> Option<SocketAddr> {
723        match self {
724            Self::Ip(ip) => Some(ip),
725            Self::Relay(..) => None,
726            Self::Custom(_) => None,
727        }
728    }
729}
730
731/// The local address of a network path.
732#[derive(Debug, Clone, PartialEq, Eq, Hash)]
733#[non_exhaustive]
734pub enum LocalTransportAddr {
735    /// The local IP.
736    ///
737    /// This is almost always present, only some very old operating systems do not support
738    /// it.
739    Ip(Option<IpAddr>),
740    /// The relay over which this network path is connected.
741    Relay(RelayUrl),
742    /// The local custom address, if the transport reports one.
743    Custom(Option<iroh_base::CustomAddr>),
744}
745
746impl LocalTransportAddr {
747    /// Converts a local address from noq into a [`LocalTransportAddr`].
748    ///
749    /// This also needs the `remote_addr`, because currently the meaning of the local_ip as returned
750    /// from noq depends on the kind of network path, which we can gather from the remote address.
751    ///
752    /// The meaning of the local IP is a bit particular:
753    ///
754    /// * For IP transports, it is the address of the local socket.
755    /// * For relay transports, we never set the local_ip in the recv meta.
756    ///   We take the relay URL of the remote address here instead.
757    /// * For custom transports, the custom transport implementation can set a [`CustomAddr`]
758    ///   through [`RecvInfo`], which is passed as a mapped address to noq. So we convert it
759    ///   back into the [`CustomAddr`] here.
760    pub(super) fn from_noq_local_ip(
761        noq_local_ip: Option<IpAddr>,
762        remote_addr: &Addr,
763        custom_mapped_addrs: &AddrMap<CustomAddr, CustomMappedAddr>,
764    ) -> Self {
765        match &remote_addr {
766            // If the remote is a relay, noq_local_ip will be unset because we never set it for relay transports.
767            // We return a [`LocalTransportAddr`] with the relay URL.
768            Addr::Relay(url, _endpoint_id) => LocalTransportAddr::Relay(url.clone()),
769            // For IP transports, the local_ip as reported from noq is the interface IP (umapped), if known.
770            Addr::Ip(_) => LocalTransportAddr::Ip(noq_local_ip),
771            // For custom transports, the custom transport implementation can set a `CustomAddr` in `RecvInfo`.
772            // The custom addr is converted to a mapped address in `super::Socket::process_datagrams`.
773            // We convert back to a `CustomAddr` here.
774            Addr::Custom(_) => {
775                let addr = noq_local_ip
776                    .and_then(|ip_addr| CustomMappedAddr::try_from(ip_addr).ok())
777                    .and_then(|custom_mapped_addr| custom_mapped_addrs.lookup(&custom_mapped_addr));
778                LocalTransportAddr::Custom(addr)
779            }
780        }
781    }
782}
783
784/// The kind of a transport address, used for configuring bias.
785#[derive(Debug, Clone, PartialEq, Eq, Hash)]
786#[cfg_attr(not(feature = "unstable-custom-transports"), allow(unreachable_pub))]
787pub enum AddrKind {
788    /// An IPv4 address.
789    IpV4,
790    /// An IPv6 address.
791    IpV6,
792    /// A relay address.
793    Relay,
794    /// A custom transport address with the given id.
795    Custom(u64),
796}
797
798impl PartialEq<TransportAddr> for Addr {
799    fn eq(&self, other: &TransportAddr) -> bool {
800        match self {
801            Addr::Ip(socket_addr) => {
802                matches!(other, TransportAddr::Ip(a) if a == socket_addr)
803            }
804            Addr::Relay(relay_url, _) => {
805                matches!(other, TransportAddr::Relay(a) if a == relay_url)
806            }
807            Addr::Custom(custom_addr) => {
808                matches!(other, TransportAddr::Custom(a) if a == custom_addr)
809            }
810        }
811    }
812}
813
814/// Identifies a network path by the combination of remote and local addresses.
815///
816/// The meaning of the local address is a bit particular:
817/// * For IP transports it is the interface IP, if known.
818/// * For custom transports it is a custom transport address, if the transport implementation reports one.
819/// * For relay transports there is no separate local address.
820#[derive(Debug, Clone, PartialEq, Eq, Hash)]
821#[cfg_attr(not(feature = "unstable-custom-transports"), allow(unreachable_pub))]
822pub enum FourTuple {
823    /// A path over an IP transport.
824    Ip {
825        /// The remote socket address.
826        remote: SocketAddr,
827        /// The local interface IP, if the OS reported one.
828        local: Option<IpAddr>,
829    },
830    /// A path over a relay transport.
831    Relay {
832        /// The URL of the relay server carrying this path.
833        url: RelayUrl,
834        /// The remote endpoint reached through the relay.
835        endpoint_id: EndpointId,
836    },
837    /// A path over a custom transport.
838    Custom {
839        /// The remote custom transport address.
840        remote: CustomAddr,
841        /// The local custom transport address, if the transport reports one.
842        local: Option<CustomAddr>,
843    },
844}
845
846#[cfg_attr(not(feature = "unstable-custom-transports"), allow(unreachable_pub))]
847impl FourTuple {
848    /// Creates a four-tuple from a remote address, with no known local address.
849    pub fn from_remote(remote: Addr) -> Self {
850        match remote {
851            Addr::Ip(remote) => Self::Ip {
852                remote,
853                local: None,
854            },
855            Addr::Relay(url, endpoint_id) => Self::Relay { url, endpoint_id },
856            Addr::Custom(remote) => Self::Custom {
857                remote,
858                local: None,
859            },
860        }
861    }
862
863    /// Creates a four-tuple from a remote and a local transport address.
864    ///
865    /// The variant is determined by `remote`. The `local` address is retained only when
866    /// it matches that variant. A mismatched `local` is dropped, which cannot happen for
867    /// values derived together from the same network path.
868    pub fn new(remote: Addr, local: LocalTransportAddr) -> Self {
869        match remote {
870            Addr::Ip(remote) => Self::Ip {
871                remote,
872                local: match local {
873                    LocalTransportAddr::Ip(local) => local,
874                    _ => None,
875                },
876            },
877            Addr::Relay(url, endpoint_id) => Self::Relay { url, endpoint_id },
878            Addr::Custom(remote) => Self::Custom {
879                remote,
880                local: match local {
881                    LocalTransportAddr::Custom(local) => local,
882                    _ => None,
883                },
884            },
885        }
886    }
887
888    /// Returns the remote transport address.
889    pub fn remote(&self) -> Addr {
890        match self {
891            Self::Ip { remote, .. } => Addr::Ip(*remote),
892            Self::Relay { url, endpoint_id } => Addr::Relay(url.clone(), *endpoint_id),
893            Self::Custom { remote, .. } => Addr::Custom(remote.clone()),
894        }
895    }
896
897    /// Returns the local transport address.
898    pub fn local(&self) -> LocalTransportAddr {
899        match self {
900            Self::Ip { local, .. } => LocalTransportAddr::Ip(*local),
901            Self::Relay { url, .. } => LocalTransportAddr::Relay(url.clone()),
902            Self::Custom { local, .. } => LocalTransportAddr::Custom(local.clone()),
903        }
904    }
905
906    /// Returns `true` if the remote is an IP address.
907    pub fn is_ip(&self) -> bool {
908        matches!(self, Self::Ip { .. })
909    }
910
911    /// Returns `true` if the remote is a relay address.
912    pub fn is_relay(&self) -> bool {
913        matches!(self, Self::Relay { .. })
914    }
915
916    /// Returns the kind of address, for configuring bias.
917    pub fn addr_kind(&self) -> AddrKind {
918        match self {
919            Self::Ip { remote, .. } => match remote {
920                SocketAddr::V4(_) => AddrKind::IpV4,
921                SocketAddr::V6(_) => AddrKind::IpV6,
922            },
923            Self::Relay { .. } => AddrKind::Relay,
924            Self::Custom { remote, .. } => AddrKind::Custom(remote.id()),
925        }
926    }
927}
928
929impl fmt::Display for FourTuple {
930    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
931        match self {
932            FourTuple::Ip { remote, local } => {
933                if let Some(local) = local {
934                    write!(f, "Ip({local}->{remote})")
935                } else {
936                    write!(f, "Ip({remote})")
937                }
938            }
939            FourTuple::Relay { url, endpoint_id } => {
940                write!(f, "Relay({url}, {})", endpoint_id.fmt_short())
941            }
942            FourTuple::Custom { remote, local } => {
943                if let Some(local) = local {
944                    write!(f, "Custom({local}->{remote})")
945                } else {
946                    write!(f, "Custom({remote})")
947                }
948            }
949        }
950    }
951}
952
953/// A sender that sends to all our transports.
954#[derive(Debug, Clone)]
955pub(crate) struct TransportsSender {
956    #[cfg(not(wasm_browser))]
957    ip: IpTransportsSender,
958    relay: Vec<RelaySender>,
959    custom: Vec<Arc<dyn CustomSender>>,
960    max_transmit_segments: NonZeroUsize,
961}
962
963impl TransportsSender {
964    #[instrument(name = "poll_send", skip(self, cx, transmit), fields(len = transmit.contents.len()))]
965    pub(crate) fn poll_send(
966        mut self: Pin<&mut Self>,
967        cx: &mut std::task::Context,
968        network_path: &FourTuple,
969        transmit: &Transmit<'_>,
970    ) -> Poll<io::Result<()>> {
971        match network_path {
972            #[cfg(wasm_browser)]
973            FourTuple::Ip { .. } => {
974                return Poll::Ready(Err(io::Error::other("IP is unsupported in browser")));
975            }
976            #[cfg(not(wasm_browser))]
977            FourTuple::Ip {
978                remote: dst_addr,
979                local: src,
980            } => match dst_addr {
981                SocketAddr::V4(_) => {
982                    if let Some(sender) = self
983                        .ip
984                        .v4_iter_mut()
985                        .find(|s| s.is_valid_send_addr(*src, dst_addr))
986                    {
987                        return Pin::new(sender).poll_send(cx, *dst_addr, *src, transmit);
988                    }
989                    if let Some(sender) = self.ip.v4_default_mut()
990                        && sender.is_valid_default_addr(*src, dst_addr)
991                    {
992                        return Pin::new(sender).poll_send(cx, *dst_addr, *src, transmit);
993                    }
994                }
995                SocketAddr::V6(_) => {
996                    if let Some(sender) = self
997                        .ip
998                        .v6_iter_mut()
999                        .find(|s| s.is_valid_send_addr(*src, dst_addr))
1000                    {
1001                        return Pin::new(sender).poll_send(cx, *dst_addr, *src, transmit);
1002                    }
1003                    if let Some(sender) = self.ip.v6_default_mut()
1004                        && sender.is_valid_default_addr(*src, dst_addr)
1005                    {
1006                        return Pin::new(sender).poll_send(cx, *dst_addr, *src, transmit);
1007                    }
1008                }
1009            },
1010            FourTuple::Relay { url, endpoint_id } => {
1011                let mut has_valid_sender = false;
1012                for sender in self
1013                    .relay
1014                    .iter_mut()
1015                    .filter(|s| s.is_valid_send_addr(url, endpoint_id))
1016                {
1017                    has_valid_sender = true;
1018                    match sender.poll_send(cx, url.clone(), *endpoint_id, transmit) {
1019                        Poll::Pending => {}
1020                        Poll::Ready(res) => return Poll::Ready(res),
1021                    }
1022                }
1023                if has_valid_sender {
1024                    return Poll::Pending;
1025                }
1026            }
1027            FourTuple::Custom { remote, local } => {
1028                for sender in &mut self.custom {
1029                    if sender.is_valid_send_addr(remote) {
1030                        match sender.poll_send(cx, remote, local.as_ref(), transmit) {
1031                            Poll::Pending => {}
1032                            Poll::Ready(res) => return Poll::Ready(res),
1033                        }
1034                    }
1035                }
1036            }
1037        }
1038
1039        // We "blackhole" data that we have not found any usable transport for on
1040        // to make sure the QUIC stack picks up that currently this data does not arrive.
1041        trace!(%network_path, "no valid transport available");
1042        Poll::Ready(Ok(()))
1043    }
1044}
1045
1046/// A [`Transports`] that works with [`MultipathMappedAddr`]s and their IPv6 representation.
1047///
1048/// The [`MultipathMappedAddr`]s have an IPv6 representation that Noq uses.  This struct
1049/// knows about these and maps them back to the transport [`Addr`]s used by the wrapped
1050/// [`Transports`].
1051#[derive(Debug)]
1052pub(crate) struct Transport {
1053    sock: Arc<Socket>,
1054    transports: Transports,
1055}
1056
1057impl Transport {
1058    pub(crate) fn new(sock: Arc<Socket>, transports: Transports) -> Self {
1059        Self { sock, transports }
1060    }
1061}
1062
1063impl noq::AsyncUdpSocket for Transport {
1064    fn create_sender(&self) -> Pin<Box<dyn noq::UdpSender>> {
1065        Box::pin(Sender {
1066            sock: self.sock.clone(),
1067            sender: self.transports.create_sender(),
1068        })
1069    }
1070
1071    fn poll_recv(
1072        &mut self,
1073        cx: &mut Context,
1074        bufs: &mut [IoSliceMut<'_>],
1075        meta: &mut [noq_udp::RecvMeta],
1076    ) -> Poll<io::Result<usize>> {
1077        self.transports.poll_recv(cx, bufs, meta, &self.sock)
1078    }
1079
1080    #[cfg(not(wasm_browser))]
1081    fn local_addr(&self) -> io::Result<SocketAddr> {
1082        let local_addrs = self.transports.local_addrs();
1083        let addrs: Vec<_> = local_addrs
1084            .into_iter()
1085            .map(|addr| {
1086                use crate::socket::mapped_addrs::DEFAULT_FAKE_ADDR;
1087
1088                match addr {
1089                    Addr::Ip(addr) => addr,
1090                    Addr::Relay(..) => DEFAULT_FAKE_ADDR.into(),
1091                    Addr::Custom(_) => DEFAULT_FAKE_ADDR.into(),
1092                }
1093            })
1094            .collect();
1095
1096        if let Some(addr) = addrs.iter().find(|addr| addr.is_ipv6()) {
1097            return Ok(*addr);
1098        }
1099        if let Some(SocketAddr::V4(addr)) = addrs.first() {
1100            // Pretend to be IPv6, because our `MappedAddr`s need to be IPv6.
1101            let ip = addr.ip().to_ipv6_mapped().into();
1102            return Ok(SocketAddr::new(ip, addr.port()));
1103        }
1104
1105        if !self.transports.relay.is_empty() {
1106            // pretend we have an address to make sure things are not too sad during startup
1107            use crate::socket::mapped_addrs::DEFAULT_FAKE_ADDR;
1108
1109            return Ok(DEFAULT_FAKE_ADDR.into());
1110        }
1111        if !self.transports.custom.is_empty() {
1112            // pretend we have an address to make sure things are not too sad during startup
1113            use crate::socket::mapped_addrs::DEFAULT_FAKE_ADDR;
1114
1115            return Ok(DEFAULT_FAKE_ADDR.into());
1116        }
1117        Err(io::Error::other("no valid address available"))
1118    }
1119
1120    #[cfg(wasm_browser)]
1121    fn local_addr(&self) -> io::Result<SocketAddr> {
1122        // Again, we need to pretend we're IPv6, because of our `MappedAddr`s.
1123        Ok(SocketAddr::new(std::net::Ipv6Addr::LOCALHOST.into(), 0))
1124    }
1125
1126    fn max_receive_segments(&self) -> NonZeroUsize {
1127        self.transports.max_receive_segments()
1128    }
1129
1130    fn may_fragment(&self) -> bool {
1131        self.transports.may_fragment()
1132    }
1133}
1134
1135/// A sender for [`Transport`].
1136///
1137/// This is special in that it handles [`MultipathMappedAddr::Mixed`] by delegating to the
1138/// [`Socket`] which expands it back to one or more [`Addr`]s and sends it
1139/// using the underlying [`Transports`].
1140#[derive(Debug)]
1141#[pin_project::pin_project]
1142pub(crate) struct Sender {
1143    sock: Arc<Socket>,
1144    #[pin]
1145    sender: TransportsSender,
1146}
1147
1148impl Sender {
1149    /// Extracts the right [`Addr`] from the [`noq_udp::Transmit`].
1150    ///
1151    /// Because Noq does only know about IP transports we map other transports to private
1152    /// IPv6 Unique Local Address ranges.  This extracts the transport addresses out of the
1153    /// transmit's destination.
1154    fn mapped_addr(&self, transmit: &noq_udp::Transmit) -> io::Result<MultipathMappedAddr> {
1155        if self.sock.is_closed() {
1156            return Err(io::Error::new(
1157                io::ErrorKind::NotConnected,
1158                "connection closed",
1159            ));
1160        }
1161
1162        Ok(MultipathMappedAddr::from(transmit.destination))
1163    }
1164}
1165
1166impl noq::UdpSender for Sender {
1167    fn poll_send(
1168        self: Pin<&mut Self>,
1169        noq_transmit: &noq_udp::Transmit,
1170        cx: &mut Context,
1171    ) -> Poll<io::Result<()>> {
1172        // On errors this methods prefers returning Ok(()) to Noq.  Returning an error
1173        // should only happen if the error is permanent and fatal and it will never be
1174        // possible to send anything again.  Doing so kills the Noq EndpointDriver.  Most
1175        // send errors are intermittent errors, returning Ok(()) in those cases will mean
1176        // Noq eventually considers the packets that had send errors as lost and will try
1177        // and re-send them.
1178        let mapped_addr = self.mapped_addr(noq_transmit)?;
1179
1180        let network_path = match mapped_addr {
1181            MultipathMappedAddr::Mixed(mapped_addr) => {
1182                let Some(endpoint_id) = self.sock.mapped_addrs.endpoint_addrs.lookup(&mapped_addr)
1183                else {
1184                    error!(dst = ?mapped_addr, "unknown NodeIdMappedAddr, dropped transmit");
1185                    return Poll::Ready(Ok(()));
1186                };
1187
1188                // Note we drop the src_ip set in the Noq Transmit.  This is only the
1189                // Initial packet we are sending, so we do not yet have an src address we
1190                // need to respond from.
1191                if let Some(src_ip) = noq_transmit.src_ip {
1192                    warn!(dst = ?mapped_addr, ?src_ip, dst_endpoint = %endpoint_id.fmt_short(),
1193                        "oops, flub didn't think this would happen");
1194                }
1195
1196                match self.sock.try_send_remote_state_msg(
1197                    endpoint_id,
1198                    super::RemoteStateMessage::SendDatagram(
1199                        Box::new(self.sender.clone()),
1200                        OwnedTransmit::from(noq_transmit),
1201                    ),
1202                ) {
1203                    Ok(()) => {
1204                        trace!(dst = ?mapped_addr, dst_endpoint = %endpoint_id.fmt_short(), "sent transmit");
1205                        return Poll::Ready(Ok(()));
1206                    }
1207                    Err(msg) => {
1208                        // We do not want to block the next send which might be on a
1209                        // different transport.  Instead we let Noq handle this as
1210                        // a lost datagram.
1211                        // TODO: Revisit this: we might want to do something better.
1212                        debug!(
1213                            dst = ?mapped_addr,
1214                            dst_endpoint = %endpoint_id.fmt_short(),
1215                            ?msg,
1216                            "RemoteStateActor inbox dropped message"
1217                        );
1218                        return Poll::Ready(Ok(()));
1219                    }
1220                };
1221            }
1222            MultipathMappedAddr::Relay(relay_mapped_addr) => {
1223                match self
1224                    .sock
1225                    .mapped_addrs
1226                    .relay_addrs
1227                    .lookup(&relay_mapped_addr)
1228                {
1229                    Some((url, endpoint_id)) => FourTuple::Relay { url, endpoint_id },
1230                    None => {
1231                        error!("unknown RelayMappedAddr, dropped transmit");
1232                        return Poll::Ready(Ok(()));
1233                    }
1234                }
1235            }
1236            MultipathMappedAddr::Custom(custom_mapped_addr) => {
1237                match self
1238                    .sock
1239                    .mapped_addrs
1240                    .custom_addrs
1241                    .lookup(&custom_mapped_addr)
1242                {
1243                    Some(addr) => {
1244                        let local = noq_transmit
1245                            .src_ip
1246                            .and_then(|ip_addr| CustomMappedAddr::try_from(ip_addr).ok())
1247                            .and_then(|addr| self.sock.mapped_addrs.custom_addrs.lookup(&addr));
1248                        FourTuple::Custom {
1249                            remote: addr,
1250                            local,
1251                        }
1252                    }
1253                    None => {
1254                        error!("unknown CustomMappedAddr, dropped transmit");
1255                        return Poll::Ready(Ok(()));
1256                    }
1257                }
1258            }
1259            MultipathMappedAddr::Ip(socket_addr) => {
1260                // Ensure IPv6 mapped addresses are converted back
1261                let socket_addr =
1262                    SocketAddr::new(socket_addr.ip().to_canonical(), socket_addr.port());
1263                FourTuple::Ip {
1264                    remote: socket_addr,
1265                    local: noq_transmit.src_ip,
1266                }
1267            }
1268        };
1269
1270        let transmit = Transmit {
1271            ecn: noq_transmit.ecn,
1272            contents: noq_transmit.contents,
1273            segment_size: noq_transmit.segment_size,
1274        };
1275        let this = self.project();
1276
1277        match this.sender.poll_send(cx, &network_path, &transmit) {
1278            Poll::Ready(Ok(())) => {
1279                trace!(
1280                    dst = %network_path,
1281                    len = transmit.contents.len(),
1282                    datagram_count = transmit.datagram_count(),
1283                    "sent transmit"
1284                );
1285                Poll::Ready(Ok(()))
1286            }
1287            Poll::Ready(Err(ref err)) => {
1288                debug!(dst=%network_path, "dropped transmit: {err:#}");
1289                Poll::Ready(Ok(()))
1290            }
1291            Poll::Pending => {
1292                // We do not want to block the next send which might be on a
1293                // different transport.  Instead we let Noq handle this as a lost
1294                // datagram.
1295                // TODO: Revisit this: we might want to do something better.
1296                trace!(dst=%network_path, "transport pending, dropped transmit");
1297                Poll::Ready(Ok(()))
1298            }
1299        }
1300    }
1301
1302    fn max_transmit_segments(&self) -> NonZeroUsize {
1303        self.sender.max_transmit_segments
1304    }
1305}
1306
1307#[cfg(test)]
1308mod tests {
1309    use std::sync::{
1310        Arc,
1311        atomic::{AtomicUsize, Ordering},
1312    };
1313
1314    use n0_watcher::Watchable;
1315
1316    use super::*;
1317
1318    impl TransportsSender {
1319        pub(in crate::socket) fn with_bounded_relay(
1320            capacity: usize,
1321            #[cfg(not(wasm_browser))] ip_configs: impl Iterator<Item = IpConfig>,
1322        ) -> (
1323            TransportsSender,
1324            impl futures_util::Stream<Item = ()> + Unpin,
1325        ) {
1326            use futures_util::StreamExt;
1327            let (sender, receiver) = RelaySender::bounded_for_test(capacity);
1328            let sender = TransportsSender {
1329                #[cfg(not(wasm_browser))]
1330                ip: IpTransports::bind(ip_configs, &EndpointMetrics::default())
1331                    .expect("test transports must bind")
1332                    .create_sender(),
1333                relay: vec![sender],
1334                custom: Vec::new(),
1335                max_transmit_segments: NonZeroUsize::new(1).unwrap(),
1336            };
1337            (
1338                sender,
1339                tokio_stream::wrappers::ReceiverStream::new(receiver).map(|_| ()),
1340            )
1341        }
1342    }
1343
1344    const FAIRNESS_SAMPLE_POLLS: usize = 10_000;
1345
1346    #[test]
1347    fn ready_custom_transports_are_polled_fairly() {
1348        // GIVEN: two custom transport lanes that are always ready.
1349        let first_polls = Arc::new(AtomicUsize::new(0));
1350        let second_polls = Arc::new(AtomicUsize::new(0));
1351        let mut transports = custom_only_transports(vec![
1352            ready_custom_endpoint(1, first_polls.clone()),
1353            ready_custom_endpoint(2, second_polls.clone()),
1354        ]);
1355
1356        // WHEN: receive polling runs long enough to exercise both polling orders.
1357        let selected =
1358            sample_ready_custom_transport_selection(&mut transports, FAIRNESS_SAMPLE_POLLS);
1359
1360        let first_selected = selected.iter().filter(|&&id| id == 1).count();
1361        let second_selected = selected.iter().filter(|&&id| id == 2).count();
1362
1363        // THEN: selection and actual polling are split evenly between lanes.
1364        assert_eq!(first_selected, FAIRNESS_SAMPLE_POLLS / 2);
1365        assert_eq!(second_selected, FAIRNESS_SAMPLE_POLLS / 2);
1366        assert_eq!(
1367            first_polls.load(Ordering::Relaxed),
1368            FAIRNESS_SAMPLE_POLLS / 2
1369        );
1370        assert_eq!(
1371            second_polls.load(Ordering::Relaxed),
1372            FAIRNESS_SAMPLE_POLLS / 2
1373        );
1374
1375        // And the lane order alternates from the first poll.
1376        assert_eq!(
1377            selected.iter().take(4).copied().collect::<Vec<_>>(),
1378            vec![2, 1, 2, 1],
1379        );
1380    }
1381
1382    fn custom_only_transports(custom: Vec<Box<dyn CustomEndpoint>>) -> Transports {
1383        let metrics = EndpointMetrics::default();
1384        Transports {
1385            #[cfg(not(wasm_browser))]
1386            ip: ip::IpTransports::bind(std::iter::empty(), &metrics).unwrap(),
1387            relay: Vec::new(),
1388            custom,
1389            poll_recv_counter: 0,
1390            recv_infos: Default::default(),
1391            consecutive_total_recv_failures: 0,
1392        }
1393    }
1394
1395    fn ready_custom_endpoint(id: u8, polls: Arc<AtomicUsize>) -> Box<dyn CustomEndpoint> {
1396        Box::new(ReadyCustomEndpoint {
1397            id,
1398            polls,
1399            local_addr: CustomAddr::from_parts(1, &[id]),
1400            remote_addr: CustomAddr::from_parts(2, &[id]),
1401            local_addr_watch: Watchable::new(vec![CustomAddr::from_parts(1, &[id])]),
1402        })
1403    }
1404
1405    fn sample_ready_custom_transport_selection(
1406        transports: &mut Transports,
1407        polls: usize,
1408    ) -> Vec<u8> {
1409        let mut selected = Vec::with_capacity(polls);
1410        let waker = futures_util::task::noop_waker();
1411        let mut cx = Context::from_waker(&waker);
1412        let mut storage = [0u8; 1];
1413        let mut metas = [noq_udp::RecvMeta::default()];
1414
1415        for _ in 0..polls {
1416            let mut bufs = [IoSliceMut::new(&mut storage)];
1417            let n = match transports.inner_poll_recv(&mut cx, &mut bufs, &mut metas) {
1418                Poll::Ready(Ok(n)) => n,
1419                Poll::Ready(Err(err)) => panic!("custom transport poll failed: {err}"),
1420                Poll::Pending => panic!("ready custom transport returned pending"),
1421            };
1422            assert_eq!(n, 1);
1423            selected.push(storage[0]);
1424            storage[0] = 0;
1425            metas[0] = noq_udp::RecvMeta::default();
1426        }
1427
1428        selected
1429    }
1430
1431    #[derive(Debug)]
1432    struct ReadyCustomEndpoint {
1433        id: u8,
1434        polls: Arc<AtomicUsize>,
1435        local_addr: CustomAddr,
1436        remote_addr: CustomAddr,
1437        local_addr_watch: Watchable<Vec<CustomAddr>>,
1438    }
1439
1440    impl CustomEndpoint for ReadyCustomEndpoint {
1441        fn watch_local_addrs(&self) -> n0_watcher::Direct<Vec<CustomAddr>> {
1442            self.local_addr_watch.watch()
1443        }
1444
1445        fn create_sender(&self) -> Arc<dyn CustomSender> {
1446            Arc::new(NoopCustomSender)
1447        }
1448
1449        fn poll_recv(
1450            &mut self,
1451            _cx: &mut Context,
1452            bufs: &mut [io::IoSliceMut<'_>],
1453            metas: &mut [noq_udp::RecvMeta],
1454            recv_infos: &mut [RecvInfo],
1455        ) -> Poll<io::Result<usize>> {
1456            self.polls.fetch_add(1, Ordering::Relaxed);
1457            bufs[0][0] = self.id;
1458            metas[0].len = 1;
1459            metas[0].stride = 1;
1460            recv_infos[0] = RecvInfo {
1461                remote: Addr::Custom(self.remote_addr.clone()),
1462                local: Some(self.local_addr.clone()),
1463            };
1464            Poll::Ready(Ok(1))
1465        }
1466    }
1467
1468    #[derive(Debug)]
1469    struct NoopCustomSender;
1470
1471    impl CustomSender for NoopCustomSender {
1472        fn is_valid_send_addr(&self, _addr: &CustomAddr) -> bool {
1473            false
1474        }
1475
1476        fn poll_send(
1477            &self,
1478            _cx: &mut Context,
1479            _dst: &CustomAddr,
1480            _src: Option<&CustomAddr>,
1481            _transmit: &Transmit<'_>,
1482        ) -> Poll<io::Result<()>> {
1483            Poll::Ready(Ok(()))
1484        }
1485    }
1486}