From a2d5ccdfe3580673acdea8ac65068497d0cbde86 Mon Sep 17 00:00:00 2001 From: dignifiedquire Date: Wed, 18 Jun 2025 14:06:49 +0000 Subject: [PATCH] deploy: 35e8f3f2d96858fc6c2a04852746eb412d3a0e7a --- pr/3314/docs/iroh/net_report/index.html | 2 +- .../client/enum.ReceivedMessage.html | 8 +- .../iroh_relay/client/enum.SendMessage.html | 4 +- .../client/struct.ClientBuilder.html | 4 +- .../iroh_relay/dns/struct.DnsResolver.html | 8 +- pr/3314/docs/iroh_relay/index.html | 2 +- pr/3314/docs/iroh_relay/node_info/index.html | 10 +- .../iroh_relay/node_info/struct.NodeData.html | 16 +- .../iroh_relay/node_info/struct.NodeInfo.html | 26 +- .../iroh_relay/node_info/trait.NodeIdExt.html | 10 +- .../iroh_relay/server/enum.AccessConfig.html | 6 +- .../docs/iroh_relay/server/struct.Server.html | 4 +- pr/3314/docs/iroh_relay/struct.RelayMap.html | 10 +- pr/3314/docs/iroh_relay/struct.RelayNode.html | 6 +- pr/3314/docs/src/iroh/net_report.rs.html | 2059 +++++++++-------- .../docs/src/iroh/net_report/probes.rs.html | 398 ++-- .../trait.impl/core/convert/trait.From.js | 4 +- .../iter/traits/collect/trait.FromIterator.js | 4 +- 18 files changed, 1242 insertions(+), 1339 deletions(-) diff --git a/pr/3314/docs/iroh/net_report/index.html b/pr/3314/docs/iroh/net_report/index.html index 1254814660..073de53a57 100644 --- a/pr/3314/docs/iroh/net_report/index.html +++ b/pr/3314/docs/iroh/net_report/index.html @@ -1,4 +1,4 @@ -iroh::net_report - Rust

Module net_report

Source
Expand description

Checks the network conditions from the current host.

+iroh::net_report - Rust

Module net_report

Source
Expand description

Checks the network conditions from the current host.

NetReport is responsible for finding out the network conditions of the current host, like whether it is connected to the internet via IPv4 and/or IPv6, what the NAT situation is etc and reachability to the configured relays.

diff --git a/pr/3314/docs/iroh_relay/client/enum.ReceivedMessage.html b/pr/3314/docs/iroh_relay/client/enum.ReceivedMessage.html index 7c862d05b7..4f2e1b3f73 100644 --- a/pr/3314/docs/iroh_relay/client/enum.ReceivedMessage.html +++ b/pr/3314/docs/iroh_relay/client/enum.ReceivedMessage.html @@ -1,9 +1,9 @@ ReceivedMessage in iroh_relay::client - Rust

Enum ReceivedMessage

Source
pub enum ReceivedMessage {
     ReceivedPacket {
-        remote_node_id: NodeId,
+        remote_node_id: NodeId,
         data: Bytes,
     },
-    NodeGone(NodeId),
+    NodeGone(NodeId),
     Ping([u8; 8]),
     Pong([u8; 8]),
     KeepAlive,
@@ -17,9 +17,9 @@
 }
Expand description

The messages received from a framed relay stream.

This is a type-validated version of the Frames on the RelayCodec.

Variants§

§

ReceivedPacket

Represents an incoming packet.

-

Fields

§remote_node_id: NodeId

The NodeId of the packet sender.

+

Fields

§remote_node_id: NodeId

The [NodeId] of the packet sender.

§data: Bytes

The received packet bytes.

-
§

NodeGone(NodeId)

Indicates that the client identified by the underlying public key had previously sent you a +

§

NodeGone(NodeId)

Indicates that the client identified by the underlying public key had previously sent you a packet but has now disconnected from the server.

§

Ping([u8; 8])

Request from a client or server to reply to the other side with a ReceivedMessage::Pong with the given payload.

diff --git a/pr/3314/docs/iroh_relay/client/enum.SendMessage.html b/pr/3314/docs/iroh_relay/client/enum.SendMessage.html index e07368647b..6a3c982bf5 100644 --- a/pr/3314/docs/iroh_relay/client/enum.SendMessage.html +++ b/pr/3314/docs/iroh_relay/client/enum.SendMessage.html @@ -1,9 +1,9 @@ SendMessage in iroh_relay::client - Rust

Enum SendMessage

Source
pub enum SendMessage {
-    SendPacket(NodeId, Bytes),
+    SendPacket(NodeId, Bytes),
     Ping([u8; 8]),
     Pong([u8; 8]),
 }
Expand description

Messages we can send to a relay server.

-

Variants§

§

SendPacket(NodeId, Bytes)

Send a packet of data to the NodeId.

+

Variants§

§

SendPacket(NodeId, Bytes)

Send a packet of data to the [NodeId].

§

Ping([u8; 8])

Sends a ping message to the connected relay server.

§

Pong([u8; 8])

Sends a pong message to the connected relay server.

Trait Implementations§

Source§

impl Debug for SendMessage

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Sink<SendMessage> for Client

Source§

type Error = SendError

The type of value produced by the sink when an error occurs.
Source§

fn poll_ready( diff --git a/pr/3314/docs/iroh_relay/client/struct.ClientBuilder.html b/pr/3314/docs/iroh_relay/client/struct.ClientBuilder.html index 6e63827fbb..53e281c526 100644 --- a/pr/3314/docs/iroh_relay/client/struct.ClientBuilder.html +++ b/pr/3314/docs/iroh_relay/client/struct.ClientBuilder.html @@ -1,7 +1,7 @@ ClientBuilder in iroh_relay::client - Rust

Struct ClientBuilder

Source
pub struct ClientBuilder { /* private fields */ }
Expand description

Build a Client.

Implementations§

Source§

impl ClientBuilder

Source

pub fn new( - url: impl Into<RelayUrl>, - secret_key: SecretKey, + url: impl Into<RelayUrl>, + secret_key: SecretKey, dns_resolver: DnsResolver, ) -> Self

Create a new ClientBuilder

Source

pub fn protocol(self, protocol: Protocol) -> Self

Sets whether to connect to the relay via websockets or not. diff --git a/pr/3314/docs/iroh_relay/dns/struct.DnsResolver.html b/pr/3314/docs/iroh_relay/dns/struct.DnsResolver.html index 5e3f358013..0136952b4c 100644 --- a/pr/3314/docs/iroh_relay/dns/struct.DnsResolver.html +++ b/pr/3314/docs/iroh_relay/dns/struct.DnsResolver.html @@ -68,9 +68,9 @@ at T+0ms, T+200ms and T+300ms. The timeout is applied as stated in summary of all errors otherwise.

Source

pub async fn lookup_node_by_id( &self, - node_id: &NodeId, + node_id: &NodeId, origin: &str, -) -> Result<NodeInfo, LookupError>

Looks up node info by NodeId and origin domain name.

+) -> Result<NodeInfo, LookupError>

Looks up node info by [NodeId] and origin domain name.

To lookup nodes that published their node info to the DNS servers run by n0, pass N0_DNS_NODE_ORIGIN_PROD as origin.

Source

pub async fn lookup_node_by_domain_name( @@ -88,10 +88,10 @@ at T+0ms, T+200ms and T+300ms. The result of the first successful call is return summary of all errors otherwise.

Source

pub async fn lookup_node_by_id_staggered( &self, - node_id: &NodeId, + node_id: &NodeId, origin: &str, delays_ms: &[u64], -) -> Result<NodeInfo, StaggeredError<LookupError>>

Looks up node info by NodeId and origin domain name.

+) -> Result<NodeInfo, StaggeredError<LookupError>>

Looks up node info by [NodeId] and origin domain name.

From the moment this function is called, each lookup is scheduled after the delays in delays_ms with the first call being done immediately. [200ms, 300ms] results in calls at T+0ms, T+200ms and T+300ms. The result of the first successful call is returned, or a diff --git a/pr/3314/docs/iroh_relay/index.html b/pr/3314/docs/iroh_relay/index.html index 5b1f8aca6e..a4c2940432 100644 --- a/pr/3314/docs/iroh_relay/index.html +++ b/pr/3314/docs/iroh_relay/index.html @@ -25,6 +25,6 @@ Tailscale.

STUN support and expose metrics.

-

Re-exports§

pub use protos::relay::MAX_PACKET_SIZE;

Modules§

client
Exposes Client, which allows to establish connections to a relay server.
defaults
Default values used in the relay.
dnsNon-wasm_browser
DNS resolver
http
HTTP-specific constants for the relay server and client.
node_info
Support for handling DNS resource records for dialing by NodeId.
protos
Protocols used by the iroh-relay
quic
Create a QUIC server that accepts connections +

Re-exports§

pub use protos::relay::MAX_PACKET_SIZE;

Modules§

client
Exposes Client, which allows to establish connections to a relay server.
defaults
Default values used in the relay.
dnsNon-wasm_browser
DNS resolver
http
HTTP-specific constants for the relay server and client.
node_info
Support for handling DNS resource records for dialing by [NodeId].
protos
Protocols used by the iroh-relay
quic
Create a QUIC server that accepts connections for QUIC address discovery.
serverserver
A fully-fledged iroh-relay server over HTTP or HTTPS.

Structs§

PingTracker
Tracks pings on a single relay connection.
RelayMap
Configuration of all the relay servers that can be used.
RelayNode
Information on a specific relay server.
RelayQuicConfig
Configuration for speaking to the QUIC endpoint on the relay server to do QUIC address discovery.
\ No newline at end of file diff --git a/pr/3314/docs/iroh_relay/node_info/index.html b/pr/3314/docs/iroh_relay/node_info/index.html index 7c44a3876d..00c61b2d49 100644 --- a/pr/3314/docs/iroh_relay/node_info/index.html +++ b/pr/3314/docs/iroh_relay/node_info/index.html @@ -1,5 +1,5 @@ -iroh_relay::node_info - Rust

Module node_info

Source
Expand description

Support for handling DNS resource records for dialing by NodeId.

-

Dialing by NodeId is supported by iroh nodes publishing Pkarr records to DNS +iroh_relay::node_info - Rust

Module node_info

Source
Expand description

Support for handling DNS resource records for dialing by [NodeId].

+

Dialing by [NodeId] is supported by iroh nodes publishing Pkarr records to DNS servers or the Mainline DHT. This module supports creating and parsing these records.

DNS records are published under the following names:

_iroh.<z32-node-id>.<origin-domain> TXT

@@ -8,7 +8,7 @@ servers or the Mainline DHT. This module supports creating and parsing these re

_iroh is the record name as defined by IROH_TXT_NAME.

  • -

    <z32-node-id> is the z-base-32 encoding of the NodeId.

    +

    <z32-node-id> is the z-base-32 encoding of the [NodeId].

  • <origin-domain> is the domain name of the publishing DNS server, @@ -23,12 +23,12 @@ servers or the Mainline DHT. This module supports creating and parsing these re in RFC1464. The following attributes are defined:

    • -

      relay=<url>: The home RelayUrl of this node.

      +

      relay=<url>: The home RelayUrl of this node.

    • addr=<addr> <addr>: A space-separated list of sockets addresses for this iroh node. Each address is an IPv4 or IPv6 address with a port.

    -
  • Structs§

    MaxLengthExceededError
    Error returned when an input value is too long for UserData.
    NodeData
    Data about a node that may be published to and resolved from discovery services.
    NodeInfo
    Information about a node that may be published to and resolved from discovery services.
    UserData
    Under the hood this is a UTF-8 String is no longer than UserData::MAX_LENGTH bytes.

    Enums§

    DecodingError
    EncodingError
    LookupErrorNon-wasm_browser
    ParseError

    Constants§

    IROH_TXT_NAME
    The DNS name for the iroh TXT record.

    Traits§

    NodeIdExt
    Extension methods for NodeId to encode to and decode from [z32], +

    Structs§

    MaxLengthExceededError
    Error returned when an input value is too long for UserData.
    NodeData
    Data about a node that may be published to and resolved from discovery services.
    NodeInfo
    Information about a node that may be published to and resolved from discovery services.
    UserData
    Under the hood this is a UTF-8 String is no longer than UserData::MAX_LENGTH bytes.

    Enums§

    DecodingError
    EncodingError
    LookupErrorNon-wasm_browser
    ParseError

    Constants§

    IROH_TXT_NAME
    The DNS name for the iroh TXT record.

    Traits§

    NodeIdExt
    Extension methods for [NodeId] to encode to and decode from [z32], which is the encoding used in [pkarr] domain names.
    \ No newline at end of file diff --git a/pr/3314/docs/iroh_relay/node_info/struct.NodeData.html b/pr/3314/docs/iroh_relay/node_info/struct.NodeData.html index 238c3986d7..8315d3cd78 100644 --- a/pr/3314/docs/iroh_relay/node_info/struct.NodeData.html +++ b/pr/3314/docs/iroh_relay/node_info/struct.NodeData.html @@ -1,20 +1,20 @@ NodeData in iroh_relay::node_info - Rust

    Struct NodeData

    Source
    pub struct NodeData { /* private fields */ }
    Expand description

    Data about a node that may be published to and resolved from discovery services.

    -

    This includes an optional RelayUrl, a set of direct addresses, and the optional +

    This includes an optional [RelayUrl], a set of direct addresses, and the optional UserData, a string that can be set by applications and is not parsed or used by iroh itself.

    -

    This struct does not include the node’s NodeId, only the data about a certain -node. See NodeInfo for a struct that contains a NodeId with associated NodeData.

    +

    This struct does not include the node’s [NodeId], only the data about a certain +node. See NodeInfo for a struct that contains a [NodeId] with associated NodeData.

    Implementations§

    Source§

    impl NodeData

    Source

    pub fn new( - relay_url: Option<RelayUrl>, + relay_url: Option<RelayUrl>, direct_addresses: BTreeSet<SocketAddr>, ) -> Self

    Creates a new NodeData with a relay URL and a set of direct addresses.

    -
    Source

    pub fn with_relay_url(self, relay_url: Option<RelayUrl>) -> Self

    Sets the relay URL and returns the updated node data.

    +
    Source

    pub fn with_relay_url(self, relay_url: Option<RelayUrl>) -> Self

    Sets the relay URL and returns the updated node data.

    Source

    pub fn with_direct_addresses( self, direct_addresses: BTreeSet<SocketAddr>, ) -> Self

    Sets the direct addresses and returns the updated node data.

    Source

    pub fn with_user_data(self, user_data: Option<UserData>) -> Self

    Sets the user-defined data and returns the updated node data.

    -
    Source

    pub fn relay_url(&self) -> Option<&RelayUrl>

    Returns the relay URL of the node.

    +
    Source

    pub fn relay_url(&self) -> Option<&RelayUrl>

    Returns the relay URL of the node.

    Source

    pub fn user_data(&self) -> Option<&UserData>

    Returns the optional user-defined data of the node.

    Source

    pub fn direct_addresses(&self) -> &BTreeSet<SocketAddr>

    Returns the direct addresses of the node.

    Source

    pub fn clear_direct_addresses(&mut self)

    Removes all direct addresses from the node data.

    @@ -22,9 +22,9 @@ node. See IntoIterator<Item = SocketAddr>, )

    Adds direct addresses to the node data.

    -
    Source

    pub fn set_relay_url(&mut self, relay_url: Option<RelayUrl>)

    Sets the relay URL of the node data.

    +
    Source

    pub fn set_relay_url(&mut self, relay_url: Option<RelayUrl>)

    Sets the relay URL of the node data.

    Source

    pub fn set_user_data(&mut self, user_data: Option<UserData>)

    Sets the user-defined data of the node data.

    -

    Trait Implementations§

    Source§

    impl Clone for NodeData

    Source§

    fn clone(&self) -> NodeData

    Returns a copy of the value. Read more
    1.0.0 · Source§

    fn clone_from(&mut self, source: &Self)

    Performs copy-assignment from source. Read more
    Source§

    impl Debug for NodeData

    Source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    Source§

    impl Default for NodeData

    Source§

    fn default() -> NodeData

    Returns the “default value” for a type. Read more
    Source§

    impl From<NodeAddr> for NodeData

    Source§

    fn from(node_addr: NodeAddr) -> Self

    Converts to this type from the input type.
    Source§

    impl PartialEq for NodeData

    Source§

    fn eq(&self, other: &NodeData) -> bool

    Tests for self and other values to be equal, and is used by ==.
    1.0.0 · Source§

    fn ne(&self, other: &Rhs) -> bool

    Tests for !=. The default implementation is almost always sufficient, +

    Trait Implementations§

    Source§

    impl Clone for NodeData

    Source§

    fn clone(&self) -> NodeData

    Returns a copy of the value. Read more
    1.0.0 · Source§

    fn clone_from(&mut self, source: &Self)

    Performs copy-assignment from source. Read more
    Source§

    impl Debug for NodeData

    Source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    Source§

    impl Default for NodeData

    Source§

    fn default() -> NodeData

    Returns the “default value” for a type. Read more
    Source§

    impl From<NodeAddr> for NodeData

    Source§

    fn from(node_addr: NodeAddr) -> Self

    Converts to this type from the input type.
    Source§

    impl PartialEq for NodeData

    Source§

    fn eq(&self, other: &NodeData) -> bool

    Tests for self and other values to be equal, and is used by ==.
    1.0.0 · Source§

    fn ne(&self, other: &Rhs) -> bool

    Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
    Source§

    impl Eq for NodeData

    Source§

    impl StructuralPartialEq for NodeData

    Auto Trait Implementations§

    Blanket Implementations§

    Source§

    impl<T> Any for T
    where T: 'static + ?Sized,

    Source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    §

    impl<'a, T, E> AsTaggedExplicit<'a, E> for T
    where T: 'a,

    §

    fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

    §

    impl<'a, T, E> AsTaggedImplicit<'a, E> for T
    where diff --git a/pr/3314/docs/iroh_relay/node_info/struct.NodeInfo.html b/pr/3314/docs/iroh_relay/node_info/struct.NodeInfo.html index 62193891d4..3009617365 100644 --- a/pr/3314/docs/iroh_relay/node_info/struct.NodeInfo.html +++ b/pr/3314/docs/iroh_relay/node_info/struct.NodeInfo.html @@ -1,32 +1,32 @@ NodeInfo in iroh_relay::node_info - Rust

    Struct NodeInfo

    Source
    pub struct NodeInfo {
    -    pub node_id: NodeId,
    +    pub node_id: NodeId,
         pub data: NodeData,
     }
    Expand description

    Information about a node that may be published to and resolved from discovery services.

    -

    This struct couples a NodeId with its associated NodeData.

    -

    Fields§

    §node_id: NodeId

    The NodeId of the node this is about.

    +

    This struct couples a [NodeId] with its associated NodeData.

    +

    Fields§

    §node_id: NodeId

    The [NodeId] of the node this is about.

    §data: NodeData

    The information published about the node.

    -

    Implementations§

    Source§

    impl NodeInfo

    Source

    pub fn new(node_id: NodeId) -> Self

    Creates a new NodeInfo with an empty NodeData.

    -
    Source

    pub fn from_parts(node_id: NodeId, data: NodeData) -> Self

    Creates a new NodeInfo from its parts.

    -
    Source

    pub fn with_relay_url(self, relay_url: Option<RelayUrl>) -> Self

    Sets the relay URL and returns the updated node info.

    +

    Implementations§

    Source§

    impl NodeInfo

    Source

    pub fn new(node_id: NodeId) -> Self

    Creates a new NodeInfo with an empty NodeData.

    +
    Source

    pub fn from_parts(node_id: NodeId, data: NodeData) -> Self

    Creates a new NodeInfo from its parts.

    +
    Source

    pub fn with_relay_url(self, relay_url: Option<RelayUrl>) -> Self

    Sets the relay URL and returns the updated node info.

    Source

    pub fn with_direct_addresses( self, direct_addresses: BTreeSet<SocketAddr>, ) -> Self

    Sets the direct addresses and returns the updated node info.

    Source

    pub fn with_user_data(self, user_data: Option<UserData>) -> Self

    Sets the user-defined data and returns the updated node info.

    -
    Source

    pub fn to_node_addr(&self) -> NodeAddr

    Converts into a NodeAddr by cloning the needed fields.

    -
    Source

    pub fn into_node_addr(self) -> NodeAddr

    Converts into a NodeAddr without cloning.

    +
    Source

    pub fn to_node_addr(&self) -> NodeAddr

    Converts into a [NodeAddr] by cloning the needed fields.

    +
    Source

    pub fn into_node_addr(self) -> NodeAddr

    Converts into a [NodeAddr] without cloning.

    Source

    pub fn from_txt_lookup(lookup: TxtLookup) -> Result<Self, ParseError>

    Available on non-wasm_browser only.

    Parses a NodeInfo from a TXT records lookup.

    Source

    pub fn from_pkarr_signed_packet( packet: &SignedPacket, ) -> Result<Self, ParseError>

    Parses a NodeInfo from a [pkarr::SignedPacket].

    Source

    pub fn to_pkarr_signed_packet( &self, - secret_key: &SecretKey, + secret_key: &SecretKey, ttl: u32, ) -> Result<SignedPacket, EncodingError>

    Creates a [pkarr::SignedPacket].

    -

    This constructs a DNS packet and signs it with a SecretKey.

    +

    This constructs a DNS packet and signs it with a [SecretKey].

    Source

    pub fn to_txt_strings(&self) -> Vec<String>

    Converts into a list of {key}={value} strings.

    -

    Methods from Deref<Target = NodeData>§

    Source

    pub fn relay_url(&self) -> Option<&RelayUrl>

    Returns the relay URL of the node.

    +

    Methods from Deref<Target = NodeData>§

    Source

    pub fn relay_url(&self) -> Option<&RelayUrl>

    Returns the relay URL of the node.

    Source

    pub fn user_data(&self) -> Option<&UserData>

    Returns the optional user-defined data of the node.

    Source

    pub fn direct_addresses(&self) -> &BTreeSet<SocketAddr>

    Returns the direct addresses of the node.

    Source

    pub fn clear_direct_addresses(&mut self)

    Removes all direct addresses from the node data.

    @@ -34,9 +34,9 @@ &mut self, addrs: impl IntoIterator<Item = SocketAddr>, )

    Adds direct addresses to the node data.

    -
    Source

    pub fn set_relay_url(&mut self, relay_url: Option<RelayUrl>)

    Sets the relay URL of the node data.

    +
    Source

    pub fn set_relay_url(&mut self, relay_url: Option<RelayUrl>)

    Sets the relay URL of the node data.

    Source

    pub fn set_user_data(&mut self, user_data: Option<UserData>)

    Sets the user-defined data of the node data.

    -

    Trait Implementations§

    Source§

    impl Clone for NodeInfo

    Source§

    fn clone(&self) -> NodeInfo

    Returns a copy of the value. Read more
    1.0.0 · Source§

    fn clone_from(&mut self, source: &Self)

    Performs copy-assignment from source. Read more
    Source§

    impl Debug for NodeInfo

    Source§

    fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    Source§

    impl Deref for NodeInfo

    Source§

    type Target = NodeData

    The resulting type after dereferencing.
    Source§

    fn deref(&self) -> &Self::Target

    Dereferences the value.
    Source§

    impl DerefMut for NodeInfo

    Source§

    fn deref_mut(&mut self) -> &mut Self::Target

    Mutably dereferences the value.
    Source§

    impl From<NodeAddr> for NodeInfo

    Source§

    fn from(addr: NodeAddr) -> Self

    Converts to this type from the input type.
    Source§

    impl From<NodeInfo> for NodeAddr

    Source§

    fn from(value: NodeInfo) -> Self

    Converts to this type from the input type.
    Source§

    impl PartialEq for NodeInfo

    Source§

    fn eq(&self, other: &NodeInfo) -> bool

    Tests for self and other values to be equal, and is used by ==.
    1.0.0 · Source§

    fn ne(&self, other: &Rhs) -> bool

    Tests for !=. The default implementation is almost always sufficient, +

    Trait Implementations§

    Source§

    impl Clone for NodeInfo

    Source§

    fn clone(&self) -> NodeInfo

    Returns a copy of the value. Read more
    1.0.0 · Source§

    fn clone_from(&mut self, source: &Self)

    Performs copy-assignment from source. Read more
    Source§

    impl Debug for NodeInfo

    Source§

    fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    Source§

    impl Deref for NodeInfo

    Source§

    type Target = NodeData

    The resulting type after dereferencing.
    Source§

    fn deref(&self) -> &Self::Target

    Dereferences the value.
    Source§

    impl DerefMut for NodeInfo

    Source§

    fn deref_mut(&mut self) -> &mut Self::Target

    Mutably dereferences the value.
    Source§

    impl From<NodeAddr> for NodeInfo

    Source§

    fn from(addr: NodeAddr) -> Self

    Converts to this type from the input type.
    Source§

    impl From<NodeInfo> for NodeAddr

    Source§

    fn from(value: NodeInfo) -> Self

    Converts to this type from the input type.
    Source§

    impl PartialEq for NodeInfo

    Source§

    fn eq(&self, other: &NodeInfo) -> bool

    Tests for self and other values to be equal, and is used by ==.
    1.0.0 · Source§

    fn ne(&self, other: &Rhs) -> bool

    Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
    Source§

    impl Eq for NodeInfo

    Source§

    impl StructuralPartialEq for NodeInfo

    Auto Trait Implementations§

    Blanket Implementations§

    Source§

    impl<T> Any for T
    where T: 'static + ?Sized,

    Source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    §

    impl<'a, T, E> AsTaggedExplicit<'a, E> for T
    where T: 'a,

    §

    fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

    §

    impl<'a, T, E> AsTaggedImplicit<'a, E> for T
    where diff --git a/pr/3314/docs/iroh_relay/node_info/trait.NodeIdExt.html b/pr/3314/docs/iroh_relay/node_info/trait.NodeIdExt.html index 19265ef095..e60ccd0737 100644 --- a/pr/3314/docs/iroh_relay/node_info/trait.NodeIdExt.html +++ b/pr/3314/docs/iroh_relay/node_info/trait.NodeIdExt.html @@ -1,9 +1,9 @@ NodeIdExt in iroh_relay::node_info - Rust

    Trait NodeIdExt

    Source
    pub trait NodeIdExt {
         // Required methods
         fn to_z32(&self) -> String;
    -    fn from_z32(s: &str) -> Result<NodeId, DecodingError>;
    -}
    Expand description

    Extension methods for NodeId to encode to and decode from [z32], + fn from_z32(s: &str) -> Result<NodeId, DecodingError>; +}

    Expand description

    Extension methods for [NodeId] to encode to and decode from [z32], which is the encoding used in [pkarr] domain names.

    -

    Required Methods§

    Source

    fn to_z32(&self) -> String

    Encodes a NodeId in [z-base-32] encoding.

    -
    Source

    fn from_z32(s: &str) -> Result<NodeId, DecodingError>

    Parses a NodeId from [z-base-32] encoding.

    -

    Dyn Compatibility§

    This trait is not dyn compatible.

    In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

    Implementations on Foreign Types§

    Source§

    impl NodeIdExt for NodeId

    Implementors§

    \ No newline at end of file +

    Required Methods§

    Source

    fn to_z32(&self) -> String

    Encodes a [NodeId] in [z-base-32] encoding.

    +
    Source

    fn from_z32(s: &str) -> Result<NodeId, DecodingError>

    Parses a [NodeId] from [z-base-32] encoding.

    +

    Dyn Compatibility§

    This trait is not dyn compatible.

    In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

    Implementations on Foreign Types§

    Source§

    impl NodeIdExt for NodeId

    Implementors§

    \ No newline at end of file diff --git a/pr/3314/docs/iroh_relay/server/enum.AccessConfig.html b/pr/3314/docs/iroh_relay/server/enum.AccessConfig.html index 2d0d8688ca..373edbb00a 100644 --- a/pr/3314/docs/iroh_relay/server/enum.AccessConfig.html +++ b/pr/3314/docs/iroh_relay/server/enum.AccessConfig.html @@ -1,10 +1,10 @@ AccessConfig in iroh_relay::server - Rust

    Enum AccessConfig

    Source
    pub enum AccessConfig {
         Everyone,
    -    Restricted(Box<dyn Fn(NodeId) -> Boxed<Access> + Send + Sync + 'static>),
    +    Restricted(Box<dyn Fn(NodeId) -> Boxed<Access> + Send + Sync + 'static>),
     }
    Available on crate feature server only.
    Expand description

    Controls which nodes are allowed to use the relay.

    Variants§

    §

    Everyone

    Everyone

    -
    §

    Restricted(Box<dyn Fn(NodeId) -> Boxed<Access> + Send + Sync + 'static>)

    Only nodes for which the function returns Access::Allow.

    -

    Implementations§

    Source§

    impl AccessConfig

    Source

    pub async fn is_allowed(&self, node: NodeId) -> bool

    Is this node allowed?

    +
    §

    Restricted(Box<dyn Fn(NodeId) -> Boxed<Access> + Send + Sync + 'static>)

    Only nodes for which the function returns Access::Allow.

    +

    Implementations§

    Source§

    impl AccessConfig

    Source

    pub async fn is_allowed(&self, node: NodeId) -> bool

    Is this node allowed?

    Trait Implementations§

    Source§

    impl Debug for AccessConfig

    Source§

    fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more

    Auto Trait Implementations§

    Blanket Implementations§

    Source§

    impl<T> Any for T
    where T: 'static + ?Sized,

    Source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    §

    impl<'a, T, E> AsTaggedExplicit<'a, E> for T
    where T: 'a,

    §

    fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

    §

    impl<'a, T, E> AsTaggedImplicit<'a, E> for T
    where diff --git a/pr/3314/docs/iroh_relay/server/struct.Server.html b/pr/3314/docs/iroh_relay/server/struct.Server.html index 94e5e378fe..3f3165c60d 100644 --- a/pr/3314/docs/iroh_relay/server/struct.Server.html +++ b/pr/3314/docs/iroh_relay/server/struct.Server.html @@ -17,9 +17,9 @@ case there is an error in the server before it is shut down.

    Source

    pub fn http_addr(&self) -> Option<SocketAddr>

    The socket address the HTTP server is listening on.

    Source

    pub fn quic_addr(&self) -> Option<SocketAddr>

    The socket address the QUIC server is listening on.

    Source

    pub fn certificates(&self) -> Option<Vec<CertificateDer<'static>>>

    The certificates chain if configured with manual TLS certificates.

    -
    Source

    pub fn https_url(&self) -> Option<RelayUrl>

    Available on crate feature test-utils only.

    Get the server’s https RelayUrl.

    +
    Source

    pub fn https_url(&self) -> Option<RelayUrl>

    Available on crate feature test-utils only.

    Get the server’s https [RelayUrl].

    This uses Self::https_addr so it’s mostly useful for local development.

    -
    Source

    pub fn http_url(&self) -> Option<RelayUrl>

    Available on crate feature test-utils only.

    Get the server’s http RelayUrl.

    +
    Source

    pub fn http_url(&self) -> Option<RelayUrl>

    Available on crate feature test-utils only.

    Get the server’s http [RelayUrl].

    This uses Self::http_addr so it’s mostly useful for local development.

    Source

    pub fn metrics(&self) -> &RelayMetrics

    Returns the metrics collected in the relay server.

    Trait Implementations§

    Source§

    impl Debug for Server

    Source§

    fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more

    Auto Trait Implementations§

    §

    impl Freeze for Server

    §

    impl RefUnwindSafe for Server

    §

    impl Send for Server

    §

    impl Sync for Server

    §

    impl Unpin for Server

    §

    impl UnwindSafe for Server

    Blanket Implementations§

    Source§

    impl<T> Any for T
    where diff --git a/pr/3314/docs/iroh_relay/struct.RelayMap.html b/pr/3314/docs/iroh_relay/struct.RelayMap.html index 66406bee10..0c33630093 100644 --- a/pr/3314/docs/iroh_relay/struct.RelayMap.html +++ b/pr/3314/docs/iroh_relay/struct.RelayMap.html @@ -1,15 +1,15 @@ RelayMap in iroh_relay - Rust

    Struct RelayMap

    Source
    pub struct RelayMap { /* private fields */ }
    Expand description

    Configuration of all the relay servers that can be used.

    -

    Implementations§

    Source§

    impl RelayMap

    Source

    pub fn urls(&self) -> impl Iterator<Item = &RelayUrl>

    Returns the sorted relay URLs.

    +

    Implementations§

    Source§

    impl RelayMap

    Source

    pub fn urls(&self) -> impl Iterator<Item = &RelayUrl>

    Returns the sorted relay URLs.

    Source

    pub fn empty() -> Self

    Create an empty relay map.

    Source

    pub fn nodes(&self) -> impl Iterator<Item = &Arc<RelayNode>>

    Returns an Iterator over all known nodes.

    -
    Source

    pub fn contains_node(&self, url: &RelayUrl) -> bool

    Is this a known node?

    -
    Source

    pub fn get_node(&self, url: &RelayUrl) -> Option<&Arc<RelayNode>>

    Get the given node.

    +
    Source

    pub fn contains_node(&self, url: &RelayUrl) -> bool

    Is this a known node?

    +
    Source

    pub fn get_node(&self, url: &RelayUrl) -> Option<&Arc<RelayNode>>

    Get the given node.

    Source

    pub fn len(&self) -> usize

    How many nodes are known?

    Source

    pub fn is_empty(&self) -> bool

    Are there any nodes in this map?

    -

    Trait Implementations§

    Source§

    impl Clone for RelayMap

    Source§

    fn clone(&self) -> RelayMap

    Returns a copy of the value. Read more
    1.0.0 · Source§

    fn clone_from(&mut self, source: &Self)

    Performs copy-assignment from source. Read more
    Source§

    impl Debug for RelayMap

    Source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    Source§

    impl Display for RelayMap

    Source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    Source§

    impl From<RelayNode> for RelayMap

    Source§

    fn from(value: RelayNode) -> Self

    Converts to this type from the input type.
    Source§

    impl From<RelayUrl> for RelayMap

    Source§

    fn from(value: RelayUrl) -> Self

    Creates a RelayMap from a RelayUrl.

    +

    Trait Implementations§

    Source§

    impl Clone for RelayMap

    Source§

    fn clone(&self) -> RelayMap

    Returns a copy of the value. Read more
    1.0.0 · Source§

    fn clone_from(&mut self, source: &Self)

    Performs copy-assignment from source. Read more
    Source§

    impl Debug for RelayMap

    Source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    Source§

    impl Display for RelayMap

    Source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    Source§

    impl From<RelayNode> for RelayMap

    Source§

    fn from(value: RelayNode) -> Self

    Converts to this type from the input type.
    Source§

    impl From<RelayUrl> for RelayMap

    Source§

    fn from(value: RelayUrl) -> Self

    Creates a RelayMap from a [RelayUrl].

    The RelayNodes in the RelayMap will have the default STUN and QUIC address discovery ports.

    -
    Source§

    impl FromIterator<RelayNode> for RelayMap

    Source§

    fn from_iter<T: IntoIterator<Item = RelayNode>>(iter: T) -> Self

    Creates a value from an iterator. Read more
    Source§

    impl FromIterator<RelayUrl> for RelayMap

    Source§

    fn from_iter<T: IntoIterator<Item = RelayUrl>>(iter: T) -> Self

    Creates a RelayMap from an iterator of RelayUrl.

    +
    Source§

    impl FromIterator<RelayNode> for RelayMap

    Source§

    fn from_iter<T: IntoIterator<Item = RelayNode>>(iter: T) -> Self

    Creates a value from an iterator. Read more
    Source§

    impl FromIterator<RelayUrl> for RelayMap

    Source§

    fn from_iter<T: IntoIterator<Item = RelayUrl>>(iter: T) -> Self

    Creates a RelayMap from an iterator of [RelayUrl].

    The RelayNodes in the RelayMap will have the default STUN and QUIC address discovery ports.

    Source§

    impl PartialEq for RelayMap

    Source§

    fn eq(&self, other: &RelayMap) -> bool

    Tests for self and other values to be equal, and is used by ==.
    1.0.0 · Source§

    fn ne(&self, other: &Rhs) -> bool

    Tests for !=. The default implementation is almost always sufficient, diff --git a/pr/3314/docs/iroh_relay/struct.RelayNode.html b/pr/3314/docs/iroh_relay/struct.RelayNode.html index 8a05266a98..070ba435ce 100644 --- a/pr/3314/docs/iroh_relay/struct.RelayNode.html +++ b/pr/3314/docs/iroh_relay/struct.RelayNode.html @@ -1,14 +1,14 @@ RelayNode in iroh_relay - Rust

    Struct RelayNode

    Source
    pub struct RelayNode {
    -    pub url: RelayUrl,
    +    pub url: RelayUrl,
         pub quic: Option<RelayQuicConfig>,
     }
    Expand description

    Information on a specific relay server.

    Includes the Url where it can be dialed.

    -

    Fields§

    §url: RelayUrl

    The RelayUrl where this relay server can be dialed.

    +

    Fields§

    §url: RelayUrl

    The [RelayUrl] where this relay server can be dialed.

    §quic: Option<RelayQuicConfig>

    Configuration to speak to the QUIC endpoint on the relay server.

    When None, we will not attempt to do QUIC address discovery with this relay server.

    Trait Implementations§

    Source§

    impl Clone for RelayNode

    Source§

    fn clone(&self) -> RelayNode

    Returns a copy of the value. Read more
    1.0.0 · Source§

    fn clone_from(&mut self, source: &Self)

    Performs copy-assignment from source. Read more
    Source§

    impl Debug for RelayNode

    Source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    Source§

    impl<'de> Deserialize<'de> for RelayNode

    Source§

    fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
    where - __D: Deserializer<'de>,

    Deserialize this value from the given Serde deserializer. Read more
    Source§

    impl Display for RelayNode

    Source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    Source§

    impl From<RelayNode> for RelayMap

    Source§

    fn from(value: RelayNode) -> Self

    Converts to this type from the input type.
    Source§

    impl From<RelayUrl> for RelayNode

    Source§

    fn from(value: RelayUrl) -> Self

    Converts to this type from the input type.
    Source§

    impl FromIterator<RelayNode> for RelayMap

    Source§

    fn from_iter<T: IntoIterator<Item = RelayNode>>(iter: T) -> Self

    Creates a value from an iterator. Read more
    Source§

    impl Ord for RelayNode

    Source§

    fn cmp(&self, other: &RelayNode) -> Ordering

    This method returns an Ordering between self and other. Read more
    1.21.0 · Source§

    fn max(self, other: Self) -> Self
    where + __D: Deserializer<'de>,

    Deserialize this value from the given Serde deserializer. Read more
    Source§

    impl Display for RelayNode

    Source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    Source§

    impl From<RelayNode> for RelayMap

    Source§

    fn from(value: RelayNode) -> Self

    Converts to this type from the input type.
    Source§

    impl From<RelayUrl> for RelayNode

    Source§

    fn from(value: RelayUrl) -> Self

    Converts to this type from the input type.
    Source§

    impl FromIterator<RelayNode> for RelayMap

    Source§

    fn from_iter<T: IntoIterator<Item = RelayNode>>(iter: T) -> Self

    Creates a value from an iterator. Read more
    Source§

    impl Ord for RelayNode

    Source§

    fn cmp(&self, other: &RelayNode) -> Ordering

    This method returns an Ordering between self and other. Read more
    1.21.0 · Source§

    fn max(self, other: Self) -> Self
    where Self: Sized,

    Compares and returns the maximum of two values. Read more
    1.21.0 · Source§

    fn min(self, other: Self) -> Self
    where Self: Sized,

    Compares and returns the minimum of two values. Read more
    1.50.0 · Source§

    fn clamp(self, min: Self, max: Self) -> Self
    where Self: Sized,

    Restrict a value to a certain interval. Read more
    Source§

    impl PartialEq for RelayNode

    Source§

    fn eq(&self, other: &RelayNode) -> bool

    Tests for self and other values to be equal, and is used by ==.
    1.0.0 · Source§

    fn ne(&self, other: &Rhs) -> bool

    Tests for !=. The default implementation is almost always sufficient, diff --git a/pr/3314/docs/src/iroh/net_report.rs.html b/pr/3314/docs/src/iroh/net_report.rs.html index 8c197b80f0..139736fd25 100644 --- a/pr/3314/docs/src/iroh/net_report.rs.html +++ b/pr/3314/docs/src/iroh/net_report.rs.html @@ -37,1033 +37,1050 @@ 37 StreamExt, 38}; 39use n0_watcher::{Watchable, Watcher}; -40use reportgen::{ProbeFinished, ProbeReport, QadProbeReport}; -41use tokio::task::JoinSet; -42use tokio_util::sync::CancellationToken; -43use tracing::{debug, trace}; -44 -45mod defaults; -46mod ip_mapped_addrs; -47mod metrics; -48mod probes; -49mod report; -50mod reportgen; -51 -52mod options; -53 -54/// We "vendor" what we need of the library in browsers for simplicity. -55/// -56/// We could consider making `portmapper` compile to wasm in the future, -57/// but what we need is so little it's likely not worth it. -58#[cfg(wasm_browser)] -59pub(crate) mod portmapper { -60 /// Output of a port mapping probe. -61 #[derive(Debug, Clone, PartialEq, Eq, derive_more::Display)] -62 #[display("portmap={{ UPnP: {upnp}, PMP: {nat_pmp}, PCP: {pcp} }}")] -63 pub struct ProbeOutput { -64 /// If UPnP can be considered available. -65 pub upnp: bool, -66 /// If PCP can be considered available. -67 pub pcp: bool, -68 /// If PMP can be considered available. -69 pub nat_pmp: bool, -70 } -71} -72 -73pub(crate) use ip_mapped_addrs::{IpMappedAddr, IpMappedAddresses}; -74 -75pub(crate) use self::reportgen::IfStateDetails; -76#[cfg(not(wasm_browser))] -77use self::reportgen::SocketState; -78pub use self::{ -79 metrics::Metrics, -80 options::Options, -81 probes::Probe, -82 report::{RelayLatencies, Report}, -83 reportgen::QuicConfig, -84}; -85use crate::util::MaybeFuture; -86 -87const FULL_REPORT_INTERVAL: Duration = Duration::from_secs(5 * 60); -88 -89/// The maximum latency of all nodes, if none are found yet. -90/// -91/// Normally the max latency of all nodes is computed, but if we don't yet know any nodes -92/// latencies we return this as default. This is the value of the initial STUN probe -93/// delays. It is only used as time to wait for further latencies to arrive, which *should* -94/// never happen unless there already is at least one latency. Yet here we are, defining a -95/// default which will never be used. -96const DEFAULT_MAX_LATENCY: Duration = Duration::from_millis(100); -97 -98const ENOUGH_NODES: usize = 3; -99 -100/// Client to run net_reports. -101/// -102/// Creating this creates a net_report actor which runs in the background. Most of the time -103/// it is idle unless [`Client::get_report`] is called, which is the main interface. +40use tokio::task::JoinSet; +41use tokio_util::sync::CancellationToken; +42use tracing::{debug, trace}; +43 +44#[cfg(not(wasm_browser))] +45use self::reportgen::QadProbeReport; +46use self::reportgen::{ProbeFinished, ProbeReport}; +47 +48mod defaults; +49mod ip_mapped_addrs; +50mod metrics; +51mod probes; +52mod report; +53mod reportgen; +54 +55mod options; +56 +57/// We "vendor" what we need of the library in browsers for simplicity. +58/// +59/// We could consider making `portmapper` compile to wasm in the future, +60/// but what we need is so little it's likely not worth it. +61#[cfg(wasm_browser)] +62pub(crate) mod portmapper { +63 /// Output of a port mapping probe. +64 #[derive(Debug, Clone, PartialEq, Eq, derive_more::Display)] +65 #[display("portmap={{ UPnP: {upnp}, PMP: {nat_pmp}, PCP: {pcp} }}")] +66 pub struct ProbeOutput { +67 /// If UPnP can be considered available. +68 pub upnp: bool, +69 /// If PCP can be considered available. +70 pub pcp: bool, +71 /// If PMP can be considered available. +72 pub nat_pmp: bool, +73 } +74} +75 +76pub(crate) use ip_mapped_addrs::{IpMappedAddr, IpMappedAddresses}; +77 +78pub(crate) use self::reportgen::IfStateDetails; +79#[cfg(not(wasm_browser))] +80use self::reportgen::SocketState; +81pub use self::{ +82 metrics::Metrics, +83 options::Options, +84 probes::Probe, +85 report::{RelayLatencies, Report}, +86 reportgen::QuicConfig, +87}; +88use crate::util::MaybeFuture; +89 +90const FULL_REPORT_INTERVAL: Duration = Duration::from_secs(5 * 60); +91 +92/// The maximum latency of all nodes, if none are found yet. +93/// +94/// Normally the max latency of all nodes is computed, but if we don't yet know any nodes +95/// latencies we return this as default. This is the value of the initial STUN probe +96/// delays. It is only used as time to wait for further latencies to arrive, which *should* +97/// never happen unless there already is at least one latency. Yet here we are, defining a +98/// default which will never be used. +99const DEFAULT_MAX_LATENCY: Duration = Duration::from_millis(100); +100 +101const ENOUGH_NODES: usize = 3; +102 +103/// Client to run net_reports. 104/// -105/// The [`Client`] struct can be cloned and results multiple handles to the running actor. -106/// If all [`Client`]s are dropped the actor stops running. +105/// Creating this creates a net_report actor which runs in the background. Most of the time +106/// it is idle unless [`Client::get_report`] is called, which is the main interface. 107/// -108/// While running the net_report actor expects to be passed all received stun packets using -109/// `Addr::receive_stun_packet`. -110#[derive(Debug)] -111pub(crate) struct Client { -112 #[cfg(not(wasm_browser))] -113 socket_state: SocketState, -114 metrics: Arc<Metrics>, -115 probes: BTreeSet<Probe>, -116 relay_map: RelayMap, -117 #[cfg(not(wasm_browser))] -118 qad_conns: QadConns, -119 #[cfg(any(test, feature = "test-utils"))] -120 insecure_skip_relay_cert_verify: bool, -121 -122 /// A collection of previously generated reports. -123 /// -124 /// Sometimes it is useful to look at past reports to decide what to do. -125 reports: Reports, -126} -127 -128#[cfg(not(wasm_browser))] -129#[derive(Debug, Default)] -130struct QadConns { -131 v4: Option<(RelayUrl, QadConn)>, -132 v6: Option<(RelayUrl, QadConn)>, -133} -134 -135#[cfg(not(wasm_browser))] -136impl QadConns { -137 fn clear(&mut self) { -138 if let Some((_, conn)) = self.v4.take() { -139 conn.conn -140 .close(QUIC_ADDR_DISC_CLOSE_CODE, QUIC_ADDR_DISC_CLOSE_REASON); -141 } -142 if let Some((_, conn)) = self.v6.take() { -143 conn.conn -144 .close(QUIC_ADDR_DISC_CLOSE_CODE, QUIC_ADDR_DISC_CLOSE_REASON); -145 } -146 } -147 -148 fn current(&self) -> Vec<ProbeReport> { -149 let mut reports = Vec::new(); -150 if let Some((_, ref conn)) = self.v4 { -151 if let Some(mut r) = conn.observer.get() { -152 // grab latest rtt -153 r.latency = conn.conn.rtt(); -154 reports.push(ProbeReport::QadIpv4(r)); -155 } -156 } -157 -158 if let Some((_, ref conn)) = self.v6 { -159 if let Some(mut r) = conn.observer.get() { -160 // grab latest rtt -161 r.latency = conn.conn.rtt(); -162 reports.push(ProbeReport::QadIpv6(r)); -163 } -164 } -165 -166 reports -167 } +108/// The [`Client`] struct can be cloned and results multiple handles to the running actor. +109/// If all [`Client`]s are dropped the actor stops running. +110/// +111/// While running the net_report actor expects to be passed all received stun packets using +112/// `Addr::receive_stun_packet`. +113#[derive(Debug)] +114pub(crate) struct Client { +115 #[cfg(not(wasm_browser))] +116 socket_state: SocketState, +117 metrics: Arc<Metrics>, +118 probes: BTreeSet<Probe>, +119 relay_map: RelayMap, +120 #[cfg(not(wasm_browser))] +121 qad_conns: QadConns, +122 #[cfg(any(test, feature = "test-utils"))] +123 insecure_skip_relay_cert_verify: bool, +124 +125 /// A collection of previously generated reports. +126 /// +127 /// Sometimes it is useful to look at past reports to decide what to do. +128 reports: Reports, +129} +130 +131#[cfg(not(wasm_browser))] +132#[derive(Debug, Default)] +133struct QadConns { +134 v4: Option<(RelayUrl, QadConn)>, +135 v6: Option<(RelayUrl, QadConn)>, +136} +137 +138#[cfg(not(wasm_browser))] +139impl QadConns { +140 fn clear(&mut self) { +141 if let Some((_, conn)) = self.v4.take() { +142 conn.conn +143 .close(QUIC_ADDR_DISC_CLOSE_CODE, QUIC_ADDR_DISC_CLOSE_REASON); +144 } +145 if let Some((_, conn)) = self.v6.take() { +146 conn.conn +147 .close(QUIC_ADDR_DISC_CLOSE_CODE, QUIC_ADDR_DISC_CLOSE_REASON); +148 } +149 } +150 +151 fn current(&self) -> Vec<ProbeReport> { +152 let mut reports = Vec::new(); +153 if let Some((_, ref conn)) = self.v4 { +154 if let Some(mut r) = conn.observer.get() { +155 // grab latest rtt +156 r.latency = conn.conn.rtt(); +157 reports.push(ProbeReport::QadIpv4(r)); +158 } +159 } +160 +161 if let Some((_, ref conn)) = self.v6 { +162 if let Some(mut r) = conn.observer.get() { +163 // grab latest rtt +164 r.latency = conn.conn.rtt(); +165 reports.push(ProbeReport::QadIpv6(r)); +166 } +167 } 168 -169 fn watch_v4(&self) -> impl n0_future::Stream<Item = Option<QadProbeReport>> + Unpin { -170 let watcher = self.v4.as_ref().map(|(_url, conn)| conn.observer.watch()); +169 reports +170 } 171 -172 if let Some(watcher) = watcher { -173 watcher.stream_updates_only().boxed() -174 } else { -175 n0_future::stream::empty().boxed() -176 } -177 } -178 -179 fn watch_v6(&self) -> impl n0_future::Stream<Item = Option<QadProbeReport>> + Unpin { -180 let watcher = self.v6.as_ref().map(|(_url, conn)| conn.observer.watch()); -181 if let Some(watcher) = watcher { -182 watcher.stream_updates_only().boxed() -183 } else { -184 n0_future::stream::empty().boxed() -185 } -186 } -187} -188 -189#[cfg(not(wasm_browser))] -190#[derive(Debug)] -191struct QadConn { -192 conn: quinn::Connection, -193 observer: Watchable<Option<QadProbeReport>>, -194 _handle: AbortOnDropHandle<()>, -195} -196 -197#[derive(Debug)] -198struct Reports { -199 /// Do a full relay scan, even if last is `Some`. -200 next_full: bool, -201 /// Some previous reports. -202 prev: BTreeMap<Instant, Report>, -203 /// Most recent report. -204 last: Option<Report>, -205 /// Time of last full (non-incremental) report. -206 last_full: Instant, -207} -208 -209impl Default for Reports { -210 fn default() -> Self { -211 Self { -212 next_full: true, -213 prev: Default::default(), -214 last: Default::default(), -215 last_full: Instant::now(), -216 } -217 } -218} -219 -220impl Client { -221 /// Creates a new net_report client. -222 pub(crate) fn new( -223 #[cfg(not(wasm_browser))] dns_resolver: DnsResolver, -224 #[cfg(not(wasm_browser))] ip_mapped_addrs: Option<IpMappedAddresses>, -225 relay_map: RelayMap, -226 opts: Options, -227 metrics: Arc<Metrics>, -228 ) -> Self { -229 let probes = opts.as_protocols(); -230 #[cfg(any(test, feature = "test-utils"))] -231 let insecure_skip_relay_cert_verify = opts.insecure_skip_relay_cert_verify; -232 -233 #[cfg(not(wasm_browser))] -234 let quic_client = opts -235 .quic_config -236 .map(|c| iroh_relay::quic::QuicClient::new(c.ep, c.client_config)); -237 -238 #[cfg(not(wasm_browser))] -239 let socket_state = SocketState { -240 quic_client, -241 dns_resolver, -242 ip_mapped_addrs, -243 }; -244 -245 Client { -246 #[cfg(not(wasm_browser))] -247 socket_state, -248 metrics, -249 reports: Reports::default(), -250 probes, -251 relay_map, -252 qad_conns: QadConns::default(), -253 #[cfg(any(test, feature = "test-utils"))] -254 insecure_skip_relay_cert_verify, -255 } -256 } -257 -258 /// Generates a [`Report`]. -259 /// -260 /// Look at [`Options`] for the different configuration options. -261 pub(crate) async fn get_report(&mut self, if_state: IfStateDetails, is_major: bool) -> Report { -262 let now = Instant::now(); -263 -264 let mut do_full = is_major -265 || self.reports.next_full -266 || now.duration_since(self.reports.last_full) > FULL_REPORT_INTERVAL; +172 fn watch_v4(&self) -> impl n0_future::Stream<Item = Option<QadProbeReport>> + Unpin { +173 let watcher = self.v4.as_ref().map(|(_url, conn)| conn.observer.watch()); +174 +175 if let Some(watcher) = watcher { +176 watcher.stream_updates_only().boxed() +177 } else { +178 n0_future::stream::empty().boxed() +179 } +180 } +181 +182 fn watch_v6(&self) -> impl n0_future::Stream<Item = Option<QadProbeReport>> + Unpin { +183 let watcher = self.v6.as_ref().map(|(_url, conn)| conn.observer.watch()); +184 if let Some(watcher) = watcher { +185 watcher.stream_updates_only().boxed() +186 } else { +187 n0_future::stream::empty().boxed() +188 } +189 } +190} +191 +192#[cfg(not(wasm_browser))] +193#[derive(Debug)] +194struct QadConn { +195 conn: quinn::Connection, +196 observer: Watchable<Option<QadProbeReport>>, +197 _handle: AbortOnDropHandle<()>, +198} +199 +200#[derive(Debug)] +201struct Reports { +202 /// Do a full relay scan, even if last is `Some`. +203 next_full: bool, +204 /// Some previous reports. +205 prev: BTreeMap<Instant, Report>, +206 /// Most recent report. +207 last: Option<Report>, +208 /// Time of last full (non-incremental) report. +209 last_full: Instant, +210} +211 +212impl Default for Reports { +213 fn default() -> Self { +214 Self { +215 next_full: true, +216 prev: Default::default(), +217 last: Default::default(), +218 last_full: Instant::now(), +219 } +220 } +221} +222 +223impl Client { +224 /// Creates a new net_report client. +225 pub(crate) fn new( +226 #[cfg(not(wasm_browser))] dns_resolver: DnsResolver, +227 #[cfg(not(wasm_browser))] ip_mapped_addrs: Option<IpMappedAddresses>, +228 relay_map: RelayMap, +229 opts: Options, +230 metrics: Arc<Metrics>, +231 ) -> Self { +232 let probes = opts.as_protocols(); +233 #[cfg(any(test, feature = "test-utils"))] +234 let insecure_skip_relay_cert_verify = opts.insecure_skip_relay_cert_verify; +235 +236 #[cfg(not(wasm_browser))] +237 let quic_client = opts +238 .quic_config +239 .map(|c| iroh_relay::quic::QuicClient::new(c.ep, c.client_config)); +240 +241 #[cfg(not(wasm_browser))] +242 let socket_state = SocketState { +243 quic_client, +244 dns_resolver, +245 ip_mapped_addrs, +246 }; +247 +248 Client { +249 #[cfg(not(wasm_browser))] +250 socket_state, +251 metrics, +252 reports: Reports::default(), +253 probes, +254 relay_map, +255 #[cfg(not(wasm_browser))] +256 qad_conns: QadConns::default(), +257 #[cfg(any(test, feature = "test-utils"))] +258 insecure_skip_relay_cert_verify, +259 } +260 } +261 +262 /// Generates a [`Report`]. +263 /// +264 /// Look at [`Options`] for the different configuration options. +265 pub(crate) async fn get_report(&mut self, if_state: IfStateDetails, is_major: bool) -> Report { +266 let now = Instant::now(); 267 -268 debug!(%do_full, "net_report starting"); -269 -270 // If the last report had a captive portal and reported no UDP access, -271 // it's possible that we didn't get a useful net_report due to the -272 // captive portal blocking us. If so, make this report a full (non-incremental) one. -273 if !do_full { -274 if let Some(ref last) = self.reports.last { -275 if !last.has_udp() && last.captive_portal == Some(true) { -276 do_full = true; -277 } -278 } -279 } -280 if do_full { -281 self.reports.last = None; // causes ProbePlan::new below to do a full (initial) plan -282 self.reports.next_full = false; -283 self.reports.last_full = now; -284 self.metrics.reports_full.inc(); -285 } -286 self.metrics.reports.inc(); -287 -288 let enough_relays = std::cmp::min(self.relay_map.len(), ENOUGH_NODES); -289 #[cfg(wasm_browser)] -290 let if_state = IfStateDetails::default(); -291 #[cfg(not(wasm_browser))] -292 let if_state = IfStateDetails { -293 have_v4: if_state.have_v4, -294 have_v6: if_state.have_v6, -295 }; -296 -297 let mut report = Report::default(); -298 -299 #[cfg(not(wasm_browser))] -300 let reports = self -301 .spawn_qad_probes(&if_state, enough_relays, do_full) -302 .await; -303 -304 #[cfg(not(wasm_browser))] -305 for r in reports { -306 report.update(&r); -307 } -308 -309 let (actor, mut probe_rx) = reportgen::Client::new( -310 self.reports.last.clone(), -311 self.relay_map.clone(), -312 self.probes.clone(), -313 if_state, -314 #[cfg(not(wasm_browser))] -315 self.socket_state.clone(), -316 #[cfg(any(test, feature = "test-utils"))] -317 self.insecure_skip_relay_cert_verify, -318 ); -319 -320 let mut timeout_fut = std::pin::pin!(MaybeFuture::default()); -321 -322 #[cfg(not(wasm_browser))] -323 let mut qad_v4_stream = self.qad_conns.watch_v4(); -324 #[cfg(not(wasm_browser))] -325 let mut qad_v6_stream = self.qad_conns.watch_v6(); -326 -327 loop { -328 tokio::select! { -329 biased; -330 -331 _ = &mut timeout_fut, if timeout_fut.is_some() => { -332 trace!("timeout done, shutting down"); -333 drop(actor); // shuts down the probes -334 break; -335 } -336 -337 Some(Some(r)) = qad_v4_stream.next() => { -338 trace!(?r, "new report from QAD V4"); -339 report.update(&ProbeReport::QadIpv4(r)); -340 } -341 -342 Some(Some(r)) = qad_v6_stream.next() => { -343 trace!(?r, "new report from QAD V6"); -344 report.update(&ProbeReport::QadIpv6(r)); -345 } -346 -347 maybe_probe = probe_rx.recv() => { -348 let Some(probe_res) = maybe_probe else { -349 break; -350 }; -351 trace!(?probe_res, "handling probe"); -352 match probe_res { -353 ProbeFinished::Regular(probe) => match probe { -354 Ok(probe) => { -355 report.update(&probe); -356 if timeout_fut.is_none() { -357 if let Some(timeout) = self.have_enough_reports(enough_relays, &report) { -358 timeout_fut.as_mut().set_future(time::sleep(timeout)); -359 } -360 } -361 } -362 Err(err) => { -363 trace!("probe errored: {:?}", err); -364 } -365 }, -366 #[cfg(not(wasm_browser))] -367 ProbeFinished::CaptivePortal(portal) => { -368 report.captive_portal = portal; -369 } -370 } -371 } -372 } -373 } -374 -375 self.add_report_history_and_set_preferred_relay(&mut report); -376 debug!( -377 ?report, -378 "generated report in {:02}ms", -379 now.elapsed().as_millis() -380 ); -381 -382 report -383 } -384 -385 #[cfg(not(wasm_browser))] -386 async fn spawn_qad_probes( -387 &mut self, -388 if_state: &IfStateDetails, -389 enough_relays: usize, -390 do_full: bool, -391 ) -> Vec<ProbeReport> { -392 use tracing::{info_span, Instrument}; -393 -394 debug!("spawning QAD probes"); +268 let mut do_full = is_major +269 || self.reports.next_full +270 || now.duration_since(self.reports.last_full) > FULL_REPORT_INTERVAL; +271 +272 debug!(%do_full, "net_report starting"); +273 +274 // If the last report had a captive portal and reported no UDP access, +275 // it's possible that we didn't get a useful net_report due to the +276 // captive portal blocking us. If so, make this report a full (non-incremental) one. +277 if !do_full { +278 if let Some(ref last) = self.reports.last { +279 if !last.has_udp() && last.captive_portal == Some(true) { +280 do_full = true; +281 } +282 } +283 } +284 if do_full { +285 self.reports.last = None; // causes ProbePlan::new below to do a full (initial) plan +286 self.reports.next_full = false; +287 self.reports.last_full = now; +288 self.metrics.reports_full.inc(); +289 } +290 self.metrics.reports.inc(); +291 +292 let enough_relays = std::cmp::min(self.relay_map.len(), ENOUGH_NODES); +293 #[cfg(wasm_browser)] +294 let if_state = IfStateDetails::default(); +295 #[cfg(not(wasm_browser))] +296 let if_state = IfStateDetails { +297 have_v4: if_state.have_v4, +298 have_v6: if_state.have_v6, +299 }; +300 +301 let mut report = Report::default(); +302 +303 #[cfg(not(wasm_browser))] +304 let reports = self +305 .spawn_qad_probes(&if_state, enough_relays, do_full) +306 .await; +307 +308 #[cfg(not(wasm_browser))] +309 for r in reports { +310 report.update(&r); +311 } +312 +313 let (actor, mut probe_rx) = reportgen::Client::new( +314 self.reports.last.clone(), +315 self.relay_map.clone(), +316 self.probes.clone(), +317 if_state, +318 #[cfg(not(wasm_browser))] +319 self.socket_state.clone(), +320 #[cfg(any(test, feature = "test-utils"))] +321 self.insecure_skip_relay_cert_verify, +322 ); +323 +324 let mut timeout_fut = std::pin::pin!(MaybeFuture::default()); +325 +326 #[cfg(not(wasm_browser))] +327 let mut qad_v4_stream = self.qad_conns.watch_v4(); +328 #[cfg(wasm_browser)] +329 let mut qad_v4_stream = n0_future::stream::empty::<Option<()>>(); +330 #[cfg(not(wasm_browser))] +331 let mut qad_v6_stream = self.qad_conns.watch_v6(); +332 #[cfg(wasm_browser)] +333 let mut qad_v6_stream = n0_future::stream::empty::<Option<()>>(); +334 +335 loop { +336 tokio::select! { +337 biased; +338 +339 _ = &mut timeout_fut, if timeout_fut.is_some() => { +340 trace!("timeout done, shutting down"); +341 drop(actor); // shuts down the probes +342 break; +343 } +344 +345 Some(Some(r)) = qad_v4_stream.next() => { +346 #[cfg(not(wasm_browser))] +347 { +348 trace!(?r, "new report from QAD V4"); +349 report.update(&ProbeReport::QadIpv4(r)); +350 } +351 } +352 +353 Some(Some(r)) = qad_v6_stream.next() => { +354 #[cfg(not(wasm_browser))] +355 { +356 trace!(?r, "new report from QAD V6"); +357 report.update(&ProbeReport::QadIpv6(r)); +358 } +359 } +360 +361 maybe_probe = probe_rx.recv() => { +362 let Some(probe_res) = maybe_probe else { +363 break; +364 }; +365 trace!(?probe_res, "handling probe"); +366 match probe_res { +367 ProbeFinished::Regular(probe) => match probe { +368 Ok(probe) => { +369 report.update(&probe); +370 if timeout_fut.is_none() { +371 if let Some(timeout) = self.have_enough_reports(enough_relays, &report) { +372 timeout_fut.as_mut().set_future(time::sleep(timeout)); +373 } +374 } +375 } +376 Err(err) => { +377 trace!("probe errored: {:?}", err); +378 } +379 }, +380 #[cfg(not(wasm_browser))] +381 ProbeFinished::CaptivePortal(portal) => { +382 report.captive_portal = portal; +383 } +384 } +385 } +386 } +387 } +388 +389 self.add_report_history_and_set_preferred_relay(&mut report); +390 debug!( +391 ?report, +392 "generated report in {:02}ms", +393 now.elapsed().as_millis() +394 ); 395 -396 let Some(ref quic_client) = self.socket_state.quic_client else { -397 return Vec::new(); -398 }; -399 -400 if do_full { -401 // clear out existing connections if we are doing a full reset -402 self.qad_conns.clear(); -403 } -404 -405 if let Some((url, conn)) = &self.qad_conns.v4 { -406 // verify conn is still around -407 if let Some(reason) = conn.conn.close_reason() { -408 trace!(?url, "QAD v4 conn closed: {}", reason); -409 self.qad_conns.v4.take(); -410 } -411 } -412 if let Some((url, conn)) = &self.qad_conns.v6 { -413 // verify conn is still around -414 if let Some(reason) = conn.conn.close_reason() { -415 trace!(?url, "QAD v6 conn closed: {}", reason); -416 self.qad_conns.v6.take(); -417 } -418 } -419 if self.qad_conns.v4.is_some() && self.qad_conns.v6.is_some() == if_state.have_v6 { -420 trace!("not spawning QAD, already have probes"); -421 return self.qad_conns.current(); -422 } -423 -424 // TODO: randomize choice? -425 const MAX_RELAYS: usize = 5; -426 -427 let mut v4_buf = JoinSet::new(); -428 let cancel_v4 = CancellationToken::new(); -429 let mut v6_buf = JoinSet::new(); -430 let cancel_v6 = CancellationToken::new(); -431 -432 for relay_node in self.relay_map.nodes().take(MAX_RELAYS) { -433 if if_state.have_v4 { -434 debug!(?relay_node.url, "v4 QAD probe"); -435 let ip_mapped_addrs = self.socket_state.ip_mapped_addrs.clone(); -436 let relay_node = relay_node.clone(); -437 let dns_resolver = self.socket_state.dns_resolver.clone(); -438 let quic_client = quic_client.clone(); -439 let relay_url = relay_node.url.clone(); -440 v4_buf.spawn( -441 cancel_v4 -442 .child_token() -443 .run_until_cancelled_owned(time::timeout( -444 PROBES_TIMEOUT, -445 run_probe_v4(ip_mapped_addrs, relay_node, quic_client, dns_resolver), -446 )) -447 .instrument(info_span!("QAD IPv6", %relay_url)), -448 ); -449 } -450 -451 if if_state.have_v6 { -452 debug!(?relay_node.url, "v6 QAD probe"); -453 let ip_mapped_addrs = self.socket_state.ip_mapped_addrs.clone(); -454 let relay_node = relay_node.clone(); -455 let dns_resolver = self.socket_state.dns_resolver.clone(); -456 let quic_client = quic_client.clone(); -457 let relay_url = relay_node.url.clone(); -458 v6_buf.spawn( -459 cancel_v6 -460 .child_token() -461 .run_until_cancelled_owned(time::timeout( -462 PROBES_TIMEOUT, -463 run_probe_v6(ip_mapped_addrs, relay_node, quic_client, dns_resolver), -464 )) -465 .instrument(info_span!("QAD IPv6", %relay_url)), -466 ); -467 } -468 } -469 -470 let mut reports = Vec::new(); -471 -472 loop { -473 trace!("tick: qad probes"); -474 -475 if reports.len() >= enough_relays { -476 debug!("enough probes: {}", reports.len()); -477 cancel_v4.cancel(); -478 cancel_v6.cancel(); -479 break; -480 } -481 -482 // TODO: verify select and join_next work as expected -483 tokio::select! { -484 biased; +396 report +397 } +398 +399 #[cfg(not(wasm_browser))] +400 async fn spawn_qad_probes( +401 &mut self, +402 if_state: &IfStateDetails, +403 enough_relays: usize, +404 do_full: bool, +405 ) -> Vec<ProbeReport> { +406 use tracing::{info_span, Instrument}; +407 +408 debug!("spawning QAD probes"); +409 +410 let Some(ref quic_client) = self.socket_state.quic_client else { +411 return Vec::new(); +412 }; +413 +414 if do_full { +415 // clear out existing connections if we are doing a full reset +416 self.qad_conns.clear(); +417 } +418 +419 if let Some((url, conn)) = &self.qad_conns.v4 { +420 // verify conn is still around +421 if let Some(reason) = conn.conn.close_reason() { +422 trace!(?url, "QAD v4 conn closed: {}", reason); +423 self.qad_conns.v4.take(); +424 } +425 } +426 if let Some((url, conn)) = &self.qad_conns.v6 { +427 // verify conn is still around +428 if let Some(reason) = conn.conn.close_reason() { +429 trace!(?url, "QAD v6 conn closed: {}", reason); +430 self.qad_conns.v6.take(); +431 } +432 } +433 if self.qad_conns.v4.is_some() && self.qad_conns.v6.is_some() == if_state.have_v6 { +434 trace!("not spawning QAD, already have probes"); +435 return self.qad_conns.current(); +436 } +437 +438 // TODO: randomize choice? +439 const MAX_RELAYS: usize = 5; +440 +441 let mut v4_buf = JoinSet::new(); +442 let cancel_v4 = CancellationToken::new(); +443 let mut v6_buf = JoinSet::new(); +444 let cancel_v6 = CancellationToken::new(); +445 +446 for relay_node in self.relay_map.nodes().take(MAX_RELAYS) { +447 if if_state.have_v4 { +448 debug!(?relay_node.url, "v4 QAD probe"); +449 let ip_mapped_addrs = self.socket_state.ip_mapped_addrs.clone(); +450 let relay_node = relay_node.clone(); +451 let dns_resolver = self.socket_state.dns_resolver.clone(); +452 let quic_client = quic_client.clone(); +453 let relay_url = relay_node.url.clone(); +454 v4_buf.spawn( +455 cancel_v4 +456 .child_token() +457 .run_until_cancelled_owned(time::timeout( +458 PROBES_TIMEOUT, +459 run_probe_v4(ip_mapped_addrs, relay_node, quic_client, dns_resolver), +460 )) +461 .instrument(info_span!("QAD IPv6", %relay_url)), +462 ); +463 } +464 +465 if if_state.have_v6 { +466 debug!(?relay_node.url, "v6 QAD probe"); +467 let ip_mapped_addrs = self.socket_state.ip_mapped_addrs.clone(); +468 let relay_node = relay_node.clone(); +469 let dns_resolver = self.socket_state.dns_resolver.clone(); +470 let quic_client = quic_client.clone(); +471 let relay_url = relay_node.url.clone(); +472 v6_buf.spawn( +473 cancel_v6 +474 .child_token() +475 .run_until_cancelled_owned(time::timeout( +476 PROBES_TIMEOUT, +477 run_probe_v6(ip_mapped_addrs, relay_node, quic_client, dns_resolver), +478 )) +479 .instrument(info_span!("QAD IPv6", %relay_url)), +480 ); +481 } +482 } +483 +484 let mut reports = Vec::new(); 485 -486 val = v4_buf.join_next(), if !v4_buf.is_empty() => { -487 if let Some(Ok(Some(Ok(res)))) = val { -488 match res { -489 Ok((r, conn)) => { -490 debug!(?r, "got v4 QAD conn"); -491 let url = r.node.clone(); -492 reports.push(ProbeReport::QadIpv4(r)); -493 if self.qad_conns.v4.is_none() { -494 self.qad_conns.v4.replace((url, conn)); -495 } else { -496 conn.conn.close(QUIC_ADDR_DISC_CLOSE_CODE, QUIC_ADDR_DISC_CLOSE_REASON); -497 } -498 } -499 Err(err) => { -500 debug!("probe v4 failed: {:?}", err); -501 } -502 } -503 } else { -504 dbg!(val); -505 } -506 } -507 val = v6_buf.join_next(), if !v6_buf.is_empty() => { -508 if let Some(Ok(Some(Ok(res)))) = val { -509 match res { -510 Ok((r, conn)) => { -511 debug!(?r, "got v6 QAD conn"); -512 let url = r.node.clone(); -513 reports.push(ProbeReport::QadIpv6(r)); -514 if self.qad_conns.v6.is_none() { -515 self.qad_conns.v6.replace((url, conn)); -516 } else { -517 conn.conn.close(QUIC_ADDR_DISC_CLOSE_CODE, QUIC_ADDR_DISC_CLOSE_REASON); -518 } -519 } -520 Err(err) => { -521 debug!("probe v6 failed: {:?}", err); -522 } -523 } -524 } else { -525 dbg!(val); -526 } -527 } -528 else => { -529 break; -530 } -531 } -532 } -533 -534 reports -535 } -536 -537 fn have_enough_reports(&self, enough_relays: usize, report: &Report) -> Option<Duration> { -538 // Once we've heard from enough relay servers (3), start a timer to give up on the other -539 // probes. The timer's duration is a function of whether this is our initial full -540 // probe or an incremental one. For incremental ones, wait for the duration of the -541 // slowest relay. For initial ones, double that. -542 let latencies: Vec<Duration> = report.relay_latency.iter().map(|(_, l)| l).collect(); -543 let have_enough_latencies = latencies.len() >= enough_relays; -544 -545 if have_enough_latencies { -546 let timeout = match self.reports.last.is_some() { -547 true => Duration::from_secs(0), -548 false => latencies -549 .iter() -550 .max() -551 .copied() -552 .unwrap_or(DEFAULT_MAX_LATENCY), -553 }; -554 debug!( -555 reports=latencies.len(), -556 delay=?timeout, -557 "Have enough probe reports, aborting further probes soon", -558 ); -559 -560 Some(timeout) -561 } else { -562 None -563 } -564 } -565 -566 /// Adds `r` to the set of recent Reports and mutates `r.preferred_relay` to contain the best recent one. -567 fn add_report_history_and_set_preferred_relay(&mut self, r: &mut Report) { -568 let mut prev_relay = None; -569 if let Some(ref last) = self.reports.last { -570 prev_relay.clone_from(&last.preferred_relay); -571 -572 // If we don't have new information, copy this from the last report -573 if r.mapping_varies_by_dest_ipv4.is_none() { -574 r.mapping_varies_by_dest_ipv4 = last.mapping_varies_by_dest_ipv4; -575 } -576 if r.mapping_varies_by_dest_ipv6.is_none() { -577 r.mapping_varies_by_dest_ipv6 = last.mapping_varies_by_dest_ipv6; -578 } -579 } -580 -581 let now = Instant::now(); -582 const MAX_AGE: Duration = Duration::from_secs(5 * 60); -583 -584 // relay ID => its best recent latency in last MAX_AGE -585 let mut best_recent = RelayLatencies::default(); -586 -587 // chain the current report as we are still mutating it -588 let prevs_iter = self -589 .reports -590 .prev -591 .iter() -592 .map(|(a, b)| -> (&Instant, &Report) { (a, b) }); -593 -594 let mut to_remove = Vec::new(); -595 for (t, pr) in prevs_iter { -596 if now.duration_since(*t) > MAX_AGE { -597 to_remove.push(*t); -598 continue; -599 } -600 best_recent.merge(&pr.relay_latency); -601 } -602 // merge in current run -603 best_recent.merge(&r.relay_latency); -604 -605 for t in to_remove { -606 self.reports.prev.remove(&t); -607 } -608 -609 // Then, pick which currently-alive relay server from the -610 // current report has the best latency over the past MAX_AGE. -611 let mut best_any = Duration::default(); -612 let mut old_relay_cur_latency = Duration::default(); -613 { -614 for (url, duration) in r.relay_latency.iter() { -615 if Some(url) == prev_relay.as_ref() { -616 old_relay_cur_latency = duration; -617 } -618 if let Some(best) = best_recent.get(url) { -619 if r.preferred_relay.is_none() || best < best_any { -620 best_any = best; -621 r.preferred_relay.replace(url.clone()); -622 } -623 } -624 } -625 -626 // If we're changing our preferred relay but the old one's still -627 // accessible and the new one's not much better, just stick with -628 // where we are. -629 if prev_relay.is_some() -630 && r.preferred_relay != prev_relay -631 && !old_relay_cur_latency.is_zero() -632 && best_any > old_relay_cur_latency / 3 * 2 -633 { -634 r.preferred_relay = prev_relay; -635 } -636 } -637 -638 self.reports.prev.insert(now, r.clone()); -639 self.reports.last = Some(r.clone()); -640 } -641} -642 -643async fn run_probe_v4( -644 ip_mapped_addrs: Option<IpMappedAddresses>, -645 relay_node: Arc<RelayNode>, -646 quic_client: QuicClient, -647 dns_resolver: DnsResolver, -648) -> n0_snafu::Result<(QadProbeReport, QadConn)> { -649 use n0_snafu::ResultExt; -650 -651 let relay_addr_orig = reportgen::get_relay_addr_ipv4(&dns_resolver, &relay_node).await?; -652 let relay_addr = -653 reportgen::maybe_to_mapped_addr(ip_mapped_addrs.as_ref(), relay_addr_orig.into()); -654 -655 debug!(?relay_addr_orig, ?relay_addr, "relay addr v4"); -656 let host = relay_node.url.host_str().context("missing host url")?; -657 let conn = quic_client.create_conn(relay_addr, host).await?; -658 let mut receiver = conn.observed_external_addr(); -659 -660 // wait for an addr -661 let addr = receiver -662 .wait_for(|addr| addr.is_some()) -663 .await -664 .context("receiver dropped")? -665 .expect("known"); -666 let report = QadProbeReport { -667 node: relay_node.url.clone(), -668 addr: SocketAddr::new(addr.ip().to_canonical(), addr.port()), -669 latency: conn.rtt(), -670 }; -671 -672 let observer = Watchable::new(None); -673 // TODO: this is sad -674 let ob = observer.clone(); -675 let node = relay_node.url.clone(); -676 let conn2 = conn.clone(); -677 let handle = task::spawn(async move { -678 loop { -679 let val = *receiver.borrow(); -680 // if we've sent to an ipv4 address, but received an observed address -681 // that is ivp6 then the address is an [IPv4-Mapped IPv6 Addresses](https://doc.rust-lang.org/beta/std/net/struct.Ipv6Addr.html#ipv4-mapped-ipv6-addresses) -682 let val = val.map(|val| SocketAddr::new(val.ip().to_canonical(), val.port())); -683 let latency = conn2.rtt(); -684 trace!(?val, ?relay_addr, ?latency, "got addr V4"); -685 if ob -686 .set(val.map(|addr| QadProbeReport { -687 node: node.clone(), -688 addr, -689 latency, -690 })) -691 .is_err() -692 { -693 // cancel if the observer is gone -694 break; -695 } -696 if receiver.changed().await.is_err() { -697 break; -698 } -699 } -700 }); -701 let handle = AbortOnDropHandle::new(handle); -702 -703 Ok(( -704 report, -705 QadConn { -706 conn, -707 observer, -708 _handle: handle, -709 }, -710 )) -711} -712 -713async fn run_probe_v6( -714 ip_mapped_addrs: Option<IpMappedAddresses>, -715 relay_node: Arc<RelayNode>, -716 quic_client: QuicClient, -717 dns_resolver: DnsResolver, -718) -> n0_snafu::Result<(QadProbeReport, QadConn)> { -719 use n0_snafu::ResultExt; -720 let relay_addr_orig = reportgen::get_relay_addr_ipv6(&dns_resolver, &relay_node).await?; -721 let relay_addr = -722 reportgen::maybe_to_mapped_addr(ip_mapped_addrs.as_ref(), relay_addr_orig.into()); -723 -724 debug!(?relay_addr_orig, ?relay_addr, "relay addr v6"); -725 let host = relay_node.url.host_str().context("missing host url")?; -726 let conn = quic_client.create_conn(relay_addr, host).await?; -727 let mut receiver = conn.observed_external_addr(); -728 -729 // wait for an addr -730 let addr = receiver -731 .wait_for(|addr| addr.is_some()) -732 .await -733 .context("receiver dropped")? -734 .expect("known"); -735 let report = QadProbeReport { -736 node: relay_node.url.clone(), -737 addr: SocketAddr::new(addr.ip().to_canonical(), addr.port()), -738 latency: conn.rtt(), -739 }; -740 -741 let observer = Watchable::new(None); -742 // TODO: this is sad -743 let ob = observer.clone(); -744 let node = relay_node.url.clone(); -745 let conn2 = conn.clone(); -746 let handle = task::spawn(async move { -747 loop { -748 let val = *receiver.borrow(); -749 // if we've sent to an ipv4 address, but received an observed address -750 // that is ivp6 then the address is an IPv4-Mapped IPv6 Addresses -751 let val = val.map(|val| SocketAddr::new(val.ip().to_canonical(), val.port())); -752 let latency = conn2.rtt(); -753 trace!(?val, ?relay_addr, ?latency, "got addr V6"); -754 if ob -755 .set(val.map(|addr| QadProbeReport { -756 node: node.clone(), -757 addr, -758 latency, -759 })) -760 .is_err() -761 { -762 // cancel if the observer is gone -763 break; -764 } -765 if receiver.changed().await.is_err() { -766 break; -767 } -768 } -769 }); -770 let handle = AbortOnDropHandle::new(handle); -771 -772 Ok(( -773 report, -774 QadConn { -775 conn, -776 observer, -777 _handle: handle, -778 }, -779 )) -780} -781 -782#[cfg(test)] -783mod test_utils { -784 //! Creates a relay server against which to perform tests -785 -786 use iroh_relay::{server, RelayNode, RelayQuicConfig}; +486 loop { +487 trace!("tick: qad probes"); +488 +489 if reports.len() >= enough_relays { +490 debug!("enough probes: {}", reports.len()); +491 cancel_v4.cancel(); +492 cancel_v6.cancel(); +493 break; +494 } +495 +496 // TODO: verify select and join_next work as expected +497 tokio::select! { +498 biased; +499 +500 val = v4_buf.join_next(), if !v4_buf.is_empty() => { +501 if let Some(Ok(Some(Ok(res)))) = val { +502 match res { +503 Ok((r, conn)) => { +504 debug!(?r, "got v4 QAD conn"); +505 let url = r.node.clone(); +506 reports.push(ProbeReport::QadIpv4(r)); +507 if self.qad_conns.v4.is_none() { +508 self.qad_conns.v4.replace((url, conn)); +509 } else { +510 conn.conn.close(QUIC_ADDR_DISC_CLOSE_CODE, QUIC_ADDR_DISC_CLOSE_REASON); +511 } +512 } +513 Err(err) => { +514 debug!("probe v4 failed: {:?}", err); +515 } +516 } +517 } else { +518 dbg!(val); +519 } +520 } +521 val = v6_buf.join_next(), if !v6_buf.is_empty() => { +522 if let Some(Ok(Some(Ok(res)))) = val { +523 match res { +524 Ok((r, conn)) => { +525 debug!(?r, "got v6 QAD conn"); +526 let url = r.node.clone(); +527 reports.push(ProbeReport::QadIpv6(r)); +528 if self.qad_conns.v6.is_none() { +529 self.qad_conns.v6.replace((url, conn)); +530 } else { +531 conn.conn.close(QUIC_ADDR_DISC_CLOSE_CODE, QUIC_ADDR_DISC_CLOSE_REASON); +532 } +533 } +534 Err(err) => { +535 debug!("probe v6 failed: {:?}", err); +536 } +537 } +538 } else { +539 dbg!(val); +540 } +541 } +542 else => { +543 break; +544 } +545 } +546 } +547 +548 reports +549 } +550 +551 fn have_enough_reports(&self, enough_relays: usize, report: &Report) -> Option<Duration> { +552 // Once we've heard from enough relay servers (3), start a timer to give up on the other +553 // probes. The timer's duration is a function of whether this is our initial full +554 // probe or an incremental one. For incremental ones, wait for the duration of the +555 // slowest relay. For initial ones, double that. +556 let latencies: Vec<Duration> = report.relay_latency.iter().map(|(_, l)| l).collect(); +557 let have_enough_latencies = latencies.len() >= enough_relays; +558 +559 if have_enough_latencies { +560 let timeout = match self.reports.last.is_some() { +561 true => Duration::from_secs(0), +562 false => latencies +563 .iter() +564 .max() +565 .copied() +566 .unwrap_or(DEFAULT_MAX_LATENCY), +567 }; +568 debug!( +569 reports=latencies.len(), +570 delay=?timeout, +571 "Have enough probe reports, aborting further probes soon", +572 ); +573 +574 Some(timeout) +575 } else { +576 None +577 } +578 } +579 +580 /// Adds `r` to the set of recent Reports and mutates `r.preferred_relay` to contain the best recent one. +581 fn add_report_history_and_set_preferred_relay(&mut self, r: &mut Report) { +582 let mut prev_relay = None; +583 if let Some(ref last) = self.reports.last { +584 prev_relay.clone_from(&last.preferred_relay); +585 +586 // If we don't have new information, copy this from the last report +587 if r.mapping_varies_by_dest_ipv4.is_none() { +588 r.mapping_varies_by_dest_ipv4 = last.mapping_varies_by_dest_ipv4; +589 } +590 if r.mapping_varies_by_dest_ipv6.is_none() { +591 r.mapping_varies_by_dest_ipv6 = last.mapping_varies_by_dest_ipv6; +592 } +593 } +594 +595 let now = Instant::now(); +596 const MAX_AGE: Duration = Duration::from_secs(5 * 60); +597 +598 // relay ID => its best recent latency in last MAX_AGE +599 let mut best_recent = RelayLatencies::default(); +600 +601 // chain the current report as we are still mutating it +602 let prevs_iter = self +603 .reports +604 .prev +605 .iter() +606 .map(|(a, b)| -> (&Instant, &Report) { (a, b) }); +607 +608 let mut to_remove = Vec::new(); +609 for (t, pr) in prevs_iter { +610 if now.duration_since(*t) > MAX_AGE { +611 to_remove.push(*t); +612 continue; +613 } +614 best_recent.merge(&pr.relay_latency); +615 } +616 // merge in current run +617 best_recent.merge(&r.relay_latency); +618 +619 for t in to_remove { +620 self.reports.prev.remove(&t); +621 } +622 +623 // Then, pick which currently-alive relay server from the +624 // current report has the best latency over the past MAX_AGE. +625 let mut best_any = Duration::default(); +626 let mut old_relay_cur_latency = Duration::default(); +627 { +628 for (url, duration) in r.relay_latency.iter() { +629 if Some(url) == prev_relay.as_ref() { +630 old_relay_cur_latency = duration; +631 } +632 if let Some(best) = best_recent.get(url) { +633 if r.preferred_relay.is_none() || best < best_any { +634 best_any = best; +635 r.preferred_relay.replace(url.clone()); +636 } +637 } +638 } +639 +640 // If we're changing our preferred relay but the old one's still +641 // accessible and the new one's not much better, just stick with +642 // where we are. +643 if prev_relay.is_some() +644 && r.preferred_relay != prev_relay +645 && !old_relay_cur_latency.is_zero() +646 && best_any > old_relay_cur_latency / 3 * 2 +647 { +648 r.preferred_relay = prev_relay; +649 } +650 } +651 +652 self.reports.prev.insert(now, r.clone()); +653 self.reports.last = Some(r.clone()); +654 } +655} +656 +657#[cfg(not(wasm_browser))] +658async fn run_probe_v4( +659 ip_mapped_addrs: Option<IpMappedAddresses>, +660 relay_node: Arc<RelayNode>, +661 quic_client: QuicClient, +662 dns_resolver: DnsResolver, +663) -> n0_snafu::Result<(QadProbeReport, QadConn)> { +664 use n0_snafu::ResultExt; +665 +666 let relay_addr_orig = reportgen::get_relay_addr_ipv4(&dns_resolver, &relay_node).await?; +667 let relay_addr = +668 reportgen::maybe_to_mapped_addr(ip_mapped_addrs.as_ref(), relay_addr_orig.into()); +669 +670 debug!(?relay_addr_orig, ?relay_addr, "relay addr v4"); +671 let host = relay_node.url.host_str().context("missing host url")?; +672 let conn = quic_client.create_conn(relay_addr, host).await?; +673 let mut receiver = conn.observed_external_addr(); +674 +675 // wait for an addr +676 let addr = receiver +677 .wait_for(|addr| addr.is_some()) +678 .await +679 .context("receiver dropped")? +680 .expect("known"); +681 let report = QadProbeReport { +682 node: relay_node.url.clone(), +683 addr: SocketAddr::new(addr.ip().to_canonical(), addr.port()), +684 latency: conn.rtt(), +685 }; +686 +687 let observer = Watchable::new(None); +688 // TODO: this is sad +689 let ob = observer.clone(); +690 let node = relay_node.url.clone(); +691 let conn2 = conn.clone(); +692 let handle = task::spawn(async move { +693 loop { +694 let val = *receiver.borrow(); +695 // if we've sent to an ipv4 address, but received an observed address +696 // that is ivp6 then the address is an [IPv4-Mapped IPv6 Addresses](https://doc.rust-lang.org/beta/std/net/struct.Ipv6Addr.html#ipv4-mapped-ipv6-addresses) +697 let val = val.map(|val| SocketAddr::new(val.ip().to_canonical(), val.port())); +698 let latency = conn2.rtt(); +699 trace!(?val, ?relay_addr, ?latency, "got addr V4"); +700 if ob +701 .set(val.map(|addr| QadProbeReport { +702 node: node.clone(), +703 addr, +704 latency, +705 })) +706 .is_err() +707 { +708 // cancel if the observer is gone +709 break; +710 } +711 if receiver.changed().await.is_err() { +712 break; +713 } +714 } +715 }); +716 let handle = AbortOnDropHandle::new(handle); +717 +718 Ok(( +719 report, +720 QadConn { +721 conn, +722 observer, +723 _handle: handle, +724 }, +725 )) +726} +727 +728#[cfg(not(wasm_browser))] +729async fn run_probe_v6( +730 ip_mapped_addrs: Option<IpMappedAddresses>, +731 relay_node: Arc<RelayNode>, +732 quic_client: QuicClient, +733 dns_resolver: DnsResolver, +734) -> n0_snafu::Result<(QadProbeReport, QadConn)> { +735 use n0_snafu::ResultExt; +736 let relay_addr_orig = reportgen::get_relay_addr_ipv6(&dns_resolver, &relay_node).await?; +737 let relay_addr = +738 reportgen::maybe_to_mapped_addr(ip_mapped_addrs.as_ref(), relay_addr_orig.into()); +739 +740 debug!(?relay_addr_orig, ?relay_addr, "relay addr v6"); +741 let host = relay_node.url.host_str().context("missing host url")?; +742 let conn = quic_client.create_conn(relay_addr, host).await?; +743 let mut receiver = conn.observed_external_addr(); +744 +745 // wait for an addr +746 let addr = receiver +747 .wait_for(|addr| addr.is_some()) +748 .await +749 .context("receiver dropped")? +750 .expect("known"); +751 let report = QadProbeReport { +752 node: relay_node.url.clone(), +753 addr: SocketAddr::new(addr.ip().to_canonical(), addr.port()), +754 latency: conn.rtt(), +755 }; +756 +757 let observer = Watchable::new(None); +758 // TODO: this is sad +759 let ob = observer.clone(); +760 let node = relay_node.url.clone(); +761 let conn2 = conn.clone(); +762 let handle = task::spawn(async move { +763 loop { +764 let val = *receiver.borrow(); +765 // if we've sent to an ipv4 address, but received an observed address +766 // that is ivp6 then the address is an IPv4-Mapped IPv6 Addresses +767 let val = val.map(|val| SocketAddr::new(val.ip().to_canonical(), val.port())); +768 let latency = conn2.rtt(); +769 trace!(?val, ?relay_addr, ?latency, "got addr V6"); +770 if ob +771 .set(val.map(|addr| QadProbeReport { +772 node: node.clone(), +773 addr, +774 latency, +775 })) +776 .is_err() +777 { +778 // cancel if the observer is gone +779 break; +780 } +781 if receiver.changed().await.is_err() { +782 break; +783 } +784 } +785 }); +786 let handle = AbortOnDropHandle::new(handle); 787 -788 pub(crate) async fn relay() -> (server::Server, RelayNode) { -789 let server = server::Server::spawn(server::testing::server_config()) -790 .await -791 .expect("should serve relay"); -792 let quic = Some(RelayQuicConfig { -793 port: server.quic_addr().expect("server should run quic").port(), -794 }); -795 let node_desc = RelayNode { -796 url: server.https_url().expect("should work as relay"), -797 quic, -798 }; -799 -800 (server, node_desc) -801 } -802 -803 /// Create a [`crate::RelayMap`] of the given size. -804 /// -805 /// This function uses [`relay`]. Note that the returned map uses internal order that will -806 /// often _not_ match the order of the servers. -807 pub(crate) async fn relay_map(relays: usize) -> (Vec<server::Server>, crate::RelayMap) { -808 let mut servers = Vec::with_capacity(relays); -809 let mut nodes = Vec::with_capacity(relays); -810 for _ in 0..relays { -811 let (relay_server, node) = relay().await; -812 servers.push(relay_server); -813 nodes.push(node); -814 } -815 (servers, crate::RelayMap::from_iter(nodes)) -816 } -817} +788 Ok(( +789 report, +790 QadConn { +791 conn, +792 observer, +793 _handle: handle, +794 }, +795 )) +796} +797 +798#[cfg(test)] +799mod test_utils { +800 //! Creates a relay server against which to perform tests +801 +802 use iroh_relay::{server, RelayNode, RelayQuicConfig}; +803 +804 pub(crate) async fn relay() -> (server::Server, RelayNode) { +805 let server = server::Server::spawn(server::testing::server_config()) +806 .await +807 .expect("should serve relay"); +808 let quic = Some(RelayQuicConfig { +809 port: server.quic_addr().expect("server should run quic").port(), +810 }); +811 let node_desc = RelayNode { +812 url: server.https_url().expect("should work as relay"), +813 quic, +814 }; +815 +816 (server, node_desc) +817 } 818 -819#[cfg(test)] -820mod tests { -821 use std::net::{Ipv4Addr, SocketAddr}; -822 -823 use iroh_base::RelayUrl; -824 use iroh_relay::dns::DnsResolver; -825 use n0_snafu::{Result, ResultExt}; -826 use tokio_util::sync::CancellationToken; -827 use tracing_test::traced_test; -828 -829 use super::*; -830 use crate::net_report::probes::Probe; -831 -832 #[tokio::test] -833 #[traced_test] -834 async fn test_basic() -> Result<()> { -835 let (server, relay) = test_utils::relay().await; -836 let client_config = iroh_relay::client::make_dangerous_client_config(); -837 let ep = quinn::Endpoint::client(SocketAddr::new(Ipv4Addr::LOCALHOST.into(), 0)).e()?; -838 let quic_addr_disc = QuicConfig { -839 ep: ep.clone(), -840 client_config, -841 ipv4: true, -842 ipv6: true, -843 }; -844 let relay_map = RelayMap::from(relay); -845 -846 let resolver = DnsResolver::new(); -847 let opts = Options::default().quic_config(Some(quic_addr_disc.clone())); -848 let mut client = Client::new( -849 resolver.clone(), -850 None, -851 relay_map.clone(), -852 opts.clone(), -853 Default::default(), -854 ); -855 let if_state = IfStateDetails::fake(); -856 -857 // Note that the ProbePlan will change with each iteration. -858 for i in 0..5 { -859 let cancel = CancellationToken::new(); -860 println!("--round {}", i); -861 let r = client.get_report(if_state.clone(), false).await; -862 -863 assert!(r.has_udp(), "want UDP"); -864 assert_eq!( -865 r.relay_latency.len(), -866 1, -867 "expected 1 key in RelayLatency; got {}", -868 r.relay_latency.len() -869 ); -870 assert!( -871 r.relay_latency.iter().next().is_some(), -872 "expected key 1 in RelayLatency; got {:?}", -873 r.relay_latency -874 ); -875 assert!(r.global_v4.is_some(), "expected globalV4 set"); -876 assert!(r.preferred_relay.is_some(),); -877 cancel.cancel(); -878 } -879 -880 ep.wait_idle().await; -881 server.shutdown().await?; -882 -883 Ok(()) -884 } -885 -886 #[tokio::test(flavor = "current_thread", start_paused = true)] -887 async fn test_add_report_history_set_preferred_relay() -> Result { -888 fn relay_url(i: u16) -> RelayUrl { -889 format!("http://{i}.com").parse().unwrap() -890 } -891 -892 // report returns a *Report from (relay host, Duration)+ pairs. -893 fn report(a: impl IntoIterator<Item = (&'static str, u64)>) -> Option<Report> { -894 let mut report = Report::default(); -895 for (s, d) in a { -896 assert!(s.starts_with('d'), "invalid relay server key"); -897 let id: u16 = s[1..].parse().unwrap(); -898 report.relay_latency.update_relay( -899 relay_url(id), -900 Duration::from_secs(d), -901 Probe::QadIpv4, -902 ); -903 } -904 -905 Some(report) -906 } -907 struct Step { -908 /// Delay in seconds -909 after: u64, -910 r: Option<Report>, -911 } -912 struct Test { -913 name: &'static str, -914 steps: Vec<Step>, -915 /// want PreferredRelay on final step -916 want_relay: Option<RelayUrl>, -917 // wanted len(c.prev) -918 want_prev_len: usize, -919 } -920 -921 let tests = [ -922 Test { -923 name: "first_reading", -924 steps: vec![Step { -925 after: 0, -926 r: report([("d1", 2), ("d2", 3)]), -927 }], -928 want_prev_len: 1, -929 want_relay: Some(relay_url(1)), -930 }, -931 Test { -932 name: "with_two", -933 steps: vec![ -934 Step { -935 after: 0, -936 r: report([("d1", 2), ("d2", 3)]), -937 }, -938 Step { -939 after: 1, -940 r: report([("d1", 4), ("d2", 3)]), -941 }, -942 ], -943 want_prev_len: 2, -944 want_relay: Some(relay_url(1)), // t0's d1 of 2 is still best -945 }, -946 Test { -947 name: "but_now_d1_gone", -948 steps: vec![ -949 Step { -950 after: 0, -951 r: report([("d1", 2), ("d2", 3)]), -952 }, -953 Step { -954 after: 1, -955 r: report([("d1", 4), ("d2", 3)]), -956 }, -957 Step { -958 after: 2, -959 r: report([("d2", 3)]), -960 }, -961 ], -962 want_prev_len: 3, -963 want_relay: Some(relay_url(2)), // only option -964 }, -965 Test { -966 name: "d1_is_back", -967 steps: vec![ -968 Step { -969 after: 0, -970 r: report([("d1", 2), ("d2", 3)]), -971 }, -972 Step { -973 after: 1, -974 r: report([("d1", 4), ("d2", 3)]), -975 }, -976 Step { -977 after: 2, -978 r: report([("d2", 3)]), -979 }, -980 Step { -981 after: 3, -982 r: report([("d1", 4), ("d2", 3)]), -983 }, // same as 2 seconds ago -984 ], -985 want_prev_len: 4, -986 want_relay: Some(relay_url(1)), // t0's d1 of 2 is still best -987 }, -988 Test { -989 name: "things_clean_up", -990 steps: vec![ -991 Step { -992 after: 0, -993 r: report([("d1", 1), ("d2", 2)]), -994 }, -995 Step { -996 after: 1, -997 r: report([("d1", 1), ("d2", 2)]), -998 }, -999 Step { -1000 after: 2, -1001 r: report([("d1", 1), ("d2", 2)]), -1002 }, -1003 Step { -1004 after: 3, -1005 r: report([("d1", 1), ("d2", 2)]), -1006 }, -1007 Step { -1008 after: 10 * 60, -1009 r: report([("d3", 3)]), -1010 }, -1011 ], -1012 want_prev_len: 1, // t=[0123]s all gone. (too old, older than 10 min) -1013 want_relay: Some(relay_url(3)), // only option -1014 }, -1015 Test { -1016 name: "preferred_relay_hysteresis_no_switch", -1017 steps: vec![ -1018 Step { -1019 after: 0, -1020 r: report([("d1", 4), ("d2", 5)]), -1021 }, -1022 Step { -1023 after: 1, -1024 r: report([("d1", 4), ("d2", 3)]), -1025 }, -1026 ], -1027 want_prev_len: 2, -1028 want_relay: Some(relay_url(1)), // 2 didn't get fast enough -1029 }, -1030 Test { -1031 name: "preferred_relay_hysteresis_do_switch", -1032 steps: vec![ -1033 Step { -1034 after: 0, -1035 r: report([("d1", 4), ("d2", 5)]), -1036 }, -1037 Step { -1038 after: 1, -1039 r: report([("d1", 4), ("d2", 1)]), -1040 }, -1041 ], -1042 want_prev_len: 2, -1043 want_relay: Some(relay_url(2)), // 2 got fast enough -1044 }, -1045 ]; -1046 let resolver = DnsResolver::new(); -1047 for mut tt in tests { -1048 println!("test: {}", tt.name); -1049 let relay_map = RelayMap::empty(); -1050 let opts = Options::default(); -1051 let mut client = -1052 Client::new(resolver.clone(), None, relay_map, opts, Default::default()); -1053 for s in &mut tt.steps { -1054 // trigger the timer -1055 tokio::time::advance(Duration::from_secs(s.after)).await; -1056 client.add_report_history_and_set_preferred_relay(s.r.as_mut().unwrap()); -1057 } -1058 let last_report = tt.steps.last().unwrap().r.clone().unwrap(); -1059 let got = client.reports.prev.len(); -1060 let want = tt.want_prev_len; -1061 assert_eq!(got, want, "prev length"); -1062 let got = &last_report.preferred_relay; -1063 let want = &tt.want_relay; -1064 assert_eq!(got, want, "preferred_relay"); -1065 } -1066 -1067 Ok(()) -1068 } -1069}
    \ No newline at end of file +819 /// Create a [`crate::RelayMap`] of the given size. +820 /// +821 /// This function uses [`relay`]. Note that the returned map uses internal order that will +822 /// often _not_ match the order of the servers. +823 pub(crate) async fn relay_map(relays: usize) -> (Vec<server::Server>, crate::RelayMap) { +824 let mut servers = Vec::with_capacity(relays); +825 let mut nodes = Vec::with_capacity(relays); +826 for _ in 0..relays { +827 let (relay_server, node) = relay().await; +828 servers.push(relay_server); +829 nodes.push(node); +830 } +831 (servers, crate::RelayMap::from_iter(nodes)) +832 } +833} +834 +835#[cfg(test)] +836mod tests { +837 use std::net::{Ipv4Addr, SocketAddr}; +838 +839 use iroh_base::RelayUrl; +840 use iroh_relay::dns::DnsResolver; +841 use n0_snafu::{Result, ResultExt}; +842 use tokio_util::sync::CancellationToken; +843 use tracing_test::traced_test; +844 +845 use super::*; +846 use crate::net_report::probes::Probe; +847 +848 #[tokio::test] +849 #[traced_test] +850 async fn test_basic() -> Result<()> { +851 let (server, relay) = test_utils::relay().await; +852 let client_config = iroh_relay::client::make_dangerous_client_config(); +853 let ep = quinn::Endpoint::client(SocketAddr::new(Ipv4Addr::LOCALHOST.into(), 0)).e()?; +854 let quic_addr_disc = QuicConfig { +855 ep: ep.clone(), +856 client_config, +857 ipv4: true, +858 ipv6: true, +859 }; +860 let relay_map = RelayMap::from(relay); +861 +862 let resolver = DnsResolver::new(); +863 let opts = Options::default().quic_config(Some(quic_addr_disc.clone())); +864 let mut client = Client::new( +865 resolver.clone(), +866 None, +867 relay_map.clone(), +868 opts.clone(), +869 Default::default(), +870 ); +871 let if_state = IfStateDetails::fake(); +872 +873 // Note that the ProbePlan will change with each iteration. +874 for i in 0..5 { +875 let cancel = CancellationToken::new(); +876 println!("--round {}", i); +877 let r = client.get_report(if_state.clone(), false).await; +878 +879 assert!(r.has_udp(), "want UDP"); +880 assert_eq!( +881 r.relay_latency.len(), +882 1, +883 "expected 1 key in RelayLatency; got {}", +884 r.relay_latency.len() +885 ); +886 assert!( +887 r.relay_latency.iter().next().is_some(), +888 "expected key 1 in RelayLatency; got {:?}", +889 r.relay_latency +890 ); +891 assert!(r.global_v4.is_some(), "expected globalV4 set"); +892 assert!(r.preferred_relay.is_some(),); +893 cancel.cancel(); +894 } +895 +896 drop(client); +897 ep.wait_idle().await; +898 server.shutdown().await?; +899 +900 Ok(()) +901 } +902 +903 #[tokio::test(flavor = "current_thread", start_paused = true)] +904 async fn test_add_report_history_set_preferred_relay() -> Result { +905 fn relay_url(i: u16) -> RelayUrl { +906 format!("http://{i}.com").parse().unwrap() +907 } +908 +909 // report returns a *Report from (relay host, Duration)+ pairs. +910 fn report(a: impl IntoIterator<Item = (&'static str, u64)>) -> Option<Report> { +911 let mut report = Report::default(); +912 for (s, d) in a { +913 assert!(s.starts_with('d'), "invalid relay server key"); +914 let id: u16 = s[1..].parse().unwrap(); +915 report.relay_latency.update_relay( +916 relay_url(id), +917 Duration::from_secs(d), +918 Probe::QadIpv4, +919 ); +920 } +921 +922 Some(report) +923 } +924 struct Step { +925 /// Delay in seconds +926 after: u64, +927 r: Option<Report>, +928 } +929 struct Test { +930 name: &'static str, +931 steps: Vec<Step>, +932 /// want PreferredRelay on final step +933 want_relay: Option<RelayUrl>, +934 // wanted len(c.prev) +935 want_prev_len: usize, +936 } +937 +938 let tests = [ +939 Test { +940 name: "first_reading", +941 steps: vec![Step { +942 after: 0, +943 r: report([("d1", 2), ("d2", 3)]), +944 }], +945 want_prev_len: 1, +946 want_relay: Some(relay_url(1)), +947 }, +948 Test { +949 name: "with_two", +950 steps: vec![ +951 Step { +952 after: 0, +953 r: report([("d1", 2), ("d2", 3)]), +954 }, +955 Step { +956 after: 1, +957 r: report([("d1", 4), ("d2", 3)]), +958 }, +959 ], +960 want_prev_len: 2, +961 want_relay: Some(relay_url(1)), // t0's d1 of 2 is still best +962 }, +963 Test { +964 name: "but_now_d1_gone", +965 steps: vec![ +966 Step { +967 after: 0, +968 r: report([("d1", 2), ("d2", 3)]), +969 }, +970 Step { +971 after: 1, +972 r: report([("d1", 4), ("d2", 3)]), +973 }, +974 Step { +975 after: 2, +976 r: report([("d2", 3)]), +977 }, +978 ], +979 want_prev_len: 3, +980 want_relay: Some(relay_url(2)), // only option +981 }, +982 Test { +983 name: "d1_is_back", +984 steps: vec![ +985 Step { +986 after: 0, +987 r: report([("d1", 2), ("d2", 3)]), +988 }, +989 Step { +990 after: 1, +991 r: report([("d1", 4), ("d2", 3)]), +992 }, +993 Step { +994 after: 2, +995 r: report([("d2", 3)]), +996 }, +997 Step { +998 after: 3, +999 r: report([("d1", 4), ("d2", 3)]), +1000 }, // same as 2 seconds ago +1001 ], +1002 want_prev_len: 4, +1003 want_relay: Some(relay_url(1)), // t0's d1 of 2 is still best +1004 }, +1005 Test { +1006 name: "things_clean_up", +1007 steps: vec![ +1008 Step { +1009 after: 0, +1010 r: report([("d1", 1), ("d2", 2)]), +1011 }, +1012 Step { +1013 after: 1, +1014 r: report([("d1", 1), ("d2", 2)]), +1015 }, +1016 Step { +1017 after: 2, +1018 r: report([("d1", 1), ("d2", 2)]), +1019 }, +1020 Step { +1021 after: 3, +1022 r: report([("d1", 1), ("d2", 2)]), +1023 }, +1024 Step { +1025 after: 10 * 60, +1026 r: report([("d3", 3)]), +1027 }, +1028 ], +1029 want_prev_len: 1, // t=[0123]s all gone. (too old, older than 10 min) +1030 want_relay: Some(relay_url(3)), // only option +1031 }, +1032 Test { +1033 name: "preferred_relay_hysteresis_no_switch", +1034 steps: vec![ +1035 Step { +1036 after: 0, +1037 r: report([("d1", 4), ("d2", 5)]), +1038 }, +1039 Step { +1040 after: 1, +1041 r: report([("d1", 4), ("d2", 3)]), +1042 }, +1043 ], +1044 want_prev_len: 2, +1045 want_relay: Some(relay_url(1)), // 2 didn't get fast enough +1046 }, +1047 Test { +1048 name: "preferred_relay_hysteresis_do_switch", +1049 steps: vec![ +1050 Step { +1051 after: 0, +1052 r: report([("d1", 4), ("d2", 5)]), +1053 }, +1054 Step { +1055 after: 1, +1056 r: report([("d1", 4), ("d2", 1)]), +1057 }, +1058 ], +1059 want_prev_len: 2, +1060 want_relay: Some(relay_url(2)), // 2 got fast enough +1061 }, +1062 ]; +1063 let resolver = DnsResolver::new(); +1064 for mut tt in tests { +1065 println!("test: {}", tt.name); +1066 let relay_map = RelayMap::empty(); +1067 let opts = Options::default(); +1068 let mut client = +1069 Client::new(resolver.clone(), None, relay_map, opts, Default::default()); +1070 for s in &mut tt.steps { +1071 // trigger the timer +1072 tokio::time::advance(Duration::from_secs(s.after)).await; +1073 client.add_report_history_and_set_preferred_relay(s.r.as_mut().unwrap()); +1074 } +1075 let last_report = tt.steps.last().unwrap().r.clone().unwrap(); +1076 let got = client.reports.prev.len(); +1077 let want = tt.want_prev_len; +1078 assert_eq!(got, want, "prev length"); +1079 let got = &last_report.preferred_relay; +1080 let want = &tt.want_relay; +1081 assert_eq!(got, want, "preferred_relay"); +1082 } +1083 +1084 Ok(()) +1085 } +1086}

    \ No newline at end of file diff --git a/pr/3314/docs/src/iroh/net_report/probes.rs.html b/pr/3314/docs/src/iroh/net_report/probes.rs.html index 04ccb4825b..c05681789e 100644 --- a/pr/3314/docs/src/iroh/net_report/probes.rs.html +++ b/pr/3314/docs/src/iroh/net_report/probes.rs.html @@ -128,259 +128,145 @@ 128 if last_report.relay_latency.is_empty() { 129 return Self::initial(relay_map, protocols); 130 } -131 Self::default() -132 } -133 -134 /// Returns an iterator over the [`ProbeSet`]s in this plan. -135 pub(super) fn iter(&self) -> impl Iterator<Item = &ProbeSet> { -136 self.set.iter() -137 } -138 -139 /// Adds a [`ProbeSet`] if it contains probes and the protocol indicated in -140 /// the [`ProbeSet] matches a protocol in our set of [`Probe`]s. -141 fn add_if_enabled(&mut self, protocols: &BTreeSet<Probe>, set: ProbeSet) { -142 if !set.is_empty() && protocols.contains(&set.proto) { -143 self.set.insert(set); -144 } -145 } -146} -147 -148impl fmt::Display for ProbePlan { -149 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { -150 writeln!(f, "ProbePlan {{")?; -151 for probe_set in self.set.iter() { -152 writeln!(f, r#" ProbeSet("{}") {{"#, probe_set.proto)?; -153 for (delay, node) in probe_set.probes.iter() { -154 writeln!(f, " {delay:?} to {node},")?; -155 } -156 writeln!(f, " }}")?; -157 } -158 writeln!(f, "}}") -159 } -160} -161 -162impl FromIterator<ProbeSet> for ProbePlan { -163 fn from_iter<T: IntoIterator<Item = ProbeSet>>(iter: T) -> Self { -164 Self { -165 set: iter.into_iter().collect(), -166 } -167 } -168} -169 -170#[cfg(test)] -171mod tests { -172 use pretty_assertions::assert_eq; -173 use tracing_test::traced_test; -174 -175 use super::*; -176 use crate::net_report::{test_utils, RelayLatencies}; -177 -178 /// Shorthand which declares a new ProbeSet. -179 /// -180 /// `$kind`: The `Probe`. -181 /// `$node`: Expression which will be an `Arc<RelayNode>`. -182 /// `$delays`: A `Vec` of the delays for this probe. -183 macro_rules! probeset { -184 (proto: Probe::$kind:ident, relay: $node:expr, delays: $delays:expr,) => { -185 ProbeSet { -186 proto: Probe::$kind, -187 probes: $delays.iter().map(|delay| (*delay, $node)).collect(), -188 } -189 }; -190 } -191 -192 fn default_protocols() -> BTreeSet<Probe> { -193 BTreeSet::from([Probe::QadIpv4, Probe::QadIpv6, Probe::Https]) -194 } -195 -196 #[tokio::test] -197 async fn test_initial_probeplan() { -198 let (_servers, relay_map) = test_utils::relay_map(2).await; -199 let relay_node_1 = relay_map.nodes().next().unwrap(); -200 let relay_node_2 = relay_map.nodes().nth(1).unwrap(); -201 let plan = ProbePlan::initial(&relay_map, &default_protocols()); -202 -203 let expected_plan: ProbePlan = [ -204 probeset! { -205 proto: Probe::QadIpv4, -206 relay: relay_node_1.clone(), -207 delays: [Duration::ZERO, -208 Duration::from_millis(100), -209 Duration::from_millis(200)], -210 }, -211 probeset! { -212 proto: Probe::QadIpv6, -213 relay: relay_node_1.clone(), -214 delays: [Duration::ZERO, -215 Duration::from_millis(100), -216 Duration::from_millis(200)], -217 }, -218 probeset! { -219 proto: Probe::Https, -220 relay: relay_node_1.clone(), -221 delays: [Duration::from_millis(300), -222 Duration::from_millis(400), -223 Duration::from_millis(500)], -224 }, -225 probeset! { -226 proto: Probe::QadIpv4, -227 relay: relay_node_2.clone(), -228 delays: [Duration::ZERO, -229 Duration::from_millis(100), -230 Duration::from_millis(200)], -231 }, -232 probeset! { -233 proto: Probe::QadIpv6, -234 relay: relay_node_2.clone(), -235 delays: [Duration::ZERO, -236 Duration::from_millis(100), -237 Duration::from_millis(200)], -238 }, -239 probeset! { -240 proto: Probe::Https, -241 relay: relay_node_2.clone(), -242 delays: [Duration::from_millis(300), -243 Duration::from_millis(400), -244 Duration::from_millis(500)], -245 }, -246 ] -247 .into_iter() -248 .collect(); -249 -250 println!("expected:"); -251 println!("{expected_plan}"); -252 println!("actual:"); -253 println!("{plan}"); -254 // The readable error: -255 assert_eq!(plan.to_string(), expected_plan.to_string()); -256 // Just in case there's a bug in the Display impl: -257 assert_eq!(plan, expected_plan); -258 } -259 -260 #[tokio::test] -261 async fn test_initial_probeplan_some_protocols() { -262 let (_servers, relay_map) = test_utils::relay_map(2).await; -263 let relay_node_1 = relay_map.nodes().next().unwrap(); -264 let relay_node_2 = relay_map.nodes().nth(1).unwrap(); -265 let plan = ProbePlan::initial(&relay_map, &BTreeSet::from([Probe::Https])); -266 -267 let expected_plan: ProbePlan = [ -268 probeset! { -269 proto: Probe::Https, -270 relay: relay_node_1.clone(), -271 delays: [Duration::ZERO, -272 Duration::from_millis(100), -273 Duration::from_millis(200)], -274 }, -275 probeset! { -276 proto: Probe::Https, -277 relay: relay_node_2.clone(), -278 delays: [Duration::ZERO, -279 Duration::from_millis(100), -280 Duration::from_millis(200)], -281 }, -282 ] -283 .into_iter() -284 .collect(); -285 -286 println!("expected:"); -287 println!("{expected_plan}"); -288 println!("actual:"); -289 println!("{plan}"); -290 // The readable error: -291 assert_eq!(plan.to_string(), expected_plan.to_string()); -292 // Just in case there's a bug in the Display impl: -293 assert_eq!(plan, expected_plan); -294 } -295 -296 #[tokio::test] -297 #[traced_test] -298 async fn test_plan_with_report() { -299 let (_servers, relay_map) = test_utils::relay_map(2).await; -300 let relay_node_1 = relay_map.nodes().next().unwrap().clone(); -301 let relay_node_2 = relay_map.nodes().nth(1).unwrap().clone(); -302 -303 for i in 0..10 { -304 println!("round {}", i); -305 let mut latencies = RelayLatencies::default(); -306 latencies.update_relay( -307 relay_node_1.url.clone(), -308 Duration::from_millis(2), -309 Probe::QadIpv4, -310 ); -311 latencies.update_relay( -312 relay_node_2.url.clone(), -313 Duration::from_millis(2), -314 Probe::QadIpv4, -315 ); -316 let last_report = Report { -317 udp_v6: true, -318 udp_v4: true, -319 mapping_varies_by_dest_ipv4: Some(false), -320 mapping_varies_by_dest_ipv6: Some(false), -321 preferred_relay: Some(relay_node_1.url.clone()), -322 relay_latency: latencies.clone(), -323 global_v4: None, -324 global_v6: None, -325 captive_portal: None, -326 }; -327 let plan = ProbePlan::with_last_report(&relay_map, &last_report, &default_protocols()); -328 let expected_plan: ProbePlan = [ -329 probeset! { -330 proto: Probe::QadIpv4, -331 relay: relay_node_1.clone(), -332 delays: [Duration::ZERO, -333 Duration::from_micros(52_400), -334 Duration::from_micros(104_800), -335 Duration::from_micros(157_200)], -336 }, -337 probeset! { -338 proto: Probe::QadIpv6, -339 relay: relay_node_1.clone(), -340 delays: [Duration::ZERO, -341 Duration::from_micros(52_400), -342 Duration::from_micros(104_800), -343 Duration::from_micros(157_200)], -344 }, -345 probeset! { -346 proto: Probe::Https, -347 relay: relay_node_1.clone(), -348 delays: [Duration::from_micros(207_200), -349 Duration::from_micros(259_600), -350 Duration::from_micros(312_000), -351 Duration::from_micros(364_400)], -352 }, -353 probeset! { -354 proto: Probe::QadIpv4, -355 relay: relay_node_2.clone(), -356 delays: [Duration::ZERO, -357 Duration::from_micros(52_400)], -358 }, -359 probeset! { -360 proto: Probe::QadIpv6, -361 relay: relay_node_2.clone(), -362 delays: [Duration::ZERO, -363 Duration::from_micros(52_400)], -364 }, -365 probeset! { -366 proto: Probe::Https, -367 relay: relay_node_2.clone(), -368 delays: [Duration::from_micros(207_200), -369 Duration::from_micros(259_600)], -370 }, -371 ] -372 .into_iter() -373 .collect(); -374 -375 println!("{} round", i); -376 println!("expected:"); -377 println!("{expected_plan}"); -378 println!("actual:"); -379 println!("{plan}"); -380 // The readable error: -381 assert_eq!(plan.to_string(), expected_plan.to_string(), "{}", i); -382 // Just in case there's a bug in the Display impl: -383 assert_eq!(plan, expected_plan, "{}", i); -384 } -385 } -386} \ No newline at end of file +131 +132 // TODO: is this good? +133 Self::default() +134 } +135 +136 /// Returns an iterator over the [`ProbeSet`]s in this plan. +137 pub(super) fn iter(&self) -> impl Iterator<Item = &ProbeSet> { +138 self.set.iter() +139 } +140 +141 /// Adds a [`ProbeSet`] if it contains probes and the protocol indicated in +142 /// the [`ProbeSet] matches a protocol in our set of [`Probe`]s. +143 fn add_if_enabled(&mut self, protocols: &BTreeSet<Probe>, set: ProbeSet) { +144 if !set.is_empty() && protocols.contains(&set.proto) { +145 self.set.insert(set); +146 } +147 } +148} +149 +150impl fmt::Display for ProbePlan { +151 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { +152 writeln!(f, "ProbePlan {{")?; +153 for probe_set in self.set.iter() { +154 writeln!(f, r#" ProbeSet("{}") {{"#, probe_set.proto)?; +155 for (delay, node) in probe_set.probes.iter() { +156 writeln!(f, " {delay:?} to {node},")?; +157 } +158 writeln!(f, " }}")?; +159 } +160 writeln!(f, "}}") +161 } +162} +163 +164impl FromIterator<ProbeSet> for ProbePlan { +165 fn from_iter<T: IntoIterator<Item = ProbeSet>>(iter: T) -> Self { +166 Self { +167 set: iter.into_iter().collect(), +168 } +169 } +170} +171 +172#[cfg(test)] +173mod tests { +174 use pretty_assertions::assert_eq; +175 +176 use super::*; +177 use crate::net_report::test_utils; +178 +179 /// Shorthand which declares a new ProbeSet. +180 /// +181 /// `$kind`: The `Probe`. +182 /// `$node`: Expression which will be an `Arc<RelayNode>`. +183 /// `$delays`: A `Vec` of the delays for this probe. +184 macro_rules! probeset { +185 (proto: Probe::$kind:ident, relay: $node:expr, delays: $delays:expr,) => { +186 ProbeSet { +187 proto: Probe::$kind, +188 probes: $delays.iter().map(|delay| (*delay, $node)).collect(), +189 } +190 }; +191 } +192 +193 fn default_protocols() -> BTreeSet<Probe> { +194 BTreeSet::from([Probe::QadIpv4, Probe::QadIpv6, Probe::Https]) +195 } +196 +197 #[tokio::test] +198 async fn test_initial_probeplan() { +199 let (_servers, relay_map) = test_utils::relay_map(2).await; +200 let relay_node_1 = relay_map.nodes().next().unwrap(); +201 let relay_node_2 = relay_map.nodes().nth(1).unwrap(); +202 let plan = ProbePlan::initial(&relay_map, &default_protocols()); +203 +204 let expected_plan: ProbePlan = [ +205 probeset! { +206 proto: Probe::Https, +207 relay: relay_node_1.clone(), +208 delays: [ +209 Duration::from_millis(0), +210 Duration::from_millis(100), +211 Duration::from_millis(200) +212 ], +213 }, +214 probeset! { +215 proto: Probe::Https, +216 relay: relay_node_2.clone(), +217 delays: [ +218 Duration::from_millis(0), +219 Duration::from_millis(100), +220 Duration::from_millis(200) +221 ], +222 }, +223 ] +224 .into_iter() +225 .collect(); +226 +227 println!("expected:"); +228 println!("{expected_plan}"); +229 println!("actual:"); +230 println!("{plan}"); +231 // The readable error: +232 assert_eq!(plan.to_string(), expected_plan.to_string()); +233 // Just in case there's a bug in the Display impl: +234 assert_eq!(plan, expected_plan); +235 } +236 +237 #[tokio::test] +238 async fn test_initial_probeplan_some_protocols() { +239 let (_servers, relay_map) = test_utils::relay_map(2).await; +240 let relay_node_1 = relay_map.nodes().next().unwrap(); +241 let relay_node_2 = relay_map.nodes().nth(1).unwrap(); +242 let plan = ProbePlan::initial(&relay_map, &BTreeSet::from([Probe::Https])); +243 +244 let expected_plan: ProbePlan = [ +245 probeset! { +246 proto: Probe::Https, +247 relay: relay_node_1.clone(), +248 delays: [Duration::ZERO, +249 Duration::from_millis(100), +250 Duration::from_millis(200)], +251 }, +252 probeset! { +253 proto: Probe::Https, +254 relay: relay_node_2.clone(), +255 delays: [Duration::ZERO, +256 Duration::from_millis(100), +257 Duration::from_millis(200)], +258 }, +259 ] +260 .into_iter() +261 .collect(); +262 +263 println!("expected:"); +264 println!("{expected_plan}"); +265 println!("actual:"); +266 println!("{plan}"); +267 // The readable error: +268 assert_eq!(plan.to_string(), expected_plan.to_string()); +269 // Just in case there's a bug in the Display impl: +270 assert_eq!(plan, expected_plan); +271 } +272} \ No newline at end of file diff --git a/pr/3314/docs/trait.impl/core/convert/trait.From.js b/pr/3314/docs/trait.impl/core/convert/trait.From.js index 445a231052..887f65af98 100644 --- a/pr/3314/docs/trait.impl/core/convert/trait.From.js +++ b/pr/3314/docs/trait.impl/core/convert/trait.From.js @@ -1,9 +1,9 @@ (function() { - var implementors = Object.fromEntries([["iroh",[["impl From<PkarrError> for DiscoveryError"],["impl From<AddNodeAddrError> for ConnectWithOptsError"],["impl From<ConnectWithOptsError> for ConnectError"],["impl From<ConnectionError> for AlpnError"],["impl From<ConnectionError> for ConnectError"],["impl From<ConnectionError> for AcceptError"],["impl From<Box<dyn Error + Send + Sync>> for AcceptError"],["impl From<Error> for AcceptError"],["impl From<DiscoveryItem> for NodeInfo"],["impl From<ClosedStream> for AcceptError"],["impl From<RemoteInfo> for NodeAddr"],["impl From<RemoteNodeIdError> for AcceptError"],["impl<T> From<T> for ConcurrentDiscovery
    where\n T: IntoIterator<Item = Box<dyn Discovery>>,
    "]]],["iroh_base",[["impl From<(PublicKey, Option<RelayUrl>, &[SocketAddr])> for NodeAddr"],["impl From<Url> for RelayUrl"],["impl From<NodeAddr> for NodeTicket"],["impl From<PublicKey> for NodeAddr"],["impl From<RelayUrl> for Url"],["impl From<NodeTicket> for NodeAddr"],["impl From<DecodeError> for KeyParsingError"],["impl From<DecodeError> for ParseError"],["impl From<Error> for KeyParsingError"],["impl From<SigningKey> for SecretKey"],["impl From<VerifyingKey> for PublicKey"],["impl From<[u8; 32]> for SecretKey"]]],["iroh_relay",[["impl From<DialError> for ConnectError"],["impl From<SendError> for SendError"],["impl From<DnsError> for DialError"],["impl From<DecodingError> for ParseError"],["impl From<FrameType> for u8"],["impl From<RecvError> for RecvError"],["impl From<SendError> for ConnectError"],["impl From<SendError> for RecvError"],["impl From<u8> for FrameType"],["impl From<Error> for DialError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<NodeAddr> for NodeData"],["impl From<NodeAddr> for NodeInfo"],["impl From<RelayUrl> for RelayMap"],["impl From<RelayUrl> for RelayNode"],["impl From<NodeInfo> for NodeAddr"],["impl From<RelayNode> for RelayMap"],["impl From<ConnectError> for Error"],["impl From<ConnectionError> for Error"],["impl From<Elapsed> for DialError"],["impl From<Elapsed> for DnsError"],["impl From<Elapsed> for RecvError"],["impl From<Elapsed> for SendError"],["impl From<Error> for ConnectError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<Error> for RecvError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<JoinError> for SupervisorError"],["impl From<RecvError> for Error"],["impl From<ResolveError> for DnsError"],["impl From<Resolver<GenericConnector<TokioRuntimeProvider>>> for DnsResolver"],["impl From<SignedPacketBuildError> for EncodingError"],["impl From<TxtLookup> for TxtLookup"]]]]); + var implementors = Object.fromEntries([["iroh",[["impl From<PkarrError> for DiscoveryError"],["impl From<AddNodeAddrError> for ConnectWithOptsError"],["impl From<ConnectWithOptsError> for ConnectError"],["impl From<ConnectionError> for AlpnError"],["impl From<ConnectionError> for ConnectError"],["impl From<ConnectionError> for AcceptError"],["impl From<Box<dyn Error + Send + Sync>> for AcceptError"],["impl From<Error> for AcceptError"],["impl From<DiscoveryItem> for NodeInfo"],["impl From<ClosedStream> for AcceptError"],["impl From<RemoteInfo> for NodeAddr"],["impl From<RemoteNodeIdError> for AcceptError"],["impl<T> From<T> for ConcurrentDiscovery
    where\n T: IntoIterator<Item = Box<dyn Discovery>>,
    "]]],["iroh_base",[["impl From<(PublicKey, Option<RelayUrl>, &[SocketAddr])> for NodeAddr"],["impl From<Url> for RelayUrl"],["impl From<NodeAddr> for NodeTicket"],["impl From<PublicKey> for NodeAddr"],["impl From<RelayUrl> for Url"],["impl From<NodeTicket> for NodeAddr"],["impl From<DecodeError> for KeyParsingError"],["impl From<DecodeError> for ParseError"],["impl From<Error> for KeyParsingError"],["impl From<SigningKey> for SecretKey"],["impl From<VerifyingKey> for PublicKey"],["impl From<[u8; 32]> for SecretKey"]]],["iroh_relay",[["impl From<DialError> for ConnectError"],["impl From<SendError> for SendError"],["impl From<DnsError> for DialError"],["impl From<DecodingError> for ParseError"],["impl From<FrameType> for u8"],["impl From<RecvError> for RecvError"],["impl From<SendError> for ConnectError"],["impl From<SendError> for RecvError"],["impl From<u8> for FrameType"],["impl From<Error> for DialError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<NodeInfo> for NodeAddr"],["impl From<RelayNode> for RelayMap"],["impl From<ConnectError> for Error"],["impl From<ConnectionError> for Error"],["impl From<Elapsed> for DialError"],["impl From<Elapsed> for DnsError"],["impl From<Elapsed> for RecvError"],["impl From<Elapsed> for SendError"],["impl From<Error> for ConnectError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<Error> for RecvError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<JoinError> for SupervisorError"],["impl From<NodeAddr> for NodeData"],["impl From<NodeAddr> for NodeInfo"],["impl From<RecvError> for Error"],["impl From<RelayUrl> for RelayMap"],["impl From<RelayUrl> for RelayNode"],["impl From<ResolveError> for DnsError"],["impl From<Resolver<GenericConnector<TokioRuntimeProvider>>> for DnsResolver"],["impl From<SignedPacketBuildError> for EncodingError"],["impl From<TxtLookup> for TxtLookup"]]]]); if (window.register_implementors) { window.register_implementors(implementors); } else { window.pending_implementors = implementors; } })() -//{"start":57,"fragment_lengths":[6244,4651,13608]} \ No newline at end of file +//{"start":57,"fragment_lengths":[6244,4651,12998]} \ No newline at end of file diff --git a/pr/3314/docs/trait.impl/core/iter/traits/collect/trait.FromIterator.js b/pr/3314/docs/trait.impl/core/iter/traits/collect/trait.FromIterator.js index 8cd585bc9e..d104c409e3 100644 --- a/pr/3314/docs/trait.impl/core/iter/traits/collect/trait.FromIterator.js +++ b/pr/3314/docs/trait.impl/core/iter/traits/collect/trait.FromIterator.js @@ -1,9 +1,9 @@ (function() { - var implementors = Object.fromEntries([["iroh_relay",[["impl FromIterator<RelayUrl> for RelayMap"],["impl FromIterator<RelayNode> for RelayMap"]]]]); + var implementors = Object.fromEntries([["iroh_relay",[["impl FromIterator<RelayNode> for RelayMap"],["impl FromIterator<RelayUrl> for RelayMap"]]]]); if (window.register_implementors) { window.register_implementors(implementors); } else { window.pending_implementors = implementors; } })() -//{"start":57,"fragment_lengths":[898]} \ No newline at end of file +//{"start":57,"fragment_lengths":[776]} \ No newline at end of file