\ No newline at end of file
diff --git a/pr/3666/docs/iroh/discovery/dns/struct.DnsDiscoveryBuilder.html b/pr/3666/docs/iroh/discovery/dns/struct.DnsDiscoveryBuilder.html
index f522be5b33..15220d8763 100644
--- a/pr/3666/docs/iroh/discovery/dns/struct.DnsDiscoveryBuilder.html
+++ b/pr/3666/docs/iroh/discovery/dns/struct.DnsDiscoveryBuilder.html
@@ -1,4 +1,4 @@
-DnsDiscoveryBuilder in iroh::discovery::dns - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/discovery/enum.DiscoveryError.html b/pr/3666/docs/iroh/discovery/enum.DiscoveryError.html
index 0837065b4d..692fade48b 100644
--- a/pr/3666/docs/iroh/discovery/enum.DiscoveryError.html
+++ b/pr/3666/docs/iroh/discovery/enum.DiscoveryError.html
@@ -1,4 +1,4 @@
-DiscoveryError in iroh::discovery - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/discovery/enum.IntoDiscoveryError.html b/pr/3666/docs/iroh/discovery/enum.IntoDiscoveryError.html
index 2a624c1304..d9b020583f 100644
--- a/pr/3666/docs/iroh/discovery/enum.IntoDiscoveryError.html
+++ b/pr/3666/docs/iroh/discovery/enum.IntoDiscoveryError.html
@@ -1,4 +1,4 @@
-IntoDiscoveryError in iroh::discovery - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/discovery/enum.ParseError.html b/pr/3666/docs/iroh/discovery/enum.ParseError.html
index dc247d1011..c5f67bcea8 100644
--- a/pr/3666/docs/iroh/discovery/enum.ParseError.html
+++ b/pr/3666/docs/iroh/discovery/enum.ParseError.html
@@ -1,4 +1,4 @@
-ParseError in iroh::discovery - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/discovery/mdns/enum.DiscoveryEvent.html b/pr/3666/docs/iroh/discovery/mdns/enum.DiscoveryEvent.html
index 4625eec081..3738296fb3 100644
--- a/pr/3666/docs/iroh/discovery/mdns/enum.DiscoveryEvent.html
+++ b/pr/3666/docs/iroh/discovery/mdns/enum.DiscoveryEvent.html
@@ -1,4 +1,4 @@
-DiscoveryEvent in iroh::discovery::mdns - Rust
pub enum DiscoveryEvent {
Discovered {
endpoint_info: EndpointInfo,
last_updated: Option<u64>,
@@ -52,4 +52,5 @@ and should not be overridden without very good reason.
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/discovery/mdns/struct.MdnsDiscovery.html b/pr/3666/docs/iroh/discovery/mdns/struct.MdnsDiscovery.html
index 12e1ab780f..ad52bd0181 100644
--- a/pr/3666/docs/iroh/discovery/mdns/struct.MdnsDiscovery.html
+++ b/pr/3666/docs/iroh/discovery/mdns/struct.MdnsDiscovery.html
@@ -1,4 +1,4 @@
-MdnsDiscovery in iroh::discovery::mdns - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/discovery/mdns/struct.MdnsDiscoveryBuilder.html b/pr/3666/docs/iroh/discovery/mdns/struct.MdnsDiscoveryBuilder.html
index aff14b38ab..7430bada36 100644
--- a/pr/3666/docs/iroh/discovery/mdns/struct.MdnsDiscoveryBuilder.html
+++ b/pr/3666/docs/iroh/discovery/mdns/struct.MdnsDiscoveryBuilder.html
@@ -1,4 +1,4 @@
-MdnsDiscoveryBuilder in iroh::discovery::mdns - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/discovery/pkarr/dht/struct.Builder.html b/pr/3666/docs/iroh/discovery/pkarr/dht/struct.Builder.html
index 3b0f8be093..add3ad054c 100644
--- a/pr/3666/docs/iroh/discovery/pkarr/dht/struct.Builder.html
+++ b/pr/3666/docs/iroh/discovery/pkarr/dht/struct.Builder.html
@@ -1,4 +1,4 @@
-Builder in iroh::discovery::pkarr::dht - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/discovery/pkarr/dht/struct.DhtDiscovery.html b/pr/3666/docs/iroh/discovery/pkarr/dht/struct.DhtDiscovery.html
index 058b277aed..154f9d5a9c 100644
--- a/pr/3666/docs/iroh/discovery/pkarr/dht/struct.DhtDiscovery.html
+++ b/pr/3666/docs/iroh/discovery/pkarr/dht/struct.DhtDiscovery.html
@@ -1,4 +1,4 @@
-DhtDiscovery in iroh::discovery::pkarr::dht - Rust
Available on crate feature discovery-pkarr-dht only.
Expand description
Pkarr Mainline DHT and relay server endpoint discovery.
It stores endpoint addresses in DNS records, signed by the endpoint’s private key, and publishes
them to the BitTorrent Mainline DHT. See the pkarr module for more details.
This implements the Discovery trait to be used as an endpoint discovery service which can
@@ -46,4 +46,5 @@ a background task that periodically publishes the endpoint address.
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/discovery/pkarr/enum.PkarrError.html b/pr/3666/docs/iroh/discovery/pkarr/enum.PkarrError.html
index 974c2556cb..5b123645df 100644
--- a/pr/3666/docs/iroh/discovery/pkarr/enum.PkarrError.html
+++ b/pr/3666/docs/iroh/discovery/pkarr/enum.PkarrError.html
@@ -1,4 +1,4 @@
-PkarrError in iroh::discovery::pkarr - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/discovery/pkarr/struct.PkarrPublisher.html b/pr/3666/docs/iroh/discovery/pkarr/struct.PkarrPublisher.html
index a2d6005e70..9ee1ecb0dd 100644
--- a/pr/3666/docs/iroh/discovery/pkarr/struct.PkarrPublisher.html
+++ b/pr/3666/docs/iroh/discovery/pkarr/struct.PkarrPublisher.html
@@ -1,4 +1,4 @@
-PkarrPublisher in iroh::discovery::pkarr - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/discovery/pkarr/struct.PkarrPublisherBuilder.html b/pr/3666/docs/iroh/discovery/pkarr/struct.PkarrPublisherBuilder.html
index e0bbf50686..46f7f18d94 100644
--- a/pr/3666/docs/iroh/discovery/pkarr/struct.PkarrPublisherBuilder.html
+++ b/pr/3666/docs/iroh/discovery/pkarr/struct.PkarrPublisherBuilder.html
@@ -1,4 +1,4 @@
-PkarrPublisherBuilder in iroh::discovery::pkarr - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/discovery/pkarr/struct.PkarrRelayClient.html b/pr/3666/docs/iroh/discovery/pkarr/struct.PkarrRelayClient.html
index 469d3bbaa1..3cb2fce3a4 100644
--- a/pr/3666/docs/iroh/discovery/pkarr/struct.PkarrRelayClient.html
+++ b/pr/3666/docs/iroh/discovery/pkarr/struct.PkarrRelayClient.html
@@ -1,4 +1,4 @@
-PkarrRelayClient in iroh::discovery::pkarr - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/discovery/pkarr/struct.PkarrResolver.html b/pr/3666/docs/iroh/discovery/pkarr/struct.PkarrResolver.html
index 6d216c410f..fac2783145 100644
--- a/pr/3666/docs/iroh/discovery/pkarr/struct.PkarrResolver.html
+++ b/pr/3666/docs/iroh/discovery/pkarr/struct.PkarrResolver.html
@@ -1,4 +1,4 @@
-PkarrResolver in iroh::discovery::pkarr - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/discovery/pkarr/struct.PkarrResolverBuilder.html b/pr/3666/docs/iroh/discovery/pkarr/struct.PkarrResolverBuilder.html
index 7bf48b6055..77d7102ea4 100644
--- a/pr/3666/docs/iroh/discovery/pkarr/struct.PkarrResolverBuilder.html
+++ b/pr/3666/docs/iroh/discovery/pkarr/struct.PkarrResolverBuilder.html
@@ -1,4 +1,4 @@
-PkarrResolverBuilder in iroh::discovery::pkarr - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/discovery/static_provider/struct.StaticProvider.html b/pr/3666/docs/iroh/discovery/static_provider/struct.StaticProvider.html
index 42f1cbd67a..3c660b009f 100644
--- a/pr/3666/docs/iroh/discovery/static_provider/struct.StaticProvider.html
+++ b/pr/3666/docs/iroh/discovery/static_provider/struct.StaticProvider.html
@@ -1,4 +1,4 @@
-StaticProvider in iroh::discovery::static_provider - Rust
A static endpoint discovery to manually add endpoint addressing information.
Often an application might get endpoint addressing information out-of-band in an
application-specific way. EndpointTicket’s are one common way used to achieve this.
This “static” addressing information is often only usable for a limited time so needs to
@@ -106,4 +106,5 @@ relay URL is overwritten.
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/discovery/struct.ConcurrentDiscovery.html b/pr/3666/docs/iroh/discovery/struct.ConcurrentDiscovery.html
index 0c592cc230..779d73fb16 100644
--- a/pr/3666/docs/iroh/discovery/struct.ConcurrentDiscovery.html
+++ b/pr/3666/docs/iroh/discovery/struct.ConcurrentDiscovery.html
@@ -1,4 +1,4 @@
-ConcurrentDiscovery in iroh::discovery - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/discovery/struct.DiscoveryItem.html b/pr/3666/docs/iroh/discovery/struct.DiscoveryItem.html
index a1528ae9e1..c2a20baa66 100644
--- a/pr/3666/docs/iroh/discovery/struct.DiscoveryItem.html
+++ b/pr/3666/docs/iroh/discovery/struct.DiscoveryItem.html
@@ -1,4 +1,4 @@
-DiscoveryItem in iroh::discovery - Rust
Endpoint discovery results from Discovery services.
This is the item in the streams returned from Discovery::resolve.
It contains the EndpointData about the discovered endpoint,
and some additional metadata about the discovery.
@@ -65,4 +65,5 @@ and should not be overridden without very good reason.
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/discovery/struct.EndpointData.html b/pr/3666/docs/iroh/discovery/struct.EndpointData.html
index 3ca7e35a9d..a893d39d3b 100644
--- a/pr/3666/docs/iroh/discovery/struct.EndpointData.html
+++ b/pr/3666/docs/iroh/discovery/struct.EndpointData.html
@@ -1,4 +1,4 @@
-EndpointData in iroh::discovery - Rust
Data about an endpoint that may be published to and resolved from discovery services.
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.
@@ -56,4 +56,5 @@ and should not be overridden without very good reason.
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/discovery/struct.EndpointInfo.html b/pr/3666/docs/iroh/discovery/struct.EndpointInfo.html
index 73f4fc85eb..f690939ce5 100644
--- a/pr/3666/docs/iroh/discovery/struct.EndpointInfo.html
+++ b/pr/3666/docs/iroh/discovery/struct.EndpointInfo.html
@@ -1,4 +1,4 @@
-EndpointInfo in iroh::discovery - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/discovery/struct.UserData.html b/pr/3666/docs/iroh/discovery/struct.UserData.html
index 576f3ec4f9..66a324f35a 100644
--- a/pr/3666/docs/iroh/discovery/struct.UserData.html
+++ b/pr/3666/docs/iroh/discovery/struct.UserData.html
@@ -1,4 +1,4 @@
-UserData in iroh::discovery - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/dns/struct.DnsResolver.html b/pr/3666/docs/iroh/dns/struct.DnsResolver.html
index 024863aeb3..93c67f334a 100644
--- a/pr/3666/docs/iroh/dns/struct.DnsResolver.html
+++ b/pr/3666/docs/iroh/dns/struct.DnsResolver.html
@@ -1,4 +1,4 @@
-DnsResolver in iroh::dns - Rust
Creates a new DNS resolver with sensible cross-platform defaults.
We first try to read the system’s resolver from /etc/resolv.conf.
This does not work at least on some Androids, therefore we fallback
@@ -143,4 +143,5 @@ The return type is a future containing an iterator of SocketAddr. <
V: MultiLane<T>,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/constant.ENV_FORCE_STAGING_RELAYS.html b/pr/3666/docs/iroh/endpoint/constant.ENV_FORCE_STAGING_RELAYS.html
index 6d6d94e4a1..97e37b12f8 100644
--- a/pr/3666/docs/iroh/endpoint/constant.ENV_FORCE_STAGING_RELAYS.html
+++ b/pr/3666/docs/iroh/endpoint/constant.ENV_FORCE_STAGING_RELAYS.html
@@ -1,2 +1,2 @@
-ENV_FORCE_STAGING_RELAYS in iroh::endpoint - Rust
Environment variable to force the use of staging relays.
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/enum.AlpnError.html b/pr/3666/docs/iroh/endpoint/enum.AlpnError.html
index 6cca5fc517..6b6dbcf389 100644
--- a/pr/3666/docs/iroh/endpoint/enum.AlpnError.html
+++ b/pr/3666/docs/iroh/endpoint/enum.AlpnError.html
@@ -1,4 +1,4 @@
-AlpnError in iroh::endpoint - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/enum.AuthenticationError.html b/pr/3666/docs/iroh/endpoint/enum.AuthenticationError.html
index f91236342c..7398d4111d 100644
--- a/pr/3666/docs/iroh/endpoint/enum.AuthenticationError.html
+++ b/pr/3666/docs/iroh/endpoint/enum.AuthenticationError.html
@@ -1,4 +1,4 @@
-AuthenticationError in iroh::endpoint - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/enum.BindError.html b/pr/3666/docs/iroh/endpoint/enum.BindError.html
index 31e8d00bf4..22daff9c1d 100644
--- a/pr/3666/docs/iroh/endpoint/enum.BindError.html
+++ b/pr/3666/docs/iroh/endpoint/enum.BindError.html
@@ -1,4 +1,4 @@
-BindError in iroh::endpoint - Rust
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/enum.ConnectError.html b/pr/3666/docs/iroh/endpoint/enum.ConnectError.html
index 3e03f1304c..2e982a6cb0 100644
--- a/pr/3666/docs/iroh/endpoint/enum.ConnectError.html
+++ b/pr/3666/docs/iroh/endpoint/enum.ConnectError.html
@@ -1,4 +1,4 @@
-ConnectError in iroh::endpoint - Rust
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/enum.ConnectWithOptsError.html b/pr/3666/docs/iroh/endpoint/enum.ConnectWithOptsError.html
index 82932d4ff5..1553644f86 100644
--- a/pr/3666/docs/iroh/endpoint/enum.ConnectWithOptsError.html
+++ b/pr/3666/docs/iroh/endpoint/enum.ConnectWithOptsError.html
@@ -1,4 +1,4 @@
-ConnectWithOptsError in iroh::endpoint - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/enum.ConnectingError.html b/pr/3666/docs/iroh/endpoint/enum.ConnectingError.html
index 3a9c3ac851..8c7870fe6a 100644
--- a/pr/3666/docs/iroh/endpoint/enum.ConnectingError.html
+++ b/pr/3666/docs/iroh/endpoint/enum.ConnectingError.html
@@ -1,4 +1,4 @@
-ConnectingError in iroh::endpoint - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/enum.ConnectionError.html b/pr/3666/docs/iroh/endpoint/enum.ConnectionError.html
index ac749a793b..e1983c5df9 100644
--- a/pr/3666/docs/iroh/endpoint/enum.ConnectionError.html
+++ b/pr/3666/docs/iroh/endpoint/enum.ConnectionError.html
@@ -1,4 +1,4 @@
-ConnectionError in iroh::endpoint - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/enum.DirectAddrType.html b/pr/3666/docs/iroh/endpoint/enum.DirectAddrType.html
index e785d05140..6dcad569e2 100644
--- a/pr/3666/docs/iroh/endpoint/enum.DirectAddrType.html
+++ b/pr/3666/docs/iroh/endpoint/enum.DirectAddrType.html
@@ -1,4 +1,4 @@
-DirectAddrType in iroh::endpoint - Rust
pub enum DirectAddrType {
Unknown,
Local,
Qad,
@@ -20,16 +20,16 @@ get a publicly routable direct address.
It is possible to configure iroh to bound to a specific port and independently
configure the router to forward this port to the iroh endpoint. This indicates a
situation like this, which still uses QAD to discover the public address.
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/enum.ReadError.html b/pr/3666/docs/iroh/endpoint/enum.ReadError.html
index ef684656ba..c80dbd4cfb 100644
--- a/pr/3666/docs/iroh/endpoint/enum.ReadError.html
+++ b/pr/3666/docs/iroh/endpoint/enum.ReadError.html
@@ -1,4 +1,4 @@
-ReadError in iroh::endpoint - Rust
pub enum ReadError {
Reset(VarInt),
ConnectionLost(ConnectionError),
ClosedStream,
@@ -57,4 +57,5 @@ and should not be overridden without very good reason.
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/enum.ReadExactError.html b/pr/3666/docs/iroh/endpoint/enum.ReadExactError.html
index ed0193ac45..00f0b8ca3d 100644
--- a/pr/3666/docs/iroh/endpoint/enum.ReadExactError.html
+++ b/pr/3666/docs/iroh/endpoint/enum.ReadExactError.html
@@ -1,4 +1,4 @@
-ReadExactError in iroh::endpoint - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/enum.ReadToEndError.html b/pr/3666/docs/iroh/endpoint/enum.ReadToEndError.html
index ee27234756..8fad0b052d 100644
--- a/pr/3666/docs/iroh/endpoint/enum.ReadToEndError.html
+++ b/pr/3666/docs/iroh/endpoint/enum.ReadToEndError.html
@@ -1,4 +1,4 @@
-ReadToEndError in iroh::endpoint - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/enum.RelayMode.html b/pr/3666/docs/iroh/endpoint/enum.RelayMode.html
index ee66d9656f..f44350b85c 100644
--- a/pr/3666/docs/iroh/endpoint/enum.RelayMode.html
+++ b/pr/3666/docs/iroh/endpoint/enum.RelayMode.html
@@ -1,4 +1,4 @@
-RelayMode in iroh::endpoint - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/enum.ResetError.html b/pr/3666/docs/iroh/endpoint/enum.ResetError.html
index 28870f1ec3..810e1b3095 100644
--- a/pr/3666/docs/iroh/endpoint/enum.ResetError.html
+++ b/pr/3666/docs/iroh/endpoint/enum.ResetError.html
@@ -1,4 +1,4 @@
-ResetError in iroh::endpoint - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/enum.SendDatagramError.html b/pr/3666/docs/iroh/endpoint/enum.SendDatagramError.html
index 010a63c514..a44f96b434 100644
--- a/pr/3666/docs/iroh/endpoint/enum.SendDatagramError.html
+++ b/pr/3666/docs/iroh/endpoint/enum.SendDatagramError.html
@@ -1,4 +1,4 @@
-SendDatagramError in iroh::endpoint - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/enum.Source.html b/pr/3666/docs/iroh/endpoint/enum.Source.html
index a54698683a..4a94f146b5 100644
--- a/pr/3666/docs/iroh/endpoint/enum.Source.html
+++ b/pr/3666/docs/iroh/endpoint/enum.Source.html
@@ -1,4 +1,4 @@
-Source in iroh::endpoint - Rust
\ No newline at end of file
+ T: for<'de> Deserialize<'de>,§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/enum.StoppedError.html b/pr/3666/docs/iroh/endpoint/enum.StoppedError.html
index 11a1a05e4c..e4a9c9974e 100644
--- a/pr/3666/docs/iroh/endpoint/enum.StoppedError.html
+++ b/pr/3666/docs/iroh/endpoint/enum.StoppedError.html
@@ -1,4 +1,4 @@
-StoppedError in iroh::endpoint - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/enum.TransportConfig.html b/pr/3666/docs/iroh/endpoint/enum.TransportConfig.html
index 87486acc0e..4ddbc5a4f9 100644
--- a/pr/3666/docs/iroh/endpoint/enum.TransportConfig.html
+++ b/pr/3666/docs/iroh/endpoint/enum.TransportConfig.html
@@ -1,4 +1,4 @@
-TransportConfig in iroh::endpoint - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/enum.WriteError.html b/pr/3666/docs/iroh/endpoint/enum.WriteError.html
index 3c44192f22..b65cf1d379 100644
--- a/pr/3666/docs/iroh/endpoint/enum.WriteError.html
+++ b/pr/3666/docs/iroh/endpoint/enum.WriteError.html
@@ -1,4 +1,4 @@
-WriteError in iroh::endpoint - Rust
pub enum WriteError {
Stopped(VarInt),
ConnectionLost(ConnectionError),
ClosedStream,
@@ -53,4 +53,5 @@ and should not be overridden without very good reason.
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/enum.ZeroRttStatus.html b/pr/3666/docs/iroh/endpoint/enum.ZeroRttStatus.html
index 573f259948..99ca564bbb 100644
--- a/pr/3666/docs/iroh/endpoint/enum.ZeroRttStatus.html
+++ b/pr/3666/docs/iroh/endpoint/enum.ZeroRttStatus.html
@@ -1,4 +1,4 @@
-ZeroRttStatus in iroh::endpoint - Rust
If the 0-RTT data was rejected, any streams that were created before
the handshake was completed will error and any data that was
previously sent on those streams will need to be resent.
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/fn.default_relay_mode.html b/pr/3666/docs/iroh/endpoint/fn.default_relay_mode.html
index fc0d0257bd..cd53b96816 100644
--- a/pr/3666/docs/iroh/endpoint/fn.default_relay_mode.html
+++ b/pr/3666/docs/iroh/endpoint/fn.default_relay_mode.html
@@ -1,4 +1,4 @@
-default_relay_mode in iroh::endpoint - Rust
If the IROH_FORCE_STAGING_RELAYS environment variable is non empty, it will return RelayMode::Staging.
Otherwise, it will return RelayMode::Default.
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/fn.force_staging_infra.html b/pr/3666/docs/iroh/endpoint/fn.force_staging_infra.html
index 2d12e15ff8..c3ae850d2a 100644
--- a/pr/3666/docs/iroh/endpoint/fn.force_staging_infra.html
+++ b/pr/3666/docs/iroh/endpoint/fn.force_staging_infra.html
@@ -1,2 +1,2 @@
-force_staging_infra in iroh::endpoint - Rust
Returns true if the use of staging relays is forced.
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/index.html b/pr/3666/docs/iroh/endpoint/index.html
index 045915ab18..88fb555a42 100644
--- a/pr/3666/docs/iroh/endpoint/index.html
+++ b/pr/3666/docs/iroh/endpoint/index.html
@@ -1,4 +1,4 @@
-iroh::endpoint - Rust
The Endpoint allows establishing connections to other iroh endpoints.
The Endpoint is the main API interface to manage a local iroh endpoint. It allows
connecting to and accepting connections from other endpoints. See the module docs for
more details on how iroh connections work.
diff --git a/pr/3666/docs/iroh/endpoint/presets/struct.N0.html b/pr/3666/docs/iroh/endpoint/presets/struct.N0.html
index 778fd3806a..3f2e3911c7 100644
--- a/pr/3666/docs/iroh/endpoint/presets/struct.N0.html
+++ b/pr/3666/docs/iroh/endpoint/presets/struct.N0.html
@@ -1,4 +1,4 @@
-N0 in iroh::endpoint::presets - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.Accept.html b/pr/3666/docs/iroh/endpoint/struct.Accept.html
index 0f7983cb57..64583a08e7 100644
--- a/pr/3666/docs/iroh/endpoint/struct.Accept.html
+++ b/pr/3666/docs/iroh/endpoint/struct.Accept.html
@@ -1,4 +1,4 @@
-Accept in iroh::endpoint - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.AcceptBi.html b/pr/3666/docs/iroh/endpoint/struct.AcceptBi.html
index 9b322bd65c..1893b7e9de 100644
--- a/pr/3666/docs/iroh/endpoint/struct.AcceptBi.html
+++ b/pr/3666/docs/iroh/endpoint/struct.AcceptBi.html
@@ -1,4 +1,4 @@
-AcceptBi in iroh::endpoint - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.AcceptUni.html b/pr/3666/docs/iroh/endpoint/struct.AcceptUni.html
index 63f270c174..471615f092 100644
--- a/pr/3666/docs/iroh/endpoint/struct.AcceptUni.html
+++ b/pr/3666/docs/iroh/endpoint/struct.AcceptUni.html
@@ -1,4 +1,4 @@
-AcceptUni in iroh::endpoint - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.Accepting.html b/pr/3666/docs/iroh/endpoint/struct.Accepting.html
index d9de02d730..a1d57e17ce 100644
--- a/pr/3666/docs/iroh/endpoint/struct.Accepting.html
+++ b/pr/3666/docs/iroh/endpoint/struct.Accepting.html
@@ -1,5 +1,5 @@
-Accepting in iroh::endpoint - Rust
If the connection was initiated with 0-RTT by the remote endpoint, the local endpoint
@@ -16,9 +16,9 @@ authentication is required.
You can use RecvStream::is_0rtt to check whether a stream has been opened in 0-RTT
and thus whether parts of the stream are operating under this reduced security level.
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.AckFrequencyConfig.html b/pr/3666/docs/iroh/endpoint/struct.AckFrequencyConfig.html
index 5228d760f7..a16c5649a8 100644
--- a/pr/3666/docs/iroh/endpoint/struct.AckFrequencyConfig.html
+++ b/pr/3666/docs/iroh/endpoint/struct.AckFrequencyConfig.html
@@ -1,4 +1,4 @@
-AckFrequencyConfig in iroh::endpoint - Rust
Parameters for controlling the peer’s acknowledgement frequency
The parameters provided in this config will be sent to the peer at the beginning of the
connection, so it can take them into account when sending acknowledgements (see each parameter’s
description for details on how it influences acknowledgement frequency).
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.ApplicationClose.html b/pr/3666/docs/iroh/endpoint/struct.ApplicationClose.html
index ac7cb13019..0f9d0bd308 100644
--- a/pr/3666/docs/iroh/endpoint/struct.ApplicationClose.html
+++ b/pr/3666/docs/iroh/endpoint/struct.ApplicationClose.html
@@ -1,4 +1,4 @@
-ApplicationClose in iroh::endpoint - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.Builder.html b/pr/3666/docs/iroh/endpoint/struct.Builder.html
index 990f623c5d..91c78df332 100644
--- a/pr/3666/docs/iroh/endpoint/struct.Builder.html
+++ b/pr/3666/docs/iroh/endpoint/struct.Builder.html
@@ -1,30 +1,30 @@
-Builder in iroh::endpoint - Rust
Sets the relay servers to assist in establishing connectivity.
Relay servers are used to establish initial connection with another iroh endpoint.
They also perform various functions related to hole punching, see the crate docs
for more details.
@@ -32,11 +32,11 @@ for more details.
When using RelayMode::Custom, the provided relay_map must contain at least one
configured relay endpoint. If an invalid RelayMap is provided bind
will result in an error.
The function discovery
will be called on endpoint creation with the configured secret key of
the endpoint. Discovery services that need to publish information need
@@ -47,13 +47,13 @@ to use this secret key to sign the information.
Sets the initial user-defined data to be published in discovery services for this node.
When using discovery services, this string of UserData will be published together
with the endpoint’s addresses and relay URL. When other endpoints discover this endpoint,
they retrieve the UserData in addition to the addressing info.
Iroh itself does not interpret the user-defined data in any way, it is purely left
for applications to parse and use.
The transport config contains parameters governing the QUIC state machine.
If unset, the default config is used. Default values should be suitable for most
internet applications. Applications protocols which forbid remotely-initiated
@@ -61,29 +61,29 @@ streams should set max_concurrent_bidi_streams and max_concur
zero.
Please be aware that changing some settings may have adverse effects on establishing
and maintaining direct connections.
By default, a new DNS resolver is created which is configured to use the
host system’s DNS configuration. You can pass a custom instance of DnsResolver
here to use a differently configured DNS resolver for this endpoint, or to share
a DnsResolver between multiple endpoints.
Enables saving the TLS pre-master key for connections.
This key should normally remain secret but can be useful to debug networking issues
by decrypting captured traffic.
If keylog is true then setting the SSLKEYLOGFILE environment variable to a
filename will result in this file being used to log the TLS pre-master keys.
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.Chunk.html b/pr/3666/docs/iroh/endpoint/struct.Chunk.html
index 6344095e37..5218f49be0 100644
--- a/pr/3666/docs/iroh/endpoint/struct.Chunk.html
+++ b/pr/3666/docs/iroh/endpoint/struct.Chunk.html
@@ -1,4 +1,4 @@
-Chunk in iroh::endpoint - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.ClosedStream.html b/pr/3666/docs/iroh/endpoint/struct.ClosedStream.html
index da7bcd60be..6e5cb33173 100644
--- a/pr/3666/docs/iroh/endpoint/struct.ClosedStream.html
+++ b/pr/3666/docs/iroh/endpoint/struct.ClosedStream.html
@@ -1,4 +1,4 @@
-ClosedStream in iroh::endpoint - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.ConnectOptions.html b/pr/3666/docs/iroh/endpoint/struct.ConnectOptions.html
index f8a5dd4c30..1085d5646e 100644
--- a/pr/3666/docs/iroh/endpoint/struct.ConnectOptions.html
+++ b/pr/3666/docs/iroh/endpoint/struct.ConnectOptions.html
@@ -1,12 +1,12 @@
-ConnectOptions in iroh::endpoint - Rust
Sets ALPN identifiers that should be signaled as supported on connection, in
addition to the main ALPN identifier used in Endpoint::connect_with_opts.
This allows connecting to servers that may only support older versions of your
protocol. In this case, you would add the older ALPN identifiers with this
@@ -20,7 +20,7 @@ list or the main ALPN identifiers on the accept side, see the endpoint
builder’s Builder::alpns function.
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.Connecting.html b/pr/3666/docs/iroh/endpoint/struct.Connecting.html
index d2ce789a85..0e540ba28d 100644
--- a/pr/3666/docs/iroh/endpoint/struct.Connecting.html
+++ b/pr/3666/docs/iroh/endpoint/struct.Connecting.html
@@ -1,4 +1,4 @@
-Connecting in iroh::endpoint - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.Connection.html b/pr/3666/docs/iroh/endpoint/struct.Connection.html
index bc869a2c67..d8bedd6cd7 100644
--- a/pr/3666/docs/iroh/endpoint/struct.Connection.html
+++ b/pr/3666/docs/iroh/endpoint/struct.Connection.html
@@ -1,4 +1,4 @@
-Connection in iroh::endpoint - Rust
If all references to a connection (including every clone of the Connection handle,
streams of incoming streams, and the various stream types) have been dropped, then the
connection will be automatically closed with an error_code of 0 and an empty reason. You
@@ -8,29 +8,29 @@ receiving CONNECTION_CLOSE the peer may drop any stream data not yet delivered t
application. Connection::close describes in more detail how to gracefully close a
connection without losing application data.
May be cloned to obtain another handle to the same connection.
Streams are cheap and instantaneous to open unless blocked by flow control. As a
consequence, the peer won’t be notified that a stream has been opened until the
stream is actually used.
Streams are cheap and instantaneous to open unless blocked by flow control. As a
consequence, the peer won’t be notified that a stream has been opened until the
stream is actually used. Calling open_bi then waiting on the RecvStream
without writing anything to SendStream will never succeed.
Important Note: The peer that calls open_bi must write to its SendStream
before the peer Connection is able to accept the stream using
accept_bi(). Calling open_bi then waiting on the RecvStream without
writing anything to the connected SendStream will never succeed.
Pending operations will fail immediately with ConnectionError::LocallyClosed. No
more data is sent to the peer and the peer may drop buffered data upon receiving the
CONNECTION_CLOSE frame.
@@ -51,35 +51,35 @@ endpoint. Once the local side sends a CONNECTION_CLOSE frame in response to call
close the remote endpoint may drop any data it received but is as yet
undelivered to the application, including data that was acknowledged as received to
the local endpoint.
-
Transmits data as an unreliable, unordered application datagram.
Application datagrams are a low-level primitive. They may be lost or delivered out
of order, and data must both fit inside a single QUIC packet and be smaller than
the maximum dictated by the peer.
Computes the maximum size of datagrams that may be passed to send_datagram.
Returns None if datagrams are unsupported by the peer or disabled locally.
This may change over the lifetime of a connection according to variation in the path
MTU estimate. The peer can also enforce an arbitrarily small fixed limit, but if the
peer’s limit is large this is guaranteed to be a little over a kilobyte at minimum.
Not necessarily the maximum size of received datagrams.
Guaranteed to return Some on fully established connections or after
Connecting::handshake_data() succeeds. See that method’s documentations for
details on the returned value.
The dynamic type returned is determined by the configured Session. For the
default rustls session, the return value can be downcast to a
Vec<[rustls::pki_types::CertificateDer]>
pub fn export_keying_material(
&self,
output: &mut [u8],
label: &[u8],
@@ -90,20 +90,20 @@ arguments and output buffers of equal length, they will get the
same sequence of bytes in output. These bytes are cryptographically
strong and pseudorandom, and are suitable for use as keying material.
Returns the EndpointId from the peer’s TLS certificate.
The PublicKey of an endpoint is also known as an EndpointId. This PublicKey is
included in the TLS certificate presented during the handshake when connecting.
This function allows you to get the EndpointId of the remote endpoint of this
connection.
Returns a Watcher for the network paths of this connection.
A connection can have several network paths to the remote endpoint, commonly there
@@ -112,8 +112,8 @@ will be a path via the relay server and a holepunched path.
Waits until the full handshake occurs and then returns a Connection.
This may fail with ConnectingError::ConnectionError, if there was
some general failure with the connection, such as a network timeout since
we accepted the connection.
@@ -122,8 +122,8 @@ doesn’t use the right TLS authentication, which usually every iroh endpoint
uses and requires.
Thus, those errors should only occur if someone connects to you with a
modified iroh endpoint or with a plain QUIC client.
Waits until the full handshake occurs and returns a ZeroRttStatus.
If ZeroRttStatus::Accepted is returned, than any streams created before
@@ -139,9 +139,9 @@ doesn’t use the right TLS authentication, which usually every iroh endpoint
uses and requires.
Thus, those errors should only occur if someone connects to you with a
modified iroh endpoint or with a plain QUIC client.
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.ConnectionClose.html b/pr/3666/docs/iroh/endpoint/struct.ConnectionClose.html
index 0ed17a30c9..01e56866ed 100644
--- a/pr/3666/docs/iroh/endpoint/struct.ConnectionClose.html
+++ b/pr/3666/docs/iroh/endpoint/struct.ConnectionClose.html
@@ -1,4 +1,4 @@
-ConnectionClose in iroh::endpoint - Rust
pub struct ConnectionClose {
pub error_code: Code,
pub frame_type: Option<FrameType>,
pub reason: Bytes,
@@ -48,4 +48,5 @@ and should not be overridden without very good reason.
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.ConnectionStats.html b/pr/3666/docs/iroh/endpoint/struct.ConnectionStats.html
index d1431c9477..2e21ea9b14 100644
--- a/pr/3666/docs/iroh/endpoint/struct.ConnectionStats.html
+++ b/pr/3666/docs/iroh/endpoint/struct.ConnectionStats.html
@@ -1,4 +1,4 @@
-ConnectionStats in iroh::endpoint - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.CryptoError.html b/pr/3666/docs/iroh/endpoint/struct.CryptoError.html
index 9156f338c4..c3691fae5a 100644
--- a/pr/3666/docs/iroh/endpoint/struct.CryptoError.html
+++ b/pr/3666/docs/iroh/endpoint/struct.CryptoError.html
@@ -1,4 +1,4 @@
-CryptoError in iroh::endpoint - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.DirectAddr.html b/pr/3666/docs/iroh/endpoint/struct.DirectAddr.html
index e5d501214d..ae8b5f30e1 100644
--- a/pr/3666/docs/iroh/endpoint/struct.DirectAddr.html
+++ b/pr/3666/docs/iroh/endpoint/struct.DirectAddr.html
@@ -1,4 +1,4 @@
-DirectAddr in iroh::endpoint - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.Endpoint.html b/pr/3666/docs/iroh/endpoint/struct.Endpoint.html
index 103521eddd..1b5d9ff139 100644
--- a/pr/3666/docs/iroh/endpoint/struct.Endpoint.html
+++ b/pr/3666/docs/iroh/endpoint/struct.Endpoint.html
@@ -1,4 +1,4 @@
-Endpoint in iroh::endpoint - Rust
Controls an iroh endpoint, establishing connections with other endpoints.
This is the main API interface to create connections to, and accept connections from
other iroh endpoints. The connections are peer-to-peer and encrypted, a Relay server is
used to make the connections reliable. See the [crate docs] for a more detailed
@@ -16,24 +16,24 @@ the peer are created using the Connection::open_uni and Connection::open_bi functions.
Note that due to the light-weight properties of streams a stream will only be accepted
once the initiating peer has sent some data on it.
pub async fn connect(
&self,
endpoint_addr: impl Into<EndpointAddr>,
alpn: &[u8],
@@ -53,7 +53,7 @@ connection attempt will fail with an error.
The alpn, or application-level protocol identifier, is also required. The remote
endpoint must support this alpn, otherwise the connection attempt will fail with
an error.
pub async fn connect_with_opts(
&self,
endpoint_addr: impl Into<EndpointAddr>,
alpn: &[u8],
@@ -73,17 +73,17 @@ security concerns.
establishing and maintaining direct connections. Carefully test settings you use and
consider this currently as still rather experimental.
-
Only connections with the ALPNs configured in Builder::alpns will be accepted.
If multiple ALPNs have been configured the ALPN can be inspected before accepting
the connection using Connecting::alpn.
The returned future will yield None if the endpoint is closed by calling
Endpoint::close.
Returns the current EndpointAddr.
As long as the endpoint was able to bind to a network interface, some
local addresses will be available.
The state of other fields depends on the state of networking and connectivity.
@@ -93,7 +93,7 @@ to ensure that the EndpointAddr will contain enough information to
to be dialable by a remote endpoint over the internet.
You can use the Endpoint::watch_addr method to get updates when the EndpointAddr
changes.
A convenience method that waits for the endpoint to be considered “online”.
This currently means at least one relay server was connected,
and at least one local IP address is available.
Event if no relays are configured, this will still wait for a relay connection.
@@ -129,16 +129,16 @@ timeout. We recommend using a timeout close to
To understand if the endpoint has gone back “offline”,
you must use the Endpoint::watch_addr method, to
get information on the current relay and direct address information.
On many systems iroh is able to detect network changes by itself, however
some systems like android do not expose this functionality to native code.
Android does however provide this functionality to Java code. This
@@ -216,12 +216,12 @@ function allows for notifying iroh of any potential network changes like
this.
Even when the network did not change, or iroh was already able to detect
the network change itself, there is no harm in calling this function.
Sets the initial user-defined data to be published in discovery services for this endpoint.
If the user-defined data passed to this function is different to the previous one,
the endpoint will republish its endpoint info to the configured discovery services.
This will close any remaining open Connections with an error code
of 0 and an empty reason. Though it is best practice to close those
explicitly before with a custom error code and reason.
@@ -247,8 +247,8 @@ while TCP sockets usually get closed and drained by the operating system in the
kernel during the “Time-Wait” period of the TCP socket.
Be aware however that the underlying UDP sockets are only closed once all clones of
the the respective Endpoint are dropped.
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.ExportKeyingMaterialError.html b/pr/3666/docs/iroh/endpoint/struct.ExportKeyingMaterialError.html
index 5419bf2f8d..2f07b8c0b8 100644
--- a/pr/3666/docs/iroh/endpoint/struct.ExportKeyingMaterialError.html
+++ b/pr/3666/docs/iroh/endpoint/struct.ExportKeyingMaterialError.html
@@ -1,4 +1,4 @@
-ExportKeyingMaterialError in iroh::endpoint - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.FrameStats.html b/pr/3666/docs/iroh/endpoint/struct.FrameStats.html
index 632afcd7ac..8a3d5dc766 100644
--- a/pr/3666/docs/iroh/endpoint/struct.FrameStats.html
+++ b/pr/3666/docs/iroh/endpoint/struct.FrameStats.html
@@ -1,4 +1,4 @@
-FrameStats in iroh::endpoint - Rust
Non-exhaustive structs could have additional fields added in future. Therefore, non-exhaustive structs cannot be constructed in external crates using the traditional Struct { .. } syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.
Non-exhaustive structs could have additional fields added in future. Therefore, non-exhaustive structs cannot be constructed in external crates using the traditional Struct { .. } syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.HandshakeCompleted.html b/pr/3666/docs/iroh/endpoint/struct.HandshakeCompleted.html
index 5e6dfd65e0..98c87b3e49 100644
--- a/pr/3666/docs/iroh/endpoint/struct.HandshakeCompleted.html
+++ b/pr/3666/docs/iroh/endpoint/struct.HandshakeCompleted.html
@@ -1,5 +1,5 @@
-HandshakeCompleted in iroh::endpoint - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.Incoming.html b/pr/3666/docs/iroh/endpoint/struct.Incoming.html
index 9cb4b4cd42..23169a0afc 100644
--- a/pr/3666/docs/iroh/endpoint/struct.Incoming.html
+++ b/pr/3666/docs/iroh/endpoint/struct.Incoming.html
@@ -1,4 +1,4 @@
-Incoming in iroh::endpoint - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.IncomingZeroRtt.html b/pr/3666/docs/iroh/endpoint/struct.IncomingZeroRtt.html
index c47f0db034..502b220b33 100644
--- a/pr/3666/docs/iroh/endpoint/struct.IncomingZeroRtt.html
+++ b/pr/3666/docs/iroh/endpoint/struct.IncomingZeroRtt.html
@@ -1,5 +1,5 @@
-IncomingZeroRtt in iroh::endpoint - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.MtuDiscoveryConfig.html b/pr/3666/docs/iroh/endpoint/struct.MtuDiscoveryConfig.html
index 4371892b2e..e3eaae2347 100644
--- a/pr/3666/docs/iroh/endpoint/struct.MtuDiscoveryConfig.html
+++ b/pr/3666/docs/iroh/endpoint/struct.MtuDiscoveryConfig.html
@@ -1,4 +1,4 @@
-MtuDiscoveryConfig in iroh::endpoint - Rust
By design, QUIC ensures during the handshake that the network path between the client and the
server is able to transmit unfragmented UDP packets with a body of 1200 bytes. In other words,
@@ -94,4 +94,5 @@ Defaults to 20.
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.OpenBi.html b/pr/3666/docs/iroh/endpoint/struct.OpenBi.html
index 7c12243064..1b43ea9552 100644
--- a/pr/3666/docs/iroh/endpoint/struct.OpenBi.html
+++ b/pr/3666/docs/iroh/endpoint/struct.OpenBi.html
@@ -1,4 +1,4 @@
-OpenBi in iroh::endpoint - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.OpenUni.html b/pr/3666/docs/iroh/endpoint/struct.OpenUni.html
index f9f9e7500c..b739c7207d 100644
--- a/pr/3666/docs/iroh/endpoint/struct.OpenUni.html
+++ b/pr/3666/docs/iroh/endpoint/struct.OpenUni.html
@@ -1,4 +1,4 @@
-OpenUni in iroh::endpoint - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.OutgoingZeroRtt.html b/pr/3666/docs/iroh/endpoint/struct.OutgoingZeroRtt.html
index 8fa90f2231..0fcf8a6cbf 100644
--- a/pr/3666/docs/iroh/endpoint/struct.OutgoingZeroRtt.html
+++ b/pr/3666/docs/iroh/endpoint/struct.OutgoingZeroRtt.html
@@ -1,5 +1,5 @@
-OutgoingZeroRtt in iroh::endpoint - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.PathInfo.html b/pr/3666/docs/iroh/endpoint/struct.PathInfo.html
index 2c89e6029e..83fae6e659 100644
--- a/pr/3666/docs/iroh/endpoint/struct.PathInfo.html
+++ b/pr/3666/docs/iroh/endpoint/struct.PathInfo.html
@@ -1,12 +1,12 @@
-PathInfo in iroh::endpoint - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.PathInfoList.html b/pr/3666/docs/iroh/endpoint/struct.PathInfoList.html
index c65ee338be..2862d78f3a 100644
--- a/pr/3666/docs/iroh/endpoint/struct.PathInfoList.html
+++ b/pr/3666/docs/iroh/endpoint/struct.PathInfoList.html
@@ -1,11 +1,11 @@
-PathInfoList in iroh::endpoint - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.PathStats.html b/pr/3666/docs/iroh/endpoint/struct.PathStats.html
index 60ea15cb9b..398ecaefd1 100644
--- a/pr/3666/docs/iroh/endpoint/struct.PathStats.html
+++ b/pr/3666/docs/iroh/endpoint/struct.PathStats.html
@@ -1,4 +1,4 @@
-PathStats in iroh::endpoint - Rust
pub struct PathStats {
pub rtt: Duration,
pub cwnd: u64,
pub congestion_events: u64,
@@ -60,4 +60,5 @@ and should not be overridden without very good reason.
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.QuinnTransportConfig.html b/pr/3666/docs/iroh/endpoint/struct.QuinnTransportConfig.html
index 934609c3a5..bb496aebff 100644
--- a/pr/3666/docs/iroh/endpoint/struct.QuinnTransportConfig.html
+++ b/pr/3666/docs/iroh/endpoint/struct.QuinnTransportConfig.html
@@ -1,4 +1,4 @@
-QuinnTransportConfig in iroh::endpoint - Rust
Default values should be suitable for most internet applications. Applications protocols which
forbid remotely-initiated streams should set max_concurrent_bidi_streams and
max_concurrent_uni_streams to zero.
@@ -194,18 +194,17 @@ existing paths.
control over which path is used for this.
This implementation expects the multipath extension to be enabled as well. if not yet
enabled via Self::max_concurrent_multipath_paths, a default value of
[DEFAULT_CONCURRENT_MULTIPATH_PATHS_WHEN_ENABLED] will be used.
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.ReadDatagram.html b/pr/3666/docs/iroh/endpoint/struct.ReadDatagram.html
index 53c59ed0a5..e01241c06e 100644
--- a/pr/3666/docs/iroh/endpoint/struct.ReadDatagram.html
+++ b/pr/3666/docs/iroh/endpoint/struct.ReadDatagram.html
@@ -1,4 +1,4 @@
-ReadDatagram in iroh::endpoint - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.RecvStream.html b/pr/3666/docs/iroh/endpoint/struct.RecvStream.html
index 1690ae3224..3af14f1d41 100644
--- a/pr/3666/docs/iroh/endpoint/struct.RecvStream.html
+++ b/pr/3666/docs/iroh/endpoint/struct.RecvStream.html
@@ -1,4 +1,4 @@
-RecvStream in iroh::endpoint - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.RemoteEndpointIdError.html b/pr/3666/docs/iroh/endpoint/struct.RemoteEndpointIdError.html
index e4b73bd081..f9db249a20 100644
--- a/pr/3666/docs/iroh/endpoint/struct.RemoteEndpointIdError.html
+++ b/pr/3666/docs/iroh/endpoint/struct.RemoteEndpointIdError.html
@@ -1,5 +1,5 @@
-RemoteEndpointIdError in iroh::endpoint - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.RetryError.html b/pr/3666/docs/iroh/endpoint/struct.RetryError.html
index 9331e6c753..b5c8c13c15 100644
--- a/pr/3666/docs/iroh/endpoint/struct.RetryError.html
+++ b/pr/3666/docs/iroh/endpoint/struct.RetryError.html
@@ -1,4 +1,4 @@
-RetryError in iroh::endpoint - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.SendStream.html b/pr/3666/docs/iroh/endpoint/struct.SendStream.html
index d6d0bc22f2..0b05bd2c13 100644
--- a/pr/3666/docs/iroh/endpoint/struct.SendStream.html
+++ b/pr/3666/docs/iroh/endpoint/struct.SendStream.html
@@ -1,4 +1,4 @@
-SendStream in iroh::endpoint - Rust
If dropped, streams that haven’t been explicitly reset() will be implicitly finish()ed,
continuing to (re)transmit previously written data until it has been fully acknowledged or the
connection is closed.
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.ServerConfig.html b/pr/3666/docs/iroh/endpoint/struct.ServerConfig.html
index d5b0d6126e..85e2add448 100644
--- a/pr/3666/docs/iroh/endpoint/struct.ServerConfig.html
+++ b/pr/3666/docs/iroh/endpoint/struct.ServerConfig.html
@@ -1,4 +1,4 @@
-ServerConfig in iroh::endpoint - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.StreamId.html b/pr/3666/docs/iroh/endpoint/struct.StreamId.html
index 0204a11293..24c681132d 100644
--- a/pr/3666/docs/iroh/endpoint/struct.StreamId.html
+++ b/pr/3666/docs/iroh/endpoint/struct.StreamId.html
@@ -1,4 +1,4 @@
-StreamId in iroh::endpoint - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.TransportError.html b/pr/3666/docs/iroh/endpoint/struct.TransportError.html
index 4dc3f7c6ab..4e535c2788 100644
--- a/pr/3666/docs/iroh/endpoint/struct.TransportError.html
+++ b/pr/3666/docs/iroh/endpoint/struct.TransportError.html
@@ -1,4 +1,4 @@
-TransportError in iroh::endpoint - Rust
pub struct TransportError {
pub code: Code,
pub frame: Option<FrameType>,
pub reason: String,
@@ -48,4 +48,5 @@ and should not be overridden without very good reason.
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.TransportErrorCode.html b/pr/3666/docs/iroh/endpoint/struct.TransportErrorCode.html
index ccda383fb5..1747ae65c5 100644
--- a/pr/3666/docs/iroh/endpoint/struct.TransportErrorCode.html
+++ b/pr/3666/docs/iroh/endpoint/struct.TransportErrorCode.html
@@ -1,4 +1,4 @@
-TransportErrorCode in iroh::endpoint - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.UdpStats.html b/pr/3666/docs/iroh/endpoint/struct.UdpStats.html
index e5125e17c3..17c4c06af2 100644
--- a/pr/3666/docs/iroh/endpoint/struct.UdpStats.html
+++ b/pr/3666/docs/iroh/endpoint/struct.UdpStats.html
@@ -1,4 +1,4 @@
-UdpStats in iroh::endpoint - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.UnsupportedVersion.html b/pr/3666/docs/iroh/endpoint/struct.UnsupportedVersion.html
index 04f742545b..db50055e8d 100644
--- a/pr/3666/docs/iroh/endpoint/struct.UnsupportedVersion.html
+++ b/pr/3666/docs/iroh/endpoint/struct.UnsupportedVersion.html
@@ -1,4 +1,4 @@
-UnsupportedVersion in iroh::endpoint - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.VarInt.html b/pr/3666/docs/iroh/endpoint/struct.VarInt.html
index e68cebad14..b8f79d524a 100644
--- a/pr/3666/docs/iroh/endpoint/struct.VarInt.html
+++ b/pr/3666/docs/iroh/endpoint/struct.VarInt.html
@@ -1,4 +1,4 @@
-VarInt in iroh::endpoint - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.WeakConnectionHandle.html b/pr/3666/docs/iroh/endpoint/struct.WeakConnectionHandle.html
index e0ca9eefa7..4b27946a2e 100644
--- a/pr/3666/docs/iroh/endpoint/struct.WeakConnectionHandle.html
+++ b/pr/3666/docs/iroh/endpoint/struct.WeakConnectionHandle.html
@@ -1,4 +1,4 @@
-WeakConnectionHandle in iroh::endpoint - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/struct.Written.html b/pr/3666/docs/iroh/endpoint/struct.Written.html
index fe46d6b7c7..28e64e1160 100644
--- a/pr/3666/docs/iroh/endpoint/struct.Written.html
+++ b/pr/3666/docs/iroh/endpoint/struct.Written.html
@@ -1,4 +1,4 @@
-Written in iroh::endpoint - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/trait.ConnectionState.html b/pr/3666/docs/iroh/endpoint/trait.ConnectionState.html
index 227f457d7d..6febf7b4ce 100644
--- a/pr/3666/docs/iroh/endpoint/trait.ConnectionState.html
+++ b/pr/3666/docs/iroh/endpoint/trait.ConnectionState.html
@@ -1,5 +1,5 @@
-ConnectionState in iroh::endpoint - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint/type.IncomingZeroRttConnection.html b/pr/3666/docs/iroh/endpoint/type.IncomingZeroRttConnection.html
index d83b1c963a..748cd4737f 100644
--- a/pr/3666/docs/iroh/endpoint/type.IncomingZeroRttConnection.html
+++ b/pr/3666/docs/iroh/endpoint/type.IncomingZeroRttConnection.html
@@ -1,4 +1,4 @@
-IncomingZeroRttConnection in iroh::endpoint - Rust
A QUIC connection on the server-side that can possibly accept 0-RTT data.
It is very similar to a Connection, but the IncomingZeroRttConnection::remote_id
and IncomingZeroRttConnection::alpn may not be set yet, since the handshake has
not necessarily occurred yet.
diff --git a/pr/3666/docs/iroh/endpoint/type.OutgoingZeroRttConnection.html b/pr/3666/docs/iroh/endpoint/type.OutgoingZeroRttConnection.html
index 90347f46ca..733e6909c6 100644
--- a/pr/3666/docs/iroh/endpoint/type.OutgoingZeroRttConnection.html
+++ b/pr/3666/docs/iroh/endpoint/type.OutgoingZeroRttConnection.html
@@ -1,4 +1,4 @@
-OutgoingZeroRttConnection in iroh::endpoint - Rust
Creating a OutgoingZeroRttConnection means that the endpoint is capable
of attempting a 0-RTT connection with the remote. The remote may still
diff --git a/pr/3666/docs/iroh/endpoint_info/enum.DecodingError.html b/pr/3666/docs/iroh/endpoint_info/enum.DecodingError.html
index 6d85928a4c..c5c9ac1086 100644
--- a/pr/3666/docs/iroh/endpoint_info/enum.DecodingError.html
+++ b/pr/3666/docs/iroh/endpoint_info/enum.DecodingError.html
@@ -1,4 +1,4 @@
-
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint_info/enum.EncodingError.html b/pr/3666/docs/iroh/endpoint_info/enum.EncodingError.html
index b3e634bf32..9cea8f3ef9 100644
--- a/pr/3666/docs/iroh/endpoint_info/enum.EncodingError.html
+++ b/pr/3666/docs/iroh/endpoint_info/enum.EncodingError.html
@@ -1,4 +1,4 @@
-EncodingError in iroh::endpoint_info - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint_info/enum.ParseError.html b/pr/3666/docs/iroh/endpoint_info/enum.ParseError.html
index ded19ea9d7..89cdb34306 100644
--- a/pr/3666/docs/iroh/endpoint_info/enum.ParseError.html
+++ b/pr/3666/docs/iroh/endpoint_info/enum.ParseError.html
@@ -1,4 +1,4 @@
-ParseError in iroh::endpoint_info - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint_info/struct.EndpointData.html b/pr/3666/docs/iroh/endpoint_info/struct.EndpointData.html
index 4895018f57..057e1fad12 100644
--- a/pr/3666/docs/iroh/endpoint_info/struct.EndpointData.html
+++ b/pr/3666/docs/iroh/endpoint_info/struct.EndpointData.html
@@ -1,4 +1,4 @@
-EndpointData in iroh::endpoint_info - Rust
Data about an endpoint that may be published to and resolved from discovery services.
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.
@@ -56,4 +56,5 @@ and should not be overridden without very good reason.
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint_info/struct.EndpointInfo.html b/pr/3666/docs/iroh/endpoint_info/struct.EndpointInfo.html
index b9f9bf8caf..18b7fc6c60 100644
--- a/pr/3666/docs/iroh/endpoint_info/struct.EndpointInfo.html
+++ b/pr/3666/docs/iroh/endpoint_info/struct.EndpointInfo.html
@@ -1,4 +1,4 @@
-EndpointInfo in iroh::endpoint_info - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint_info/struct.MaxLengthExceededError.html b/pr/3666/docs/iroh/endpoint_info/struct.MaxLengthExceededError.html
index de09fd00a7..fb63356865 100644
--- a/pr/3666/docs/iroh/endpoint_info/struct.MaxLengthExceededError.html
+++ b/pr/3666/docs/iroh/endpoint_info/struct.MaxLengthExceededError.html
@@ -1,4 +1,4 @@
-MaxLengthExceededError in iroh::endpoint_info - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/endpoint_info/struct.UserData.html b/pr/3666/docs/iroh/endpoint_info/struct.UserData.html
index 0bda5cd34a..c32e6a2daf 100644
--- a/pr/3666/docs/iroh/endpoint_info/struct.UserData.html
+++ b/pr/3666/docs/iroh/endpoint_info/struct.UserData.html
@@ -1,4 +1,4 @@
-UserData in iroh::endpoint_info - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/enum.KeyParsingError.html b/pr/3666/docs/iroh/enum.KeyParsingError.html
index b9da5b4e19..64ab826668 100644
--- a/pr/3666/docs/iroh/enum.KeyParsingError.html
+++ b/pr/3666/docs/iroh/enum.KeyParsingError.html
@@ -1,4 +1,4 @@
-KeyParsingError in iroh - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/enum.TransportAddr.html b/pr/3666/docs/iroh/enum.TransportAddr.html
index 8f9d729f8d..8000323df4 100644
--- a/pr/3666/docs/iroh/enum.TransportAddr.html
+++ b/pr/3666/docs/iroh/enum.TransportAddr.html
@@ -1,4 +1,4 @@
-TransportAddr in iroh - Rust
\ No newline at end of file
+ T: for<'de> Deserialize<'de>,§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/index.html b/pr/3666/docs/iroh/index.html
index 4bf05966f6..b1fa740f88 100644
--- a/pr/3666/docs/iroh/index.html
+++ b/pr/3666/docs/iroh/index.html
@@ -1,4 +1,4 @@
-iroh - Rust
iroh is a library to establish direct connectivity between peers. It exposes an
interface to QUIC connections and streams to the user, while implementing direct
connectivity using hole punching complemented by relay servers under the hood.
diff --git a/pr/3666/docs/iroh/metrics/struct.EndpointMetrics.html b/pr/3666/docs/iroh/metrics/struct.EndpointMetrics.html
index 2cbc9a51ce..a060e5cb19 100644
--- a/pr/3666/docs/iroh/metrics/struct.EndpointMetrics.html
+++ b/pr/3666/docs/iroh/metrics/struct.EndpointMetrics.html
@@ -1,4 +1,4 @@
-EndpointMetrics in iroh::metrics - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/metrics/struct.MagicsockMetrics.html b/pr/3666/docs/iroh/metrics/struct.MagicsockMetrics.html
index 1bc172454f..e8f65ee31d 100644
--- a/pr/3666/docs/iroh/metrics/struct.MagicsockMetrics.html
+++ b/pr/3666/docs/iroh/metrics/struct.MagicsockMetrics.html
@@ -1,4 +1,4 @@
-MagicsockMetrics in iroh::metrics - Rust
Non-exhaustive structs could have additional fields added in future. Therefore, non-exhaustive structs cannot be constructed in external crates using the traditional Struct { .. } syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.
\ No newline at end of file
+ T: for<'de> Deserialize<'de>,§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/metrics/struct.PortmapMetrics.html b/pr/3666/docs/iroh/metrics/struct.PortmapMetrics.html
index 84857720be..511d49b9ed 100644
--- a/pr/3666/docs/iroh/metrics/struct.PortmapMetrics.html
+++ b/pr/3666/docs/iroh/metrics/struct.PortmapMetrics.html
@@ -1,4 +1,4 @@
-PortmapMetrics in iroh::metrics - Rust
\ No newline at end of file
+ T: for<'de> Deserialize<'de>,§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/metrics/struct.RelayMetrics.html b/pr/3666/docs/iroh/metrics/struct.RelayMetrics.html
index 351c7b78d3..8448f6dffe 100644
--- a/pr/3666/docs/iroh/metrics/struct.RelayMetrics.html
+++ b/pr/3666/docs/iroh/metrics/struct.RelayMetrics.html
@@ -1,4 +1,4 @@
-RelayMetrics in iroh::metrics - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/net_report/enum.Probe.html b/pr/3666/docs/iroh/net_report/enum.Probe.html
index 44410c7a8b..8ad871eaca 100644
--- a/pr/3666/docs/iroh/net_report/enum.Probe.html
+++ b/pr/3666/docs/iroh/net_report/enum.Probe.html
@@ -1,4 +1,4 @@
-Probe in iroh::net_report - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/net_report/struct.Metrics.html b/pr/3666/docs/iroh/net_report/struct.Metrics.html
index aecc1bef7e..ef52a61c0b 100644
--- a/pr/3666/docs/iroh/net_report/struct.Metrics.html
+++ b/pr/3666/docs/iroh/net_report/struct.Metrics.html
@@ -1,4 +1,4 @@
-Metrics in iroh::net_report - Rust
\ No newline at end of file
+ T: for<'de> Deserialize<'de>,§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/net_report/struct.Options.html b/pr/3666/docs/iroh/net_report/struct.Options.html
index 24a1892d94..83da90c282 100644
--- a/pr/3666/docs/iroh/net_report/struct.Options.html
+++ b/pr/3666/docs/iroh/net_report/struct.Options.html
@@ -1,4 +1,4 @@
-Options in iroh::net_report - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/net_report/struct.QuicConfig.html b/pr/3666/docs/iroh/net_report/struct.QuicConfig.html
index 6e43ad1676..4c3a0f83b0 100644
--- a/pr/3666/docs/iroh/net_report/struct.QuicConfig.html
+++ b/pr/3666/docs/iroh/net_report/struct.QuicConfig.html
@@ -1,4 +1,4 @@
-QuicConfig in iroh::net_report - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/net_report/struct.RelayLatencies.html b/pr/3666/docs/iroh/net_report/struct.RelayLatencies.html
index 1f302809b8..e5838a1c99 100644
--- a/pr/3666/docs/iroh/net_report/struct.RelayLatencies.html
+++ b/pr/3666/docs/iroh/net_report/struct.RelayLatencies.html
@@ -1,4 +1,4 @@
-RelayLatencies in iroh::net_report - Rust
\ No newline at end of file
+ T: for<'de> Deserialize<'de>,§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/net_report/struct.Report.html b/pr/3666/docs/iroh/net_report/struct.Report.html
index 63975d5840..fb28da0cbc 100644
--- a/pr/3666/docs/iroh/net_report/struct.Report.html
+++ b/pr/3666/docs/iroh/net_report/struct.Report.html
@@ -1,4 +1,4 @@
-Report in iroh::net_report - Rust
pub struct Report {
pub udp_v4: bool,
pub udp_v6: bool,
pub mapping_varies_by_dest_ipv4: Option<bool>,
@@ -67,4 +67,5 @@ and should not be overridden without very good reason.
Into<Dispatch>,
Attaches the provided Subscriber to this type, returning a
[WithDispatch] wrapper. Read more
\ No newline at end of file
+ T: for<'de> Deserialize<'de>,§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/protocol/enum.AcceptError.html b/pr/3666/docs/iroh/protocol/enum.AcceptError.html
index 1bd8644232..0a5bf4c92c 100644
--- a/pr/3666/docs/iroh/protocol/enum.AcceptError.html
+++ b/pr/3666/docs/iroh/protocol/enum.AcceptError.html
@@ -1,4 +1,4 @@
-AcceptError in iroh::protocol - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/protocol/struct.AccessLimit.html b/pr/3666/docs/iroh/protocol/struct.AccessLimit.html
index 640bb4284e..533ab9c766 100644
--- a/pr/3666/docs/iroh/protocol/struct.AccessLimit.html
+++ b/pr/3666/docs/iroh/protocol/struct.AccessLimit.html
@@ -1,4 +1,4 @@
-AccessLimit in iroh::protocol - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/protocol/struct.Router.html b/pr/3666/docs/iroh/protocol/struct.Router.html
index 5c29fd8eeb..61897b3514 100644
--- a/pr/3666/docs/iroh/protocol/struct.Router.html
+++ b/pr/3666/docs/iroh/protocol/struct.Router.html
@@ -1,4 +1,4 @@
-Router in iroh::protocol - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/protocol/struct.RouterBuilder.html b/pr/3666/docs/iroh/protocol/struct.RouterBuilder.html
index 840db2ce9c..253ded18bc 100644
--- a/pr/3666/docs/iroh/protocol/struct.RouterBuilder.html
+++ b/pr/3666/docs/iroh/protocol/struct.RouterBuilder.html
@@ -1,4 +1,4 @@
-RouterBuilder in iroh::protocol - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/struct.EndpointAddr.html b/pr/3666/docs/iroh/struct.EndpointAddr.html
index 9b2cd01e35..20f65b0c4f 100644
--- a/pr/3666/docs/iroh/struct.EndpointAddr.html
+++ b/pr/3666/docs/iroh/struct.EndpointAddr.html
@@ -1,4 +1,4 @@
-EndpointAddr in iroh - Rust
\ No newline at end of file
+ T: for<'de> Deserialize<'de>,§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/struct.PublicKey.html b/pr/3666/docs/iroh/struct.PublicKey.html
index 7541cfcd4e..cf927e1f2b 100644
--- a/pr/3666/docs/iroh/struct.PublicKey.html
+++ b/pr/3666/docs/iroh/struct.PublicKey.html
@@ -1,4 +1,4 @@
-PublicKey in iroh - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/struct.RelayConfig.html b/pr/3666/docs/iroh/struct.RelayConfig.html
index ef6bf85eb4..72ae659445 100644
--- a/pr/3666/docs/iroh/struct.RelayConfig.html
+++ b/pr/3666/docs/iroh/struct.RelayConfig.html
@@ -1,4 +1,4 @@
-RelayConfig in iroh - Rust
\ No newline at end of file
+ T: for<'de> Deserialize<'de>,§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/struct.RelayMap.html b/pr/3666/docs/iroh/struct.RelayMap.html
index 2f7b3d1718..8b03b7fec2 100644
--- a/pr/3666/docs/iroh/struct.RelayMap.html
+++ b/pr/3666/docs/iroh/struct.RelayMap.html
@@ -1,4 +1,4 @@
-RelayMap in iroh - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/struct.RelayUrl.html b/pr/3666/docs/iroh/struct.RelayUrl.html
index 384568fcc5..d493f27195 100644
--- a/pr/3666/docs/iroh/struct.RelayUrl.html
+++ b/pr/3666/docs/iroh/struct.RelayUrl.html
@@ -1,4 +1,4 @@
-RelayUrl in iroh - Rust
\ No newline at end of file
+ T: for<'de> Deserialize<'de>,§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/struct.RelayUrlParseError.html b/pr/3666/docs/iroh/struct.RelayUrlParseError.html
index ad462cc5d9..143e0f5991 100644
--- a/pr/3666/docs/iroh/struct.RelayUrlParseError.html
+++ b/pr/3666/docs/iroh/struct.RelayUrlParseError.html
@@ -1,4 +1,4 @@
-RelayUrlParseError in iroh - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/struct.SecretKey.html b/pr/3666/docs/iroh/struct.SecretKey.html
index 8bb3d25249..186f17308f 100644
--- a/pr/3666/docs/iroh/struct.SecretKey.html
+++ b/pr/3666/docs/iroh/struct.SecretKey.html
@@ -1,4 +1,4 @@
-SecretKey in iroh - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/struct.Signature.html b/pr/3666/docs/iroh/struct.Signature.html
index a9e18b9ae3..4b38de869e 100644
--- a/pr/3666/docs/iroh/struct.Signature.html
+++ b/pr/3666/docs/iroh/struct.Signature.html
@@ -1,4 +1,4 @@
-Signature in iroh - Rust
\ No newline at end of file
+ T: for<'de> Deserialize<'de>,§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/struct.SignatureError.html b/pr/3666/docs/iroh/struct.SignatureError.html
index 5a5ad9bdc4..464b7fa0f1 100644
--- a/pr/3666/docs/iroh/struct.SignatureError.html
+++ b/pr/3666/docs/iroh/struct.SignatureError.html
@@ -1,4 +1,4 @@
-SignatureError in iroh - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/test_utils/struct.CleanupDropGuard.html b/pr/3666/docs/iroh/test_utils/struct.CleanupDropGuard.html
index c65a1447c6..34b0775247 100644
--- a/pr/3666/docs/iroh/test_utils/struct.CleanupDropGuard.html
+++ b/pr/3666/docs/iroh/test_utils/struct.CleanupDropGuard.html
@@ -1,4 +1,4 @@
-CleanupDropGuard in iroh::test_utils - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh/test_utils/struct.DnsPkarrServer.html b/pr/3666/docs/iroh/test_utils/struct.DnsPkarrServer.html
index e5b66e23e1..ed77232077 100644
--- a/pr/3666/docs/iroh/test_utils/struct.DnsPkarrServer.html
+++ b/pr/3666/docs/iroh/test_utils/struct.DnsPkarrServer.html
@@ -1,4 +1,4 @@
-DnsPkarrServer in iroh::test_utils - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_base/enum.KeyParsingError.html b/pr/3666/docs/iroh_base/enum.KeyParsingError.html
index 6c26de2c57..f2137178ef 100644
--- a/pr/3666/docs/iroh_base/enum.KeyParsingError.html
+++ b/pr/3666/docs/iroh_base/enum.KeyParsingError.html
@@ -1,4 +1,4 @@
-KeyParsingError in iroh_base - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_base/enum.TransportAddr.html b/pr/3666/docs/iroh_base/enum.TransportAddr.html
index 99e586a126..695c416d34 100644
--- a/pr/3666/docs/iroh_base/enum.TransportAddr.html
+++ b/pr/3666/docs/iroh_base/enum.TransportAddr.html
@@ -1,4 +1,4 @@
-TransportAddr in iroh_base - Rust
\ No newline at end of file
+ T: for<'de> Deserialize<'de>,§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_base/struct.EndpointAddr.html b/pr/3666/docs/iroh_base/struct.EndpointAddr.html
index 6a996ae533..6ad35b5895 100644
--- a/pr/3666/docs/iroh_base/struct.EndpointAddr.html
+++ b/pr/3666/docs/iroh_base/struct.EndpointAddr.html
@@ -1,4 +1,4 @@
-EndpointAddr in iroh_base - Rust
\ No newline at end of file
+ T: for<'de> Deserialize<'de>,§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_base/struct.PublicKey.html b/pr/3666/docs/iroh_base/struct.PublicKey.html
index 4439112d97..d07933a30b 100644
--- a/pr/3666/docs/iroh_base/struct.PublicKey.html
+++ b/pr/3666/docs/iroh_base/struct.PublicKey.html
@@ -1,4 +1,4 @@
-PublicKey in iroh_base - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_base/struct.RelayUrl.html b/pr/3666/docs/iroh_base/struct.RelayUrl.html
index 28e36de9ad..e8bb91e1cc 100644
--- a/pr/3666/docs/iroh_base/struct.RelayUrl.html
+++ b/pr/3666/docs/iroh_base/struct.RelayUrl.html
@@ -1,4 +1,4 @@
-RelayUrl in iroh_base - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_base/struct.RelayUrlParseError.html b/pr/3666/docs/iroh_base/struct.RelayUrlParseError.html
index f1666d48d3..88ab58447d 100644
--- a/pr/3666/docs/iroh_base/struct.RelayUrlParseError.html
+++ b/pr/3666/docs/iroh_base/struct.RelayUrlParseError.html
@@ -1,4 +1,4 @@
-RelayUrlParseError in iroh_base - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_base/struct.SecretKey.html b/pr/3666/docs/iroh_base/struct.SecretKey.html
index 37ee92ef94..e2a30dc88b 100644
--- a/pr/3666/docs/iroh_base/struct.SecretKey.html
+++ b/pr/3666/docs/iroh_base/struct.SecretKey.html
@@ -1,4 +1,4 @@
-SecretKey in iroh_base - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_base/struct.Signature.html b/pr/3666/docs/iroh_base/struct.Signature.html
index a639fcfd8d..4f7af00c09 100644
--- a/pr/3666/docs/iroh_base/struct.Signature.html
+++ b/pr/3666/docs/iroh_base/struct.Signature.html
@@ -1,4 +1,4 @@
-Signature in iroh_base - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_base/struct.SignatureError.html b/pr/3666/docs/iroh_base/struct.SignatureError.html
index 6ac7e97269..51fb47867a 100644
--- a/pr/3666/docs/iroh_base/struct.SignatureError.html
+++ b/pr/3666/docs/iroh_base/struct.SignatureError.html
@@ -1,4 +1,4 @@
-SignatureError in iroh_base - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_bench/enum.Commands.html b/pr/3666/docs/iroh_bench/enum.Commands.html
index 5a0ad0e189..221f7dbd9f 100644
--- a/pr/3666/docs/iroh_bench/enum.Commands.html
+++ b/pr/3666/docs/iroh_bench/enum.Commands.html
@@ -1,4 +1,4 @@
-Commands in iroh_bench - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_bench/enum.ConnectionSelector.html b/pr/3666/docs/iroh_bench/enum.ConnectionSelector.html
index 48cad6eacb..b677282b8e 100644
--- a/pr/3666/docs/iroh_bench/enum.ConnectionSelector.html
+++ b/pr/3666/docs/iroh_bench/enum.ConnectionSelector.html
@@ -1,4 +1,4 @@
-ConnectionSelector in iroh_bench - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_bench/enum.EndpointSelector.html b/pr/3666/docs/iroh_bench/enum.EndpointSelector.html
index a5ce196b89..488175d912 100644
--- a/pr/3666/docs/iroh_bench/enum.EndpointSelector.html
+++ b/pr/3666/docs/iroh_bench/enum.EndpointSelector.html
@@ -1,4 +1,4 @@
-EndpointSelector in iroh_bench - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_bench/s2n/struct.Opt.html b/pr/3666/docs/iroh_bench/s2n/struct.Opt.html
index e4e1e44369..90b59d6f21 100644
--- a/pr/3666/docs/iroh_bench/s2n/struct.Opt.html
+++ b/pr/3666/docs/iroh_bench/s2n/struct.Opt.html
@@ -1,4 +1,4 @@
-Opt in iroh_bench::s2n - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_bench/stats/struct.Stats.html b/pr/3666/docs/iroh_bench/stats/struct.Stats.html
index 3e3afcd1f9..5d3b39c446 100644
--- a/pr/3666/docs/iroh_bench/stats/struct.Stats.html
+++ b/pr/3666/docs/iroh_bench/stats/struct.Stats.html
@@ -1,4 +1,4 @@
-Stats in iroh_bench::stats - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_bench/stats/struct.StreamStats.html b/pr/3666/docs/iroh_bench/stats/struct.StreamStats.html
index ce781e0e66..8d7b2b8340 100644
--- a/pr/3666/docs/iroh_bench/stats/struct.StreamStats.html
+++ b/pr/3666/docs/iroh_bench/stats/struct.StreamStats.html
@@ -1,4 +1,4 @@
-StreamStats in iroh_bench::stats - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_bench/stats/struct.TransferResult.html b/pr/3666/docs/iroh_bench/stats/struct.TransferResult.html
index a437f383cc..ca0e6ab6a8 100644
--- a/pr/3666/docs/iroh_bench/stats/struct.TransferResult.html
+++ b/pr/3666/docs/iroh_bench/stats/struct.TransferResult.html
@@ -1,4 +1,4 @@
-TransferResult in iroh_bench::stats - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_bench/struct.ClientStats.html b/pr/3666/docs/iroh_bench/struct.ClientStats.html
index 8817940c2d..4e56216501 100644
--- a/pr/3666/docs/iroh_bench/struct.ClientStats.html
+++ b/pr/3666/docs/iroh_bench/struct.ClientStats.html
@@ -1,4 +1,4 @@
-ClientStats in iroh_bench - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_bench/struct.Opt.html b/pr/3666/docs/iroh_bench/struct.Opt.html
index aeb14b674f..9e73fc529b 100644
--- a/pr/3666/docs/iroh_bench/struct.Opt.html
+++ b/pr/3666/docs/iroh_bench/struct.Opt.html
@@ -1,4 +1,4 @@
-Opt in iroh_bench - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_dns_server/config/enum.BootstrapOption.html b/pr/3666/docs/iroh_dns_server/config/enum.BootstrapOption.html
index 61a87946a3..a00eb452e1 100644
--- a/pr/3666/docs/iroh_dns_server/config/enum.BootstrapOption.html
+++ b/pr/3666/docs/iroh_dns_server/config/enum.BootstrapOption.html
@@ -1,4 +1,4 @@
-BootstrapOption in iroh_dns_server::config - Rust
\ No newline at end of file
+ T: for<'de> Deserialize<'de>,§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_dns_server/config/struct.Config.html b/pr/3666/docs/iroh_dns_server/config/struct.Config.html
index 0354ceca6e..b86e87c7d8 100644
--- a/pr/3666/docs/iroh_dns_server/config/struct.Config.html
+++ b/pr/3666/docs/iroh_dns_server/config/struct.Config.html
@@ -1,4 +1,4 @@
-Config in iroh_dns_server::config - Rust
\ No newline at end of file
+ T: for<'de> Deserialize<'de>,§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_dns_server/config/struct.MainlineConfig.html b/pr/3666/docs/iroh_dns_server/config/struct.MainlineConfig.html
index 1e07d04fdd..558cd27dea 100644
--- a/pr/3666/docs/iroh_dns_server/config/struct.MainlineConfig.html
+++ b/pr/3666/docs/iroh_dns_server/config/struct.MainlineConfig.html
@@ -1,4 +1,4 @@
-MainlineConfig in iroh_dns_server::config - Rust
\ No newline at end of file
+ T: for<'de> Deserialize<'de>,§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_dns_server/config/struct.MetricsConfig.html b/pr/3666/docs/iroh_dns_server/config/struct.MetricsConfig.html
index ca14b10591..96907505b3 100644
--- a/pr/3666/docs/iroh_dns_server/config/struct.MetricsConfig.html
+++ b/pr/3666/docs/iroh_dns_server/config/struct.MetricsConfig.html
@@ -1,4 +1,4 @@
-MetricsConfig in iroh_dns_server::config - Rust
\ No newline at end of file
+ T: for<'de> Deserialize<'de>,§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_dns_server/config/struct.StoreConfig.html b/pr/3666/docs/iroh_dns_server/config/struct.StoreConfig.html
index e750f3bef0..b3ab1d692f 100644
--- a/pr/3666/docs/iroh_dns_server/config/struct.StoreConfig.html
+++ b/pr/3666/docs/iroh_dns_server/config/struct.StoreConfig.html
@@ -1,4 +1,4 @@
-StoreConfig in iroh_dns_server::config - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_dns_server/dns/struct.DnsConfig.html b/pr/3666/docs/iroh_dns_server/dns/struct.DnsConfig.html
index 310bc0557f..9d37aa29d5 100644
--- a/pr/3666/docs/iroh_dns_server/dns/struct.DnsConfig.html
+++ b/pr/3666/docs/iroh_dns_server/dns/struct.DnsConfig.html
@@ -1,4 +1,4 @@
-DnsConfig in iroh_dns_server::dns - Rust
\ No newline at end of file
+ T: for<'de> Deserialize<'de>,§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_dns_server/dns/struct.DnsHandler.html b/pr/3666/docs/iroh_dns_server/dns/struct.DnsHandler.html
index 09bcda1ad6..f38f6fafba 100644
--- a/pr/3666/docs/iroh_dns_server/dns/struct.DnsHandler.html
+++ b/pr/3666/docs/iroh_dns_server/dns/struct.DnsHandler.html
@@ -1,4 +1,4 @@
-DnsHandler in iroh_dns_server::dns - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_dns_server/dns/struct.DnsServer.html b/pr/3666/docs/iroh_dns_server/dns/struct.DnsServer.html
index e873cdf172..b0f3843d41 100644
--- a/pr/3666/docs/iroh_dns_server/dns/struct.DnsServer.html
+++ b/pr/3666/docs/iroh_dns_server/dns/struct.DnsServer.html
@@ -1,4 +1,4 @@
-DnsServer in iroh_dns_server::dns - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_dns_server/dns/struct.Handle.html b/pr/3666/docs/iroh_dns_server/dns/struct.Handle.html
index a1e61aaffa..79b34326a8 100644
--- a/pr/3666/docs/iroh_dns_server/dns/struct.Handle.html
+++ b/pr/3666/docs/iroh_dns_server/dns/struct.Handle.html
@@ -1,4 +1,4 @@
-Handle in iroh_dns_server::dns - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_dns_server/http/enum.CertMode.html b/pr/3666/docs/iroh_dns_server/http/enum.CertMode.html
index 6e8218af21..14011a3777 100644
--- a/pr/3666/docs/iroh_dns_server/http/enum.CertMode.html
+++ b/pr/3666/docs/iroh_dns_server/http/enum.CertMode.html
@@ -1,4 +1,4 @@
-CertMode in iroh_dns_server::http - Rust
\ No newline at end of file
+ T: for<'de> Deserialize<'de>,§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_dns_server/http/enum.RateLimitConfig.html b/pr/3666/docs/iroh_dns_server/http/enum.RateLimitConfig.html
index 1f082fd787..a95db94a25 100644
--- a/pr/3666/docs/iroh_dns_server/http/enum.RateLimitConfig.html
+++ b/pr/3666/docs/iroh_dns_server/http/enum.RateLimitConfig.html
@@ -1,4 +1,4 @@
-RateLimitConfig in iroh_dns_server::http - Rust
\ No newline at end of file
+ T: for<'de> Deserialize<'de>,§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_dns_server/http/struct.HttpConfig.html b/pr/3666/docs/iroh_dns_server/http/struct.HttpConfig.html
index 7deb7c9b71..74957f701d 100644
--- a/pr/3666/docs/iroh_dns_server/http/struct.HttpConfig.html
+++ b/pr/3666/docs/iroh_dns_server/http/struct.HttpConfig.html
@@ -1,4 +1,4 @@
-HttpConfig in iroh_dns_server::http - Rust
\ No newline at end of file
+ T: for<'de> Deserialize<'de>,§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_dns_server/http/struct.HttpServer.html b/pr/3666/docs/iroh_dns_server/http/struct.HttpServer.html
index c4484b3610..8424fe0349 100644
--- a/pr/3666/docs/iroh_dns_server/http/struct.HttpServer.html
+++ b/pr/3666/docs/iroh_dns_server/http/struct.HttpServer.html
@@ -1,4 +1,4 @@
-HttpServer in iroh_dns_server::http - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_dns_server/http/struct.HttpsConfig.html b/pr/3666/docs/iroh_dns_server/http/struct.HttpsConfig.html
index d086998299..e5e0d2010d 100644
--- a/pr/3666/docs/iroh_dns_server/http/struct.HttpsConfig.html
+++ b/pr/3666/docs/iroh_dns_server/http/struct.HttpsConfig.html
@@ -1,4 +1,4 @@
-HttpsConfig in iroh_dns_server::http - Rust
\ No newline at end of file
+ T: for<'de> Deserialize<'de>,§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_dns_server/metrics/struct.Metrics.html b/pr/3666/docs/iroh_dns_server/metrics/struct.Metrics.html
index 6bbbcc7e7c..1b77e84e22 100644
--- a/pr/3666/docs/iroh_dns_server/metrics/struct.Metrics.html
+++ b/pr/3666/docs/iroh_dns_server/metrics/struct.Metrics.html
@@ -1,4 +1,4 @@
-Metrics in iroh_dns_server::metrics - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_dns_server/server/struct.Server.html b/pr/3666/docs/iroh_dns_server/server/struct.Server.html
index bbf7080bb8..b8f0e9d3db 100644
--- a/pr/3666/docs/iroh_dns_server/server/struct.Server.html
+++ b/pr/3666/docs/iroh_dns_server/server/struct.Server.html
@@ -1,4 +1,4 @@
-Server in iroh_dns_server::server - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_dns_server/state/struct.AppState.html b/pr/3666/docs/iroh_dns_server/state/struct.AppState.html
index 8723acd32b..f2aca1e73e 100644
--- a/pr/3666/docs/iroh_dns_server/state/struct.AppState.html
+++ b/pr/3666/docs/iroh_dns_server/state/struct.AppState.html
@@ -1,4 +1,4 @@
-AppState in iroh_dns_server::state - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_dns_server/struct.ZoneStore.html b/pr/3666/docs/iroh_dns_server/struct.ZoneStore.html
index 6204f5a7a8..e54b41db99 100644
--- a/pr/3666/docs/iroh_dns_server/struct.ZoneStore.html
+++ b/pr/3666/docs/iroh_dns_server/struct.ZoneStore.html
@@ -1,4 +1,4 @@
-ZoneStore in iroh_dns_server - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/client/enum.ConnectError.html b/pr/3666/docs/iroh_relay/client/enum.ConnectError.html
index b87d5eb757..0c73094892 100644
--- a/pr/3666/docs/iroh_relay/client/enum.ConnectError.html
+++ b/pr/3666/docs/iroh_relay/client/enum.ConnectError.html
@@ -1,4 +1,4 @@
-ConnectError in iroh_relay::client - Rust
pub enum ConnectError {
InvalidWebsocketUrl {
url: Url,
meta: Meta,
@@ -84,4 +84,5 @@ relay, as well as errors that occur while creating or maintaining a connection.<
V: MultiLane<T>,
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/client/enum.DialError.html b/pr/3666/docs/iroh_relay/client/enum.DialError.html
index ba796e4d19..faea5e77dc 100644
--- a/pr/3666/docs/iroh_relay/client/enum.DialError.html
+++ b/pr/3666/docs/iroh_relay/client/enum.DialError.html
@@ -1,4 +1,4 @@
-DialError in iroh_relay::client - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/client/enum.RecvError.html b/pr/3666/docs/iroh_relay/client/enum.RecvError.html
index 3b4d6ff9fc..e4bdb09d43 100644
--- a/pr/3666/docs/iroh_relay/client/enum.RecvError.html
+++ b/pr/3666/docs/iroh_relay/client/enum.RecvError.html
@@ -1,4 +1,4 @@
-RecvError in iroh_relay::client - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/client/enum.SendError.html b/pr/3666/docs/iroh_relay/client/enum.SendError.html
index 8d720d6976..99673ce1e1 100644
--- a/pr/3666/docs/iroh_relay/client/enum.SendError.html
+++ b/pr/3666/docs/iroh_relay/client/enum.SendError.html
@@ -1,4 +1,4 @@
-SendError in iroh_relay::client - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/client/struct.Client.html b/pr/3666/docs/iroh_relay/client/struct.Client.html
index a5cc94523c..011b5f7ba9 100644
--- a/pr/3666/docs/iroh_relay/client/struct.Client.html
+++ b/pr/3666/docs/iroh_relay/client/struct.Client.html
@@ -1,4 +1,4 @@
-Client in iroh_relay::client - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/client/struct.ClientBuilder.html b/pr/3666/docs/iroh_relay/client/struct.ClientBuilder.html
index c66fab1488..ea8d623f90 100644
--- a/pr/3666/docs/iroh_relay/client/struct.ClientBuilder.html
+++ b/pr/3666/docs/iroh_relay/client/struct.ClientBuilder.html
@@ -1,7 +1,7 @@
-ClientBuilder in iroh_relay::client - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/client/struct.ClientSink.html b/pr/3666/docs/iroh_relay/client/struct.ClientSink.html
index d80329c4d0..d42984d224 100644
--- a/pr/3666/docs/iroh_relay/client/struct.ClientSink.html
+++ b/pr/3666/docs/iroh_relay/client/struct.ClientSink.html
@@ -1,4 +1,4 @@
-ClientSink in iroh_relay::client - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/client/struct.ClientStream.html b/pr/3666/docs/iroh_relay/client/struct.ClientStream.html
index 7b00fff260..01459a8eeb 100644
--- a/pr/3666/docs/iroh_relay/client/struct.ClientStream.html
+++ b/pr/3666/docs/iroh_relay/client/struct.ClientStream.html
@@ -1,4 +1,4 @@
-ClientStream in iroh_relay::client - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/dns/enum.DnsError.html b/pr/3666/docs/iroh_relay/dns/enum.DnsError.html
index 9703eb58ee..365b3e8add 100644
--- a/pr/3666/docs/iroh_relay/dns/enum.DnsError.html
+++ b/pr/3666/docs/iroh_relay/dns/enum.DnsError.html
@@ -1,4 +1,4 @@
-DnsError in iroh_relay::dns - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/dns/enum.DnsProtocol.html b/pr/3666/docs/iroh_relay/dns/enum.DnsProtocol.html
index 2f35f2681d..ecd4d2bc15 100644
--- a/pr/3666/docs/iroh_relay/dns/enum.DnsProtocol.html
+++ b/pr/3666/docs/iroh_relay/dns/enum.DnsProtocol.html
@@ -1,4 +1,4 @@
-DnsProtocol in iroh_relay::dns - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/dns/enum.LookupError.html b/pr/3666/docs/iroh_relay/dns/enum.LookupError.html
index c4da28267e..fa87600fbc 100644
--- a/pr/3666/docs/iroh_relay/dns/enum.LookupError.html
+++ b/pr/3666/docs/iroh_relay/dns/enum.LookupError.html
@@ -1,4 +1,4 @@
-LookupError in iroh_relay::dns - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/dns/struct.Builder.html b/pr/3666/docs/iroh_relay/dns/struct.Builder.html
index 88651478c9..0b98a6bd47 100644
--- a/pr/3666/docs/iroh_relay/dns/struct.Builder.html
+++ b/pr/3666/docs/iroh_relay/dns/struct.Builder.html
@@ -1,4 +1,4 @@
-Builder in iroh_relay::dns - Rust
Makes the builder respect the host system’s DNS configuration.
We first try to read the system’s resolver from /etc/resolv.conf.
This does not work at least on some Androids, therefore we fallback
@@ -42,4 +42,5 @@ to a default config which uses Google’s 8.8.8.8 or 8.8.4.4<
V: MultiLane<T>,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/dns/struct.DnsResolver.html b/pr/3666/docs/iroh_relay/dns/struct.DnsResolver.html
index 246ff55953..cfc84d18dc 100644
--- a/pr/3666/docs/iroh_relay/dns/struct.DnsResolver.html
+++ b/pr/3666/docs/iroh_relay/dns/struct.DnsResolver.html
@@ -1,4 +1,4 @@
-DnsResolver in iroh_relay::dns - Rust
Creates a new DNS resolver with sensible cross-platform defaults.
We first try to read the system’s resolver from /etc/resolv.conf.
This does not work at least on some Androids, therefore we fallback
@@ -73,9 +73,9 @@ at T+0ms, T+200ms and T+300ms. The timeout is applied as stated in
summary of all errors otherwise.
pub async fn lookup_endpoint_by_domain_name(
@@ -93,10 +93,10 @@ at T+0ms, T+200ms and T+300ms. The result of the first successful call is return
summary of all errors otherwise.
Looks up endpoint info by [EndpointId] 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
@@ -135,4 +135,5 @@ The return type is a future containing an iterator of SocketAddr. <
V: MultiLane<T>,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/dns/struct.StaggeredError.html b/pr/3666/docs/iroh_relay/dns/struct.StaggeredError.html
index a46e1950c5..2305a65f23 100644
--- a/pr/3666/docs/iroh_relay/dns/struct.StaggeredError.html
+++ b/pr/3666/docs/iroh_relay/dns/struct.StaggeredError.html
@@ -1,4 +1,4 @@
-StaggeredError in iroh_relay::dns - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/dns/struct.TxtRecordData.html b/pr/3666/docs/iroh_relay/dns/struct.TxtRecordData.html
index 4974f2b244..4d884d9e52 100644
--- a/pr/3666/docs/iroh_relay/dns/struct.TxtRecordData.html
+++ b/pr/3666/docs/iroh_relay/dns/struct.TxtRecordData.html
@@ -1,4 +1,4 @@
-TxtRecordData in iroh_relay::dns - Rust
TxtRecordData implements fmt::Display, so you can call ToString::to_string to
convert the record data into a string. This will parse each character string with
@@ -41,4 +41,5 @@ convert the record data into a string. This will parse each character string wit
V: MultiLane<T>,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/endpoint_info/enum.DecodingError.html b/pr/3666/docs/iroh_relay/endpoint_info/enum.DecodingError.html
index daa76b8135..c320512d14 100644
--- a/pr/3666/docs/iroh_relay/endpoint_info/enum.DecodingError.html
+++ b/pr/3666/docs/iroh_relay/endpoint_info/enum.DecodingError.html
@@ -1,4 +1,4 @@
-DecodingError in iroh_relay::endpoint_info - Rust
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/endpoint_info/enum.EncodingError.html b/pr/3666/docs/iroh_relay/endpoint_info/enum.EncodingError.html
index 82989b7093..42066d814d 100644
--- a/pr/3666/docs/iroh_relay/endpoint_info/enum.EncodingError.html
+++ b/pr/3666/docs/iroh_relay/endpoint_info/enum.EncodingError.html
@@ -1,4 +1,4 @@
-EncodingError in iroh_relay::endpoint_info - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/endpoint_info/enum.ParseError.html b/pr/3666/docs/iroh_relay/endpoint_info/enum.ParseError.html
index a06a25c04f..37d7d70c1e 100644
--- a/pr/3666/docs/iroh_relay/endpoint_info/enum.ParseError.html
+++ b/pr/3666/docs/iroh_relay/endpoint_info/enum.ParseError.html
@@ -1,4 +1,4 @@
-ParseError in iroh_relay::endpoint_info - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/endpoint_info/index.html b/pr/3666/docs/iroh_relay/endpoint_info/index.html
index 9de61c4142..4a43824b7c 100644
--- a/pr/3666/docs/iroh_relay/endpoint_info/index.html
+++ b/pr/3666/docs/iroh_relay/endpoint_info/index.html
@@ -1,5 +1,5 @@
-iroh_relay::endpoint_info - Rust
Support for handling DNS resource records for dialing by [EndpointId].
+
Dialing by [EndpointId] is supported by iroh endpoints 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-endpoint-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-endpoint-id> is the z-base-32 encoding of the [EndpointId].
<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:
Extension methods for [EndpointId] 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/3666/docs/iroh_relay/endpoint_info/struct.EndpointData.html b/pr/3666/docs/iroh_relay/endpoint_info/struct.EndpointData.html
index b6e5f6b39f..d8a25e06bf 100644
--- a/pr/3666/docs/iroh_relay/endpoint_info/struct.EndpointData.html
+++ b/pr/3666/docs/iroh_relay/endpoint_info/struct.EndpointData.html
@@ -1,23 +1,23 @@
-EndpointData in iroh_relay::endpoint_info - Rust
Data about an endpoint that may be published to and resolved from discovery services.
+
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 endpoint’s EndpointId, only the data about a certain
-endpoint. See EndpointInfo for a struct that contains a EndpointId with associated EndpointData.
Sets the relay URL and returns the updated endpoint data.
+
This struct does not include the endpoint’s [EndpointId], only the data about a certain
+endpoint. See EndpointInfo for a struct that contains a [EndpointId] with associated EndpointData.
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/endpoint_info/struct.EndpointInfo.html b/pr/3666/docs/iroh_relay/endpoint_info/struct.EndpointInfo.html
index c6a136c7d7..1b8e4f1e79 100644
--- a/pr/3666/docs/iroh_relay/endpoint_info/struct.EndpointInfo.html
+++ b/pr/3666/docs/iroh_relay/endpoint_info/struct.EndpointInfo.html
@@ -1,17 +1,17 @@
-EndpointInfo in iroh_relay::endpoint_info - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/endpoint_info/struct.MaxLengthExceededError.html b/pr/3666/docs/iroh_relay/endpoint_info/struct.MaxLengthExceededError.html
index ccead6528b..543e0f3913 100644
--- a/pr/3666/docs/iroh_relay/endpoint_info/struct.MaxLengthExceededError.html
+++ b/pr/3666/docs/iroh_relay/endpoint_info/struct.MaxLengthExceededError.html
@@ -1,4 +1,4 @@
-MaxLengthExceededError in iroh_relay::endpoint_info - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/endpoint_info/struct.UserData.html b/pr/3666/docs/iroh_relay/endpoint_info/struct.UserData.html
index 4098e27ae8..a817cd4041 100644
--- a/pr/3666/docs/iroh_relay/endpoint_info/struct.UserData.html
+++ b/pr/3666/docs/iroh_relay/endpoint_info/struct.UserData.html
@@ -1,4 +1,4 @@
-UserData in iroh_relay::endpoint_info - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/endpoint_info/trait.EndpointIdExt.html b/pr/3666/docs/iroh_relay/endpoint_info/trait.EndpointIdExt.html
index 103efb1882..2cfafe8d14 100644
--- a/pr/3666/docs/iroh_relay/endpoint_info/trait.EndpointIdExt.html
+++ b/pr/3666/docs/iroh_relay/endpoint_info/trait.EndpointIdExt.html
@@ -1,9 +1,9 @@
EndpointIdExt in iroh_relay::endpoint_info - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/index.html b/pr/3666/docs/iroh_relay/index.html
index d16544ab4a..9fd890b801 100644
--- a/pr/3666/docs/iroh_relay/index.html
+++ b/pr/3666/docs/iroh_relay/index.html
@@ -25,6 +25,6 @@ Tailscale.
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/3666/docs/iroh_relay/protos/common/enum.FrameType.html b/pr/3666/docs/iroh_relay/protos/common/enum.FrameType.html
index 3f4738e902..fb6268e7c7 100644
--- a/pr/3666/docs/iroh_relay/protos/common/enum.FrameType.html
+++ b/pr/3666/docs/iroh_relay/protos/common/enum.FrameType.html
@@ -1,4 +1,4 @@
-FrameType in iroh_relay::protos::common - Rust
pub enum FrameType {
Show 13 variants ServerChallenge = 0,
ClientAuth = 1,
ServerConfirmsAuth = 2,
@@ -73,4 +73,5 @@ and should not be overridden without very good reason.
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/protos/common/enum.FrameTypeError.html b/pr/3666/docs/iroh_relay/protos/common/enum.FrameTypeError.html
index b3cfaf1155..73604093d8 100644
--- a/pr/3666/docs/iroh_relay/protos/common/enum.FrameTypeError.html
+++ b/pr/3666/docs/iroh_relay/protos/common/enum.FrameTypeError.html
@@ -1,4 +1,4 @@
-FrameTypeError in iroh_relay::protos::common - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/protos/handshake/enum.Error.html b/pr/3666/docs/iroh_relay/protos/handshake/enum.Error.html
index 903097b9d6..fc17235139 100644
--- a/pr/3666/docs/iroh_relay/protos/handshake/enum.Error.html
+++ b/pr/3666/docs/iroh_relay/protos/handshake/enum.Error.html
@@ -1,4 +1,4 @@
-Error in iroh_relay::protos::handshake - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/protos/relay/enum.ClientToRelayMsg.html b/pr/3666/docs/iroh_relay/protos/relay/enum.ClientToRelayMsg.html
index e07e71e1c5..2d04f650c5 100644
--- a/pr/3666/docs/iroh_relay/protos/relay/enum.ClientToRelayMsg.html
+++ b/pr/3666/docs/iroh_relay/protos/relay/enum.ClientToRelayMsg.html
@@ -1,8 +1,8 @@
-ClientToRelayMsg in iroh_relay::protos::relay - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/protos/relay/enum.Error.html b/pr/3666/docs/iroh_relay/protos/relay/enum.Error.html
index 27fca77b09..f1dc2ecafc 100644
--- a/pr/3666/docs/iroh_relay/protos/relay/enum.Error.html
+++ b/pr/3666/docs/iroh_relay/protos/relay/enum.Error.html
@@ -1,4 +1,4 @@
-Error in iroh_relay::protos::relay - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/protos/relay/enum.RelayToClientMsg.html b/pr/3666/docs/iroh_relay/protos/relay/enum.RelayToClientMsg.html
index 7858ef2c19..78d82f570e 100644
--- a/pr/3666/docs/iroh_relay/protos/relay/enum.RelayToClientMsg.html
+++ b/pr/3666/docs/iroh_relay/protos/relay/enum.RelayToClientMsg.html
@@ -1,9 +1,9 @@
-RelayToClientMsg in iroh_relay::protos::relay - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/protos/relay/struct.Datagrams.html b/pr/3666/docs/iroh_relay/protos/relay/struct.Datagrams.html
index c028b169ab..68f0c81016 100644
--- a/pr/3666/docs/iroh_relay/protos/relay/struct.Datagrams.html
+++ b/pr/3666/docs/iroh_relay/protos/relay/struct.Datagrams.html
@@ -1,4 +1,4 @@
-Datagrams in iroh_relay::protos::relay - Rust
pub struct Datagrams {
pub ecn: Option<EcnCodepoint>,
pub segment_size: Option<NonZeroU16>,
pub contents: Bytes,
@@ -56,4 +56,5 @@ and should not be overridden without very good reason.
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/quic/enum.Error.html b/pr/3666/docs/iroh_relay/quic/enum.Error.html
index 3a9d761e2e..f2220c76d0 100644
--- a/pr/3666/docs/iroh_relay/quic/enum.Error.html
+++ b/pr/3666/docs/iroh_relay/quic/enum.Error.html
@@ -1,4 +1,4 @@
-Error in iroh_relay::quic - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/quic/struct.QuicClient.html b/pr/3666/docs/iroh_relay/quic/struct.QuicClient.html
index 19d7e4353f..67330d0a26 100644
--- a/pr/3666/docs/iroh_relay/quic/struct.QuicClient.html
+++ b/pr/3666/docs/iroh_relay/quic/struct.QuicClient.html
@@ -1,4 +1,4 @@
-QuicClient in iroh_relay::quic - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/server/enum.Access.html b/pr/3666/docs/iroh_relay/server/enum.Access.html
index 6c03837134..3152b2d357 100644
--- a/pr/3666/docs/iroh_relay/server/enum.Access.html
+++ b/pr/3666/docs/iroh_relay/server/enum.Access.html
@@ -1,4 +1,4 @@
-Access in iroh_relay::server - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/server/enum.AccessConfig.html b/pr/3666/docs/iroh_relay/server/enum.AccessConfig.html
index 28681a8228..2b84ea06bb 100644
--- a/pr/3666/docs/iroh_relay/server/enum.AccessConfig.html
+++ b/pr/3666/docs/iroh_relay/server/enum.AccessConfig.html
@@ -1,10 +1,10 @@
-AccessConfig in iroh_relay::server - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/server/enum.CertConfig.html b/pr/3666/docs/iroh_relay/server/enum.CertConfig.html
index 44b2e7f1e6..ede2980326 100644
--- a/pr/3666/docs/iroh_relay/server/enum.CertConfig.html
+++ b/pr/3666/docs/iroh_relay/server/enum.CertConfig.html
@@ -1,4 +1,4 @@
-CertConfig in iroh_relay::server - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/server/enum.SpawnError.html b/pr/3666/docs/iroh_relay/server/enum.SpawnError.html
index d2a2d8ab50..eb77470110 100644
--- a/pr/3666/docs/iroh_relay/server/enum.SpawnError.html
+++ b/pr/3666/docs/iroh_relay/server/enum.SpawnError.html
@@ -1,4 +1,4 @@
-SpawnError in iroh_relay::server - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/server/enum.SupervisorError.html b/pr/3666/docs/iroh_relay/server/enum.SupervisorError.html
index 8dd147dafe..5e904c5403 100644
--- a/pr/3666/docs/iroh_relay/server/enum.SupervisorError.html
+++ b/pr/3666/docs/iroh_relay/server/enum.SupervisorError.html
@@ -1,4 +1,4 @@
-SupervisorError in iroh_relay::server - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/server/struct.ClientRateLimit.html b/pr/3666/docs/iroh_relay/server/struct.ClientRateLimit.html
index 554e98bdbb..cb4deeb3c0 100644
--- a/pr/3666/docs/iroh_relay/server/struct.ClientRateLimit.html
+++ b/pr/3666/docs/iroh_relay/server/struct.ClientRateLimit.html
@@ -1,4 +1,4 @@
-ClientRateLimit in iroh_relay::server - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/server/struct.Limits.html b/pr/3666/docs/iroh_relay/server/struct.Limits.html
index 9596ddfd6f..451a0a53d3 100644
--- a/pr/3666/docs/iroh_relay/server/struct.Limits.html
+++ b/pr/3666/docs/iroh_relay/server/struct.Limits.html
@@ -1,4 +1,4 @@
-Limits in iroh_relay::server - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/server/struct.Metrics.html b/pr/3666/docs/iroh_relay/server/struct.Metrics.html
index e063bbc2f1..b02f976225 100644
--- a/pr/3666/docs/iroh_relay/server/struct.Metrics.html
+++ b/pr/3666/docs/iroh_relay/server/struct.Metrics.html
@@ -1,4 +1,4 @@
-Metrics in iroh_relay::server - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/server/struct.QuicConfig.html b/pr/3666/docs/iroh_relay/server/struct.QuicConfig.html
index 064462f342..3b7c490351 100644
--- a/pr/3666/docs/iroh_relay/server/struct.QuicConfig.html
+++ b/pr/3666/docs/iroh_relay/server/struct.QuicConfig.html
@@ -1,4 +1,4 @@
-QuicConfig in iroh_relay::server - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/server/struct.RelayConfig.html b/pr/3666/docs/iroh_relay/server/struct.RelayConfig.html
index ed098d47ad..4fe613156f 100644
--- a/pr/3666/docs/iroh_relay/server/struct.RelayConfig.html
+++ b/pr/3666/docs/iroh_relay/server/struct.RelayConfig.html
@@ -1,4 +1,4 @@
-RelayConfig in iroh_relay::server - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/server/struct.RelayMetrics.html b/pr/3666/docs/iroh_relay/server/struct.RelayMetrics.html
index 47cb633dea..debc618c42 100644
--- a/pr/3666/docs/iroh_relay/server/struct.RelayMetrics.html
+++ b/pr/3666/docs/iroh_relay/server/struct.RelayMetrics.html
@@ -1,4 +1,4 @@
-RelayMetrics in iroh_relay::server - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/server/struct.ReloadingResolver.html b/pr/3666/docs/iroh_relay/server/struct.ReloadingResolver.html
index 621dbf453c..2a662a3810 100644
--- a/pr/3666/docs/iroh_relay/server/struct.ReloadingResolver.html
+++ b/pr/3666/docs/iroh_relay/server/struct.ReloadingResolver.html
@@ -1,4 +1,4 @@
-ReloadingResolver in iroh_relay::server - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/server/struct.Server.html b/pr/3666/docs/iroh_relay/server/struct.Server.html
index 2d8987915e..545d97aa1a 100644
--- a/pr/3666/docs/iroh_relay/server/struct.Server.html
+++ b/pr/3666/docs/iroh_relay/server/struct.Server.html
@@ -1,4 +1,4 @@
-Server in iroh_relay::server - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/server/struct.ServerConfig.html b/pr/3666/docs/iroh_relay/server/struct.ServerConfig.html
index 44e71e4453..22c77b2da3 100644
--- a/pr/3666/docs/iroh_relay/server/struct.ServerConfig.html
+++ b/pr/3666/docs/iroh_relay/server/struct.ServerConfig.html
@@ -1,4 +1,4 @@
-ServerConfig in iroh_relay::server - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/server/struct.TlsConfig.html b/pr/3666/docs/iroh_relay/server/struct.TlsConfig.html
index 8b74688e54..9de19da60c 100644
--- a/pr/3666/docs/iroh_relay/server/struct.TlsConfig.html
+++ b/pr/3666/docs/iroh_relay/server/struct.TlsConfig.html
@@ -1,4 +1,4 @@
-TlsConfig in iroh_relay::server - Rust
\ No newline at end of file
+[WithDispatch] wrapper. Read more§
impl<T> ErasedDestructor for T
where
+ T: 'static,
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/struct.PingTracker.html b/pr/3666/docs/iroh_relay/struct.PingTracker.html
index ceb97613ff..621cd1f12b 100644
--- a/pr/3666/docs/iroh_relay/struct.PingTracker.html
+++ b/pr/3666/docs/iroh_relay/struct.PingTracker.html
@@ -1,4 +1,4 @@
-PingTracker in iroh_relay - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/struct.RelayConfig.html b/pr/3666/docs/iroh_relay/struct.RelayConfig.html
index 4ba3e30d09..c04bd7a028 100644
--- a/pr/3666/docs/iroh_relay/struct.RelayConfig.html
+++ b/pr/3666/docs/iroh_relay/struct.RelayConfig.html
@@ -1,14 +1,14 @@
-RelayConfig in iroh_relay - Rust
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/struct.RelayMap.html b/pr/3666/docs/iroh_relay/struct.RelayMap.html
index 3a6131c7c6..67f1a92685 100644
--- a/pr/3666/docs/iroh_relay/struct.RelayMap.html
+++ b/pr/3666/docs/iroh_relay/struct.RelayMap.html
@@ -1,4 +1,4 @@
-RelayMap in iroh_relay - Rust
Returns the URLs of all servers in this relay map.
This function is generic over the container to collect into. If you simply want a list
of URLs, call this with map.urls::<Vec<_>>() to get a Vec<RelayUrl>.
Returns a list with the RelayConfig for each relay in this relay map.
This function is generic over the container to collect into. If you simply want a list
of URLs, call this with map.relays::<Vec<_>>() to get a Vec<RelayConfig>.
\ No newline at end of file
diff --git a/pr/3666/docs/iroh_relay/struct.RelayQuicConfig.html b/pr/3666/docs/iroh_relay/struct.RelayQuicConfig.html
index 776cc1f2dc..a55101c5b0 100644
--- a/pr/3666/docs/iroh_relay/struct.RelayQuicConfig.html
+++ b/pr/3666/docs/iroh_relay/struct.RelayQuicConfig.html
@@ -1,4 +1,4 @@
-RelayQuicConfig in iroh_relay - Rust
1//! Contains the discovery message types.
-2//!
-3//! A discovery message is:
-4//!
-5//! Header:
-6//!
-7//! ```ignore
-8//! magic: [u8; 6] // “TS💬” (0x54 53 f0 9f 92 ac)
-9//! sender_disco_pub: [u8; 32] // nacl public key
-10//! nonce: [u8; 24]
-11//! ````
-12//! The recipient then decrypts the bytes following (the nacl secretbox)
-13//! and then the inner payload structure is:
-14//!
-15//! ```ignore
-16//! message_type: u8 // (the MessageType constants below)
-17//! message_version: u8 // (0 for now; but always ignore bytes at the end)
-18//! message_payload: &[u8]
-19//! ```
-20
-21use std::{
-22 fmt::{self, Display},
-23 net::{IpAddr, SocketAddr},
-24};
-25
-26use data_encoding::HEXLOWER;
-27use iroh_base::{EndpointId, PublicKey, RelayUrl};
-28use n0_error::{e, ensure, stack_error};
-29use rand::Rng;
-30use serde::{Deserialize, Serialize};
-31use url::Url;
-32
-33use crate::magicsock::transports;
-34
-35// TODO: custom magicn
-36/// The 6 byte header of all discovery messages.
-37pub const MAGIC: &str = "TS💬"; // 6 bytes: 0x54 53 f0 9f 92 ac
-38pub const MAGIC_LEN: usize = MAGIC.len();
-39
-40/// Current Version.
-41const V0: u8 = 0;
-42
-43pub(crate) const KEY_LEN: usize = 32;
-44const TX_LEN: usize = 12;
-45
-46// Sizes for the inner message structure.
-47
-48/// Header: Type | Version
-49const HEADER_LEN: usize = 2;
-50
-51const PING_LEN: usize = TX_LEN + iroh_base::PublicKey::LENGTH;
-52const EP_LENGTH: usize = 16 + 2; // 16 byte IP address + 2 byte port
-53
-54#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
-55#[repr(u8)]
-56pub enum MessageType {
-57 Ping = 0x01,
-58 Pong = 0x02,
-59 CallMeMaybe = 0x03,
-60}
-61
-62impl TryFrom<u8> for MessageType {
-63type Error = u8;
-64
-65fn try_from(value: u8) -> std::result::Result<Self, Self::Error> {
-66match value {
-670x01 => Ok(MessageType::Ping),
-680x02 => Ok(MessageType::Pong),
-690x03 => Ok(MessageType::CallMeMaybe),
-70_ => Err(value),
-71 }
-72 }
-73}
-74
-75const MESSAGE_HEADER_LEN: usize = MAGIC_LEN + KEY_LEN;
-76
-77pub fn encode_message(sender: &PublicKey, seal: Vec<u8>) -> Vec<u8> {
-78let mut out = Vec::with_capacity(MESSAGE_HEADER_LEN);
-79 out.extend_from_slice(MAGIC.as_bytes());
-80 out.extend_from_slice(sender.as_bytes());
-81 out.extend(seal);
-82
-83 out
-84}
-85
-86/// Reports whether p looks like it's a packet containing an encrypted disco message.
-87pub fn looks_like_disco_wrapper(p: &[u8]) -> bool {
-88if p.len() < MESSAGE_HEADER_LEN {
-89return false;
-90 }
-91
-92&p[..MAGIC_LEN] == MAGIC.as_bytes()
-93}
-94
-95/// If `p` looks like a disco message it returns the slice of `p` that represents the disco public key source,
-96/// and the part that is the box.
-97pub fn source_and_box(p: &[u8]) -> Option<(PublicKey, &[u8])> {
-98if !looks_like_disco_wrapper(p) {
-99return None;
-100 }
-101
-102let source = &p[MAGIC_LEN..MAGIC_LEN + KEY_LEN];
-103let sender = PublicKey::try_from(source).ok()?;
-104let sealed_box = &p[MAGIC_LEN + KEY_LEN..];
-105Some((sender, sealed_box))
-106}
-107
-108/// A discovery message.
-109#[derive(Debug, Clone, PartialEq, Eq)]
-110pub enum Message {
-111 Ping(Ping),
-112 Pong(Pong),
-113 CallMeMaybe(CallMeMaybe),
-114}
-115
-116#[derive(Debug, Clone, PartialEq, Eq)]
-117pub struct Ping {
-118/// Random client-generated per-ping transaction ID.
-119pub tx_id: TransactionId,
-120
-121/// Allegedly the ping sender's public key.
-122 ///
-123 /// It shouldn't be trusted by itself.
-124pub endpoint_key: PublicKey,
-125}
-126
-127impl Ping {
-128/// Creates a ping message to ping `node_id`.
-129 ///
-130 /// Uses a randomly generated STUN transaction ID.
-131pub(crate) fn new(endpoint_id: EndpointId) -> Self {
-132Self {
-133 tx_id: TransactionId::default(),
-134 endpoint_key: endpoint_id,
-135 }
-136 }
-137
-138fn from_bytes(p: &[u8]) -> Result<Self, ParseError> {
-139// Deliberately lax on longer-than-expected messages, for future compatibility.
-140ensure!(p.len() >= PING_LEN, ParseError::TooShort);
-141let tx_id: [u8; TX_LEN] = p[..TX_LEN].try_into().expect("length checked");
-142let raw_key = &p[TX_LEN..TX_LEN + iroh_base::PublicKey::LENGTH];
-143let endpoint_key =
-144 PublicKey::try_from(raw_key).map_err(|_| e!(ParseError::InvalidEncoding))?;
-145let tx_id = TransactionId::from(tx_id);
-146
-147Ok(Ping {
-148 tx_id,
-149 endpoint_key,
-150 })
-151 }
-152
-153fn as_bytes(&self) -> Vec<u8> {
-154let header = msg_header(MessageType::Ping, V0);
-155let mut out = vec![0u8; PING_LEN + HEADER_LEN];
-156
-157 out[..HEADER_LEN].copy_from_slice(&header);
-158 out[HEADER_LEN..HEADER_LEN + TX_LEN].copy_from_slice(&self.tx_id);
-159 out[HEADER_LEN + TX_LEN..].copy_from_slice(self.endpoint_key.as_ref());
-160
-161 out
-162 }
-163}
-164
-165/// A response a Ping.
-166///
-167/// It includes the sender's source IP + port, so it's effectively a STUN response.
-168#[derive(Debug, Clone, PartialEq, Eq)]
-169pub struct Pong {
-170pub tx_id: TransactionId,
-171/// The observed address off the ping sender.
-172 ///
-173 /// 18 bytes (16+2) on the wire; v4-mapped ipv6 for IPv4.
-174pub ping_observed_addr: SendAddr,
-175}
-176
-177/// Addresses to which we can send. This is either a UDP or a relay address.
-178#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
-179pub enum SendAddr {
-180/// UDP, the ip addr.
-181Udp(SocketAddr),
-182/// Relay Url.
-183Relay(RelayUrl),
-184}
-185
-186impl From<transports::Addr> for SendAddr {
-187fn from(addr: transports::Addr) -> Self {
-188match addr {
-189 transports::Addr::Ip(addr) => SendAddr::Udp(addr),
-190 transports::Addr::Relay(url, _) => SendAddr::Relay(url),
-191 }
-192 }
-193}
-194
-195impl From<SocketAddr> for SendAddr {
-196fn from(source: SocketAddr) -> Self {
-197 SendAddr::Udp(source)
-198 }
-199}
-200
-201impl From<RelayUrl> for SendAddr {
-202fn from(source: RelayUrl) -> Self {
-203 SendAddr::Relay(source)
-204 }
-205}
-206
-207impl PartialEq<SocketAddr> for SendAddr {
-208fn eq(&self, other: &SocketAddr) -> bool {
-209match self {
-210Self::Relay(_) => false,
-211Self::Udp(addr) => addr.eq(other),
-212 }
-213 }
-214}
-215
-216impl Display for SendAddr {
-217fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
-218match self {
-219 SendAddr::Relay(id) => write!(f, "Relay({id})"),
-220 SendAddr::Udp(addr) => write!(f, "UDP({addr})"),
-221 }
-222 }
-223}
-224
-225/// Message sent only over the relay to request that the recipient try
-226/// to open up a magicsock path back to the sender.
-227///
-228/// The sender should've already sent UDP packets to the peer to open
-229/// up the stateful firewall mappings inbound.
-230///
-231/// The recipient may choose to not open a path back, if it's already happy with its path.
-232/// But usually it will.
-233#[derive(Debug, Clone, PartialEq, Eq)]
-234pub struct CallMeMaybe {
-235/// What the peer believes its endpoints are.
-236pub my_numbers: Vec<SocketAddr>,
-237}
-238
-239#[allow(missing_docs)]
-240#[stack_error(derive, add_meta)]
-241#[non_exhaustive]
-242pub enum ParseError {
-243#[error("message is too short")]
-244TooShort,
-245#[error("invalid encoding")]
-246InvalidEncoding,
-247#[error("unknown format")]
-248UnknownFormat,
-249}
-250
-251fn send_addr_from_bytes(p: &[u8]) -> Result<SendAddr, ParseError> {
-252ensure!(p.len() > 2, ParseError::TooShort);
-253match p[0] {
-2540u8 => {
-255let bytes: [u8; EP_LENGTH] = p[1..].try_into().map_err(|_| e!(ParseError::TooShort))?;
-256let addr = socket_addr_from_bytes(bytes);
-257Ok(SendAddr::Udp(addr))
-258 }
-2591u8 => {
-260let s = std::str::from_utf8(&p[1..]).map_err(|_| e!(ParseError::InvalidEncoding))?;
-261let u: Url = s.parse().map_err(|_| e!(ParseError::InvalidEncoding))?;
-262Ok(SendAddr::Relay(u.into()))
-263 }
-264_ => Err(e!(ParseError::UnknownFormat)),
-265 }
-266}
-267
-268fn send_addr_to_vec(addr: &SendAddr) -> Vec<u8> {
-269match addr {
-270 SendAddr::Relay(url) => {
-271let mut out = vec![1u8];
-272 out.extend_from_slice(url.to_string().as_bytes());
-273 out
-274 }
-275 SendAddr::Udp(ip) => {
-276let mut out = vec![0u8];
-277 out.extend_from_slice(&socket_addr_as_bytes(ip));
-278 out
-279 }
-280 }
-281}
-282
-283// Assumes p.len() == EP_LENGTH
-284fn socket_addr_from_bytes(p: [u8; EP_LENGTH]) -> SocketAddr {
-285debug_assert_eq!(EP_LENGTH, 16 + 2);
-286
-287let raw_src_ip: [u8; 16] = p[..16].try_into().expect("array long enough");
-288let raw_port: [u8; 2] = p[16..].try_into().expect("array long enough");
-289
-290let src_ip = IpAddr::from(raw_src_ip).to_canonical();
-291let src_port = u16::from_le_bytes(raw_port);
-292
-293 SocketAddr::new(src_ip, src_port)
-294}
-295
-296fn socket_addr_as_bytes(addr: &SocketAddr) -> [u8; EP_LENGTH] {
-297let mut out = [0u8; EP_LENGTH];
-298let ipv6 = match addr.ip() {
-299 IpAddr::V4(v4) => v4.to_ipv6_mapped(),
-300 IpAddr::V6(v6) => v6,
-301 };
-302 out[..16].copy_from_slice(&ipv6.octets());
-303 out[16..].copy_from_slice(&addr.port().to_le_bytes());
-304
-305 out
-306}
-307
-308impl Pong {
-309fn from_bytes(p: &[u8]) -> Result<Self, ParseError> {
-310let tx_id: [u8; TX_LEN] = p[..TX_LEN]
-311 .try_into()
-312 .map_err(|_| e!(ParseError::TooShort))?;
-313
-314let tx_id = TransactionId::from(tx_id);
-315let src = send_addr_from_bytes(&p[TX_LEN..])?;
-316
-317Ok(Pong {
-318 tx_id,
-319 ping_observed_addr: src,
-320 })
-321 }
-322
-323fn as_bytes(&self) -> Vec<u8> {
-324let header = msg_header(MessageType::Pong, V0);
-325let mut out = header.to_vec();
-326 out.extend_from_slice(&self.tx_id);
-327
-328let src_bytes = send_addr_to_vec(&self.ping_observed_addr);
-329 out.extend(src_bytes);
-330 out
-331 }
-332}
-333
-334impl CallMeMaybe {
-335fn from_bytes(p: &[u8]) -> Result<Self, ParseError> {
-336ensure!(p.len() % EP_LENGTH == 0, ParseError::InvalidEncoding);
-337
-338let num_entries = p.len() / EP_LENGTH;
-339let mut m = CallMeMaybe {
-340 my_numbers: Vec::with_capacity(num_entries),
-341 };
-342
-343for chunk in p.chunks_exact(EP_LENGTH) {
-344let bytes: [u8; EP_LENGTH] = chunk
-345 .try_into()
-346 .map_err(|_| e!(ParseError::InvalidEncoding))?;
-347let src = socket_addr_from_bytes(bytes);
-348 m.my_numbers.push(src);
-349 }
-350
-351Ok(m)
-352 }
-353
-354fn as_bytes(&self) -> Vec<u8> {
-355let header = msg_header(MessageType::CallMeMaybe, V0);
-356let mut out = vec![0u8; HEADER_LEN + self.my_numbers.len() * EP_LENGTH];
-357 out[..HEADER_LEN].copy_from_slice(&header);
-358
-359for (m, chunk) in self
-360.my_numbers
-361 .iter()
-362 .zip(out[HEADER_LEN..].chunks_exact_mut(EP_LENGTH))
-363 {
-364let raw = socket_addr_as_bytes(m);
-365 chunk.copy_from_slice(&raw);
-366 }
-367
-368 out
-369 }
-370}
-371
-372impl Message {
-373/// Parses the encrypted part of the message from inside the nacl secretbox.
-374pub fn from_bytes(p: &[u8]) -> Result<Self, ParseError> {
-375ensure!(p.len() >= 2, ParseError::TooShort);
-376
-377let t = MessageType::try_from(p[0]).map_err(|_| e!(ParseError::UnknownFormat))?;
-378let version = p[1];
-379ensure!(version == V0, ParseError::UnknownFormat);
-380
-381let p = &p[2..];
-382match t {
-383 MessageType::Ping => {
-384let ping = Ping::from_bytes(p)?;
-385Ok(Message::Ping(ping))
-386 }
-387 MessageType::Pong => {
-388let pong = Pong::from_bytes(p)?;
-389Ok(Message::Pong(pong))
-390 }
-391 MessageType::CallMeMaybe => {
-392let cm = CallMeMaybe::from_bytes(p)?;
-393Ok(Message::CallMeMaybe(cm))
-394 }
-395 }
-396 }
-397
-398/// Serialize this message to bytes.
-399pub fn as_bytes(&self) -> Vec<u8> {
-400match self {
-401 Message::Ping(ping) => ping.as_bytes(),
-402 Message::Pong(pong) => pong.as_bytes(),
-403 Message::CallMeMaybe(cm) => cm.as_bytes(),
-404 }
-405 }
-406}
-407
-408impl Display for Message {
-409fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
-410match self {
-411 Message::Ping(ping) => {
-412write!(f, "Ping(tx={})", HEXLOWER.encode(&ping.tx_id))
-413 }
-414 Message::Pong(pong) => {
-415write!(f, "Pong(tx={})", HEXLOWER.encode(&pong.tx_id))
-416 }
-417 Message::CallMeMaybe(_) => {
-418write!(f, "CallMeMaybe")
-419 }
-420 }
-421 }
-422}
-423
-424const fn msg_header(t: MessageType, ver: u8) -> [u8; HEADER_LEN] {
-425 [t as u8, ver]
-426}
-427
-428const TRANSACTION_ID_SIZE: usize = 12;
-429
-430/// The transaction ID is a 96-bit identifier
-431///
-432/// It is used to uniquely identify STUN transactions.
-433/// It primarily serves to correlate requests with responses,
-434/// though it also plays a small role in helping to prevent
-435/// certain types of attacks. The server also uses the transaction ID as
-436/// a key to identify each transaction uniquely across all clients.
-437#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
-438pub(crate) struct TransactionId([u8; TRANSACTION_ID_SIZE]);
-439
-440impl fmt::Debug for TransactionId {
-441fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
-442write!(f, "TransactionId(0x")?;
-443 fmt_transcation_id(self.as_ref(), f)
-444 }
-445}
-446
-447impl fmt::Display for TransactionId {
-448fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
-449write!(f, "transaction id (0x")?;
-450 fmt_transcation_id(self.as_ref(), f)
-451 }
-452}
-453
-454fn fmt_transcation_id(bytes: &[u8], f: &mut fmt::Formatter) -> fmt::Result {
-455for byte in bytes {
-456write!(f, "{:02X}", byte)?;
-457 }
-458write!(f, ")")
-459}
-460
-461impl std::ops::Deref for TransactionId {
-462type Target = [u8];
-463
-464fn deref(&self) -> &[u8] {
-465&self.0
-466}
-467}
-468
-469impl AsRef<[u8]> for TransactionId {
-470fn as_ref(&self) -> &[u8] {
-471&self.0[..]
-472 }
-473}
-474
-475impl From<&[u8; TRANSACTION_ID_SIZE]> for TransactionId {
-476fn from(buff: &[u8; TRANSACTION_ID_SIZE]) -> Self {
-477Self(*buff)
-478 }
-479}
-480
-481impl From<[u8; TRANSACTION_ID_SIZE]> for TransactionId {
-482fn from(buff: [u8; TRANSACTION_ID_SIZE]) -> Self {
-483Self(buff)
-484 }
-485}
-486
-487impl rand::distr::Distribution<TransactionId> for rand::distr::StandardUniform {
-488fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> TransactionId {
-489let mut buffer = [0u8; TRANSACTION_ID_SIZE];
-490 rng.fill_bytes(&mut buffer);
-491 TransactionId::from(buffer)
-492 }
-493}
-494
-495impl Default for TransactionId {
-496/// Creates a cryptographically random transaction ID chosen from the interval 0 .. 2**96-1.
-497fn default() -> Self {
-498let mut rng = rand::rng();
-499 rng.random()
-500 }
-501}
-502
-503#[cfg(test)]
-504mod tests {
-505use iroh_base::SecretKey;
-506use rand::SeedableRng;
-507
-508use super::*;
-509use crate::key::{SharedSecret, public_ed_box, secret_ed_box};
-510
-511#[test]
-512fn test_to_from_bytes() {
-513struct Test {
-514 name: &'static str,
-515 m: Message,
-516 want: &'static str,
-517 }
-518let tests = [
-519 Test {
-520 name: "ping_with_endpointkey_src",
-521 m: Message::Ping(Ping {
-522 tx_id: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].into(),
-523 endpoint_key: PublicKey::try_from(
-524&[
-525190, 243, 65, 104, 37, 102, 175, 75, 243, 22, 69, 200, 167, 107, 24,
-52663, 216, 140, 120, 43, 4, 112, 16, 62, 117, 155, 45, 215, 72, 175, 40,
-527189,
-528 ][..],
-529 )
-530 .unwrap(),
-531 }),
-532 want: "01 00 01 02 03 04 05 06 07 08 09 0a 0b 0c be f3 41 68 25 66 af 4b f3 16 45 c8 a7 6b 18 3f d8 8c 78 2b 04 70 10 3e 75 9b 2d d7 48 af 28 bd",
-533 },
-534 Test {
-535 name: "pong",
-536 m: Message::Pong(Pong {
-537 tx_id: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].into(),
-538 ping_observed_addr: SendAddr::Udp("2.3.4.5:1234".parse().unwrap()),
-539 }),
-540 want: "02 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 00 00 00 00 00 00 00 00 00 00 00 ff ff 02 03 04 05 d2 04",
-541 },
-542 Test {
-543 name: "pongv6",
-544 m: Message::Pong(Pong {
-545 tx_id: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].into(),
-546 ping_observed_addr: SendAddr::Udp("[fed0::12]:6666".parse().unwrap()),
-547 }),
-548 want: "02 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 00 fe d0 00 00 00 00 00 00 00 00 00 00 00 00 00 12 0a 1a",
-549 },
-550 Test {
-551 name: "call_me_maybe",
-552 m: Message::CallMeMaybe(CallMeMaybe {
-553 my_numbers: Vec::new(),
-554 }),
-555 want: "03 00",
-556 },
-557 Test {
-558 name: "call_me_maybe_endpoints",
-559 m: Message::CallMeMaybe(CallMeMaybe {
-560 my_numbers: vec![
-561"1.2.3.4:567".parse().unwrap(),
-562"[2001::3456]:789".parse().unwrap(),
-563 ],
-564 }),
-565 want: "03 00 00 00 00 00 00 00 00 00 00 00 ff ff 01 02 03 04 37 02 20 01 00 00 00 00 00 00 00 00 00 00 00 00 34 56 15 03",
-566 },
-567 ];
-568for test in tests {
-569println!("{}", test.name);
-570
-571let got = test.m.as_bytes();
-572assert_eq!(
-573 got,
-574 data_encoding::HEXLOWER
-575 .decode(test.want.replace(' ', "").as_bytes())
-576 .unwrap(),
-577"wrong as_bytes"
-578);
-579
-580let back = Message::from_bytes(&got).expect("failed to parse");
-581assert_eq!(test.m, back, "wrong from_bytes");
-582 }
-583 }
-584
-585#[test]
-586fn test_extraction() {
-587let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
-588let sender_key = SecretKey::generate(&mut rng);
-589let recv_key = SecretKey::generate(&mut rng);
-590
-591let msg = Message::Ping(Ping {
-592 tx_id: TransactionId::default(),
-593 endpoint_key: sender_key.public(),
-594 });
-595
-596let sender_secret = secret_ed_box(&sender_key);
-597let shared = SharedSecret::new(&sender_secret, &public_ed_box(&recv_key.public()));
-598let mut seal = msg.as_bytes();
-599 shared.seal(&mut seal);
-600
-601let bytes = encode_message(&sender_key.public(), seal.clone());
-602
-603assert!(looks_like_disco_wrapper(&bytes));
-604assert_eq!(source_and_box(&bytes).unwrap().0, sender_key.public());
-605
-606let (raw_key, seal_back) = source_and_box(&bytes).unwrap();
-607assert_eq!(raw_key, sender_key.public());
-608assert_eq!(seal_back, seal);
-609
-610let recv_secret = secret_ed_box(&recv_key);
-611let shared_recv = SharedSecret::new(&recv_secret, &public_ed_box(&sender_key.public()));
-612let mut open_seal = seal_back.to_vec();
-613 shared_recv
-614 .open(&mut open_seal)
-615 .expect("failed to open seal_back");
-616let msg_back = Message::from_bytes(&open_seal).unwrap();
-617assert_eq!(msg_back, msg);
-618 }
-619}
\ No newline at end of file
diff --git a/pr/3666/docs/src/iroh/endpoint.rs.html b/pr/3666/docs/src/iroh/endpoint.rs.html
index 6026e6de74..4c89885063 100644
--- a/pr/3666/docs/src/iroh/endpoint.rs.html
+++ b/pr/3666/docs/src/iroh/endpoint.rs.html
@@ -174,2277 +174,2279 @@
174self.transport_config
175 .default_path_max_idle_timeout(Some(PATH_MAX_IDLE_TIMEOUT));
176self.transport_config
-177 .max_concurrent_multipath_paths(MAX_MULTIPATH_PATHS);
-178
-179let static_config = StaticConfig {
-180 transport_config: Arc::new(self.transport_config),
-181 tls_config: tls::TlsConfig::new(secret_key.clone(), self.max_tls_tickets),
-182 keylog: self.keylog,
-183 };
-184let server_config = static_config.create_server_config(self.alpn_protocols);
-185
-186#[cfg(not(wasm_browser))]
-187let dns_resolver = self.dns_resolver.unwrap_or_default();
-188
-189let metrics = EndpointMetrics::default();
+177 .max_concurrent_multipath_paths(MAX_MULTIPATH_PATHS + 1);
+178self.transport_config
+179 .set_max_remote_nat_traversal_addresses(MAX_MULTIPATH_PATHS as u8);
+180
+181let static_config = StaticConfig {
+182 transport_config: Arc::new(self.transport_config),
+183 tls_config: tls::TlsConfig::new(secret_key.clone(), self.max_tls_tickets),
+184 keylog: self.keylog,
+185 };
+186let server_config = static_config.create_server_config(self.alpn_protocols);
+187
+188#[cfg(not(wasm_browser))]
+189let dns_resolver = self.dns_resolver.unwrap_or_default();
190
-191let msock_opts = magicsock::Options {
-192 transports: self.transports,
-193 secret_key,
-194 discovery_user_data: self.discovery_user_data,
-195 proxy_url: self.proxy_url,
-196#[cfg(not(wasm_browser))]
-197dns_resolver,
-198 server_config,
-199#[cfg(any(test, feature = "test-utils"))]
-200insecure_skip_relay_cert_verify: self.insecure_skip_relay_cert_verify,
-201 metrics,
-202 };
-203
-204let msock = magicsock::MagicSock::spawn(msock_opts).await?;
-205trace!("created magicsock");
-206debug!(version = env!("CARGO_PKG_VERSION"), "iroh Endpoint created");
-207
-208let ep = Endpoint {
-209 msock,
-210 static_config: Arc::new(static_config),
-211 };
-212
-213// Add discovery mechanisms
-214for create_service in self.discovery {
-215let service = create_service.into_discovery(&ep)?;
-216 ep.discovery().add_boxed(service);
-217 }
-218
-219Ok(ep)
-220 }
-221
-222// # The very common methods everyone basically needs.
+191let metrics = EndpointMetrics::default();
+192
+193let msock_opts = magicsock::Options {
+194 transports: self.transports,
+195 secret_key,
+196 discovery_user_data: self.discovery_user_data,
+197 proxy_url: self.proxy_url,
+198#[cfg(not(wasm_browser))]
+199dns_resolver,
+200 server_config,
+201#[cfg(any(test, feature = "test-utils"))]
+202insecure_skip_relay_cert_verify: self.insecure_skip_relay_cert_verify,
+203 metrics,
+204 };
+205
+206let msock = magicsock::MagicSock::spawn(msock_opts).await?;
+207trace!("created magicsock");
+208debug!(version = env!("CARGO_PKG_VERSION"), "iroh Endpoint created");
+209
+210let ep = Endpoint {
+211 msock,
+212 static_config: Arc::new(static_config),
+213 };
+214
+215// Add discovery mechanisms
+216for create_service in self.discovery {
+217let service = create_service.into_discovery(&ep)?;
+218 ep.discovery().add_boxed(service);
+219 }
+220
+221Ok(ep)
+222 }
223
-224/// Adds an IP transport, binding to the provided IPv4 address.
-225 ///
-226 /// If you want to remove the default transports, make sure to call `clear_ip` first.
+224// # The very common methods everyone basically needs.
+225
+226/// Adds an IP transport, binding to the provided IPv4 address.
227 ///
-228 /// Setting the port to `0` will use a random port.
-229 /// If the port specified is already in use, it will fallback to choosing a random port.
-230#[cfg(not(wasm_browser))]
-231pub fn bind_addr_v4(mut self, bind_addr: SocketAddrV4) -> Self {
-232self.transports.push(TransportConfig::Ip {
-233 bind_addr: bind_addr.into(),
-234 });
-235self
-236}
-237
-238/// Adds an IP transport, binding to the provided IPv6 address.
-239 ///
-240 /// If you want to remove the default transports, make sure to call `clear_ip` first.
+228 /// If you want to remove the default transports, make sure to call `clear_ip` first.
+229 ///
+230 /// Setting the port to `0` will use a random port.
+231 /// If the port specified is already in use, it will fallback to choosing a random port.
+232#[cfg(not(wasm_browser))]
+233pub fn bind_addr_v4(mut self, bind_addr: SocketAddrV4) -> Self {
+234self.transports.push(TransportConfig::Ip {
+235 bind_addr: bind_addr.into(),
+236 });
+237self
+238}
+239
+240/// Adds an IP transport, binding to the provided IPv6 address.
241 ///
-242 /// Setting the port to `0` will use a random port.
-243 /// If the port specified is already in use, it will fallback to choosing a random port.
-244#[cfg(not(wasm_browser))]
-245pub fn bind_addr_v6(mut self, bind_addr: SocketAddrV6) -> Self {
-246self.transports.push(TransportConfig::Ip {
-247 bind_addr: bind_addr.into(),
-248 });
-249self
-250}
-251
-252/// Removes all IP based transports
-253#[cfg(not(wasm_browser))]
-254pub fn clear_ip_transports(mut self) -> Self {
-255self.transports
-256 .retain(|t| !matches!(t, TransportConfig::Ip { .. }));
-257self
-258}
-259
-260/// Removes all relay based transports
-261pub fn clear_relay_transports(mut self) -> Self {
-262self.transports
-263 .retain(|t| !matches!(t, TransportConfig::Relay { .. }));
-264self
-265}
-266
-267/// Sets a secret key to authenticate with other peers.
-268 ///
-269 /// This secret key's public key will be the [`PublicKey`] of this endpoint and thus
-270 /// also its [`EndpointId`]
-271 ///
-272 /// If not set, a new secret key will be generated.
+242 /// If you want to remove the default transports, make sure to call `clear_ip` first.
+243 ///
+244 /// Setting the port to `0` will use a random port.
+245 /// If the port specified is already in use, it will fallback to choosing a random port.
+246#[cfg(not(wasm_browser))]
+247pub fn bind_addr_v6(mut self, bind_addr: SocketAddrV6) -> Self {
+248self.transports.push(TransportConfig::Ip {
+249 bind_addr: bind_addr.into(),
+250 });
+251self
+252}
+253
+254/// Removes all IP based transports
+255#[cfg(not(wasm_browser))]
+256pub fn clear_ip_transports(mut self) -> Self {
+257self.transports
+258 .retain(|t| !matches!(t, TransportConfig::Ip { .. }));
+259self
+260}
+261
+262/// Removes all relay based transports
+263pub fn clear_relay_transports(mut self) -> Self {
+264self.transports
+265 .retain(|t| !matches!(t, TransportConfig::Relay { .. }));
+266self
+267}
+268
+269/// Sets a secret key to authenticate with other peers.
+270 ///
+271 /// This secret key's public key will be the [`PublicKey`] of this endpoint and thus
+272 /// also its [`EndpointId`]
273 ///
-274 /// [`PublicKey`]: iroh_base::PublicKey
-275pub fn secret_key(mut self, secret_key: SecretKey) -> Self {
-276self.secret_key = Some(secret_key);
-277self
-278}
-279
-280/// Sets the [ALPN] protocols that this endpoint will accept on incoming connections.
-281 ///
-282 /// Not setting this will still allow creating connections, but to accept incoming
-283 /// connections at least one [ALPN] must be set.
-284 ///
-285 /// [ALPN]: https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation
-286pub fn alpns(mut self, alpn_protocols: Vec<Vec<u8>>) -> Self {
-287self.alpn_protocols = alpn_protocols;
-288self
-289}
-290
-291// # Methods for common customisation items.
+274 /// If not set, a new secret key will be generated.
+275 ///
+276 /// [`PublicKey`]: iroh_base::PublicKey
+277pub fn secret_key(mut self, secret_key: SecretKey) -> Self {
+278self.secret_key = Some(secret_key);
+279self
+280}
+281
+282/// Sets the [ALPN] protocols that this endpoint will accept on incoming connections.
+283 ///
+284 /// Not setting this will still allow creating connections, but to accept incoming
+285 /// connections at least one [ALPN] must be set.
+286 ///
+287 /// [ALPN]: https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation
+288pub fn alpns(mut self, alpn_protocols: Vec<Vec<u8>>) -> Self {
+289self.alpn_protocols = alpn_protocols;
+290self
+291}
292
-293/// Sets the relay servers to assist in establishing connectivity.
-294 ///
-295 /// Relay servers are used to establish initial connection with another iroh endpoint.
-296 /// They also perform various functions related to hole punching, see the [crate docs]
-297 /// for more details.
-298 ///
-299 /// By default the [number 0] relay servers are used, see [`RelayMode::Default`].
+293// # Methods for common customisation items.
+294
+295/// Sets the relay servers to assist in establishing connectivity.
+296 ///
+297 /// Relay servers are used to establish initial connection with another iroh endpoint.
+298 /// They also perform various functions related to hole punching, see the [crate docs]
+299 /// for more details.
300 ///
-301 /// When using [RelayMode::Custom], the provided `relay_map` must contain at least one
-302 /// configured relay endpoint. If an invalid RelayMap is provided [`bind`]
-303 /// will result in an error.
-304 ///
-305 /// [`bind`]: Builder::bind
-306 /// [crate docs]: crate
-307 /// [number 0]: https://n0.computer
-308pub fn relay_mode(mut self, relay_mode: RelayMode) -> Self {
-309let transport: Option<_> = relay_mode.into();
-310match transport {
-311Some(transport) => {
-312if let Some(og) = self
-313.transports
-314 .iter_mut()
-315 .find(|t| matches!(t, TransportConfig::Relay { .. }))
-316 {
-317*og = transport;
-318 } else {
-319self.transports.push(transport);
-320 }
-321 }
-322None => {
-323self.transports
-324 .retain(|t| !matches!(t, TransportConfig::Relay { .. }));
-325 }
-326 }
-327self
-328}
-329
-330/// Removes all discovery services from the builder.
-331 ///
-332 /// If no discovery service is set, connecting to an endpoint without providing its
-333 /// direct addresses or relay URLs will fail.
-334 ///
-335 /// See the documentation of the [`crate::discovery::Discovery`] trait for details.
-336pub fn clear_discovery(mut self) -> Self {
-337self.discovery.clear();
-338self
-339}
-340
-341/// Adds a discovery mechanism for this endpoint.
-342 ///
-343 /// The function `discovery`
-344 /// will be called on endpoint creation with the configured secret key of
-345 /// the endpoint. Discovery services that need to publish information need
-346 /// to use this secret key to sign the information.
-347 ///
-348 /// If you add multiple discovery services, they will be combined using a
-349 /// [`crate::discovery::ConcurrentDiscovery`].
-350 ///
-351 /// If no discovery service is set, connecting to an endpoint without providing its
-352 /// direct addresses or relay URLs will fail.
-353 ///
-354 /// To clear all discovery services, use [`Builder::clear_discovery`].
+301 /// By default the [number 0] relay servers are used, see [`RelayMode::Default`].
+302 ///
+303 /// When using [RelayMode::Custom], the provided `relay_map` must contain at least one
+304 /// configured relay endpoint. If an invalid RelayMap is provided [`bind`]
+305 /// will result in an error.
+306 ///
+307 /// [`bind`]: Builder::bind
+308 /// [crate docs]: crate
+309 /// [number 0]: https://n0.computer
+310pub fn relay_mode(mut self, relay_mode: RelayMode) -> Self {
+311let transport: Option<_> = relay_mode.into();
+312match transport {
+313Some(transport) => {
+314if let Some(og) = self
+315.transports
+316 .iter_mut()
+317 .find(|t| matches!(t, TransportConfig::Relay { .. }))
+318 {
+319*og = transport;
+320 } else {
+321self.transports.push(transport);
+322 }
+323 }
+324None => {
+325self.transports
+326 .retain(|t| !matches!(t, TransportConfig::Relay { .. }));
+327 }
+328 }
+329self
+330}
+331
+332/// Removes all discovery services from the builder.
+333 ///
+334 /// If no discovery service is set, connecting to an endpoint without providing its
+335 /// direct addresses or relay URLs will fail.
+336 ///
+337 /// See the documentation of the [`crate::discovery::Discovery`] trait for details.
+338pub fn clear_discovery(mut self) -> Self {
+339self.discovery.clear();
+340self
+341}
+342
+343/// Adds a discovery mechanism for this endpoint.
+344 ///
+345 /// The function `discovery`
+346 /// will be called on endpoint creation with the configured secret key of
+347 /// the endpoint. Discovery services that need to publish information need
+348 /// to use this secret key to sign the information.
+349 ///
+350 /// If you add multiple discovery services, they will be combined using a
+351 /// [`crate::discovery::ConcurrentDiscovery`].
+352 ///
+353 /// If no discovery service is set, connecting to an endpoint without providing its
+354 /// direct addresses or relay URLs will fail.
355 ///
-356 /// See the documentation of the [`crate::discovery::Discovery`] trait for details.
-357pub fn discovery(mut self, discovery: impl IntoDiscovery) -> Self {
-358self.discovery.push(Box::new(discovery));
-359self
-360}
-361
-362/// Sets the initial user-defined data to be published in discovery services for this node.
-363 ///
-364 /// When using discovery services, this string of [`UserData`] will be published together
-365 /// with the endpoint's addresses and relay URL. When other endpoints discover this endpoint,
-366 /// they retrieve the [`UserData`] in addition to the addressing info.
-367 ///
-368 /// Iroh itself does not interpret the user-defined data in any way, it is purely left
-369 /// for applications to parse and use.
-370pub fn user_data_for_discovery(mut self, user_data: UserData) -> Self {
-371self.discovery_user_data = Some(user_data);
-372self
-373}
-374
-375// # Methods for more specialist customisation.
+356 /// To clear all discovery services, use [`Builder::clear_discovery`].
+357 ///
+358 /// See the documentation of the [`crate::discovery::Discovery`] trait for details.
+359pub fn discovery(mut self, discovery: impl IntoDiscovery) -> Self {
+360self.discovery.push(Box::new(discovery));
+361self
+362}
+363
+364/// Sets the initial user-defined data to be published in discovery services for this node.
+365 ///
+366 /// When using discovery services, this string of [`UserData`] will be published together
+367 /// with the endpoint's addresses and relay URL. When other endpoints discover this endpoint,
+368 /// they retrieve the [`UserData`] in addition to the addressing info.
+369 ///
+370 /// Iroh itself does not interpret the user-defined data in any way, it is purely left
+371 /// for applications to parse and use.
+372pub fn user_data_for_discovery(mut self, user_data: UserData) -> Self {
+373self.discovery_user_data = Some(user_data);
+374self
+375}
376
-377/// Sets a custom [`quinn::TransportConfig`] for this endpoint.
-378 ///
-379 /// The transport config contains parameters governing the QUIC state machine.
+377// # Methods for more specialist customisation.
+378
+379/// Sets a custom [`quinn::TransportConfig`] for this endpoint.
380 ///
-381 /// If unset, the default config is used. Default values should be suitable for most
-382 /// internet applications. Applications protocols which forbid remotely-initiated
-383 /// streams should set `max_concurrent_bidi_streams` and `max_concurrent_uni_streams` to
-384 /// zero.
-385 ///
-386 /// Please be aware that changing some settings may have adverse effects on establishing
-387 /// and maintaining direct connections.
-388pub fn transport_config(mut self, transport_config: quinn::TransportConfig) -> Self {
-389self.transport_config = transport_config;
-390self
-391}
-392
-393/// Optionally sets a custom DNS resolver to use for this endpoint.
-394 ///
-395 /// The DNS resolver is used to resolve relay hostnames, and endpoint addresses if
-396 /// [`crate::discovery::dns::DnsDiscovery`] is configured.
-397 ///
-398 /// By default, a new DNS resolver is created which is configured to use the
-399 /// host system's DNS configuration. You can pass a custom instance of [`DnsResolver`]
-400 /// here to use a differently configured DNS resolver for this endpoint, or to share
-401 /// a [`DnsResolver`] between multiple endpoints.
-402#[cfg(not(wasm_browser))]
-403pub fn dns_resolver(mut self, dns_resolver: DnsResolver) -> Self {
-404self.dns_resolver = Some(dns_resolver);
-405self
-406}
-407
-408/// Sets an explicit proxy url to proxy all HTTP(S) traffic through.
-409pub fn proxy_url(mut self, url: Url) -> Self {
-410self.proxy_url.replace(url);
-411self
-412}
-413
-414/// Sets the proxy url from the environment, in this order:
-415 ///
-416 /// - `HTTP_PROXY`
-417 /// - `http_proxy`
-418 /// - `HTTPS_PROXY`
-419 /// - `https_proxy`
-420pub fn proxy_from_env(mut self) -> Self {
-421self.proxy_url = proxy_url_from_env();
-422self
-423}
-424
-425/// Enables saving the TLS pre-master key for connections.
-426 ///
-427 /// This key should normally remain secret but can be useful to debug networking issues
-428 /// by decrypting captured traffic.
-429 ///
-430 /// If *keylog* is `true` then setting the `SSLKEYLOGFILE` environment variable to a
-431 /// filename will result in this file being used to log the TLS pre-master keys.
-432pub fn keylog(mut self, keylog: bool) -> Self {
-433self.keylog = keylog;
-434self
-435}
-436
-437/// Skip verification of SSL certificates from relay servers
-438 ///
-439 /// May only be used in tests.
-440#[cfg(any(test, feature = "test-utils"))]
-441pub fn insecure_skip_relay_cert_verify(mut self, skip_verify: bool) -> Self {
-442self.insecure_skip_relay_cert_verify = skip_verify;
-443self
-444}
-445
-446/// Set the maximum number of TLS tickets to cache.
-447 ///
-448 /// Set this to a larger value if you want to do 0rtt connections to a large
-449 /// number of clients.
-450 ///
-451 /// The default is 256, taking about 150 KiB in memory.
-452pub fn max_tls_tickets(mut self, n: usize) -> Self {
-453self.max_tls_tickets = n;
-454self
-455}
-456}
-457
-458/// Configuration for a [`quinn::Endpoint`] that cannot be changed at runtime.
-459#[derive(Debug)]
-460struct StaticConfig {
-461 tls_config: tls::TlsConfig,
-462 transport_config: Arc<quinn::TransportConfig>,
-463 keylog: bool,
-464}
-465
-466impl StaticConfig {
-467/// Create a [`quinn::ServerConfig`] with the specified ALPN protocols.
-468fn create_server_config(&self, alpn_protocols: Vec<Vec<u8>>) -> ServerConfig {
-469let quic_server_config = self
-470.tls_config
-471 .make_server_config(alpn_protocols, self.keylog);
-472let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config));
-473 server_config.transport_config(self.transport_config.clone());
-474
-475 server_config
-476 }
-477}
-478
-479/// Controls an iroh endpoint, establishing connections with other endpoints.
-480///
-481/// This is the main API interface to create connections to, and accept connections from
-482/// other iroh endpoints. The connections are peer-to-peer and encrypted, a Relay server is
-483/// used to make the connections reliable. See the [crate docs] for a more detailed
-484/// overview of iroh.
-485///
-486/// It is recommended to only create a single instance per application. This ensures all
-487/// the connections made share the same peer-to-peer connections to other iroh endpoints,
-488/// while still remaining independent connections. This will result in more optimal network
-489/// behaviour.
-490///
-491/// The endpoint is created using the [`Builder`], which can be created using
-492/// [`Endpoint::builder`].
-493///
-494/// Once an endpoint exists, new connections are typically created using the
-495/// [`Endpoint::connect`] and [`Endpoint::accept`] methods. Once established, the
-496/// [`Connection`] gives access to most [QUIC] features. Individual streams to send data to
-497/// the peer are created using the [`Connection::open_bi`], [`Connection::accept_bi`],
-498/// [`Connection::open_uni`] and [`Connection::open_bi`] functions.
-499///
-500/// Note that due to the light-weight properties of streams a stream will only be accepted
-501/// once the initiating peer has sent some data on it.
-502///
-503/// [QUIC]: https://quicwg.org
-504#[derive(Clone, Debug)]
-505pub struct Endpoint {
-506/// Handle to the magicsocket/actor
-507pub(crate) msock: Handle,
-508/// Configuration structs for quinn, holds the transport config, certificate setup, secret key etc.
-509static_config: Arc<StaticConfig>,
-510}
-511
-512#[allow(missing_docs)]
-513#[stack_error(derive, add_meta, from_sources)]
-514#[non_exhaustive]
-515#[allow(private_interfaces)]
-516pub enum ConnectWithOptsError {
-517#[error("Connecting to ourself is not supported")]
-518SelfConnect,
-519#[error("No addressing information available")]
-520NoAddress { source: DiscoveryError },
-521#[error("Unable to connect to remote")]
-522Quinn {
-523#[error(std_err)]
-524source: quinn_proto::ConnectError,
-525 },
-526#[error("Internal consistency error")]
-527InternalConsistencyError {
-528/// Private source type, cannot be created publicly.
-529source: RemoteStateActorStoppedError,
-530 },
-531}
-532
-533#[allow(missing_docs)]
-534#[stack_error(derive, add_meta, from_sources)]
-535#[non_exhaustive]
-536pub enum ConnectError {
-537#[error(transparent)]
-538Connect { source: ConnectWithOptsError },
+381 /// The transport config contains parameters governing the QUIC state machine.
+382 ///
+383 /// If unset, the default config is used. Default values should be suitable for most
+384 /// internet applications. Applications protocols which forbid remotely-initiated
+385 /// streams should set `max_concurrent_bidi_streams` and `max_concurrent_uni_streams` to
+386 /// zero.
+387 ///
+388 /// Please be aware that changing some settings may have adverse effects on establishing
+389 /// and maintaining direct connections.
+390pub fn transport_config(mut self, transport_config: quinn::TransportConfig) -> Self {
+391self.transport_config = transport_config;
+392self
+393}
+394
+395/// Optionally sets a custom DNS resolver to use for this endpoint.
+396 ///
+397 /// The DNS resolver is used to resolve relay hostnames, and endpoint addresses if
+398 /// [`crate::discovery::dns::DnsDiscovery`] is configured.
+399 ///
+400 /// By default, a new DNS resolver is created which is configured to use the
+401 /// host system's DNS configuration. You can pass a custom instance of [`DnsResolver`]
+402 /// here to use a differently configured DNS resolver for this endpoint, or to share
+403 /// a [`DnsResolver`] between multiple endpoints.
+404#[cfg(not(wasm_browser))]
+405pub fn dns_resolver(mut self, dns_resolver: DnsResolver) -> Self {
+406self.dns_resolver = Some(dns_resolver);
+407self
+408}
+409
+410/// Sets an explicit proxy url to proxy all HTTP(S) traffic through.
+411pub fn proxy_url(mut self, url: Url) -> Self {
+412self.proxy_url.replace(url);
+413self
+414}
+415
+416/// Sets the proxy url from the environment, in this order:
+417 ///
+418 /// - `HTTP_PROXY`
+419 /// - `http_proxy`
+420 /// - `HTTPS_PROXY`
+421 /// - `https_proxy`
+422pub fn proxy_from_env(mut self) -> Self {
+423self.proxy_url = proxy_url_from_env();
+424self
+425}
+426
+427/// Enables saving the TLS pre-master key for connections.
+428 ///
+429 /// This key should normally remain secret but can be useful to debug networking issues
+430 /// by decrypting captured traffic.
+431 ///
+432 /// If *keylog* is `true` then setting the `SSLKEYLOGFILE` environment variable to a
+433 /// filename will result in this file being used to log the TLS pre-master keys.
+434pub fn keylog(mut self, keylog: bool) -> Self {
+435self.keylog = keylog;
+436self
+437}
+438
+439/// Skip verification of SSL certificates from relay servers
+440 ///
+441 /// May only be used in tests.
+442#[cfg(any(test, feature = "test-utils"))]
+443pub fn insecure_skip_relay_cert_verify(mut self, skip_verify: bool) -> Self {
+444self.insecure_skip_relay_cert_verify = skip_verify;
+445self
+446}
+447
+448/// Set the maximum number of TLS tickets to cache.
+449 ///
+450 /// Set this to a larger value if you want to do 0rtt connections to a large
+451 /// number of clients.
+452 ///
+453 /// The default is 256, taking about 150 KiB in memory.
+454pub fn max_tls_tickets(mut self, n: usize) -> Self {
+455self.max_tls_tickets = n;
+456self
+457}
+458}
+459
+460/// Configuration for a [`quinn::Endpoint`] that cannot be changed at runtime.
+461#[derive(Debug)]
+462struct StaticConfig {
+463 tls_config: tls::TlsConfig,
+464 transport_config: Arc<quinn::TransportConfig>,
+465 keylog: bool,
+466}
+467
+468impl StaticConfig {
+469/// Create a [`quinn::ServerConfig`] with the specified ALPN protocols.
+470fn create_server_config(&self, alpn_protocols: Vec<Vec<u8>>) -> ServerConfig {
+471let quic_server_config = self
+472.tls_config
+473 .make_server_config(alpn_protocols, self.keylog);
+474let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config));
+475 server_config.transport_config(self.transport_config.clone());
+476
+477 server_config
+478 }
+479}
+480
+481/// Controls an iroh endpoint, establishing connections with other endpoints.
+482///
+483/// This is the main API interface to create connections to, and accept connections from
+484/// other iroh endpoints. The connections are peer-to-peer and encrypted, a Relay server is
+485/// used to make the connections reliable. See the [crate docs] for a more detailed
+486/// overview of iroh.
+487///
+488/// It is recommended to only create a single instance per application. This ensures all
+489/// the connections made share the same peer-to-peer connections to other iroh endpoints,
+490/// while still remaining independent connections. This will result in more optimal network
+491/// behaviour.
+492///
+493/// The endpoint is created using the [`Builder`], which can be created using
+494/// [`Endpoint::builder`].
+495///
+496/// Once an endpoint exists, new connections are typically created using the
+497/// [`Endpoint::connect`] and [`Endpoint::accept`] methods. Once established, the
+498/// [`Connection`] gives access to most [QUIC] features. Individual streams to send data to
+499/// the peer are created using the [`Connection::open_bi`], [`Connection::accept_bi`],
+500/// [`Connection::open_uni`] and [`Connection::open_bi`] functions.
+501///
+502/// Note that due to the light-weight properties of streams a stream will only be accepted
+503/// once the initiating peer has sent some data on it.
+504///
+505/// [QUIC]: https://quicwg.org
+506#[derive(Clone, Debug)]
+507pub struct Endpoint {
+508/// Handle to the magicsocket/actor
+509pub(crate) msock: Handle,
+510/// Configuration structs for quinn, holds the transport config, certificate setup, secret key etc.
+511static_config: Arc<StaticConfig>,
+512}
+513
+514#[allow(missing_docs)]
+515#[stack_error(derive, add_meta, from_sources)]
+516#[non_exhaustive]
+517#[allow(private_interfaces)]
+518pub enum ConnectWithOptsError {
+519#[error("Connecting to ourself is not supported")]
+520SelfConnect,
+521#[error("No addressing information available")]
+522NoAddress { source: DiscoveryError },
+523#[error("Unable to connect to remote")]
+524Quinn {
+525#[error(std_err)]
+526source: quinn_proto::ConnectError,
+527 },
+528#[error("Internal consistency error")]
+529InternalConsistencyError {
+530/// Private source type, cannot be created publicly.
+531source: RemoteStateActorStoppedError,
+532 },
+533}
+534
+535#[allow(missing_docs)]
+536#[stack_error(derive, add_meta, from_sources)]
+537#[non_exhaustive]
+538pub enum ConnectError {
539#[error(transparent)]
-540Connecting { source: ConnectingError },
+540 Connect { source: ConnectWithOptsError },
541#[error(transparent)]
-542Connection {
-543#[error(std_err)]
-544source: ConnectionError,
-545 },
-546}
-547
-548#[allow(missing_docs)]
-549#[stack_error(derive, add_meta, from_sources)]
-550#[non_exhaustive]
-551pub enum BindError {
-552#[error(transparent)]
-553MagicSpawn {
-554 source: magicsock::CreateHandleError,
-555 },
-556#[error(transparent)]
-557Discovery {
-558 source: crate::discovery::IntoDiscoveryError,
-559 },
-560}
-561
-562impl Endpoint {
-563// The ordering of public methods is reflected directly in the documentation. This is
-564 // roughly ordered by what is most commonly needed by users, but grouped in similar
-565 // items.
-566
-567 // # Methods relating to construction.
+542Connecting { source: ConnectingError },
+543#[error(transparent)]
+544Connection {
+545#[error(std_err)]
+546source: ConnectionError,
+547 },
+548}
+549
+550#[allow(missing_docs)]
+551#[stack_error(derive, add_meta, from_sources)]
+552#[non_exhaustive]
+553pub enum BindError {
+554#[error(transparent)]
+555MagicSpawn {
+556 source: magicsock::CreateHandleError,
+557 },
+558#[error(transparent)]
+559Discovery {
+560 source: crate::discovery::IntoDiscoveryError,
+561 },
+562}
+563
+564impl Endpoint {
+565// The ordering of public methods is reflected directly in the documentation. This is
+566 // roughly ordered by what is most commonly needed by users, but grouped in similar
+567 // items.
568
-569/// Returns the builder for an [`Endpoint`], with a production configuration.
-570 ///
-571 /// This uses the [`presets::N0`] as the configuration.
-572pub fn builder() -> Builder {
-573 Builder::new(presets::N0)
-574 }
-575
-576/// Returns the builder for an [`Endpoint`], with an empty configuration.
-577 ///
-578 /// See [`Builder::empty`] for details.
-579pub fn empty_builder(relay_mode: RelayMode) -> Builder {
-580 Builder::empty(relay_mode)
-581 }
-582
-583/// Constructs a default [`Endpoint`] and binds it immediately.
-584 ///
-585 /// Uses the [`presets::N0`] as configuration.
-586pub async fn bind() -> Result<Self, BindError> {
-587Self::builder().bind().await
-588}
-589
-590/// Sets the list of accepted ALPN protocols.
-591 ///
-592 /// This will only affect new incoming connections.
-593 /// Note that this *overrides* the current list of ALPNs.
-594pub fn set_alpns(&self, alpns: Vec<Vec<u8>>) {
-595let server_config = self.static_config.create_server_config(alpns);
-596self.msock.endpoint().set_server_config(Some(server_config));
-597 }
-598
-599/// Adds the provided configuration to the [`RelayMap`].
-600 ///
-601 /// Replacing and returning any existing configuration for [`RelayUrl`].
-602pub async fn insert_relay(
-603&self,
-604 relay: RelayUrl,
-605 config: Arc<RelayConfig>,
-606 ) -> Option<Arc<RelayConfig>> {
-607self.msock.insert_relay(relay, config).await
-608}
-609
-610/// Removes the configuration from the [`RelayMap`] for the provided [`RelayUrl`].
-611 ///
-612 /// Returns any existing configuration.
-613pub async fn remove_relay(&self, relay: &RelayUrl) -> Option<Arc<RelayConfig>> {
-614self.msock.remove_relay(relay).await
-615}
-616
-617// # Methods for establishing connectivity.
+569 // # Methods relating to construction.
+570
+571/// Returns the builder for an [`Endpoint`], with a production configuration.
+572 ///
+573 /// This uses the [`presets::N0`] as the configuration.
+574pub fn builder() -> Builder {
+575 Builder::new(presets::N0)
+576 }
+577
+578/// Returns the builder for an [`Endpoint`], with an empty configuration.
+579 ///
+580 /// See [`Builder::empty`] for details.
+581pub fn empty_builder(relay_mode: RelayMode) -> Builder {
+582 Builder::empty(relay_mode)
+583 }
+584
+585/// Constructs a default [`Endpoint`] and binds it immediately.
+586 ///
+587 /// Uses the [`presets::N0`] as configuration.
+588pub async fn bind() -> Result<Self, BindError> {
+589Self::builder().bind().await
+590}
+591
+592/// Sets the list of accepted ALPN protocols.
+593 ///
+594 /// This will only affect new incoming connections.
+595 /// Note that this *overrides* the current list of ALPNs.
+596pub fn set_alpns(&self, alpns: Vec<Vec<u8>>) {
+597let server_config = self.static_config.create_server_config(alpns);
+598self.msock.endpoint().set_server_config(Some(server_config));
+599 }
+600
+601/// Adds the provided configuration to the [`RelayMap`].
+602 ///
+603 /// Replacing and returning any existing configuration for [`RelayUrl`].
+604pub async fn insert_relay(
+605&self,
+606 relay: RelayUrl,
+607 config: Arc<RelayConfig>,
+608 ) -> Option<Arc<RelayConfig>> {
+609self.msock.insert_relay(relay, config).await
+610}
+611
+612/// Removes the configuration from the [`RelayMap`] for the provided [`RelayUrl`].
+613 ///
+614 /// Returns any existing configuration.
+615pub async fn remove_relay(&self, relay: &RelayUrl) -> Option<Arc<RelayConfig>> {
+616self.msock.remove_relay(relay).await
+617}
618
-619/// Connects to a remote [`Endpoint`].
-620 ///
-621 /// A value that can be converted into an [`EndpointAddr`] is required. This can be either an
-622 /// [`EndpointAddr`] or an [`EndpointId`].
-623 ///
-624 /// The [`EndpointAddr`] must contain the [`EndpointId`] to dial and may also contain a [`RelayUrl`]
-625 /// and direct addresses. If direct addresses are provided, they will be used to try and
-626 /// establish a direct connection without involving a relay server.
-627 ///
-628 /// If neither a [`RelayUrl`] or direct addresses are configured in the [`EndpointAddr`] it
-629 /// may still be possible a connection can be established. This depends on which, if any,
-630 /// [`crate::discovery::Discovery`] services were configured using [`Builder::discovery`]. The discovery
-631 /// service will also be used if the remote endpoint is not reachable on the provided direct
-632 /// addresses and there is no [`RelayUrl`].
-633 ///
-634 /// If addresses or relay servers are neither provided nor can be discovered, the
-635 /// connection attempt will fail with an error.
-636 ///
-637 /// The `alpn`, or application-level protocol identifier, is also required. The remote
-638 /// endpoint must support this `alpn`, otherwise the connection attempt will fail with
-639 /// an error.
-640 ///
-641 /// [`RelayUrl`]: crate::RelayUrl
-642pub async fn connect(
-643&self,
-644 endpoint_addr: impl Into<EndpointAddr>,
-645 alpn: &[u8],
-646 ) -> Result<Connection, ConnectError> {
-647let endpoint_addr = endpoint_addr.into();
-648let remote = endpoint_addr.id;
-649let connecting = self
-650.connect_with_opts(endpoint_addr, alpn, Default::default())
-651 .await?;
-652let conn = connecting.await?;
-653
-654debug!(
-655 me = %self.id().fmt_short(),
-656 remote = %remote.fmt_short(),
-657 alpn = %String::from_utf8_lossy(alpn),
-658"Connection established."
-659);
-660Ok(conn)
-661 }
-662
-663/// Starts a connection attempt with a remote [`Endpoint`].
-664 ///
-665 /// Like [`Endpoint::connect`] (see also its docs for general details), but allows for a more
-666 /// advanced connection setup with more customization in two aspects:
-667 /// 1. The returned future resolves to a [`Connecting`], which can be further processed into
-668 /// a [`Connection`] by awaiting, or alternatively allows connecting with 0-RTT via
-669 /// [`Connecting::into_0rtt`].
-670 /// **Note:** Please read the documentation for `into_0rtt` carefully to assess
-671 /// security concerns.
-672 /// 2. The [`TransportConfig`] for the connection can be modified via the provided
-673 /// [`ConnectOptions`].
-674 /// **Note:** Please be aware that changing transport config settings may have adverse effects on
-675 /// establishing and maintaining direct connections. Carefully test settings you use and
-676 /// consider this currently as still rather experimental.
-677#[instrument(name = "connect", skip_all, fields(
-678 me = %self.id().fmt_short(),
-679 remote = tracing::field::Empty,
-680 alpn = String::from_utf8_lossy(alpn).to_string(),
-681 ))]
-682pub async fn connect_with_opts(
-683&self,
-684 endpoint_addr: impl Into<EndpointAddr>,
-685 alpn: &[u8],
-686 options: ConnectOptions,
-687 ) -> Result<Connecting, ConnectWithOptsError> {
-688let endpoint_addr: EndpointAddr = endpoint_addr.into();
-689let endpoint_id = endpoint_addr.id;
-690
-691 tracing::Span::current().record("remote", tracing::field::display(endpoint_id.fmt_short()));
+619// # Methods for establishing connectivity.
+620
+621/// Connects to a remote [`Endpoint`].
+622 ///
+623 /// A value that can be converted into an [`EndpointAddr`] is required. This can be either an
+624 /// [`EndpointAddr`] or an [`EndpointId`].
+625 ///
+626 /// The [`EndpointAddr`] must contain the [`EndpointId`] to dial and may also contain a [`RelayUrl`]
+627 /// and direct addresses. If direct addresses are provided, they will be used to try and
+628 /// establish a direct connection without involving a relay server.
+629 ///
+630 /// If neither a [`RelayUrl`] or direct addresses are configured in the [`EndpointAddr`] it
+631 /// may still be possible a connection can be established. This depends on which, if any,
+632 /// [`crate::discovery::Discovery`] services were configured using [`Builder::discovery`]. The discovery
+633 /// service will also be used if the remote endpoint is not reachable on the provided direct
+634 /// addresses and there is no [`RelayUrl`].
+635 ///
+636 /// If addresses or relay servers are neither provided nor can be discovered, the
+637 /// connection attempt will fail with an error.
+638 ///
+639 /// The `alpn`, or application-level protocol identifier, is also required. The remote
+640 /// endpoint must support this `alpn`, otherwise the connection attempt will fail with
+641 /// an error.
+642 ///
+643 /// [`RelayUrl`]: crate::RelayUrl
+644pub async fn connect(
+645&self,
+646 endpoint_addr: impl Into<EndpointAddr>,
+647 alpn: &[u8],
+648 ) -> Result<Connection, ConnectError> {
+649let endpoint_addr = endpoint_addr.into();
+650let remote = endpoint_addr.id;
+651let connecting = self
+652.connect_with_opts(endpoint_addr, alpn, Default::default())
+653 .await?;
+654let conn = connecting.await?;
+655
+656debug!(
+657 me = %self.id().fmt_short(),
+658 remote = %remote.fmt_short(),
+659 alpn = %String::from_utf8_lossy(alpn),
+660"Connection established."
+661);
+662Ok(conn)
+663 }
+664
+665/// Starts a connection attempt with a remote [`Endpoint`].
+666 ///
+667 /// Like [`Endpoint::connect`] (see also its docs for general details), but allows for a more
+668 /// advanced connection setup with more customization in two aspects:
+669 /// 1. The returned future resolves to a [`Connecting`], which can be further processed into
+670 /// a [`Connection`] by awaiting, or alternatively allows connecting with 0-RTT via
+671 /// [`Connecting::into_0rtt`].
+672 /// **Note:** Please read the documentation for `into_0rtt` carefully to assess
+673 /// security concerns.
+674 /// 2. The [`TransportConfig`] for the connection can be modified via the provided
+675 /// [`ConnectOptions`].
+676 /// **Note:** Please be aware that changing transport config settings may have adverse effects on
+677 /// establishing and maintaining direct connections. Carefully test settings you use and
+678 /// consider this currently as still rather experimental.
+679#[instrument(name = "connect", skip_all, fields(
+680 me = %self.id().fmt_short(),
+681 remote = tracing::field::Empty,
+682 alpn = String::from_utf8_lossy(alpn).to_string(),
+683 ))]
+684pub async fn connect_with_opts(
+685&self,
+686 endpoint_addr: impl Into<EndpointAddr>,
+687 alpn: &[u8],
+688 options: ConnectOptions,
+689 ) -> Result<Connecting, ConnectWithOptsError> {
+690let endpoint_addr: EndpointAddr = endpoint_addr.into();
+691let endpoint_id = endpoint_addr.id;
692
-693// Connecting to ourselves is not supported.
-694ensure!(endpoint_id != self.id(), ConnectWithOptsError::SelfConnect);
-695
-696trace!(
-697 dst_endpoint_id = %endpoint_id.fmt_short(),
-698 relay_url = ?endpoint_addr.relay_urls().next().cloned(),
-699 ip_addresses = ?endpoint_addr.ip_addrs().cloned().collect::<Vec<_>>(),
-700"connecting",
-701 );
-702
-703let mapped_addr = self.msock.resolve_remote(endpoint_addr).await??;
+693 tracing::Span::current().record("remote", tracing::field::display(endpoint_id.fmt_short()));
+694
+695// Connecting to ourselves is not supported.
+696ensure!(endpoint_id != self.id(), ConnectWithOptsError::SelfConnect);
+697
+698trace!(
+699 dst_endpoint_id = %endpoint_id.fmt_short(),
+700 relay_url = ?endpoint_addr.relay_urls().next().cloned(),
+701 ip_addresses = ?endpoint_addr.ip_addrs().cloned().collect::<Vec<_>>(),
+702"connecting",
+703 );
704
-705let transport_config = options
-706 .transport_config
-707 .unwrap_or(self.static_config.transport_config.clone());
-708
-709// Start connecting via quinn. This will time out after 10 seconds if no reachable
-710 // address is available.
-711
-712let client_config = {
-713let mut alpn_protocols = vec![alpn.to_vec()];
-714 alpn_protocols.extend(options.additional_alpns);
-715let quic_client_config = self
-716.static_config
-717 .tls_config
-718 .make_client_config(alpn_protocols, self.static_config.keylog);
-719let mut client_config = quinn::ClientConfig::new(Arc::new(quic_client_config));
-720 client_config.transport_config(transport_config);
-721 client_config
-722 };
-723
-724let dest_addr = mapped_addr.private_socket_addr();
-725let server_name = &tls::name::encode(endpoint_id);
-726let connect = self
-727.msock
-728 .endpoint()
-729 .connect_with(client_config, dest_addr, server_name)?;
-730
-731Ok(Connecting::new(connect, self.clone(), endpoint_id))
-732 }
-733
-734/// Accepts an incoming connection on the endpoint.
-735 ///
-736 /// Only connections with the ALPNs configured in [`Builder::alpns`] will be accepted.
-737 /// If multiple ALPNs have been configured the ALPN can be inspected before accepting
-738 /// the connection using [`Connecting::alpn`].
-739 ///
-740 /// The returned future will yield `None` if the endpoint is closed by calling
-741 /// [`Endpoint::close`].
-742pub fn accept(&self) -> Accept<'_> {
-743 Accept {
-744 inner: self.msock.endpoint().accept(),
-745 ep: self.clone(),
-746 }
-747 }
-748
-749// # Getter methods for properties of this Endpoint itself.
+705let mapped_addr = self.msock.resolve_remote(endpoint_addr).await??;
+706
+707let transport_config = options
+708 .transport_config
+709 .unwrap_or(self.static_config.transport_config.clone());
+710
+711// Start connecting via quinn. This will time out after 10 seconds if no reachable
+712 // address is available.
+713
+714let client_config = {
+715let mut alpn_protocols = vec![alpn.to_vec()];
+716 alpn_protocols.extend(options.additional_alpns);
+717let quic_client_config = self
+718.static_config
+719 .tls_config
+720 .make_client_config(alpn_protocols, self.static_config.keylog);
+721let mut client_config = quinn::ClientConfig::new(Arc::new(quic_client_config));
+722 client_config.transport_config(transport_config);
+723 client_config
+724 };
+725
+726let dest_addr = mapped_addr.private_socket_addr();
+727let server_name = &tls::name::encode(endpoint_id);
+728let connect = self
+729.msock
+730 .endpoint()
+731 .connect_with(client_config, dest_addr, server_name)?;
+732
+733Ok(Connecting::new(connect, self.clone(), endpoint_id))
+734 }
+735
+736/// Accepts an incoming connection on the endpoint.
+737 ///
+738 /// Only connections with the ALPNs configured in [`Builder::alpns`] will be accepted.
+739 /// If multiple ALPNs have been configured the ALPN can be inspected before accepting
+740 /// the connection using [`Connecting::alpn`].
+741 ///
+742 /// The returned future will yield `None` if the endpoint is closed by calling
+743 /// [`Endpoint::close`].
+744pub fn accept(&self) -> Accept<'_> {
+745 Accept {
+746 inner: self.msock.endpoint().accept(),
+747 ep: self.clone(),
+748 }
+749 }
750
-751/// Returns the secret_key of this endpoint.
-752pub fn secret_key(&self) -> &SecretKey {
-753&self.static_config.tls_config.secret_key
-754 }
-755
-756/// Returns the endpoint id of this endpoint.
-757 ///
-758 /// This ID is the unique addressing information of this endpoint and other peers must know
-759 /// it to be able to connect to this endpoint.
-760pub fn id(&self) -> EndpointId {
-761self.static_config.tls_config.secret_key.public()
-762 }
-763
-764/// Returns the current [`EndpointAddr`].
-765 /// As long as the endpoint was able to bind to a network interface, some
-766 /// local addresses will be available.
-767 ///
-768 /// The state of other fields depends on the state of networking and connectivity.
-769 /// Use the [`Endpoint::online`] method to ensure that the endpoint is considered
-770 /// "online" (has contacted a relay server) before calling this method, if you want
-771 /// to ensure that the `EndpointAddr` will contain enough information to allow this endpoint
-772 /// to be dialable by a remote endpoint over the internet.
-773 ///
-774 /// You can use the [`Endpoint::watch_addr`] method to get updates when the `EndpointAddr`
-775 /// changes.
-776pub fn addr(&self) -> EndpointAddr {
-777self.watch_addr().get()
-778 }
-779
-780/// Returns a [`Watcher`] for the current [`EndpointAddr`] for this endpoint.
-781 ///
-782 /// The observed [`EndpointAddr`] will have the current [`RelayUrl`] and direct addresses.
+751// # Getter methods for properties of this Endpoint itself.
+752
+753/// Returns the secret_key of this endpoint.
+754pub fn secret_key(&self) -> &SecretKey {
+755&self.static_config.tls_config.secret_key
+756 }
+757
+758/// Returns the endpoint id of this endpoint.
+759 ///
+760 /// This ID is the unique addressing information of this endpoint and other peers must know
+761 /// it to be able to connect to this endpoint.
+762pub fn id(&self) -> EndpointId {
+763self.static_config.tls_config.secret_key.public()
+764 }
+765
+766/// Returns the current [`EndpointAddr`].
+767 /// As long as the endpoint was able to bind to a network interface, some
+768 /// local addresses will be available.
+769 ///
+770 /// The state of other fields depends on the state of networking and connectivity.
+771 /// Use the [`Endpoint::online`] method to ensure that the endpoint is considered
+772 /// "online" (has contacted a relay server) before calling this method, if you want
+773 /// to ensure that the `EndpointAddr` will contain enough information to allow this endpoint
+774 /// to be dialable by a remote endpoint over the internet.
+775 ///
+776 /// You can use the [`Endpoint::watch_addr`] method to get updates when the `EndpointAddr`
+777 /// changes.
+778pub fn addr(&self) -> EndpointAddr {
+779self.watch_addr().get()
+780 }
+781
+782/// Returns a [`Watcher`] for the current [`EndpointAddr`] for this endpoint.
783 ///
-784 /// ```no_run
-785 /// # async fn wrapper() -> n0_error::Result<()> {
-786 /// use iroh::{Endpoint, Watcher};
-787 ///
-788 /// let endpoint = Endpoint::builder()
-789 /// .alpns(vec![b"my-alpn".to_vec()])
-790 /// .bind()
-791 /// .await?;
-792 /// let endpoint_addr = endpoint.watch_addr().get();
-793 /// # let _ = endpoint_addr;
-794 /// # Ok(())
-795 /// # }
-796 /// ```
-797 ///
-798 /// The [`Endpoint::online`] method can be used as a convenience method to
-799 /// understand if the endpoint has ever been considered "online". But after
-800 /// that initial call to [`Endpoint::online`], to understand if your
-801 /// endpoint is no longer able to be connected to by endpoints outside
-802 /// of the private or local network, watch for changes in it's [`EndpointAddr`].
-803 /// If there are no `addrs`in the [`EndpointAddr`], you may not be dialable by other endpoints
-804 /// on the internet.
-805 ///
-806 ///
-807 /// The `EndpointAddr` will change as:
-808 /// - network conditions change
-809 /// - the endpoint connects to a relay server
-810 /// - the endpoint changes its preferred relay server
-811 /// - more addresses are discovered for this endpoint
-812 ///
-813 /// [`RelayUrl`]: crate::RelayUrl
-814#[cfg(not(wasm_browser))]
-815pub fn watch_addr(&self) -> impl n0_watcher::Watcher<Value = EndpointAddr> + use<> {
-816let watch_addrs = self.msock.ip_addrs();
-817let watch_relay = self.msock.home_relay();
-818let endpoint_id = self.id();
-819
-820 watch_addrs.or(watch_relay).map(move |(addrs, relays)| {
-821 EndpointAddr::from_parts(
-822 endpoint_id,
-823 relays
-824 .into_iter()
-825 .map(TransportAddr::Relay)
-826 .chain(addrs.into_iter().map(|x| TransportAddr::Ip(x.addr))),
-827 )
-828 })
-829 }
-830
-831/// Returns a [`Watcher`] for the current [`EndpointAddr`] for this endpoint.
-832 ///
-833 /// When compiled to Wasm, this function returns a watcher that initializes
-834 /// with an [`EndpointAddr`] that only contains a relay URL, but no direct addresses,
-835 /// as there are no APIs for directly using sockets in browsers.
-836#[cfg(wasm_browser)]
-837pub fn watch_addr(&self) -> impl n0_watcher::Watcher<Value = EndpointAddr> + use<> {
-838// In browsers, there will never be any direct addresses, so we wait
-839 // for the home relay instead. This makes the `EndpointAddr` have *some* way
-840 // of connecting to us.
-841let watch_relay = self.msock.home_relay();
-842let endpoint_id = self.id();
-843 watch_relay.map(move |mut relays| {
-844 EndpointAddr::from_parts(endpoint_id, relays.into_iter().map(TransportAddr::Relay))
-845 })
-846 }
-847
-848/// A convenience method that waits for the endpoint to be considered "online".
-849 ///
-850 /// This currently means at least one relay server was connected,
-851 /// and at least one local IP address is available.
-852 /// Event if no relays are configured, this will still wait for a relay connection.
-853 ///
-854 /// Once this has been resolved once, this will always immediately resolve.
+784 /// The observed [`EndpointAddr`] will have the current [`RelayUrl`] and direct addresses.
+785 ///
+786 /// ```no_run
+787 /// # async fn wrapper() -> n0_error::Result<()> {
+788 /// use iroh::{Endpoint, Watcher};
+789 ///
+790 /// let endpoint = Endpoint::builder()
+791 /// .alpns(vec![b"my-alpn".to_vec()])
+792 /// .bind()
+793 /// .await?;
+794 /// let endpoint_addr = endpoint.watch_addr().get();
+795 /// # let _ = endpoint_addr;
+796 /// # Ok(())
+797 /// # }
+798 /// ```
+799 ///
+800 /// The [`Endpoint::online`] method can be used as a convenience method to
+801 /// understand if the endpoint has ever been considered "online". But after
+802 /// that initial call to [`Endpoint::online`], to understand if your
+803 /// endpoint is no longer able to be connected to by endpoints outside
+804 /// of the private or local network, watch for changes in it's [`EndpointAddr`].
+805 /// If there are no `addrs`in the [`EndpointAddr`], you may not be dialable by other endpoints
+806 /// on the internet.
+807 ///
+808 ///
+809 /// The `EndpointAddr` will change as:
+810 /// - network conditions change
+811 /// - the endpoint connects to a relay server
+812 /// - the endpoint changes its preferred relay server
+813 /// - more addresses are discovered for this endpoint
+814 ///
+815 /// [`RelayUrl`]: crate::RelayUrl
+816#[cfg(not(wasm_browser))]
+817pub fn watch_addr(&self) -> impl n0_watcher::Watcher<Value = EndpointAddr> + use<> {
+818let watch_addrs = self.msock.ip_addrs();
+819let watch_relay = self.msock.home_relay();
+820let endpoint_id = self.id();
+821
+822 watch_addrs.or(watch_relay).map(move |(addrs, relays)| {
+823 EndpointAddr::from_parts(
+824 endpoint_id,
+825 relays
+826 .into_iter()
+827 .map(TransportAddr::Relay)
+828 .chain(addrs.into_iter().map(|x| TransportAddr::Ip(x.addr))),
+829 )
+830 })
+831 }
+832
+833/// Returns a [`Watcher`] for the current [`EndpointAddr`] for this endpoint.
+834 ///
+835 /// When compiled to Wasm, this function returns a watcher that initializes
+836 /// with an [`EndpointAddr`] that only contains a relay URL, but no direct addresses,
+837 /// as there are no APIs for directly using sockets in browsers.
+838#[cfg(wasm_browser)]
+839pub fn watch_addr(&self) -> impl n0_watcher::Watcher<Value = EndpointAddr> + use<> {
+840// In browsers, there will never be any direct addresses, so we wait
+841 // for the home relay instead. This makes the `EndpointAddr` have *some* way
+842 // of connecting to us.
+843let watch_relay = self.msock.home_relay();
+844let endpoint_id = self.id();
+845 watch_relay.map(move |mut relays| {
+846 EndpointAddr::from_parts(endpoint_id, relays.into_iter().map(TransportAddr::Relay))
+847 })
+848 }
+849
+850/// A convenience method that waits for the endpoint to be considered "online".
+851 ///
+852 /// This currently means at least one relay server was connected,
+853 /// and at least one local IP address is available.
+854 /// Event if no relays are configured, this will still wait for a relay connection.
855 ///
-856 /// This has no timeout, so if that is needed, you need to wrap it in a
-857 /// timeout. We recommend using a timeout close to
-858 /// [`crate::net_report::TIMEOUT`], so you can be sure that at least one
-859 /// [`crate::net_report::Report`] has been attempted.
-860 ///
-861 /// To understand if the endpoint has gone back "offline",
-862 /// you must use the [`Endpoint::watch_addr`] method, to
-863 /// get information on the current relay and direct address information.
-864pub async fn online(&self) {
-865self.msock.home_relay().initialized().await;
-866 }
-867
-868/// Returns a [`Watcher`] for any net-reports run from this [`Endpoint`].
-869 ///
-870 /// A `net-report` checks the network conditions of the [`Endpoint`], such as
-871 /// whether it is connected to the internet via Ipv4 and/or Ipv6, its NAT
-872 /// status, its latency to the relay servers, and its public addresses.
-873 ///
-874 /// The [`Endpoint`] continuously runs `net-reports` to monitor if network
-875 /// conditions have changed. This [`Watcher`] will return the latest result
-876 /// of the `net-report`.
-877 ///
-878 /// When issuing the first call to this method the first report might
-879 /// still be underway, in this case the [`Watcher`] might not be initialized
-880 /// with [`Some`] value yet. Once the net-report has been successfully
-881 /// run, the [`Watcher`] will always return [`Some`] report immediately, which
-882 /// is the most recently run `net-report`.
-883 ///
-884 /// # Examples
+856 /// Once this has been resolved once, this will always immediately resolve.
+857 ///
+858 /// This has no timeout, so if that is needed, you need to wrap it in a
+859 /// timeout. We recommend using a timeout close to
+860 /// [`crate::net_report::TIMEOUT`], so you can be sure that at least one
+861 /// [`crate::net_report::Report`] has been attempted.
+862 ///
+863 /// To understand if the endpoint has gone back "offline",
+864 /// you must use the [`Endpoint::watch_addr`] method, to
+865 /// get information on the current relay and direct address information.
+866pub async fn online(&self) {
+867self.msock.home_relay().initialized().await;
+868 }
+869
+870/// Returns a [`Watcher`] for any net-reports run from this [`Endpoint`].
+871 ///
+872 /// A `net-report` checks the network conditions of the [`Endpoint`], such as
+873 /// whether it is connected to the internet via Ipv4 and/or Ipv6, its NAT
+874 /// status, its latency to the relay servers, and its public addresses.
+875 ///
+876 /// The [`Endpoint`] continuously runs `net-reports` to monitor if network
+877 /// conditions have changed. This [`Watcher`] will return the latest result
+878 /// of the `net-report`.
+879 ///
+880 /// When issuing the first call to this method the first report might
+881 /// still be underway, in this case the [`Watcher`] might not be initialized
+882 /// with [`Some`] value yet. Once the net-report has been successfully
+883 /// run, the [`Watcher`] will always return [`Some`] report immediately, which
+884 /// is the most recently run `net-report`.
885 ///
-886 /// To get the first report use [`Watcher::initialized`]:
-887 /// ```no_run
-888 /// use iroh::{Endpoint, Watcher as _};
-889 ///
-890 /// # let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
-891 /// # rt.block_on(async move {
-892 /// let ep = Endpoint::bind().await.unwrap();
-893 /// let _report = ep.net_report().initialized().await;
-894 /// # });
-895 /// ```
-896#[doc(hidden)]
-897pub fn net_report(&self) -> impl Watcher<Value = Option<Report>> + use<> {
-898self.msock.net_report()
-899 }
-900
-901/// Returns the local socket addresses on which the underlying sockets are bound.
-902 ///
-903 /// The [`Endpoint`] always binds on an IPv4 address and also tries to bind on an IPv6
-904 /// address if available.
-905pub fn bound_sockets(&self) -> Vec<SocketAddr> {
-906self.msock
-907 .local_addr()
-908 .into_iter()
-909 .filter_map(|addr| addr.into_socket_addr())
-910 .collect()
-911 }
-912
-913// # Methods for less common getters.
-914 //
-915 // Partially they return things passed into the builder.
-916
-917/// Returns the currently lowest latency for this endpoint.
-918 ///
-919 /// Will return `None` if we do not have any address information for the given `endpoint_id`.
-920pub async fn latency(&self, endpoint_id: EndpointId) -> Option<Duration> {
-921self.msock.latency(endpoint_id).await
-922}
-923
-924/// Returns the DNS resolver used in this [`Endpoint`].
-925 ///
-926 /// See [`Builder::dns_resolver`].
-927#[cfg(not(wasm_browser))]
-928pub fn dns_resolver(&self) -> &DnsResolver {
-929self.msock.dns_resolver()
-930 }
-931
-932/// Returns the discovery mechanism, if configured.
-933 ///
-934 /// See [`Builder::discovery`].
-935pub fn discovery(&self) -> &ConcurrentDiscovery {
-936self.msock.discovery()
-937 }
-938
-939/// Returns metrics collected for this endpoint.
-940 ///
-941 /// The endpoint internally collects various metrics about its operation.
-942 /// The returned [`EndpointMetrics`] struct contains all of these metrics.
-943 ///
-944 /// You can access individual metrics directly by using the public fields:
-945 /// ```rust
-946 /// # use std::collections::BTreeMap;
-947 /// # use iroh::endpoint::Endpoint;
-948 /// # async fn wrapper() -> n0_error::Result<()> {
-949 /// let endpoint = Endpoint::bind().await?;
-950 /// assert_eq!(endpoint.metrics().magicsock.recv_datagrams.get(), 0);
-951 /// # Ok(())
-952 /// # }
-953 /// ```
-954 ///
-955 /// [`EndpointMetrics`] implements [`MetricsGroupSet`], and each field
-956 /// implements [`MetricsGroup`]. These traits provide methods to iterate over
-957 /// the groups in the set, and over the individual metrics in each group, without having
-958 /// to access each field manually. With these methods, it is straightforward to collect
-959 /// all metrics into a map or push their values to a metrics collector.
-960 ///
-961 /// For example, the following snippet collects all metrics into a map:
-962 /// ```rust
-963 /// # use std::collections::BTreeMap;
-964 /// # use iroh_metrics::{Metric, MetricsGroup, MetricValue, MetricsGroupSet};
-965 /// # use iroh::endpoint::Endpoint;
-966 /// # async fn wrapper() -> n0_error::Result<()> {
-967 /// let endpoint = Endpoint::bind().await?;
-968 /// let metrics: BTreeMap<String, MetricValue> = endpoint
-969 /// .metrics()
-970 /// .iter()
-971 /// .map(|(group, metric)| {
-972 /// let name = [group, metric.name()].join(":");
-973 /// (name, metric.value())
-974 /// })
-975 /// .collect();
-976 ///
-977 /// assert_eq!(metrics["magicsock:recv_datagrams"], MetricValue::Counter(0));
-978 /// # Ok(())
-979 /// # }
-980 /// ```
-981 ///
-982 /// The metrics can also be encoded into the OpenMetrics text format, as used by Prometheus.
-983 /// To do so, use the [`iroh_metrics::Registry`], add the endpoint metrics to the
-984 /// registry with [`Registry::register_all`], and encode the metrics to a string with
-985 /// [`encode_openmetrics_to_string`]:
-986 /// ```rust
-987 /// # use iroh_metrics::{Registry, MetricsSource};
-988 /// # use iroh::endpoint::Endpoint;
-989 /// # async fn wrapper() -> n0_error::Result<()> {
-990 /// let endpoint = Endpoint::bind().await?;
-991 /// let mut registry = Registry::default();
-992 /// registry.register_all(endpoint.metrics());
-993 /// let s = registry.encode_openmetrics_to_string()?;
-994 /// assert!(s.contains(r#"TYPE magicsock_recv_datagrams counter"#));
-995 /// assert!(s.contains(r#"magicsock_recv_datagrams_total 0"#));
-996 /// # Ok(())
-997 /// # }
-998 /// ```
-999 ///
-1000 /// Through a registry, you can also add labels or prefixes to metrics with
-1001 /// [`Registry::sub_registry_with_label`] or [`Registry::sub_registry_with_prefix`].
-1002 /// Furthermore, [`iroh_metrics::service`] provides functions to easily start services
-1003 /// to serve the metrics with a HTTP server, dump them to a file, or push them
-1004 /// to a Prometheus gateway.
-1005 ///
-1006 /// For example, the following snippet launches an HTTP server that serves the metrics in the
-1007 /// OpenMetrics text format:
-1008 /// ```no_run
-1009 /// # use std::{sync::{Arc, RwLock}, time::Duration};
-1010 /// # use iroh_metrics::{Registry, MetricsSource};
-1011 /// # use iroh::endpoint::Endpoint;
-1012 /// # use n0_error::{StackResultExt, StdResultExt};
-1013 /// # async fn wrapper() -> n0_error::Result<()> {
-1014 /// // Create a registry, wrapped in a read-write lock so that we can register and serve
-1015 /// // the metrics independently.
-1016 /// let registry = Arc::new(RwLock::new(Registry::default()));
-1017 /// // Spawn a task to serve the metrics on an OpenMetrics HTTP endpoint.
-1018 /// let metrics_task = tokio::task::spawn({
-1019 /// let registry = registry.clone();
-1020 /// async move {
-1021 /// let addr = "0.0.0.0:9100".parse().unwrap();
-1022 /// iroh_metrics::service::start_metrics_server(addr, registry).await
-1023 /// }
-1024 /// });
-1025 ///
-1026 /// // Spawn an endpoint and add the metrics to the registry.
-1027 /// let endpoint = Endpoint::bind().await?;
-1028 /// registry.write().unwrap().register_all(endpoint.metrics());
-1029 ///
-1030 /// // Wait for the metrics server to bind, then fetch the metrics via HTTP.
-1031 /// tokio::time::sleep(Duration::from_millis(500));
-1032 /// let res = reqwest::get("http://localhost:9100/metrics")
-1033 /// .await
-1034 /// .std_context("get")?
-1035 /// .text()
-1036 /// .await
-1037 /// .std_context("text")?;
-1038 ///
-1039 /// assert!(res.contains(r#"TYPE magicsock_recv_datagrams counter"#));
-1040 /// assert!(res.contains(r#"magicsock_recv_datagrams_total 0"#));
-1041 /// # metrics_task.abort();
-1042 /// # Ok(())
-1043 /// # }
-1044 /// ```
-1045 ///
-1046 /// [`Registry`]: iroh_metrics::Registry
-1047 /// [`Registry::register_all`]: iroh_metrics::Registry::register_all
-1048 /// [`Registry::sub_registry_with_label`]: iroh_metrics::Registry::sub_registry_with_label
-1049 /// [`Registry::sub_registry_with_prefix`]: iroh_metrics::Registry::sub_registry_with_prefix
-1050 /// [`encode_openmetrics_to_string`]: iroh_metrics::MetricsSource::encode_openmetrics_to_string
-1051 /// [`MetricsGroup`]: iroh_metrics::MetricsGroup
-1052 /// [`MetricsGroupSet`]: iroh_metrics::MetricsGroupSet
-1053#[cfg(feature = "metrics")]
-1054pub fn metrics(&self) -> &EndpointMetrics {
-1055&self.msock.metrics
-1056 }
-1057
-1058// # Methods for less common state updates.
+886 /// # Examples
+887 ///
+888 /// To get the first report use [`Watcher::initialized`]:
+889 /// ```no_run
+890 /// use iroh::{Endpoint, Watcher as _};
+891 ///
+892 /// # let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
+893 /// # rt.block_on(async move {
+894 /// let ep = Endpoint::bind().await.unwrap();
+895 /// let _report = ep.net_report().initialized().await;
+896 /// # });
+897 /// ```
+898#[doc(hidden)]
+899pub fn net_report(&self) -> impl Watcher<Value = Option<Report>> + use<> {
+900self.msock.net_report()
+901 }
+902
+903/// Returns the local socket addresses on which the underlying sockets are bound.
+904 ///
+905 /// The [`Endpoint`] always binds on an IPv4 address and also tries to bind on an IPv6
+906 /// address if available.
+907pub fn bound_sockets(&self) -> Vec<SocketAddr> {
+908self.msock
+909 .local_addr()
+910 .into_iter()
+911 .filter_map(|addr| addr.into_socket_addr())
+912 .collect()
+913 }
+914
+915// # Methods for less common getters.
+916 //
+917 // Partially they return things passed into the builder.
+918
+919/// Returns the currently lowest latency for this endpoint.
+920 ///
+921 /// Will return `None` if we do not have any address information for the given `endpoint_id`.
+922pub async fn latency(&self, endpoint_id: EndpointId) -> Option<Duration> {
+923self.msock.latency(endpoint_id).await
+924}
+925
+926/// Returns the DNS resolver used in this [`Endpoint`].
+927 ///
+928 /// See [`Builder::dns_resolver`].
+929#[cfg(not(wasm_browser))]
+930pub fn dns_resolver(&self) -> &DnsResolver {
+931self.msock.dns_resolver()
+932 }
+933
+934/// Returns the discovery mechanism, if configured.
+935 ///
+936 /// See [`Builder::discovery`].
+937pub fn discovery(&self) -> &ConcurrentDiscovery {
+938self.msock.discovery()
+939 }
+940
+941/// Returns metrics collected for this endpoint.
+942 ///
+943 /// The endpoint internally collects various metrics about its operation.
+944 /// The returned [`EndpointMetrics`] struct contains all of these metrics.
+945 ///
+946 /// You can access individual metrics directly by using the public fields:
+947 /// ```rust
+948 /// # use std::collections::BTreeMap;
+949 /// # use iroh::endpoint::Endpoint;
+950 /// # async fn wrapper() -> n0_error::Result<()> {
+951 /// let endpoint = Endpoint::bind().await?;
+952 /// assert_eq!(endpoint.metrics().magicsock.recv_datagrams.get(), 0);
+953 /// # Ok(())
+954 /// # }
+955 /// ```
+956 ///
+957 /// [`EndpointMetrics`] implements [`MetricsGroupSet`], and each field
+958 /// implements [`MetricsGroup`]. These traits provide methods to iterate over
+959 /// the groups in the set, and over the individual metrics in each group, without having
+960 /// to access each field manually. With these methods, it is straightforward to collect
+961 /// all metrics into a map or push their values to a metrics collector.
+962 ///
+963 /// For example, the following snippet collects all metrics into a map:
+964 /// ```rust
+965 /// # use std::collections::BTreeMap;
+966 /// # use iroh_metrics::{Metric, MetricsGroup, MetricValue, MetricsGroupSet};
+967 /// # use iroh::endpoint::Endpoint;
+968 /// # async fn wrapper() -> n0_error::Result<()> {
+969 /// let endpoint = Endpoint::bind().await?;
+970 /// let metrics: BTreeMap<String, MetricValue> = endpoint
+971 /// .metrics()
+972 /// .iter()
+973 /// .map(|(group, metric)| {
+974 /// let name = [group, metric.name()].join(":");
+975 /// (name, metric.value())
+976 /// })
+977 /// .collect();
+978 ///
+979 /// assert_eq!(metrics["magicsock:recv_datagrams"], MetricValue::Counter(0));
+980 /// # Ok(())
+981 /// # }
+982 /// ```
+983 ///
+984 /// The metrics can also be encoded into the OpenMetrics text format, as used by Prometheus.
+985 /// To do so, use the [`iroh_metrics::Registry`], add the endpoint metrics to the
+986 /// registry with [`Registry::register_all`], and encode the metrics to a string with
+987 /// [`encode_openmetrics_to_string`]:
+988 /// ```rust
+989 /// # use iroh_metrics::{Registry, MetricsSource};
+990 /// # use iroh::endpoint::Endpoint;
+991 /// # async fn wrapper() -> n0_error::Result<()> {
+992 /// let endpoint = Endpoint::bind().await?;
+993 /// let mut registry = Registry::default();
+994 /// registry.register_all(endpoint.metrics());
+995 /// let s = registry.encode_openmetrics_to_string()?;
+996 /// assert!(s.contains(r#"TYPE magicsock_recv_datagrams counter"#));
+997 /// assert!(s.contains(r#"magicsock_recv_datagrams_total 0"#));
+998 /// # Ok(())
+999 /// # }
+1000 /// ```
+1001 ///
+1002 /// Through a registry, you can also add labels or prefixes to metrics with
+1003 /// [`Registry::sub_registry_with_label`] or [`Registry::sub_registry_with_prefix`].
+1004 /// Furthermore, [`iroh_metrics::service`] provides functions to easily start services
+1005 /// to serve the metrics with a HTTP server, dump them to a file, or push them
+1006 /// to a Prometheus gateway.
+1007 ///
+1008 /// For example, the following snippet launches an HTTP server that serves the metrics in the
+1009 /// OpenMetrics text format:
+1010 /// ```no_run
+1011 /// # use std::{sync::{Arc, RwLock}, time::Duration};
+1012 /// # use iroh_metrics::{Registry, MetricsSource};
+1013 /// # use iroh::endpoint::Endpoint;
+1014 /// # use n0_error::{StackResultExt, StdResultExt};
+1015 /// # async fn wrapper() -> n0_error::Result<()> {
+1016 /// // Create a registry, wrapped in a read-write lock so that we can register and serve
+1017 /// // the metrics independently.
+1018 /// let registry = Arc::new(RwLock::new(Registry::default()));
+1019 /// // Spawn a task to serve the metrics on an OpenMetrics HTTP endpoint.
+1020 /// let metrics_task = tokio::task::spawn({
+1021 /// let registry = registry.clone();
+1022 /// async move {
+1023 /// let addr = "0.0.0.0:9100".parse().unwrap();
+1024 /// iroh_metrics::service::start_metrics_server(addr, registry).await
+1025 /// }
+1026 /// });
+1027 ///
+1028 /// // Spawn an endpoint and add the metrics to the registry.
+1029 /// let endpoint = Endpoint::bind().await?;
+1030 /// registry.write().unwrap().register_all(endpoint.metrics());
+1031 ///
+1032 /// // Wait for the metrics server to bind, then fetch the metrics via HTTP.
+1033 /// tokio::time::sleep(Duration::from_millis(500));
+1034 /// let res = reqwest::get("http://localhost:9100/metrics")
+1035 /// .await
+1036 /// .std_context("get")?
+1037 /// .text()
+1038 /// .await
+1039 /// .std_context("text")?;
+1040 ///
+1041 /// assert!(res.contains(r#"TYPE magicsock_recv_datagrams counter"#));
+1042 /// assert!(res.contains(r#"magicsock_recv_datagrams_total 0"#));
+1043 /// # metrics_task.abort();
+1044 /// # Ok(())
+1045 /// # }
+1046 /// ```
+1047 ///
+1048 /// [`Registry`]: iroh_metrics::Registry
+1049 /// [`Registry::register_all`]: iroh_metrics::Registry::register_all
+1050 /// [`Registry::sub_registry_with_label`]: iroh_metrics::Registry::sub_registry_with_label
+1051 /// [`Registry::sub_registry_with_prefix`]: iroh_metrics::Registry::sub_registry_with_prefix
+1052 /// [`encode_openmetrics_to_string`]: iroh_metrics::MetricsSource::encode_openmetrics_to_string
+1053 /// [`MetricsGroup`]: iroh_metrics::MetricsGroup
+1054 /// [`MetricsGroupSet`]: iroh_metrics::MetricsGroupSet
+1055#[cfg(feature = "metrics")]
+1056pub fn metrics(&self) -> &EndpointMetrics {
+1057&self.msock.metrics
+1058 }
1059
-1060/// Notifies the system of potential network changes.
-1061 ///
-1062 /// On many systems iroh is able to detect network changes by itself, however
-1063 /// some systems like android do not expose this functionality to native code.
-1064 /// Android does however provide this functionality to Java code. This
-1065 /// function allows for notifying iroh of any potential network changes like
-1066 /// this.
-1067 ///
-1068 /// Even when the network did not change, or iroh was already able to detect
-1069 /// the network change itself, there is no harm in calling this function.
-1070pub async fn network_change(&self) {
-1071self.msock.network_change().await;
-1072 }
-1073
-1074// # Methods to update internal state.
+1060// # Methods for less common state updates.
+1061
+1062/// Notifies the system of potential network changes.
+1063 ///
+1064 /// On many systems iroh is able to detect network changes by itself, however
+1065 /// some systems like android do not expose this functionality to native code.
+1066 /// Android does however provide this functionality to Java code. This
+1067 /// function allows for notifying iroh of any potential network changes like
+1068 /// this.
+1069 ///
+1070 /// Even when the network did not change, or iroh was already able to detect
+1071 /// the network change itself, there is no harm in calling this function.
+1072pub async fn network_change(&self) {
+1073self.msock.network_change().await;
+1074 }
1075
-1076/// Sets the initial user-defined data to be published in discovery services for this endpoint.
-1077 ///
-1078 /// If the user-defined data passed to this function is different to the previous one,
-1079 /// the endpoint will republish its endpoint info to the configured discovery services.
-1080 ///
-1081 /// See also [`Builder::user_data_for_discovery`] for setting an initial value when
-1082 /// building the endpoint.
-1083pub fn set_user_data_for_discovery(&self, user_data: Option<UserData>) {
-1084self.msock.set_user_data_for_discovery(user_data);
-1085 }
-1086
-1087// # Methods for terminating the endpoint.
+1076// # Methods to update internal state.
+1077
+1078/// Sets the initial user-defined data to be published in discovery services for this endpoint.
+1079 ///
+1080 /// If the user-defined data passed to this function is different to the previous one,
+1081 /// the endpoint will republish its endpoint info to the configured discovery services.
+1082 ///
+1083 /// See also [`Builder::user_data_for_discovery`] for setting an initial value when
+1084 /// building the endpoint.
+1085pub fn set_user_data_for_discovery(&self, user_data: Option<UserData>) {
+1086self.msock.set_user_data_for_discovery(user_data);
+1087 }
1088
-1089/// Closes the QUIC endpoint and the magic socket.
-1090 ///
-1091 /// This will close any remaining open [`Connection`]s with an error code
-1092 /// of `0` and an empty reason. Though it is best practice to close those
-1093 /// explicitly before with a custom error code and reason.
-1094 ///
-1095 /// It will then make a best effort to wait for all close notifications to be
-1096 /// acknowledged by the peers, re-transmitting them if needed. This ensures the
-1097 /// peers are aware of the closed connections instead of having to wait for a timeout
-1098 /// on the connection. Once all connections are closed or timed out, the future
-1099 /// finishes.
-1100 ///
-1101 /// The maximum time-out that this future will wait for depends on QUIC transport
-1102 /// configurations of non-drained connections at the time of calling, and their current
-1103 /// estimates of round trip time. With default parameters and a conservative estimate
-1104 /// of round trip time, this call's future should take 3 seconds to resolve in cases of
-1105 /// bad connectivity or failed connections. In the usual case, this call's future should
-1106 /// return much more quickly.
-1107 ///
-1108 /// It is highly recommended you *do* wait for this close call to finish, if possible.
-1109 /// Not doing so will make connections that were still open while closing the endpoint
-1110 /// time out on the remote end. Thus remote ends will assume connections to have failed
-1111 /// even if all application data was transmitted successfully.
-1112 ///
-1113 /// Note: Someone used to closing TCP sockets might wonder why it is necessary to wait
-1114 /// for timeouts when closing QUIC endpoints, while they don't have to do this for TCP
-1115 /// sockets. This is due to QUIC and its acknowledgments being implemented in user-land,
-1116 /// while TCP sockets usually get closed and drained by the operating system in the
-1117 /// kernel during the "Time-Wait" period of the TCP socket.
-1118 ///
-1119 /// Be aware however that the underlying UDP sockets are only closed once all clones of
-1120 /// the the respective [`Endpoint`] are dropped.
-1121pub async fn close(&self) {
-1122if self.is_closed() {
-1123return;
-1124 }
-1125
-1126tracing::debug!("Connections closed");
-1127self.msock.close().await;
-1128 }
-1129
-1130/// Check if this endpoint is still alive, or already closed.
-1131pub fn is_closed(&self) -> bool {
-1132self.msock.is_closed()
-1133 }
-1134
-1135// # Remaining private methods
+1089// # Methods for terminating the endpoint.
+1090
+1091/// Closes the QUIC endpoint and the magic socket.
+1092 ///
+1093 /// This will close any remaining open [`Connection`]s with an error code
+1094 /// of `0` and an empty reason. Though it is best practice to close those
+1095 /// explicitly before with a custom error code and reason.
+1096 ///
+1097 /// It will then make a best effort to wait for all close notifications to be
+1098 /// acknowledged by the peers, re-transmitting them if needed. This ensures the
+1099 /// peers are aware of the closed connections instead of having to wait for a timeout
+1100 /// on the connection. Once all connections are closed or timed out, the future
+1101 /// finishes.
+1102 ///
+1103 /// The maximum time-out that this future will wait for depends on QUIC transport
+1104 /// configurations of non-drained connections at the time of calling, and their current
+1105 /// estimates of round trip time. With default parameters and a conservative estimate
+1106 /// of round trip time, this call's future should take 3 seconds to resolve in cases of
+1107 /// bad connectivity or failed connections. In the usual case, this call's future should
+1108 /// return much more quickly.
+1109 ///
+1110 /// It is highly recommended you *do* wait for this close call to finish, if possible.
+1111 /// Not doing so will make connections that were still open while closing the endpoint
+1112 /// time out on the remote end. Thus remote ends will assume connections to have failed
+1113 /// even if all application data was transmitted successfully.
+1114 ///
+1115 /// Note: Someone used to closing TCP sockets might wonder why it is necessary to wait
+1116 /// for timeouts when closing QUIC endpoints, while they don't have to do this for TCP
+1117 /// sockets. This is due to QUIC and its acknowledgments being implemented in user-land,
+1118 /// while TCP sockets usually get closed and drained by the operating system in the
+1119 /// kernel during the "Time-Wait" period of the TCP socket.
+1120 ///
+1121 /// Be aware however that the underlying UDP sockets are only closed once all clones of
+1122 /// the the respective [`Endpoint`] are dropped.
+1123pub async fn close(&self) {
+1124if self.is_closed() {
+1125return;
+1126 }
+1127
+1128tracing::debug!("Connections closed");
+1129self.msock.close().await;
+1130 }
+1131
+1132/// Check if this endpoint is still alive, or already closed.
+1133pub fn is_closed(&self) -> bool {
+1134self.msock.is_closed()
+1135 }
1136
-1137#[cfg(test)]
-1138pub(crate) fn magic_sock(&self) -> Handle {
-1139self.msock.clone()
-1140 }
-1141#[cfg(test)]
-1142pub(crate) fn endpoint(&self) -> &quinn::Endpoint {
-1143self.msock.endpoint()
-1144 }
-1145}
-1146
-1147/// Options for the [`Endpoint::connect_with_opts`] function.
-1148#[derive(Default, Debug, Clone)]
-1149pub struct ConnectOptions {
-1150 transport_config: Option<Arc<quinn::TransportConfig>>,
-1151 additional_alpns: Vec<Vec<u8>>,
-1152}
-1153
-1154impl ConnectOptions {
-1155/// Initializes new connection options.
-1156 ///
-1157 /// By default, the connection will use the same options
-1158 /// as [`Endpoint::connect`], e.g. a default [`TransportConfig`].
-1159pub fn new() -> Self {
-1160Self::default()
-1161 }
-1162
-1163/// Sets the QUIC transport config options for this connection.
-1164pub fn with_transport_config(mut self, transport_config: Arc<quinn::TransportConfig>) -> Self {
-1165self.transport_config = Some(transport_config);
-1166self
-1167}
-1168
-1169/// Sets [ALPN] identifiers that should be signaled as supported on connection, *in
-1170 /// addition* to the main [ALPN] identifier used in [`Endpoint::connect_with_opts`].
-1171 ///
-1172 /// This allows connecting to servers that may only support older versions of your
-1173 /// protocol. In this case, you would add the older [ALPN] identifiers with this
-1174 /// function.
-1175 ///
-1176 /// You'll know the final negotiated [ALPN] identifier once your connection was
-1177 /// established using [`Connection::alpn`], or even slightly earlier in the
-1178 /// handshake by using [`Connecting::alpn`].
-1179 /// The negotiated [ALPN] identifier may be any of the [ALPN] identifiers in this
-1180 /// list or the main [ALPN] used in [`Endpoint::connect_with_opts`].
-1181 ///
-1182 /// The [ALPN] identifier order on the connect side doesn't matter, since it's the
-1183 /// accept side that determines the protocol.
-1184 ///
-1185 /// For setting the supported [ALPN] identifiers on the accept side, see the endpoint
-1186 /// builder's [`Builder::alpns`] function.
-1187 ///
-1188 /// [ALPN]: https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation
-1189pub fn with_additional_alpns(mut self, alpns: Vec<Vec<u8>>) -> Self {
-1190self.additional_alpns = alpns;
-1191self
-1192}
-1193}
-1194
-1195/// Read a proxy url from the environment, in this order
-1196///
-1197/// - `HTTP_PROXY`
-1198/// - `http_proxy`
-1199/// - `HTTPS_PROXY`
-1200/// - `https_proxy`
-1201fn proxy_url_from_env() -> Option<Url> {
-1202if let Some(url) = std::env::var("HTTP_PROXY")
-1203 .ok()
-1204 .and_then(|s| s.parse::<Url>().ok())
-1205 {
-1206if is_cgi() {
-1207warn!("HTTP_PROXY environment variable ignored in CGI");
-1208 } else {
-1209return Some(url);
-1210 }
-1211 }
-1212if let Some(url) = std::env::var("http_proxy")
-1213 .ok()
-1214 .and_then(|s| s.parse::<Url>().ok())
-1215 {
-1216return Some(url);
-1217 }
-1218if let Some(url) = std::env::var("HTTPS_PROXY")
-1219 .ok()
-1220 .and_then(|s| s.parse::<Url>().ok())
-1221 {
-1222return Some(url);
-1223 }
-1224if let Some(url) = std::env::var("https_proxy")
-1225 .ok()
-1226 .and_then(|s| s.parse::<Url>().ok())
-1227 {
-1228return Some(url);
-1229 }
-1230
-1231None
-1232}
-1233
-1234/// Configuration of the relay servers for an [`Endpoint`].
-1235#[derive(Debug, Clone, PartialEq, Eq)]
-1236pub enum RelayMode {
-1237/// Disable relay servers completely.
-1238 /// This means that neither listening nor dialing relays will be available.
-1239Disabled,
-1240/// Use the default relay map, with production relay servers from n0.
-1241 ///
-1242 /// See [`crate::defaults::prod`] for the severs used.
-1243Default,
-1244/// Use the staging relay servers from n0.
-1245Staging,
-1246/// Use a custom relay map.
-1247Custom(RelayMap),
-1248}
-1249
-1250impl RelayMode {
-1251/// Returns the relay map for this mode.
-1252pub fn relay_map(&self) -> RelayMap {
-1253match self {
-1254 RelayMode::Disabled => RelayMap::empty(),
-1255 RelayMode::Default => crate::defaults::prod::default_relay_map(),
-1256 RelayMode::Staging => crate::defaults::staging::default_relay_map(),
-1257 RelayMode::Custom(relay_map) => relay_map.clone(),
-1258 }
-1259 }
-1260}
-1261
-1262/// Environment variable to force the use of staging relays.
-1263pub const ENV_FORCE_STAGING_RELAYS: &str = "IROH_FORCE_STAGING_RELAYS";
-1264
-1265/// Returns `true` if the use of staging relays is forced.
-1266pub fn force_staging_infra() -> bool {
-1267matches!(std::env::var(ENV_FORCE_STAGING_RELAYS), Ok(value) if !value.is_empty())
-1268}
-1269
-1270/// Returns the default relay mode.
-1271///
-1272/// If the `IROH_FORCE_STAGING_RELAYS` environment variable is non empty, it will return `RelayMode::Staging`.
-1273/// Otherwise, it will return `RelayMode::Default`.
-1274pub fn default_relay_mode() -> RelayMode {
-1275// Use staging in testing
-1276match force_staging_infra() {
-1277true => RelayMode::Staging,
-1278false => RelayMode::Default,
-1279 }
-1280}
-1281
-1282/// Check if we are being executed in a CGI context.
-1283///
-1284/// If so, a malicious client can send the `Proxy:` header, and it will
-1285/// be in the `HTTP_PROXY` env var. So we don't use it :)
-1286fn is_cgi() -> bool {
-1287 std::env::var_os("REQUEST_METHOD").is_some()
-1288}
-1289
-1290// TODO: These tests could still be flaky, lets fix that:
-1291// https://github.com/n0-computer/iroh/issues/1183
-1292#[cfg(test)]
-1293mod tests {
-1294use std::time::{Duration, Instant};
-1295
-1296use iroh_base::{EndpointAddr, EndpointId, SecretKey, TransportAddr};
-1297use n0_error::{AnyError as Error, Result, StdResultExt};
-1298use n0_future::{BufferedStreamExt, StreamExt, stream, time};
-1299use n0_watcher::Watcher;
-1300use quinn::ConnectionError;
-1301use rand::SeedableRng;
-1302use tokio::sync::oneshot;
-1303use tracing::{Instrument, error_span, info, info_span, instrument};
-1304use tracing_test::traced_test;
-1305
-1306use super::Endpoint;
-1307use crate::{
-1308 RelayMap, RelayMode,
-1309 discovery::static_provider::StaticProvider,
-1310 endpoint::{ConnectOptions, Connection},
-1311 protocol::{AcceptError, ProtocolHandler, Router},
-1312 test_utils::{run_relay_server, run_relay_server_with},
-1313 };
-1314
-1315const TEST_ALPN: &[u8] = b"n0/iroh/test";
+1137// # Remaining private methods
+1138
+1139#[cfg(test)]
+1140pub(crate) fn magic_sock(&self) -> Handle {
+1141self.msock.clone()
+1142 }
+1143#[cfg(test)]
+1144pub(crate) fn endpoint(&self) -> &quinn::Endpoint {
+1145self.msock.endpoint()
+1146 }
+1147}
+1148
+1149/// Options for the [`Endpoint::connect_with_opts`] function.
+1150#[derive(Default, Debug, Clone)]
+1151pub struct ConnectOptions {
+1152 transport_config: Option<Arc<quinn::TransportConfig>>,
+1153 additional_alpns: Vec<Vec<u8>>,
+1154}
+1155
+1156impl ConnectOptions {
+1157/// Initializes new connection options.
+1158 ///
+1159 /// By default, the connection will use the same options
+1160 /// as [`Endpoint::connect`], e.g. a default [`TransportConfig`].
+1161pub fn new() -> Self {
+1162Self::default()
+1163 }
+1164
+1165/// Sets the QUIC transport config options for this connection.
+1166pub fn with_transport_config(mut self, transport_config: Arc<quinn::TransportConfig>) -> Self {
+1167self.transport_config = Some(transport_config);
+1168self
+1169}
+1170
+1171/// Sets [ALPN] identifiers that should be signaled as supported on connection, *in
+1172 /// addition* to the main [ALPN] identifier used in [`Endpoint::connect_with_opts`].
+1173 ///
+1174 /// This allows connecting to servers that may only support older versions of your
+1175 /// protocol. In this case, you would add the older [ALPN] identifiers with this
+1176 /// function.
+1177 ///
+1178 /// You'll know the final negotiated [ALPN] identifier once your connection was
+1179 /// established using [`Connection::alpn`], or even slightly earlier in the
+1180 /// handshake by using [`Connecting::alpn`].
+1181 /// The negotiated [ALPN] identifier may be any of the [ALPN] identifiers in this
+1182 /// list or the main [ALPN] used in [`Endpoint::connect_with_opts`].
+1183 ///
+1184 /// The [ALPN] identifier order on the connect side doesn't matter, since it's the
+1185 /// accept side that determines the protocol.
+1186 ///
+1187 /// For setting the supported [ALPN] identifiers on the accept side, see the endpoint
+1188 /// builder's [`Builder::alpns`] function.
+1189 ///
+1190 /// [ALPN]: https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation
+1191pub fn with_additional_alpns(mut self, alpns: Vec<Vec<u8>>) -> Self {
+1192self.additional_alpns = alpns;
+1193self
+1194}
+1195}
+1196
+1197/// Read a proxy url from the environment, in this order
+1198///
+1199/// - `HTTP_PROXY`
+1200/// - `http_proxy`
+1201/// - `HTTPS_PROXY`
+1202/// - `https_proxy`
+1203fn proxy_url_from_env() -> Option<Url> {
+1204if let Some(url) = std::env::var("HTTP_PROXY")
+1205 .ok()
+1206 .and_then(|s| s.parse::<Url>().ok())
+1207 {
+1208if is_cgi() {
+1209warn!("HTTP_PROXY environment variable ignored in CGI");
+1210 } else {
+1211return Some(url);
+1212 }
+1213 }
+1214if let Some(url) = std::env::var("http_proxy")
+1215 .ok()
+1216 .and_then(|s| s.parse::<Url>().ok())
+1217 {
+1218return Some(url);
+1219 }
+1220if let Some(url) = std::env::var("HTTPS_PROXY")
+1221 .ok()
+1222 .and_then(|s| s.parse::<Url>().ok())
+1223 {
+1224return Some(url);
+1225 }
+1226if let Some(url) = std::env::var("https_proxy")
+1227 .ok()
+1228 .and_then(|s| s.parse::<Url>().ok())
+1229 {
+1230return Some(url);
+1231 }
+1232
+1233None
+1234}
+1235
+1236/// Configuration of the relay servers for an [`Endpoint`].
+1237#[derive(Debug, Clone, PartialEq, Eq)]
+1238pub enum RelayMode {
+1239/// Disable relay servers completely.
+1240 /// This means that neither listening nor dialing relays will be available.
+1241Disabled,
+1242/// Use the default relay map, with production relay servers from n0.
+1243 ///
+1244 /// See [`crate::defaults::prod`] for the severs used.
+1245Default,
+1246/// Use the staging relay servers from n0.
+1247Staging,
+1248/// Use a custom relay map.
+1249Custom(RelayMap),
+1250}
+1251
+1252impl RelayMode {
+1253/// Returns the relay map for this mode.
+1254pub fn relay_map(&self) -> RelayMap {
+1255match self {
+1256 RelayMode::Disabled => RelayMap::empty(),
+1257 RelayMode::Default => crate::defaults::prod::default_relay_map(),
+1258 RelayMode::Staging => crate::defaults::staging::default_relay_map(),
+1259 RelayMode::Custom(relay_map) => relay_map.clone(),
+1260 }
+1261 }
+1262}
+1263
+1264/// Environment variable to force the use of staging relays.
+1265pub const ENV_FORCE_STAGING_RELAYS: &str = "IROH_FORCE_STAGING_RELAYS";
+1266
+1267/// Returns `true` if the use of staging relays is forced.
+1268pub fn force_staging_infra() -> bool {
+1269matches!(std::env::var(ENV_FORCE_STAGING_RELAYS), Ok(value) if !value.is_empty())
+1270}
+1271
+1272/// Returns the default relay mode.
+1273///
+1274/// If the `IROH_FORCE_STAGING_RELAYS` environment variable is non empty, it will return `RelayMode::Staging`.
+1275/// Otherwise, it will return `RelayMode::Default`.
+1276pub fn default_relay_mode() -> RelayMode {
+1277// Use staging in testing
+1278match force_staging_infra() {
+1279true => RelayMode::Staging,
+1280false => RelayMode::Default,
+1281 }
+1282}
+1283
+1284/// Check if we are being executed in a CGI context.
+1285///
+1286/// If so, a malicious client can send the `Proxy:` header, and it will
+1287/// be in the `HTTP_PROXY` env var. So we don't use it :)
+1288fn is_cgi() -> bool {
+1289 std::env::var_os("REQUEST_METHOD").is_some()
+1290}
+1291
+1292// TODO: These tests could still be flaky, lets fix that:
+1293// https://github.com/n0-computer/iroh/issues/1183
+1294#[cfg(test)]
+1295mod tests {
+1296use std::time::{Duration, Instant};
+1297
+1298use iroh_base::{EndpointAddr, EndpointId, SecretKey, TransportAddr};
+1299use n0_error::{AnyError as Error, Result, StdResultExt};
+1300use n0_future::{BufferedStreamExt, StreamExt, stream, time};
+1301use n0_watcher::Watcher;
+1302use quinn::ConnectionError;
+1303use rand::SeedableRng;
+1304use tokio::sync::oneshot;
+1305use tracing::{Instrument, error_span, info, info_span, instrument};
+1306use tracing_test::traced_test;
+1307
+1308use super::Endpoint;
+1309use crate::{
+1310 RelayMap, RelayMode,
+1311 discovery::static_provider::StaticProvider,
+1312 endpoint::{ConnectOptions, Connection},
+1313 protocol::{AcceptError, ProtocolHandler, Router},
+1314 test_utils::{run_relay_server, run_relay_server_with},
+1315 };
1316
-1317#[tokio::test]
-1318 #[traced_test]
-1319async fn test_connect_self() -> Result {
-1320let ep = Endpoint::empty_builder(RelayMode::Disabled)
-1321 .alpns(vec![TEST_ALPN.to_vec()])
-1322 .bind()
-1323 .await
-1324.unwrap();
-1325let my_addr = ep.addr();
-1326let res = ep.connect(my_addr.clone(), TEST_ALPN).await;
-1327assert!(res.is_err());
-1328let err = res.err().unwrap();
-1329assert!(err.to_string().starts_with("Connecting to ourself"));
-1330
-1331Ok(())
-1332 }
-1333
-1334#[tokio::test]
-1335 #[traced_test]
-1336async fn endpoint_connect_close() -> Result {
-1337let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
-1338let (relay_map, relay_url, _guard) = run_relay_server().await?;
-1339let server_secret_key = SecretKey::generate(&mut rng);
-1340let server_peer_id = server_secret_key.public();
-1341
-1342// Wait for the endpoint to be started to make sure it's up before clients try to connect
-1343let ep = Endpoint::empty_builder(RelayMode::Custom(relay_map.clone()))
-1344 .secret_key(server_secret_key)
-1345 .alpns(vec![TEST_ALPN.to_vec()])
-1346 .insecure_skip_relay_cert_verify(true)
-1347 .bind()
-1348 .await?;
-1349// Wait for the endpoint to be reachable via relay
-1350ep.online().await;
-1351
-1352let server = tokio::spawn(
-1353async move {
-1354info!("accepting connection");
-1355let incoming = ep.accept().await.anyerr()?;
-1356let conn = incoming.await.anyerr()?;
-1357let mut stream = conn.accept_uni().await.anyerr()?;
-1358let mut buf = [0u8; 5];
-1359 stream.read_exact(&mut buf).await.anyerr()?;
-1360info!("Accepted 1 stream, received {buf:?}. Closing now.");
-1361// close the connection
-1362conn.close(7u8.into(), b"bye");
-1363
-1364let res = conn.accept_uni().await;
-1365assert_eq!(res.unwrap_err(), quinn::ConnectionError::LocallyClosed);
-1366
-1367let res = stream.read_to_end(10).await;
-1368assert_eq!(
-1369 res.unwrap_err(),
-1370 quinn::ReadToEndError::Read(quinn::ReadError::ConnectionLost(
-1371 quinn::ConnectionError::LocallyClosed
-1372 ))
-1373 );
-1374info!("server test completed");
-1375Ok::<_, Error>(())
-1376 }
-1377 .instrument(info_span!("test-server")),
-1378 );
-1379
-1380let client = tokio::spawn(
-1381async move {
-1382let ep = Endpoint::empty_builder(RelayMode::Custom(relay_map))
-1383 .alpns(vec![TEST_ALPN.to_vec()])
-1384 .insecure_skip_relay_cert_verify(true)
-1385 .bind()
-1386 .await?;
-1387info!("client connecting");
-1388let endpoint_addr = EndpointAddr::new(server_peer_id).with_relay_url(relay_url);
-1389let conn = ep.connect(endpoint_addr, TEST_ALPN).await?;
-1390let mut stream = conn.open_uni().await.anyerr()?;
-1391
-1392// First write is accepted by server. We need this bit of synchronisation
-1393 // because if the server closes after simply accepting the connection we can
-1394 // not be sure our .open_uni() call would succeed as it may already receive
-1395 // the error.
-1396stream.write_all(b"hello").await.anyerr()?;
-1397
-1398info!("waiting for closed");
-1399// Remote now closes the connection, we should see an error sometime soon.
-1400let err = conn.closed().await;
-1401let expected_err =
-1402 quinn::ConnectionError::ApplicationClosed(quinn::ApplicationClose {
-1403 error_code: 7u8.into(),
-1404 reason: b"bye".to_vec().into(),
-1405 });
-1406assert_eq!(err, expected_err);
-1407
-1408info!("opening new - expect it to fail");
-1409let res = conn.open_uni().await;
-1410assert_eq!(res.unwrap_err(), expected_err);
-1411info!("client test completed");
-1412Ok::<_, Error>(())
-1413 }
-1414 .instrument(info_span!("test-client")),
-1415 );
-1416
-1417let (server, client) = tokio::time::timeout(
-1418 Duration::from_secs(30),
-1419 n0_future::future::zip(server, client),
-1420 )
-1421 .await
-1422.anyerr()?;
-1423 server.anyerr()??;
-1424 client.anyerr()??;
-1425Ok(())
-1426 }
-1427
-1428#[tokio::test]
-1429 #[traced_test]
-1430async fn endpoint_relay_connect_loop() -> Result {
-1431let test_start = Instant::now();
-1432let n_clients = 5;
-1433let n_chunks_per_client = 2;
-1434let chunk_size = 10;
-1435let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42);
-1436let (relay_map, relay_url, _relay_guard) = run_relay_server().await.unwrap();
-1437let server_secret_key = SecretKey::generate(&mut rng);
-1438let server_endpoint_id = server_secret_key.public();
-1439
-1440// Make sure the server is bound before having clients connect to it:
-1441let ep = Endpoint::empty_builder(RelayMode::Custom(relay_map.clone()))
-1442 .insecure_skip_relay_cert_verify(true)
-1443 .secret_key(server_secret_key)
-1444 .alpns(vec![TEST_ALPN.to_vec()])
-1445 .bind()
-1446 .await?;
-1447// Also make sure the server has a working relay connection
-1448ep.online().await;
-1449
-1450info!(time = ?test_start.elapsed(), "test setup done");
+1317const TEST_ALPN: &[u8] = b"n0/iroh/test";
+1318
+1319#[tokio::test]
+1320 #[traced_test]
+1321async fn test_connect_self() -> Result {
+1322let ep = Endpoint::empty_builder(RelayMode::Disabled)
+1323 .alpns(vec![TEST_ALPN.to_vec()])
+1324 .bind()
+1325 .await
+1326.unwrap();
+1327let my_addr = ep.addr();
+1328let res = ep.connect(my_addr.clone(), TEST_ALPN).await;
+1329assert!(res.is_err());
+1330let err = res.err().unwrap();
+1331assert!(err.to_string().starts_with("Connecting to ourself"));
+1332
+1333Ok(())
+1334 }
+1335
+1336#[tokio::test]
+1337 #[traced_test]
+1338async fn endpoint_connect_close() -> Result {
+1339let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
+1340let (relay_map, relay_url, _guard) = run_relay_server().await?;
+1341let server_secret_key = SecretKey::generate(&mut rng);
+1342let server_peer_id = server_secret_key.public();
+1343
+1344// Wait for the endpoint to be started to make sure it's up before clients try to connect
+1345let ep = Endpoint::empty_builder(RelayMode::Custom(relay_map.clone()))
+1346 .secret_key(server_secret_key)
+1347 .alpns(vec![TEST_ALPN.to_vec()])
+1348 .insecure_skip_relay_cert_verify(true)
+1349 .bind()
+1350 .await?;
+1351// Wait for the endpoint to be reachable via relay
+1352ep.online().await;
+1353
+1354let server = tokio::spawn(
+1355async move {
+1356info!("accepting connection");
+1357let incoming = ep.accept().await.anyerr()?;
+1358let conn = incoming.await.anyerr()?;
+1359let mut stream = conn.accept_uni().await.anyerr()?;
+1360let mut buf = [0u8; 5];
+1361 stream.read_exact(&mut buf).await.anyerr()?;
+1362info!("Accepted 1 stream, received {buf:?}. Closing now.");
+1363// close the connection
+1364conn.close(7u8.into(), b"bye");
+1365
+1366let res = conn.accept_uni().await;
+1367assert_eq!(res.unwrap_err(), quinn::ConnectionError::LocallyClosed);
+1368
+1369let res = stream.read_to_end(10).await;
+1370assert_eq!(
+1371 res.unwrap_err(),
+1372 quinn::ReadToEndError::Read(quinn::ReadError::ConnectionLost(
+1373 quinn::ConnectionError::LocallyClosed
+1374 ))
+1375 );
+1376info!("server test completed");
+1377Ok::<_, Error>(())
+1378 }
+1379 .instrument(info_span!("test-server")),
+1380 );
+1381
+1382let client = tokio::spawn(
+1383async move {
+1384let ep = Endpoint::empty_builder(RelayMode::Custom(relay_map))
+1385 .alpns(vec![TEST_ALPN.to_vec()])
+1386 .insecure_skip_relay_cert_verify(true)
+1387 .bind()
+1388 .await?;
+1389info!("client connecting");
+1390let endpoint_addr = EndpointAddr::new(server_peer_id).with_relay_url(relay_url);
+1391let conn = ep.connect(endpoint_addr, TEST_ALPN).await?;
+1392let mut stream = conn.open_uni().await.anyerr()?;
+1393
+1394// First write is accepted by server. We need this bit of synchronisation
+1395 // because if the server closes after simply accepting the connection we can
+1396 // not be sure our .open_uni() call would succeed as it may already receive
+1397 // the error.
+1398stream.write_all(b"hello").await.anyerr()?;
+1399
+1400info!("waiting for closed");
+1401// Remote now closes the connection, we should see an error sometime soon.
+1402let err = conn.closed().await;
+1403let expected_err =
+1404 quinn::ConnectionError::ApplicationClosed(quinn::ApplicationClose {
+1405 error_code: 7u8.into(),
+1406 reason: b"bye".to_vec().into(),
+1407 });
+1408assert_eq!(err, expected_err);
+1409
+1410info!("opening new - expect it to fail");
+1411let res = conn.open_uni().await;
+1412assert_eq!(res.unwrap_err(), expected_err);
+1413info!("client test completed");
+1414Ok::<_, Error>(())
+1415 }
+1416 .instrument(info_span!("test-client")),
+1417 );
+1418
+1419let (server, client) = tokio::time::timeout(
+1420 Duration::from_secs(30),
+1421 n0_future::future::zip(server, client),
+1422 )
+1423 .await
+1424.anyerr()?;
+1425 server.anyerr()??;
+1426 client.anyerr()??;
+1427Ok(())
+1428 }
+1429
+1430#[tokio::test]
+1431 #[traced_test]
+1432async fn endpoint_relay_connect_loop() -> Result {
+1433let test_start = Instant::now();
+1434let n_clients = 5;
+1435let n_chunks_per_client = 2;
+1436let chunk_size = 10;
+1437let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42);
+1438let (relay_map, relay_url, _relay_guard) = run_relay_server().await.unwrap();
+1439let server_secret_key = SecretKey::generate(&mut rng);
+1440let server_endpoint_id = server_secret_key.public();
+1441
+1442// Make sure the server is bound before having clients connect to it:
+1443let ep = Endpoint::empty_builder(RelayMode::Custom(relay_map.clone()))
+1444 .insecure_skip_relay_cert_verify(true)
+1445 .secret_key(server_secret_key)
+1446 .alpns(vec![TEST_ALPN.to_vec()])
+1447 .bind()
+1448 .await?;
+1449// Also make sure the server has a working relay connection
+1450ep.online().await;
1451
-1452// The server accepts the connections of the clients sequentially.
-1453let server = tokio::spawn(
-1454async move {
-1455let eps = ep.bound_sockets();
-1456
-1457info!(me = %ep.id().fmt_short(), eps = ?eps, "server listening on");
-1458for i in 0..n_clients {
-1459let round_start = Instant::now();
-1460info!("[server] round {i}");
-1461let incoming = ep.accept().await.anyerr()?;
-1462let conn = incoming.await.anyerr()?;
-1463let endpoint_id = conn.remote_id();
-1464info!(%i, peer = %endpoint_id.fmt_short(), "accepted connection");
-1465let (mut send, mut recv) = conn.accept_bi().await.anyerr()?;
-1466let mut buf = vec![0u8; chunk_size];
-1467for _i in 0..n_chunks_per_client {
-1468 recv.read_exact(&mut buf).await.anyerr()?;
-1469 send.write_all(&buf).await.anyerr()?;
-1470 }
-1471 send.finish().anyerr()?;
-1472 conn.closed().await; // we're the last to send data, so we wait for the other side to close
-1473info!(%i, peer = %endpoint_id.fmt_short(), "finished");
-1474info!("[server] round {i} done in {:?}", round_start.elapsed());
-1475 }
-1476Ok::<_, Error>(())
-1477 }
-1478 .instrument(error_span!("server")),
-1479 );
-1480
-1481let start = Instant::now();
+1452info!(time = ?test_start.elapsed(), "test setup done");
+1453
+1454// The server accepts the connections of the clients sequentially.
+1455let server = tokio::spawn(
+1456async move {
+1457let eps = ep.bound_sockets();
+1458
+1459info!(me = %ep.id().fmt_short(), eps = ?eps, "server listening on");
+1460for i in 0..n_clients {
+1461let round_start = Instant::now();
+1462info!("[server] round {i}");
+1463let incoming = ep.accept().await.anyerr()?;
+1464let conn = incoming.await.anyerr()?;
+1465let endpoint_id = conn.remote_id();
+1466info!(%i, peer = %endpoint_id.fmt_short(), "accepted connection");
+1467let (mut send, mut recv) = conn.accept_bi().await.anyerr()?;
+1468let mut buf = vec![0u8; chunk_size];
+1469for _i in 0..n_chunks_per_client {
+1470 recv.read_exact(&mut buf).await.anyerr()?;
+1471 send.write_all(&buf).await.anyerr()?;
+1472 }
+1473 send.finish().anyerr()?;
+1474 conn.closed().await; // we're the last to send data, so we wait for the other side to close
+1475info!(%i, peer = %endpoint_id.fmt_short(), "finished");
+1476info!("[server] round {i} done in {:?}", round_start.elapsed());
+1477 }
+1478Ok::<_, Error>(())
+1479 }
+1480 .instrument(error_span!("server")),
+1481 );
1482
-1483for i in 0..n_clients {
-1484let round_start = Instant::now();
-1485info!("[client] round {i}");
-1486let client_secret_key = SecretKey::generate(&mut rng);
-1487async {
-1488info!("client binding");
-1489let ep = Endpoint::empty_builder(RelayMode::Custom(relay_map.clone()))
-1490 .alpns(vec![TEST_ALPN.to_vec()])
-1491 .insecure_skip_relay_cert_verify(true)
-1492 .secret_key(client_secret_key)
-1493 .bind()
-1494 .await?;
-1495let eps = ep.bound_sockets();
-1496
-1497info!(me = %ep.id().fmt_short(), eps=?eps, "client bound");
-1498let endpoint_addr =
-1499 EndpointAddr::new(server_endpoint_id).with_relay_url(relay_url.clone());
-1500info!(to = ?endpoint_addr, "client connecting");
-1501let conn = ep.connect(endpoint_addr, TEST_ALPN).await.anyerr()?;
-1502info!("client connected");
-1503let (mut send, mut recv) = conn.open_bi().await.anyerr()?;
-1504
-1505for i in 0..n_chunks_per_client {
-1506let mut buf = vec![i; chunk_size];
-1507 send.write_all(&buf).await.anyerr()?;
-1508 recv.read_exact(&mut buf).await.anyerr()?;
-1509assert_eq!(buf, vec![i; chunk_size]);
-1510 }
-1511// we're the last to receive data, so we close
-1512conn.close(0u32.into(), b"bye!");
-1513info!("client finished");
-1514 ep.close().await;
-1515info!("client closed");
-1516Ok::<_, Error>(())
-1517 }
-1518 .instrument(error_span!("client", %i))
-1519 .await?;
-1520info!("[client] round {i} done in {:?}", round_start.elapsed());
-1521 }
-1522
-1523 server.await.anyerr()??;
+1483let start = Instant::now();
+1484
+1485for i in 0..n_clients {
+1486let round_start = Instant::now();
+1487info!("[client] round {i}");
+1488let client_secret_key = SecretKey::generate(&mut rng);
+1489async {
+1490info!("client binding");
+1491let ep = Endpoint::empty_builder(RelayMode::Custom(relay_map.clone()))
+1492 .alpns(vec![TEST_ALPN.to_vec()])
+1493 .insecure_skip_relay_cert_verify(true)
+1494 .secret_key(client_secret_key)
+1495 .bind()
+1496 .await?;
+1497let eps = ep.bound_sockets();
+1498
+1499info!(me = %ep.id().fmt_short(), eps=?eps, "client bound");
+1500let endpoint_addr =
+1501 EndpointAddr::new(server_endpoint_id).with_relay_url(relay_url.clone());
+1502info!(to = ?endpoint_addr, "client connecting");
+1503let conn = ep.connect(endpoint_addr, TEST_ALPN).await.anyerr()?;
+1504info!("client connected");
+1505let (mut send, mut recv) = conn.open_bi().await.anyerr()?;
+1506
+1507for i in 0..n_chunks_per_client {
+1508let mut buf = vec![i; chunk_size];
+1509 send.write_all(&buf).await.anyerr()?;
+1510 recv.read_exact(&mut buf).await.anyerr()?;
+1511assert_eq!(buf, vec![i; chunk_size]);
+1512 }
+1513// we're the last to receive data, so we close
+1514conn.close(0u32.into(), b"bye!");
+1515info!("client finished");
+1516 ep.close().await;
+1517info!("client closed");
+1518Ok::<_, Error>(())
+1519 }
+1520 .instrument(error_span!("client", %i))
+1521 .await?;
+1522info!("[client] round {i} done in {:?}", round_start.elapsed());
+1523 }
1524
-1525// We appear to have seen this being very slow at times. So ensure we fail if this
-1526 // test is too slow. We're only making two connections transferring very little
-1527 // data, this really shouldn't take long.
-1528if start.elapsed() > Duration::from_secs(15) {
-1529panic!("Test too slow, something went wrong");
-1530 }
-1531
-1532Ok(())
-1533 }
-1534
-1535#[tokio::test]
-1536 #[traced_test]
-1537async fn endpoint_send_relay() -> Result {
-1538let (relay_map, _relay_url, _guard) = run_relay_server().await?;
-1539let client = Endpoint::empty_builder(RelayMode::Custom(relay_map.clone()))
-1540 .insecure_skip_relay_cert_verify(true)
-1541 .bind()
-1542 .await?;
-1543let server = Endpoint::empty_builder(RelayMode::Custom(relay_map))
-1544 .insecure_skip_relay_cert_verify(true)
-1545 .alpns(vec![TEST_ALPN.to_vec()])
-1546 .bind()
-1547 .await?;
-1548
-1549let task = tokio::spawn({
-1550let server = server.clone();
-1551async move {
-1552let Some(conn) = server.accept().await else {
-1553n0_error::bail_any!("Expected an incoming connection");
-1554 };
-1555let conn = conn.await.anyerr()?;
-1556let (mut send, mut recv) = conn.accept_bi().await.anyerr()?;
-1557let data = recv.read_to_end(1000).await.anyerr()?;
-1558 send.write_all(&data).await.anyerr()?;
-1559 send.finish().anyerr()?;
-1560 conn.closed().await;
-1561
-1562Ok::<_, Error>(())
-1563 }
-1564 });
-1565
-1566let addr = server.addr();
-1567let conn = client.connect(addr, TEST_ALPN).await?;
-1568let (mut send, mut recv) = conn.open_bi().await.anyerr()?;
-1569 send.write_all(b"Hello, world!").await.anyerr()?;
-1570 send.finish().anyerr()?;
-1571let data = recv.read_to_end(1000).await.anyerr()?;
-1572 conn.close(0u32.into(), b"bye!");
-1573
-1574 task.await.anyerr()??;
+1525 server.await.anyerr()??;
+1526
+1527// We appear to have seen this being very slow at times. So ensure we fail if this
+1528 // test is too slow. We're only making two connections transferring very little
+1529 // data, this really shouldn't take long.
+1530if start.elapsed() > Duration::from_secs(15) {
+1531panic!("Test too slow, something went wrong");
+1532 }
+1533
+1534Ok(())
+1535 }
+1536
+1537#[tokio::test]
+1538 #[traced_test]
+1539async fn endpoint_send_relay() -> Result {
+1540let (relay_map, _relay_url, _guard) = run_relay_server().await?;
+1541let client = Endpoint::empty_builder(RelayMode::Custom(relay_map.clone()))
+1542 .insecure_skip_relay_cert_verify(true)
+1543 .bind()
+1544 .await?;
+1545let server = Endpoint::empty_builder(RelayMode::Custom(relay_map))
+1546 .insecure_skip_relay_cert_verify(true)
+1547 .alpns(vec![TEST_ALPN.to_vec()])
+1548 .bind()
+1549 .await?;
+1550
+1551let task = tokio::spawn({
+1552let server = server.clone();
+1553async move {
+1554let Some(conn) = server.accept().await else {
+1555n0_error::bail_any!("Expected an incoming connection");
+1556 };
+1557let conn = conn.await.anyerr()?;
+1558let (mut send, mut recv) = conn.accept_bi().await.anyerr()?;
+1559let data = recv.read_to_end(1000).await.anyerr()?;
+1560 send.write_all(&data).await.anyerr()?;
+1561 send.finish().anyerr()?;
+1562 conn.closed().await;
+1563
+1564Ok::<_, Error>(())
+1565 }
+1566 });
+1567
+1568let addr = server.addr();
+1569let conn = client.connect(addr, TEST_ALPN).await?;
+1570let (mut send, mut recv) = conn.open_bi().await.anyerr()?;
+1571 send.write_all(b"Hello, world!").await.anyerr()?;
+1572 send.finish().anyerr()?;
+1573let data = recv.read_to_end(1000).await.anyerr()?;
+1574 conn.close(0u32.into(), b"bye!");
1575
-1576 client.close().await;
-1577 server.close().await;
-1578
-1579assert_eq!(&data, b"Hello, world!");
+1576 task.await.anyerr()??;
+1577
+1578 client.close().await;
+1579 server.close().await;
1580
-1581Ok(())
-1582 }
-1583
-1584#[tokio::test]
-1585 #[traced_test]
-1586async fn endpoint_two_direct_only() -> Result {
-1587// Connect two endpoints on the same network, without a relay server, without
-1588 // discovery.
-1589let ep1 = {
-1590let span = info_span!("server");
-1591let _guard = span.enter();
-1592 Endpoint::builder()
-1593 .alpns(vec![TEST_ALPN.to_vec()])
-1594 .relay_mode(RelayMode::Disabled)
-1595 .bind()
-1596 .await?
-1597};
-1598let ep2 = {
-1599let span = info_span!("client");
-1600let _guard = span.enter();
-1601 Endpoint::builder()
-1602 .alpns(vec![TEST_ALPN.to_vec()])
-1603 .relay_mode(RelayMode::Disabled)
-1604 .bind()
-1605 .await?
-1606};
-1607let ep1_nodeaddr = ep1.addr();
-1608
-1609#[instrument(name = "client", skip_all)]
-1610async fn connect(ep: Endpoint, dst: EndpointAddr) -> Result<quinn::ConnectionError> {
-1611info!(me = %ep.id().fmt_short(), "client starting");
-1612let conn = ep.connect(dst, TEST_ALPN).await?;
-1613let mut send = conn.open_uni().await.anyerr()?;
-1614 send.write_all(b"hello").await.anyerr()?;
-1615 send.finish().anyerr()?;
-1616Ok(conn.closed().await)
-1617 }
-1618
-1619#[instrument(name = "server", skip_all)]
-1620async fn accept(ep: Endpoint, src: EndpointId) -> Result {
-1621info!(me = %ep.id().fmt_short(), "server starting");
-1622let conn = ep.accept().await.anyerr()?.await.anyerr()?;
-1623let node_id = conn.remote_id();
-1624assert_eq!(node_id, src);
-1625let mut recv = conn.accept_uni().await.anyerr()?;
-1626let msg = recv.read_to_end(100).await.anyerr()?;
-1627assert_eq!(msg, b"hello");
-1628// Dropping the connection closes it just fine.
-1629Ok(())
-1630 }
-1631
-1632let ep1_accept = tokio::spawn(accept(ep1.clone(), ep2.id()));
-1633let ep2_connect = tokio::spawn(connect(ep2.clone(), ep1_nodeaddr));
-1634
-1635 ep1_accept.await.anyerr()??;
-1636let conn_closed = dbg!(ep2_connect.await.anyerr()??);
-1637assert!(matches!(
-1638 conn_closed,
-1639 ConnectionError::ApplicationClosed(quinn::ApplicationClose { .. })
-1640 ));
-1641
-1642Ok(())
-1643 }
-1644
-1645#[tokio::test]
-1646 #[traced_test]
-1647async fn endpoint_two_relay_only_becomes_direct() -> Result {
-1648// Connect two endpoints on the same network, via a relay server, without
-1649 // discovery. Wait until there is a direct connection.
-1650let (relay_map, _relay_url, _relay_server_guard) = run_relay_server().await?;
-1651let (node_addr_tx, node_addr_rx) = oneshot::channel();
-1652
-1653#[instrument(name = "client", skip_all)]
-1654async fn connect(
-1655 relay_map: RelayMap,
-1656 node_addr_rx: oneshot::Receiver<EndpointAddr>,
-1657 ) -> Result<quinn::ConnectionError> {
-1658let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
-1659let secret = SecretKey::generate(&mut rng);
-1660let ep = Endpoint::builder()
-1661 .secret_key(secret)
-1662 .alpns(vec![TEST_ALPN.to_vec()])
-1663 .insecure_skip_relay_cert_verify(true)
-1664 .relay_mode(RelayMode::Custom(relay_map))
-1665 .bind()
-1666 .await?;
-1667info!(me = %ep.id().fmt_short(), "client starting");
-1668let dst = node_addr_rx.await.anyerr()?;
-1669
-1670info!(me = %ep.id().fmt_short(), "client connecting");
-1671let conn = ep.connect(dst, TEST_ALPN).await?;
-1672let mut send = conn.open_uni().await.anyerr()?;
-1673 send.write_all(b"hello").await.anyerr()?;
-1674let mut paths = conn.paths().stream();
-1675info!("Waiting for direct connection");
-1676while let Some(infos) = paths.next().await {
-1677info!(?infos, "new PathInfos");
-1678if infos.iter().any(|info| info.is_ip()) {
-1679break;
-1680 }
-1681 }
-1682info!("Have direct connection");
-1683 send.write_all(b"close please").await.anyerr()?;
-1684 send.finish().anyerr()?;
-1685Ok(conn.closed().await)
-1686 }
-1687
-1688#[instrument(name = "server", skip_all)]
-1689async fn accept(
-1690 relay_map: RelayMap,
-1691 node_addr_tx: oneshot::Sender<EndpointAddr>,
-1692 ) -> Result {
-1693let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1u64);
-1694let secret = SecretKey::generate(&mut rng);
-1695let ep = Endpoint::builder()
-1696 .secret_key(secret)
-1697 .alpns(vec![TEST_ALPN.to_vec()])
-1698 .insecure_skip_relay_cert_verify(true)
-1699 .relay_mode(RelayMode::Custom(relay_map))
-1700 .bind()
-1701 .await?;
-1702 ep.online().await;
-1703let mut node_addr = ep.addr();
-1704 node_addr.addrs.retain(|addr| addr.is_relay());
-1705 node_addr_tx.send(node_addr).unwrap();
-1706
-1707info!(me = %ep.id().fmt_short(), "server starting");
-1708let conn = ep.accept().await.anyerr()?.await.anyerr()?;
-1709// let node_id = conn.remote_node_id()?;
-1710 // assert_eq!(node_id, src);
-1711let mut recv = conn.accept_uni().await.anyerr()?;
-1712let mut msg = [0u8; 5];
-1713 recv.read_exact(&mut msg).await.anyerr()?;
-1714assert_eq!(&msg, b"hello");
-1715info!("received hello");
-1716let msg = recv.read_to_end(100).await.anyerr()?;
-1717assert_eq!(msg, b"close please");
-1718info!("received 'close please'");
-1719// Dropping the connection closes it just fine.
-1720Ok(())
-1721 }
-1722
-1723let server_task = tokio::spawn(accept(relay_map.clone(), node_addr_tx));
-1724let client_task = tokio::spawn(connect(relay_map, node_addr_rx));
-1725
-1726 server_task.await.anyerr()??;
-1727let conn_closed = dbg!(client_task.await.anyerr()??);
-1728assert!(matches!(
-1729 conn_closed,
-1730 ConnectionError::ApplicationClosed(quinn::ApplicationClose { .. })
-1731 ));
-1732
-1733Ok(())
-1734 }
-1735
-1736#[tokio::test]
-1737 #[traced_test]
-1738async fn endpoint_two_relay_only_no_ip() -> Result {
-1739// Connect two endpoints on the same network, via a relay server, without
-1740 // discovery.
-1741let (relay_map, _relay_url, _relay_server_guard) = run_relay_server().await?;
-1742let (node_addr_tx, node_addr_rx) = oneshot::channel();
-1743
-1744#[instrument(name = "client", skip_all)]
-1745async fn connect(
-1746 relay_map: RelayMap,
-1747 node_addr_rx: oneshot::Receiver<EndpointAddr>,
-1748 ) -> Result<quinn::ConnectionError> {
-1749let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
-1750let secret = SecretKey::generate(&mut rng);
-1751let ep = Endpoint::builder()
-1752 .secret_key(secret)
-1753 .alpns(vec![TEST_ALPN.to_vec()])
-1754 .insecure_skip_relay_cert_verify(true)
-1755 .relay_mode(RelayMode::Custom(relay_map))
-1756 .clear_ip_transports() // disable direct
-1757.bind()
-1758 .await?;
-1759info!(me = %ep.id().fmt_short(), "client starting");
-1760let dst = node_addr_rx.await.anyerr()?;
-1761
-1762info!(me = %ep.id().fmt_short(), "client connecting");
-1763let conn = ep.connect(dst, TEST_ALPN).await?;
-1764let mut send = conn.open_uni().await.anyerr()?;
-1765 send.write_all(b"hello").await.anyerr()?;
-1766let mut paths = conn.paths().stream();
-1767info!("Waiting for connection");
-1768'outer: while let Some(infos) = paths.next().await {
-1769info!(?infos, "new PathInfos");
-1770for info in infos {
-1771if info.is_ip() {
-1772panic!("should not happen: {:?}", info);
-1773 }
-1774if info.is_relay() {
-1775break 'outer;
-1776 }
-1777 }
-1778 }
-1779info!("Have relay connection");
-1780 send.write_all(b"close please").await.anyerr()?;
-1781 send.finish().anyerr()?;
-1782Ok(conn.closed().await)
-1783 }
-1784
-1785#[instrument(name = "server", skip_all)]
-1786async fn accept(
-1787 relay_map: RelayMap,
-1788 node_addr_tx: oneshot::Sender<EndpointAddr>,
-1789 ) -> Result {
-1790let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1u64);
-1791let secret = SecretKey::generate(&mut rng);
-1792let ep = Endpoint::builder()
-1793 .secret_key(secret)
-1794 .alpns(vec![TEST_ALPN.to_vec()])
-1795 .insecure_skip_relay_cert_verify(true)
-1796 .relay_mode(RelayMode::Custom(relay_map))
-1797 .clear_ip_transports()
-1798 .bind()
-1799 .await?;
-1800 ep.online().await;
-1801let node_addr = ep.addr();
-1802 node_addr_tx.send(node_addr).unwrap();
-1803
-1804info!(me = %ep.id().fmt_short(), "server starting");
-1805let conn = ep.accept().await.anyerr()?.await.anyerr()?;
-1806// let node_id = conn.remote_node_id()?;
-1807 // assert_eq!(node_id, src);
-1808let mut recv = conn.accept_uni().await.anyerr()?;
-1809let mut msg = [0u8; 5];
-1810 recv.read_exact(&mut msg).await.anyerr()?;
-1811assert_eq!(&msg, b"hello");
-1812info!("received hello");
-1813let msg = recv.read_to_end(100).await.anyerr()?;
-1814assert_eq!(msg, b"close please");
-1815info!("received 'close please'");
-1816// Dropping the connection closes it just fine.
-1817Ok(())
-1818 }
-1819
-1820let server_task = tokio::spawn(accept(relay_map.clone(), node_addr_tx));
-1821let client_task = tokio::spawn(connect(relay_map, node_addr_rx));
-1822
-1823 server_task.await.anyerr()??;
-1824let conn_closed = dbg!(client_task.await.anyerr()??);
-1825assert!(matches!(
-1826 conn_closed,
-1827 ConnectionError::ApplicationClosed(quinn::ApplicationClose { .. })
-1828 ));
-1829
-1830Ok(())
-1831 }
-1832
-1833#[tokio::test]
-1834 #[traced_test]
-1835async fn endpoint_two_direct_add_relay() -> Result {
-1836// Connect two endpoints on the same network, without relay server and without
-1837 // discovery. Add a relay connection later.
-1838let (relay_map, _relay_url, _relay_server_guard) = run_relay_server().await?;
-1839let (node_addr_tx, node_addr_rx) = oneshot::channel();
-1840
-1841#[instrument(name = "client", skip_all)]
-1842async fn connect(
-1843 relay_map: RelayMap,
-1844 node_addr_rx: oneshot::Receiver<EndpointAddr>,
-1845 ) -> Result<()> {
-1846let secret = SecretKey::from([0u8; 32]);
-1847let ep = Endpoint::builder()
-1848 .secret_key(secret)
-1849 .alpns(vec![TEST_ALPN.to_vec()])
-1850 .insecure_skip_relay_cert_verify(true)
-1851 .relay_mode(RelayMode::Custom(relay_map))
-1852 .bind()
-1853 .await?;
-1854info!(me = %ep.id().fmt_short(), "client starting");
-1855let dst = node_addr_rx.await.anyerr()?;
-1856
-1857info!(me = %ep.id().fmt_short(), "client connecting");
-1858let conn = ep.connect(dst, TEST_ALPN).await?;
-1859info!(me = %ep.id().fmt_short(), "client connected");
-1860
-1861// We should be connected via IP, because it is faster than the relay server.
-1862 // TODO: Maybe not panic if this is not true?
-1863let path_info = conn.paths().get();
-1864assert_eq!(path_info.len(), 1);
-1865assert!(path_info.iter().next().unwrap().is_ip());
-1866
-1867let mut paths = conn.paths().stream();
-1868 time::timeout(Duration::from_secs(5), async move {
-1869while let Some(infos) = paths.next().await {
-1870info!(?infos, "new PathInfos");
-1871if infos.iter().any(|info| info.is_relay()) {
-1872info!("client has a relay path");
-1873break;
-1874 }
-1875 }
-1876 })
-1877 .await
-1878.anyerr()?;
-1879
-1880// wait for the server to signal it has the relay connection
-1881let mut stream = conn.accept_uni().await.anyerr()?;
-1882 stream.read_to_end(100).await.anyerr()?;
-1883
-1884info!("client closing");
-1885 conn.close(0u8.into(), b"");
-1886 ep.close().await;
-1887Ok(())
-1888 }
-1889
-1890#[instrument(name = "server", skip_all)]
-1891async fn accept(
-1892 relay_map: RelayMap,
-1893 node_addr_tx: oneshot::Sender<EndpointAddr>,
-1894 ) -> Result<quinn::ConnectionError> {
-1895let secret = SecretKey::from([1u8; 32]);
-1896let ep = Endpoint::builder()
-1897 .secret_key(secret)
-1898 .alpns(vec![TEST_ALPN.to_vec()])
-1899 .insecure_skip_relay_cert_verify(true)
-1900 .relay_mode(RelayMode::Custom(relay_map))
-1901 .bind()
-1902 .await?;
-1903 ep.online().await;
-1904let node_addr = ep.addr();
-1905 node_addr_tx.send(node_addr).unwrap();
-1906
-1907info!(me = %ep.id().fmt_short(), "server starting");
-1908let conn = ep.accept().await.anyerr()?.await.anyerr()?;
-1909info!(me = %ep.id().fmt_short(), "server accepted connection");
-1910
-1911// Wait for a relay connection to be added. Client does all the asserting here,
-1912 // we just want to wait so we get to see all the mechanics of the connection
-1913 // being added on this side too.
-1914let mut paths = conn.paths().stream();
-1915 time::timeout(Duration::from_secs(5), async move {
-1916while let Some(infos) = paths.next().await {
-1917info!(?infos, "new PathInfos");
-1918if infos.iter().any(|path| path.is_relay()) {
-1919info!("server has a relay path");
-1920break;
-1921 }
-1922 }
-1923 })
-1924 .await
-1925.anyerr()?;
-1926
-1927let mut stream = conn.open_uni().await.anyerr()?;
-1928 stream.write_all(b"have relay").await.anyerr()?;
-1929 stream.finish().anyerr()?;
-1930info!("waiting conn.closed()");
-1931
-1932Ok(conn.closed().await)
-1933 }
-1934
-1935let server_task = tokio::spawn(accept(relay_map.clone(), node_addr_tx));
-1936let client_task = tokio::spawn(connect(relay_map, node_addr_rx));
-1937
-1938 client_task.await.anyerr()??;
-1939let conn_closed = dbg!(server_task.await.anyerr()??);
-1940assert!(matches!(
-1941 conn_closed,
-1942 ConnectionError::ApplicationClosed(quinn::ApplicationClose { .. })
-1943 ));
-1944
-1945Ok(())
-1946 }
-1947
-1948#[tokio::test]
-1949 #[traced_test]
-1950async fn endpoint_relay_map_change() -> Result {
-1951let (relay_map, relay_url, _guard1) = run_relay_server().await?;
-1952let client = Endpoint::empty_builder(RelayMode::Custom(relay_map.clone()))
-1953 .insecure_skip_relay_cert_verify(true)
-1954 .bind()
-1955 .await?;
-1956let server = Endpoint::empty_builder(RelayMode::Custom(relay_map))
-1957 .insecure_skip_relay_cert_verify(true)
-1958 .alpns(vec![TEST_ALPN.to_vec()])
-1959 .bind()
-1960 .await?;
-1961
-1962let task = tokio::spawn({
-1963let server = server.clone();
-1964async move {
-1965for i in 0..2 {
-1966println!("accept: round {i}");
-1967let Some(conn) = server.accept().await else {
-1968n0_error::bail_any!("Expected an incoming connection");
-1969 };
-1970let conn = conn.await.anyerr()?;
-1971let (mut send, mut recv) = conn.accept_bi().await.anyerr()?;
-1972let data = recv.read_to_end(1000).await.anyerr()?;
-1973 send.write_all(&data).await.anyerr()?;
-1974 send.finish().anyerr()?;
-1975 conn.closed().await;
-1976 }
-1977Ok::<_, Error>(())
-1978 }
-1979 });
-1980
-1981 server.online().await;
+1581assert_eq!(&data, b"Hello, world!");
+1582
+1583Ok(())
+1584 }
+1585
+1586#[tokio::test]
+1587 #[traced_test]
+1588async fn endpoint_two_direct_only() -> Result {
+1589// Connect two endpoints on the same network, without a relay server, without
+1590 // discovery.
+1591let ep1 = {
+1592let span = info_span!("server");
+1593let _guard = span.enter();
+1594 Endpoint::builder()
+1595 .alpns(vec![TEST_ALPN.to_vec()])
+1596 .relay_mode(RelayMode::Disabled)
+1597 .bind()
+1598 .await?
+1599};
+1600let ep2 = {
+1601let span = info_span!("client");
+1602let _guard = span.enter();
+1603 Endpoint::builder()
+1604 .alpns(vec![TEST_ALPN.to_vec()])
+1605 .relay_mode(RelayMode::Disabled)
+1606 .bind()
+1607 .await?
+1608};
+1609let ep1_nodeaddr = ep1.addr();
+1610
+1611#[instrument(name = "client", skip_all)]
+1612async fn connect(ep: Endpoint, dst: EndpointAddr) -> Result<quinn::ConnectionError> {
+1613info!(me = %ep.id().fmt_short(), "client starting");
+1614let conn = ep.connect(dst, TEST_ALPN).await?;
+1615let mut send = conn.open_uni().await.anyerr()?;
+1616 send.write_all(b"hello").await.anyerr()?;
+1617 send.finish().anyerr()?;
+1618Ok(conn.closed().await)
+1619 }
+1620
+1621#[instrument(name = "server", skip_all)]
+1622async fn accept(ep: Endpoint, src: EndpointId) -> Result {
+1623info!(me = %ep.id().fmt_short(), "server starting");
+1624let conn = ep.accept().await.anyerr()?.await.anyerr()?;
+1625let node_id = conn.remote_id();
+1626assert_eq!(node_id, src);
+1627let mut recv = conn.accept_uni().await.anyerr()?;
+1628let msg = recv.read_to_end(100).await.anyerr()?;
+1629assert_eq!(msg, b"hello");
+1630// Dropping the connection closes it just fine.
+1631Ok(())
+1632 }
+1633
+1634let ep1_accept = tokio::spawn(accept(ep1.clone(), ep2.id()));
+1635let ep2_connect = tokio::spawn(connect(ep2.clone(), ep1_nodeaddr));
+1636
+1637 ep1_accept.await.anyerr()??;
+1638let conn_closed = dbg!(ep2_connect.await.anyerr()??);
+1639assert!(matches!(
+1640 conn_closed,
+1641 ConnectionError::ApplicationClosed(quinn::ApplicationClose { .. })
+1642 ));
+1643
+1644Ok(())
+1645 }
+1646
+1647#[tokio::test]
+1648 #[traced_test]
+1649async fn endpoint_two_relay_only_becomes_direct() -> Result {
+1650// Connect two endpoints on the same network, via a relay server, without
+1651 // discovery. Wait until there is a direct connection.
+1652let (relay_map, _relay_url, _relay_server_guard) = run_relay_server().await?;
+1653let (node_addr_tx, node_addr_rx) = oneshot::channel();
+1654
+1655#[instrument(name = "client", skip_all)]
+1656async fn connect(
+1657 relay_map: RelayMap,
+1658 node_addr_rx: oneshot::Receiver<EndpointAddr>,
+1659 ) -> Result<quinn::ConnectionError> {
+1660let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
+1661let secret = SecretKey::generate(&mut rng);
+1662let ep = Endpoint::builder()
+1663 .secret_key(secret)
+1664 .alpns(vec![TEST_ALPN.to_vec()])
+1665 .insecure_skip_relay_cert_verify(true)
+1666 .relay_mode(RelayMode::Custom(relay_map))
+1667 .bind()
+1668 .await?;
+1669info!(me = %ep.id().fmt_short(), "client starting");
+1670let dst = node_addr_rx.await.anyerr()?;
+1671
+1672info!(me = %ep.id().fmt_short(), "client connecting");
+1673let conn = ep.connect(dst, TEST_ALPN).await?;
+1674let mut send = conn.open_uni().await.anyerr()?;
+1675 send.write_all(b"hello").await.anyerr()?;
+1676let mut paths = conn.paths().stream();
+1677info!("Waiting for direct connection");
+1678while let Some(infos) = paths.next().await {
+1679info!(?infos, "new PathInfos");
+1680if infos.iter().any(|info| info.is_ip()) {
+1681break;
+1682 }
+1683 }
+1684info!("Have direct connection");
+1685 send.write_all(b"close please").await.anyerr()?;
+1686 send.finish().anyerr()?;
+1687Ok(conn.closed().await)
+1688 }
+1689
+1690#[instrument(name = "server", skip_all)]
+1691async fn accept(
+1692 relay_map: RelayMap,
+1693 node_addr_tx: oneshot::Sender<EndpointAddr>,
+1694 ) -> Result {
+1695let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1u64);
+1696let secret = SecretKey::generate(&mut rng);
+1697let ep = Endpoint::builder()
+1698 .secret_key(secret)
+1699 .alpns(vec![TEST_ALPN.to_vec()])
+1700 .insecure_skip_relay_cert_verify(true)
+1701 .relay_mode(RelayMode::Custom(relay_map))
+1702 .bind()
+1703 .await?;
+1704 ep.online().await;
+1705let mut node_addr = ep.addr();
+1706 node_addr.addrs.retain(|addr| addr.is_relay());
+1707 node_addr_tx.send(node_addr).unwrap();
+1708
+1709info!(me = %ep.id().fmt_short(), "server starting");
+1710let conn = ep.accept().await.anyerr()?.await.anyerr()?;
+1711// let node_id = conn.remote_node_id()?;
+1712 // assert_eq!(node_id, src);
+1713let mut recv = conn.accept_uni().await.anyerr()?;
+1714let mut msg = [0u8; 5];
+1715 recv.read_exact(&mut msg).await.anyerr()?;
+1716assert_eq!(&msg, b"hello");
+1717info!("received hello");
+1718let msg = recv.read_to_end(100).await.anyerr()?;
+1719assert_eq!(msg, b"close please");
+1720info!("received 'close please'");
+1721// Dropping the connection closes it just fine.
+1722Ok(())
+1723 }
+1724
+1725let server_task = tokio::spawn(accept(relay_map.clone(), node_addr_tx));
+1726let client_task = tokio::spawn(connect(relay_map, node_addr_rx));
+1727
+1728 server_task.await.anyerr()??;
+1729let conn_closed = dbg!(client_task.await.anyerr()??);
+1730assert!(matches!(
+1731 conn_closed,
+1732 ConnectionError::ApplicationClosed(quinn::ApplicationClose { .. })
+1733 ));
+1734
+1735Ok(())
+1736 }
+1737
+1738#[tokio::test]
+1739 #[traced_test]
+1740async fn endpoint_two_relay_only_no_ip() -> Result {
+1741// Connect two endpoints on the same network, via a relay server, without
+1742 // discovery.
+1743let (relay_map, _relay_url, _relay_server_guard) = run_relay_server().await?;
+1744let (node_addr_tx, node_addr_rx) = oneshot::channel();
+1745
+1746#[instrument(name = "client", skip_all)]
+1747async fn connect(
+1748 relay_map: RelayMap,
+1749 node_addr_rx: oneshot::Receiver<EndpointAddr>,
+1750 ) -> Result<quinn::ConnectionError> {
+1751let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
+1752let secret = SecretKey::generate(&mut rng);
+1753let ep = Endpoint::builder()
+1754 .secret_key(secret)
+1755 .alpns(vec![TEST_ALPN.to_vec()])
+1756 .insecure_skip_relay_cert_verify(true)
+1757 .relay_mode(RelayMode::Custom(relay_map))
+1758 .clear_ip_transports() // disable direct
+1759.bind()
+1760 .await?;
+1761info!(me = %ep.id().fmt_short(), "client starting");
+1762let dst = node_addr_rx.await.anyerr()?;
+1763
+1764info!(me = %ep.id().fmt_short(), "client connecting");
+1765let conn = ep.connect(dst, TEST_ALPN).await?;
+1766let mut send = conn.open_uni().await.anyerr()?;
+1767 send.write_all(b"hello").await.anyerr()?;
+1768let mut paths = conn.paths().stream();
+1769info!("Waiting for connection");
+1770'outer: while let Some(infos) = paths.next().await {
+1771info!(?infos, "new PathInfos");
+1772for info in infos {
+1773if info.is_ip() {
+1774panic!("should not happen: {:?}", info);
+1775 }
+1776if info.is_relay() {
+1777break 'outer;
+1778 }
+1779 }
+1780 }
+1781info!("Have relay connection");
+1782 send.write_all(b"close please").await.anyerr()?;
+1783 send.finish().anyerr()?;
+1784Ok(conn.closed().await)
+1785 }
+1786
+1787#[instrument(name = "server", skip_all)]
+1788async fn accept(
+1789 relay_map: RelayMap,
+1790 node_addr_tx: oneshot::Sender<EndpointAddr>,
+1791 ) -> Result {
+1792let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1u64);
+1793let secret = SecretKey::generate(&mut rng);
+1794let ep = Endpoint::builder()
+1795 .secret_key(secret)
+1796 .alpns(vec![TEST_ALPN.to_vec()])
+1797 .insecure_skip_relay_cert_verify(true)
+1798 .relay_mode(RelayMode::Custom(relay_map))
+1799 .clear_ip_transports()
+1800 .bind()
+1801 .await?;
+1802 ep.online().await;
+1803let node_addr = ep.addr();
+1804 node_addr_tx.send(node_addr).unwrap();
+1805
+1806info!(me = %ep.id().fmt_short(), "server starting");
+1807let conn = ep.accept().await.anyerr()?.await.anyerr()?;
+1808// let node_id = conn.remote_node_id()?;
+1809 // assert_eq!(node_id, src);
+1810let mut recv = conn.accept_uni().await.anyerr()?;
+1811let mut msg = [0u8; 5];
+1812 recv.read_exact(&mut msg).await.anyerr()?;
+1813assert_eq!(&msg, b"hello");
+1814info!("received hello");
+1815let msg = recv.read_to_end(100).await.anyerr()?;
+1816assert_eq!(msg, b"close please");
+1817info!("received 'close please'");
+1818// Dropping the connection closes it just fine.
+1819Ok(())
+1820 }
+1821
+1822let server_task = tokio::spawn(accept(relay_map.clone(), node_addr_tx));
+1823let client_task = tokio::spawn(connect(relay_map, node_addr_rx));
+1824
+1825 server_task.await.anyerr()??;
+1826let conn_closed = dbg!(client_task.await.anyerr()??);
+1827assert!(matches!(
+1828 conn_closed,
+1829 ConnectionError::ApplicationClosed(quinn::ApplicationClose { .. })
+1830 ));
+1831
+1832Ok(())
+1833 }
+1834
+1835#[tokio::test]
+1836 #[traced_test]
+1837async fn endpoint_two_direct_add_relay() -> Result {
+1838// Connect two endpoints on the same network, without relay server and without
+1839 // discovery. Add a relay connection later.
+1840let (relay_map, _relay_url, _relay_server_guard) = run_relay_server().await?;
+1841let (node_addr_tx, node_addr_rx) = oneshot::channel();
+1842
+1843#[instrument(name = "client", skip_all)]
+1844async fn connect(
+1845 relay_map: RelayMap,
+1846 node_addr_rx: oneshot::Receiver<EndpointAddr>,
+1847 ) -> Result<()> {
+1848let secret = SecretKey::from([0u8; 32]);
+1849let ep = Endpoint::builder()
+1850 .secret_key(secret)
+1851 .alpns(vec![TEST_ALPN.to_vec()])
+1852 .insecure_skip_relay_cert_verify(true)
+1853 .relay_mode(RelayMode::Custom(relay_map))
+1854 .bind()
+1855 .await?;
+1856info!(me = %ep.id().fmt_short(), "client starting");
+1857let dst = node_addr_rx.await.anyerr()?;
+1858
+1859info!(me = %ep.id().fmt_short(), "client connecting");
+1860let conn = ep.connect(dst, TEST_ALPN).await?;
+1861info!(me = %ep.id().fmt_short(), "client connected");
+1862
+1863// We should be connected via IP, because it is faster than the relay server.
+1864 // TODO: Maybe not panic if this is not true?
+1865let path_info = conn.paths().get();
+1866assert_eq!(path_info.len(), 1);
+1867assert!(path_info.iter().next().unwrap().is_ip());
+1868
+1869let mut paths = conn.paths().stream();
+1870 time::timeout(Duration::from_secs(5), async move {
+1871while let Some(infos) = paths.next().await {
+1872info!(?infos, "new PathInfos");
+1873if infos.iter().any(|info| info.is_relay()) {
+1874info!("client has a relay path");
+1875break;
+1876 }
+1877 }
+1878 })
+1879 .await
+1880.anyerr()?;
+1881
+1882// wait for the server to signal it has the relay connection
+1883let mut stream = conn.accept_uni().await.anyerr()?;
+1884 stream.read_to_end(100).await.anyerr()?;
+1885
+1886info!("client closing");
+1887 conn.close(0u8.into(), b"");
+1888 ep.close().await;
+1889Ok(())
+1890 }
+1891
+1892#[instrument(name = "server", skip_all)]
+1893async fn accept(
+1894 relay_map: RelayMap,
+1895 node_addr_tx: oneshot::Sender<EndpointAddr>,
+1896 ) -> Result<quinn::ConnectionError> {
+1897let secret = SecretKey::from([1u8; 32]);
+1898let ep = Endpoint::builder()
+1899 .secret_key(secret)
+1900 .alpns(vec![TEST_ALPN.to_vec()])
+1901 .insecure_skip_relay_cert_verify(true)
+1902 .relay_mode(RelayMode::Custom(relay_map))
+1903 .bind()
+1904 .await?;
+1905 ep.online().await;
+1906let node_addr = ep.addr();
+1907 node_addr_tx.send(node_addr).unwrap();
+1908
+1909info!(me = %ep.id().fmt_short(), "server starting");
+1910let conn = ep.accept().await.anyerr()?.await.anyerr()?;
+1911info!(me = %ep.id().fmt_short(), "server accepted connection");
+1912
+1913// Wait for a relay connection to be added. Client does all the asserting here,
+1914 // we just want to wait so we get to see all the mechanics of the connection
+1915 // being added on this side too.
+1916let mut paths = conn.paths().stream();
+1917 time::timeout(Duration::from_secs(5), async move {
+1918while let Some(infos) = paths.next().await {
+1919info!(?infos, "new PathInfos");
+1920if infos.iter().any(|path| path.is_relay()) {
+1921info!("server has a relay path");
+1922break;
+1923 }
+1924 }
+1925 })
+1926 .await
+1927.anyerr()?;
+1928
+1929let mut stream = conn.open_uni().await.anyerr()?;
+1930 stream.write_all(b"have relay").await.anyerr()?;
+1931 stream.finish().anyerr()?;
+1932info!("waiting conn.closed()");
+1933
+1934Ok(conn.closed().await)
+1935 }
+1936
+1937let server_task = tokio::spawn(accept(relay_map.clone(), node_addr_tx));
+1938let client_task = tokio::spawn(connect(relay_map, node_addr_rx));
+1939
+1940 client_task.await.anyerr()??;
+1941let conn_closed = dbg!(server_task.await.anyerr()??);
+1942assert!(matches!(
+1943 conn_closed,
+1944 ConnectionError::ApplicationClosed(quinn::ApplicationClose { .. })
+1945 ));
+1946
+1947Ok(())
+1948 }
+1949
+1950#[tokio::test]
+1951 #[traced_test]
+1952async fn endpoint_relay_map_change() -> Result {
+1953let (relay_map, relay_url, _guard1) = run_relay_server().await?;
+1954let client = Endpoint::empty_builder(RelayMode::Custom(relay_map.clone()))
+1955 .insecure_skip_relay_cert_verify(true)
+1956 .bind()
+1957 .await?;
+1958let server = Endpoint::empty_builder(RelayMode::Custom(relay_map))
+1959 .insecure_skip_relay_cert_verify(true)
+1960 .alpns(vec![TEST_ALPN.to_vec()])
+1961 .bind()
+1962 .await?;
+1963
+1964let task = tokio::spawn({
+1965let server = server.clone();
+1966async move {
+1967for i in 0..2 {
+1968println!("accept: round {i}");
+1969let Some(conn) = server.accept().await else {
+1970n0_error::bail_any!("Expected an incoming connection");
+1971 };
+1972let conn = conn.await.anyerr()?;
+1973let (mut send, mut recv) = conn.accept_bi().await.anyerr()?;
+1974let data = recv.read_to_end(1000).await.anyerr()?;
+1975 send.write_all(&data).await.anyerr()?;
+1976 send.finish().anyerr()?;
+1977 conn.closed().await;
+1978 }
+1979Ok::<_, Error>(())
+1980 }
+1981 });
1982
-1983let mut addr = server.addr();
-1984println!("round1: {:?}", addr);
-1985
-1986// remove direct addrs to force relay usage
-1987addr.addrs
-1988 .retain(|addr| !matches!(addr, TransportAddr::Ip(_)));
-1989
-1990let conn = client.connect(addr, TEST_ALPN).await?;
-1991let (mut send, mut recv) = conn.open_bi().await.anyerr()?;
-1992 send.write_all(b"Hello, world!").await.anyerr()?;
-1993 send.finish().anyerr()?;
-1994let data = recv.read_to_end(1000).await.anyerr()?;
-1995 conn.close(0u32.into(), b"bye!");
-1996
-1997assert_eq!(&data, b"Hello, world!");
+1983 server.online().await;
+1984
+1985let mut addr = server.addr();
+1986println!("round1: {:?}", addr);
+1987
+1988// remove direct addrs to force relay usage
+1989addr.addrs
+1990 .retain(|addr| !matches!(addr, TransportAddr::Ip(_)));
+1991
+1992let conn = client.connect(addr, TEST_ALPN).await?;
+1993let (mut send, mut recv) = conn.open_bi().await.anyerr()?;
+1994 send.write_all(b"Hello, world!").await.anyerr()?;
+1995 send.finish().anyerr()?;
+1996let data = recv.read_to_end(1000).await.anyerr()?;
+1997 conn.close(0u32.into(), b"bye!");
1998
-1999// setup a second relay server
-2000let (new_relay_map, new_relay_url, _guard2) = run_relay_server().await?;
-2001let new_endpoint = new_relay_map
-2002 .get(&new_relay_url)
-2003 .expect("missing endpoint")
-2004 .clone();
-2005dbg!(&new_relay_map);
-2006
-2007let addr_watcher = server.watch_addr();
+1999assert_eq!(&data, b"Hello, world!");
+2000
+2001// setup a second relay server
+2002let (new_relay_map, new_relay_url, _guard2) = run_relay_server().await?;
+2003let new_endpoint = new_relay_map
+2004 .get(&new_relay_url)
+2005 .expect("missing endpoint")
+2006 .clone();
+2007dbg!(&new_relay_map);
2008
-2009// add new new relay
-2010assert!(
-2011 server
-2012 .insert_relay(new_relay_url.clone(), new_endpoint.clone())
-2013 .await
-2014.is_none()
-2015 );
-2016// remove the old relay
-2017assert!(server.remove_relay(&relay_url).await.is_some());
-2018
-2019println!("------- changed ----- ");
+2009let addr_watcher = server.watch_addr();
+2010
+2011// add new new relay
+2012assert!(
+2013 server
+2014 .insert_relay(new_relay_url.clone(), new_endpoint.clone())
+2015 .await
+2016.is_none()
+2017 );
+2018// remove the old relay
+2019assert!(server.remove_relay(&relay_url).await.is_some());
2020
-2021let mut addr = tokio::time::timeout(Duration::from_secs(10), async move {
-2022let mut stream = addr_watcher.stream();
-2023while let Some(addr) = stream.next().await {
-2024if addr.relay_urls().next() != Some(&relay_url) {
-2025return addr;
-2026 }
-2027 }
-2028panic!("failed to change relay");
-2029 })
-2030 .await
-2031.anyerr()?;
-2032
-2033println!("round2: {:?}", addr);
-2034assert_eq!(addr.relay_urls().next(), Some(&new_relay_url));
-2035
-2036// remove direct addrs to force relay usage
-2037addr.addrs
-2038 .retain(|addr| !matches!(addr, TransportAddr::Ip(_)));
-2039
-2040let conn = client.connect(addr, TEST_ALPN).await?;
-2041let (mut send, mut recv) = conn.open_bi().await.anyerr()?;
-2042 send.write_all(b"Hello, world!").await.anyerr()?;
-2043 send.finish().anyerr()?;
-2044let data = recv.read_to_end(1000).await.anyerr()?;
-2045 conn.close(0u32.into(), b"bye!");
-2046
-2047 task.await.anyerr()??;
+2021println!("------- changed ----- ");
+2022
+2023let mut addr = tokio::time::timeout(Duration::from_secs(10), async move {
+2024let mut stream = addr_watcher.stream();
+2025while let Some(addr) = stream.next().await {
+2026if addr.relay_urls().next() != Some(&relay_url) {
+2027return addr;
+2028 }
+2029 }
+2030panic!("failed to change relay");
+2031 })
+2032 .await
+2033.anyerr()?;
+2034
+2035println!("round2: {:?}", addr);
+2036assert_eq!(addr.relay_urls().next(), Some(&new_relay_url));
+2037
+2038// remove direct addrs to force relay usage
+2039addr.addrs
+2040 .retain(|addr| !matches!(addr, TransportAddr::Ip(_)));
+2041
+2042let conn = client.connect(addr, TEST_ALPN).await?;
+2043let (mut send, mut recv) = conn.open_bi().await.anyerr()?;
+2044 send.write_all(b"Hello, world!").await.anyerr()?;
+2045 send.finish().anyerr()?;
+2046let data = recv.read_to_end(1000).await.anyerr()?;
+2047 conn.close(0u32.into(), b"bye!");
2048
-2049 client.close().await;
-2050 server.close().await;
-2051
-2052assert_eq!(&data, b"Hello, world!");
+2049 task.await.anyerr()??;
+2050
+2051 client.close().await;
+2052 server.close().await;
2053
-2054Ok(())
-2055 }
-2056
-2057#[tokio::test]
-2058 #[traced_test]
-2059async fn endpoint_bidi_send_recv() -> Result {
-2060let disco = StaticProvider::new();
-2061let ep1 = Endpoint::empty_builder(RelayMode::Disabled)
-2062 .discovery(disco.clone())
-2063 .alpns(vec![TEST_ALPN.to_vec()])
-2064 .bind()
-2065 .await?;
-2066
-2067let ep2 = Endpoint::empty_builder(RelayMode::Disabled)
-2068 .discovery(disco.clone())
-2069 .alpns(vec![TEST_ALPN.to_vec()])
-2070 .bind()
-2071 .await?;
-2072
-2073 disco.add_endpoint_info(ep1.addr());
-2074 disco.add_endpoint_info(ep2.addr());
-2075
-2076let ep1_endpointid = ep1.id();
-2077let ep2_endpointid = ep2.id();
-2078eprintln!("endpoint id 1 {ep1_endpointid}");
-2079eprintln!("endpoint id 2 {ep2_endpointid}");
-2080
-2081async fn connect_hello(ep: Endpoint, dst: EndpointId) -> Result {
-2082let conn = ep.connect(dst, TEST_ALPN).await?;
-2083let (mut send, mut recv) = conn.open_bi().await.anyerr()?;
-2084info!("sending hello");
-2085 send.write_all(b"hello").await.anyerr()?;
-2086 send.finish().anyerr()?;
-2087info!("receiving world");
-2088let m = recv.read_to_end(100).await.anyerr()?;
-2089assert_eq!(m, b"world");
-2090 conn.close(1u8.into(), b"done");
-2091Ok(())
-2092 }
-2093
-2094async fn accept_world(ep: Endpoint, src: EndpointId) -> Result {
-2095let incoming = ep.accept().await.anyerr()?;
-2096let mut iconn = incoming.accept().anyerr()?;
-2097let alpn = iconn.alpn().await?;
-2098let conn = iconn.await.anyerr()?;
-2099let endpoint_id = conn.remote_id();
-2100assert_eq!(endpoint_id, src);
-2101assert_eq!(alpn, TEST_ALPN);
-2102let (mut send, mut recv) = conn.accept_bi().await.anyerr()?;
-2103info!("receiving hello");
-2104let m = recv.read_to_end(100).await.anyerr()?;
-2105assert_eq!(m, b"hello");
-2106info!("sending hello");
-2107 send.write_all(b"world").await.anyerr()?;
-2108 send.finish().anyerr()?;
-2109match conn.closed().await {
-2110 ConnectionError::ApplicationClosed(closed) => {
-2111assert_eq!(closed.error_code, 1u8.into());
-2112Ok(())
-2113 }
-2114_ => panic!("wrong close error"),
-2115 }
-2116 }
-2117
-2118let p1_accept = tokio::spawn(accept_world(ep1.clone(), ep2_endpointid).instrument(
-2119info_span!(
-2120"p1_accept",
-2121 ep1 = %ep1.id().fmt_short(),
-2122 dst = %ep2_endpointid.fmt_short(),
-2123 ),
-2124 ));
-2125let p2_accept = tokio::spawn(accept_world(ep2.clone(), ep1_endpointid).instrument(
-2126info_span!(
-2127"p2_accept",
-2128 ep2 = %ep2.id().fmt_short(),
-2129 dst = %ep1_endpointid.fmt_short(),
-2130 ),
-2131 ));
-2132let p1_connect = tokio::spawn(connect_hello(ep1.clone(), ep2_endpointid).instrument(
-2133info_span!(
-2134"p1_connect",
-2135 ep1 = %ep1.id().fmt_short(),
-2136 dst = %ep2_endpointid.fmt_short(),
-2137 ),
-2138 ));
-2139let p2_connect = tokio::spawn(connect_hello(ep2.clone(), ep1_endpointid).instrument(
-2140info_span!(
-2141"p2_connect",
-2142 ep2 = %ep2.id().fmt_short(),
-2143 dst = %ep1_endpointid.fmt_short(),
-2144 ),
-2145 ));
-2146
-2147 p1_accept.await.anyerr()??;
-2148 p2_accept.await.anyerr()??;
-2149 p1_connect.await.anyerr()??;
-2150 p2_connect.await.anyerr()??;
-2151
-2152Ok(())
-2153 }
-2154
-2155#[tokio::test]
-2156 #[traced_test]
-2157async fn test_direct_addresses_no_qad_relay() -> Result {
-2158let (relay_map, _, _guard) = run_relay_server_with(false).await.unwrap();
-2159
-2160let ep = Endpoint::empty_builder(RelayMode::Custom(relay_map))
-2161 .alpns(vec![TEST_ALPN.to_vec()])
-2162 .insecure_skip_relay_cert_verify(true)
-2163 .bind()
-2164 .await?;
-2165
-2166assert!(ep.addr().ip_addrs().count() > 0);
+2054assert_eq!(&data, b"Hello, world!");
+2055
+2056Ok(())
+2057 }
+2058
+2059#[tokio::test]
+2060 #[traced_test]
+2061async fn endpoint_bidi_send_recv() -> Result {
+2062let disco = StaticProvider::new();
+2063let ep1 = Endpoint::empty_builder(RelayMode::Disabled)
+2064 .discovery(disco.clone())
+2065 .alpns(vec![TEST_ALPN.to_vec()])
+2066 .bind()
+2067 .await?;
+2068
+2069let ep2 = Endpoint::empty_builder(RelayMode::Disabled)
+2070 .discovery(disco.clone())
+2071 .alpns(vec![TEST_ALPN.to_vec()])
+2072 .bind()
+2073 .await?;
+2074
+2075 disco.add_endpoint_info(ep1.addr());
+2076 disco.add_endpoint_info(ep2.addr());
+2077
+2078let ep1_endpointid = ep1.id();
+2079let ep2_endpointid = ep2.id();
+2080eprintln!("endpoint id 1 {ep1_endpointid}");
+2081eprintln!("endpoint id 2 {ep2_endpointid}");
+2082
+2083async fn connect_hello(ep: Endpoint, dst: EndpointId) -> Result {
+2084let conn = ep.connect(dst, TEST_ALPN).await?;
+2085let (mut send, mut recv) = conn.open_bi().await.anyerr()?;
+2086info!("sending hello");
+2087 send.write_all(b"hello").await.anyerr()?;
+2088 send.finish().anyerr()?;
+2089info!("receiving world");
+2090let m = recv.read_to_end(100).await.anyerr()?;
+2091assert_eq!(m, b"world");
+2092 conn.close(1u8.into(), b"done");
+2093Ok(())
+2094 }
+2095
+2096async fn accept_world(ep: Endpoint, src: EndpointId) -> Result {
+2097let incoming = ep.accept().await.anyerr()?;
+2098let mut iconn = incoming.accept().anyerr()?;
+2099let alpn = iconn.alpn().await?;
+2100let conn = iconn.await.anyerr()?;
+2101let endpoint_id = conn.remote_id();
+2102assert_eq!(endpoint_id, src);
+2103assert_eq!(alpn, TEST_ALPN);
+2104let (mut send, mut recv) = conn.accept_bi().await.anyerr()?;
+2105info!("receiving hello");
+2106let m = recv.read_to_end(100).await.anyerr()?;
+2107assert_eq!(m, b"hello");
+2108info!("sending hello");
+2109 send.write_all(b"world").await.anyerr()?;
+2110 send.finish().anyerr()?;
+2111match conn.closed().await {
+2112 ConnectionError::ApplicationClosed(closed) => {
+2113assert_eq!(closed.error_code, 1u8.into());
+2114Ok(())
+2115 }
+2116_ => panic!("wrong close error"),
+2117 }
+2118 }
+2119
+2120let p1_accept = tokio::spawn(accept_world(ep1.clone(), ep2_endpointid).instrument(
+2121info_span!(
+2122"p1_accept",
+2123 ep1 = %ep1.id().fmt_short(),
+2124 dst = %ep2_endpointid.fmt_short(),
+2125 ),
+2126 ));
+2127let p2_accept = tokio::spawn(accept_world(ep2.clone(), ep1_endpointid).instrument(
+2128info_span!(
+2129"p2_accept",
+2130 ep2 = %ep2.id().fmt_short(),
+2131 dst = %ep1_endpointid.fmt_short(),
+2132 ),
+2133 ));
+2134let p1_connect = tokio::spawn(connect_hello(ep1.clone(), ep2_endpointid).instrument(
+2135info_span!(
+2136"p1_connect",
+2137 ep1 = %ep1.id().fmt_short(),
+2138 dst = %ep2_endpointid.fmt_short(),
+2139 ),
+2140 ));
+2141let p2_connect = tokio::spawn(connect_hello(ep2.clone(), ep1_endpointid).instrument(
+2142info_span!(
+2143"p2_connect",
+2144 ep2 = %ep2.id().fmt_short(),
+2145 dst = %ep1_endpointid.fmt_short(),
+2146 ),
+2147 ));
+2148
+2149 p1_accept.await.anyerr()??;
+2150 p2_accept.await.anyerr()??;
+2151 p1_connect.await.anyerr()??;
+2152 p2_connect.await.anyerr()??;
+2153
+2154Ok(())
+2155 }
+2156
+2157#[tokio::test]
+2158 #[traced_test]
+2159async fn test_direct_addresses_no_qad_relay() -> Result {
+2160let (relay_map, _, _guard) = run_relay_server_with(false).await.unwrap();
+2161
+2162let ep = Endpoint::empty_builder(RelayMode::Custom(relay_map))
+2163 .alpns(vec![TEST_ALPN.to_vec()])
+2164 .insecure_skip_relay_cert_verify(true)
+2165 .bind()
+2166 .await?;
2167
-2168Ok(())
-2169 }
-2170
-2171#[cfg_attr(target_os = "windows", ignore = "flaky")]
-2172 #[tokio::test]
-2173 #[traced_test]
-2174async fn graceful_close() -> Result {
-2175let client = Endpoint::empty_builder(RelayMode::Disabled).bind().await?;
-2176let server = Endpoint::empty_builder(RelayMode::Disabled)
-2177 .alpns(vec![TEST_ALPN.to_vec()])
-2178 .bind()
-2179 .await?;
-2180let server_addr = server.addr();
-2181let server_task = tokio::spawn(async move {
-2182let incoming = server.accept().await.anyerr()?;
-2183let conn = incoming.await.anyerr()?;
-2184let (mut send, mut recv) = conn.accept_bi().await.anyerr()?;
-2185let msg = recv.read_to_end(1_000).await.anyerr()?;
-2186 send.write_all(&msg).await.anyerr()?;
-2187 send.finish().anyerr()?;
-2188let close_reason = conn.closed().await;
-2189Ok::<_, Error>(close_reason)
-2190 });
-2191
-2192let conn = client.connect(server_addr, TEST_ALPN).await?;
-2193let (mut send, mut recv) = conn.open_bi().await.anyerr()?;
-2194 send.write_all(b"Hello, world!").await.anyerr()?;
-2195 send.finish().anyerr()?;
-2196 recv.read_to_end(1_000).await.anyerr()?;
-2197 conn.close(42u32.into(), b"thanks, bye!");
-2198 client.close().await;
-2199
-2200let close_err = server_task.await.anyerr()??;
-2201let ConnectionError::ApplicationClosed(app_close) = close_err else {
-2202panic!("Unexpected close reason: {close_err:?}");
-2203 };
-2204
-2205assert_eq!(app_close.error_code, 42u32.into());
-2206assert_eq!(app_close.reason.as_ref(), b"thanks, bye!");
-2207
-2208Ok(())
-2209 }
-2210
-2211#[cfg(feature = "metrics")]
-2212 #[tokio::test]
-2213 #[traced_test]
-2214async fn metrics_smoke() -> Result {
-2215use iroh_metrics::Registry;
-2216
-2217let secret_key = SecretKey::from_bytes(&[0u8; 32]);
-2218let client = Endpoint::empty_builder(RelayMode::Disabled)
-2219 .secret_key(secret_key)
-2220 .bind()
-2221 .await?;
-2222let secret_key = SecretKey::from_bytes(&[1u8; 32]);
-2223let server = Endpoint::empty_builder(RelayMode::Disabled)
-2224 .secret_key(secret_key)
-2225 .alpns(vec![TEST_ALPN.to_vec()])
-2226 .bind()
-2227 .await?;
-2228let server_addr = server.addr();
-2229let server_task = tokio::task::spawn(async move {
-2230let conn = server.accept().await.anyerr()?.await.anyerr()?;
-2231let mut uni = conn.accept_uni().await.anyerr()?;
-2232 uni.read_to_end(10).await.anyerr()?;
-2233 drop(conn);
-2234Ok::<_, Error>(server)
-2235 });
-2236let conn = client.connect(server_addr, TEST_ALPN).await?;
-2237let mut uni = conn.open_uni().await.anyerr()?;
-2238 uni.write_all(b"helloworld").await.anyerr()?;
-2239 uni.finish().anyerr()?;
-2240 conn.closed().await;
-2241 drop(conn);
-2242let server = server_task.await.anyerr()??;
-2243
-2244let m = client.metrics();
-2245// assert_eq!(m.magicsock.num_direct_conns_added.get(), 1);
-2246 // assert_eq!(m.magicsock.connection_became_direct.get(), 1);
-2247 // assert_eq!(m.magicsock.connection_handshake_success.get(), 1);
-2248 // assert_eq!(m.magicsock.endpoints_contacted_directly.get(), 1);
-2249assert!(m.magicsock.recv_datagrams.get() > 0);
-2250
-2251let m = server.metrics();
-2252// assert_eq!(m.magicsock.num_direct_conns_added.get(), 1);
-2253 // assert_eq!(m.magicsock.connection_became_direct.get(), 1);
-2254 // assert_eq!(m.magicsock.endpoints_contacted_directly.get(), 1);
-2255 // assert_eq!(m.magicsock.connection_handshake_success.get(), 1);
-2256assert!(m.magicsock.recv_datagrams.get() > 0);
-2257
-2258// test openmetrics encoding with labeled subregistries per endpoint
-2259fn register_endpoint(registry: &mut Registry, endpoint: &Endpoint) {
-2260let id = endpoint.id().fmt_short();
-2261let sub_registry = registry.sub_registry_with_label("id", id.to_string());
-2262 sub_registry.register_all(endpoint.metrics());
-2263 }
-2264let mut registry = Registry::default();
-2265 register_endpoint(&mut registry, &client);
-2266 register_endpoint(&mut registry, &server);
-2267// let s = registry.encode_openmetrics_to_string().anyerr()?;
-2268 // assert!(s.contains(r#"magicsock_endpoints_contacted_directly_total{id="3b6a27bcce"} 1"#));
-2269 // assert!(s.contains(r#"magicsock_endpoints_contacted_directly_total{id="8a88e3dd74"} 1"#));
-2270Ok(())
-2271 }
-2272
-2273/// Configures the accept side to take `accept_alpns` ALPNs, then connects to it with `primary_connect_alpn`
-2274 /// with `secondary_connect_alpns` set, and finally returns the negotiated ALPN.
-2275async fn alpn_connection_test(
-2276 accept_alpns: Vec<Vec<u8>>,
-2277 primary_connect_alpn: &[u8],
-2278 secondary_connect_alpns: Vec<Vec<u8>>,
-2279 ) -> Result<Vec<u8>> {
-2280let client = Endpoint::empty_builder(RelayMode::Disabled).bind().await?;
-2281let server = Endpoint::empty_builder(RelayMode::Disabled)
-2282 .alpns(accept_alpns)
-2283 .bind()
-2284 .await?;
-2285let server_addr = server.addr();
-2286let server_task = tokio::spawn({
-2287let server = server.clone();
-2288async move {
-2289let incoming = server.accept().await.anyerr()?;
-2290let conn = incoming.await.anyerr()?;
-2291 conn.close(0u32.into(), b"bye!");
-2292 n0_error::Ok(conn.alpn().to_vec())
-2293 }
-2294 });
-2295
-2296let conn = client
-2297 .connect_with_opts(
-2298 server_addr,
-2299 primary_connect_alpn,
-2300 ConnectOptions::new().with_additional_alpns(secondary_connect_alpns),
-2301 )
-2302 .await?;
-2303let conn = conn.await.anyerr()?;
-2304let client_alpn = conn.alpn();
-2305 conn.closed().await;
-2306 client.close().await;
-2307 server.close().await;
-2308
-2309let server_alpn = server_task.await.anyerr()??;
+2168assert!(ep.addr().ip_addrs().count() > 0);
+2169
+2170Ok(())
+2171 }
+2172
+2173#[cfg_attr(target_os = "windows", ignore = "flaky")]
+2174 #[tokio::test]
+2175 #[traced_test]
+2176async fn graceful_close() -> Result {
+2177let client = Endpoint::empty_builder(RelayMode::Disabled).bind().await?;
+2178let server = Endpoint::empty_builder(RelayMode::Disabled)
+2179 .alpns(vec![TEST_ALPN.to_vec()])
+2180 .bind()
+2181 .await?;
+2182let server_addr = server.addr();
+2183let server_task = tokio::spawn(async move {
+2184let incoming = server.accept().await.anyerr()?;
+2185let conn = incoming.await.anyerr()?;
+2186let (mut send, mut recv) = conn.accept_bi().await.anyerr()?;
+2187let msg = recv.read_to_end(1_000).await.anyerr()?;
+2188 send.write_all(&msg).await.anyerr()?;
+2189 send.finish().anyerr()?;
+2190let close_reason = conn.closed().await;
+2191Ok::<_, Error>(close_reason)
+2192 });
+2193
+2194let conn = client.connect(server_addr, TEST_ALPN).await?;
+2195let (mut send, mut recv) = conn.open_bi().await.anyerr()?;
+2196 send.write_all(b"Hello, world!").await.anyerr()?;
+2197 send.finish().anyerr()?;
+2198 recv.read_to_end(1_000).await.anyerr()?;
+2199 conn.close(42u32.into(), b"thanks, bye!");
+2200 client.close().await;
+2201
+2202let close_err = server_task.await.anyerr()??;
+2203let ConnectionError::ApplicationClosed(app_close) = close_err else {
+2204panic!("Unexpected close reason: {close_err:?}");
+2205 };
+2206
+2207assert_eq!(app_close.error_code, 42u32.into());
+2208assert_eq!(app_close.reason.as_ref(), b"thanks, bye!");
+2209
+2210Ok(())
+2211 }
+2212
+2213#[cfg(feature = "metrics")]
+2214 #[tokio::test]
+2215 #[traced_test]
+2216async fn metrics_smoke() -> Result {
+2217use iroh_metrics::Registry;
+2218
+2219let secret_key = SecretKey::from_bytes(&[0u8; 32]);
+2220let client = Endpoint::empty_builder(RelayMode::Disabled)
+2221 .secret_key(secret_key)
+2222 .bind()
+2223 .await?;
+2224let secret_key = SecretKey::from_bytes(&[1u8; 32]);
+2225let server = Endpoint::empty_builder(RelayMode::Disabled)
+2226 .secret_key(secret_key)
+2227 .alpns(vec![TEST_ALPN.to_vec()])
+2228 .bind()
+2229 .await?;
+2230let server_addr = server.addr();
+2231let server_task = tokio::task::spawn(async move {
+2232let conn = server.accept().await.anyerr()?.await.anyerr()?;
+2233let mut uni = conn.accept_uni().await.anyerr()?;
+2234 uni.read_to_end(10).await.anyerr()?;
+2235 drop(conn);
+2236Ok::<_, Error>(server)
+2237 });
+2238let conn = client.connect(server_addr, TEST_ALPN).await?;
+2239let mut uni = conn.open_uni().await.anyerr()?;
+2240 uni.write_all(b"helloworld").await.anyerr()?;
+2241 uni.finish().anyerr()?;
+2242 conn.closed().await;
+2243 drop(conn);
+2244let server = server_task.await.anyerr()??;
+2245
+2246let m = client.metrics();
+2247// assert_eq!(m.magicsock.num_direct_conns_added.get(), 1);
+2248 // assert_eq!(m.magicsock.connection_became_direct.get(), 1);
+2249 // assert_eq!(m.magicsock.connection_handshake_success.get(), 1);
+2250 // assert_eq!(m.magicsock.endpoints_contacted_directly.get(), 1);
+2251assert!(m.magicsock.recv_datagrams.get() > 0);
+2252
+2253let m = server.metrics();
+2254// assert_eq!(m.magicsock.num_direct_conns_added.get(), 1);
+2255 // assert_eq!(m.magicsock.connection_became_direct.get(), 1);
+2256 // assert_eq!(m.magicsock.endpoints_contacted_directly.get(), 1);
+2257 // assert_eq!(m.magicsock.connection_handshake_success.get(), 1);
+2258assert!(m.magicsock.recv_datagrams.get() > 0);
+2259
+2260// test openmetrics encoding with labeled subregistries per endpoint
+2261fn register_endpoint(registry: &mut Registry, endpoint: &Endpoint) {
+2262let id = endpoint.id().fmt_short();
+2263let sub_registry = registry.sub_registry_with_label("id", id.to_string());
+2264 sub_registry.register_all(endpoint.metrics());
+2265 }
+2266let mut registry = Registry::default();
+2267 register_endpoint(&mut registry, &client);
+2268 register_endpoint(&mut registry, &server);
+2269// let s = registry.encode_openmetrics_to_string().anyerr()?;
+2270 // assert!(s.contains(r#"magicsock_endpoints_contacted_directly_total{id="3b6a27bcce"} 1"#));
+2271 // assert!(s.contains(r#"magicsock_endpoints_contacted_directly_total{id="8a88e3dd74"} 1"#));
+2272Ok(())
+2273 }
+2274
+2275/// Configures the accept side to take `accept_alpns` ALPNs, then connects to it with `primary_connect_alpn`
+2276 /// with `secondary_connect_alpns` set, and finally returns the negotiated ALPN.
+2277async fn alpn_connection_test(
+2278 accept_alpns: Vec<Vec<u8>>,
+2279 primary_connect_alpn: &[u8],
+2280 secondary_connect_alpns: Vec<Vec<u8>>,
+2281 ) -> Result<Vec<u8>> {
+2282let client = Endpoint::empty_builder(RelayMode::Disabled).bind().await?;
+2283let server = Endpoint::empty_builder(RelayMode::Disabled)
+2284 .alpns(accept_alpns)
+2285 .bind()
+2286 .await?;
+2287let server_addr = server.addr();
+2288let server_task = tokio::spawn({
+2289let server = server.clone();
+2290async move {
+2291let incoming = server.accept().await.anyerr()?;
+2292let conn = incoming.await.anyerr()?;
+2293 conn.close(0u32.into(), b"bye!");
+2294 n0_error::Ok(conn.alpn().to_vec())
+2295 }
+2296 });
+2297
+2298let conn = client
+2299 .connect_with_opts(
+2300 server_addr,
+2301 primary_connect_alpn,
+2302 ConnectOptions::new().with_additional_alpns(secondary_connect_alpns),
+2303 )
+2304 .await?;
+2305let conn = conn.await.anyerr()?;
+2306let client_alpn = conn.alpn();
+2307 conn.closed().await;
+2308 client.close().await;
+2309 server.close().await;
2310
-2311assert_eq!(client_alpn, server_alpn);
+2311let server_alpn = server_task.await.anyerr()??;
2312
-2313Ok(server_alpn.to_vec())
-2314 }
-2315
-2316#[tokio::test]
-2317 #[traced_test]
-2318async fn connect_multiple_alpn_negotiated() -> Result {
-2319const ALPN_ONE: &[u8] = b"alpn/1";
-2320const ALPN_TWO: &[u8] = b"alpn/2";
-2321
-2322assert_eq!(
-2323 alpn_connection_test(
-2324// Prefer version 2 over version 1 on the accept side
-2325vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()],
-2326 ALPN_TWO,
-2327vec![ALPN_ONE.to_vec()],
-2328 )
-2329 .await?,
-2330 ALPN_TWO.to_vec(),
-2331"accept side prefers version 2 over 1"
-2332);
-2333
-2334assert_eq!(
-2335 alpn_connection_test(
-2336// Only support the old version
-2337vec![ALPN_ONE.to_vec()],
-2338 ALPN_TWO,
-2339vec![ALPN_ONE.to_vec()],
-2340 )
-2341 .await?,
-2342 ALPN_ONE.to_vec(),
-2343"accept side only supports the old version"
-2344);
-2345
-2346assert_eq!(
-2347 alpn_connection_test(
-2348vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()],
-2349 ALPN_ONE,
-2350vec![ALPN_TWO.to_vec()],
-2351 )
-2352 .await?,
-2353 ALPN_TWO.to_vec(),
-2354"connect side ALPN order doesn't matter"
-2355);
-2356
-2357assert_eq!(
-2358 alpn_connection_test(vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], ALPN_ONE, vec![],)
-2359 .await?,
-2360 ALPN_ONE.to_vec(),
-2361"connect side only supports the old version"
-2362);
-2363
-2364Ok(())
-2365 }
-2366
-2367#[tokio::test]
-2368 #[traced_test]
-2369async fn watch_net_report() -> Result {
-2370let endpoint = Endpoint::empty_builder(RelayMode::Staging).bind().await?;
-2371
-2372// can get a first report
-2373endpoint.net_report().updated().await.anyerr()?;
-2374
-2375Ok(())
-2376 }
-2377
-2378/// Tests that initial connection establishment isn't extremely slow compared
-2379 /// to subsequent connections.
-2380 ///
-2381 /// This is a time based test, but uses a very large ratio to reduce flakiness.
-2382 /// It also does a number of connections to average out any anomalies.
-2383#[tokio::test]
-2384 #[traced_test]
-2385async fn connect_multi_time() -> Result {
-2386let n = 32;
-2387
-2388const NOOP_ALPN: &[u8] = b"noop";
+2313assert_eq!(client_alpn, server_alpn);
+2314
+2315Ok(server_alpn.to_vec())
+2316 }
+2317
+2318#[tokio::test]
+2319 #[traced_test]
+2320async fn connect_multiple_alpn_negotiated() -> Result {
+2321const ALPN_ONE: &[u8] = b"alpn/1";
+2322const ALPN_TWO: &[u8] = b"alpn/2";
+2323
+2324assert_eq!(
+2325 alpn_connection_test(
+2326// Prefer version 2 over version 1 on the accept side
+2327vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()],
+2328 ALPN_TWO,
+2329vec![ALPN_ONE.to_vec()],
+2330 )
+2331 .await?,
+2332 ALPN_TWO.to_vec(),
+2333"accept side prefers version 2 over 1"
+2334);
+2335
+2336assert_eq!(
+2337 alpn_connection_test(
+2338// Only support the old version
+2339vec![ALPN_ONE.to_vec()],
+2340 ALPN_TWO,
+2341vec![ALPN_ONE.to_vec()],
+2342 )
+2343 .await?,
+2344 ALPN_ONE.to_vec(),
+2345"accept side only supports the old version"
+2346);
+2347
+2348assert_eq!(
+2349 alpn_connection_test(
+2350vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()],
+2351 ALPN_ONE,
+2352vec![ALPN_TWO.to_vec()],
+2353 )
+2354 .await?,
+2355 ALPN_TWO.to_vec(),
+2356"connect side ALPN order doesn't matter"
+2357);
+2358
+2359assert_eq!(
+2360 alpn_connection_test(vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], ALPN_ONE, vec![],)
+2361 .await?,
+2362 ALPN_ONE.to_vec(),
+2363"connect side only supports the old version"
+2364);
+2365
+2366Ok(())
+2367 }
+2368
+2369#[tokio::test]
+2370 #[traced_test]
+2371async fn watch_net_report() -> Result {
+2372let endpoint = Endpoint::empty_builder(RelayMode::Staging).bind().await?;
+2373
+2374// can get a first report
+2375endpoint.net_report().updated().await.anyerr()?;
+2376
+2377Ok(())
+2378 }
+2379
+2380/// Tests that initial connection establishment isn't extremely slow compared
+2381 /// to subsequent connections.
+2382 ///
+2383 /// This is a time based test, but uses a very large ratio to reduce flakiness.
+2384 /// It also does a number of connections to average out any anomalies.
+2385#[tokio::test]
+2386 #[traced_test]
+2387async fn connect_multi_time() -> Result {
+2388let n = 32;
2389
-2390#[derive(Debug, Clone)]
-2391struct Noop;
-2392
-2393impl ProtocolHandler for Noop {
-2394async fn accept(&self, connection: Connection) -> Result<(), AcceptError> {
-2395 connection.closed().await;
-2396Ok(())
-2397 }
-2398 }
-2399
-2400async fn noop_server() -> Result<(Router, EndpointAddr)> {
-2401let endpoint = Endpoint::empty_builder(RelayMode::Disabled)
-2402 .bind()
-2403 .await
-2404.anyerr()?;
-2405let addr = endpoint.addr();
-2406let router = Router::builder(endpoint).accept(NOOP_ALPN, Noop).spawn();
-2407Ok((router, addr))
-2408 }
-2409
-2410let routers = stream::iter(0..n)
-2411 .map(|_| noop_server())
-2412 .buffered_unordered(32)
-2413 .collect::<Vec<_>>()
-2414 .await
-2415.into_iter()
-2416 .collect::<Result<Vec<_>, _>>()
-2417 .anyerr()?;
-2418
-2419let addrs = routers
-2420 .iter()
-2421 .map(|(_, addr)| addr.clone())
-2422 .collect::<Vec<_>>();
-2423let ids = addrs.iter().map(|addr| addr.id).collect::<Vec<_>>();
-2424let discovery = StaticProvider::from_endpoint_info(addrs);
-2425let endpoint = Endpoint::empty_builder(RelayMode::Disabled)
-2426 .discovery(discovery)
-2427 .bind()
-2428 .await
-2429.anyerr()?;
-2430// wait for the endpoint to be initialized. This should not be needed,
-2431 // but we don't want to measure endpoint init time but connection time
-2432 // from a fully initialized endpoint.
-2433endpoint.addr();
-2434let t0 = Instant::now();
-2435for id in &ids {
-2436let conn = endpoint.connect(*id, NOOP_ALPN).await?;
-2437 conn.close(0u32.into(), b"done");
-2438 }
-2439let dt0 = t0.elapsed().as_secs_f64();
-2440let t1 = Instant::now();
-2441for id in &ids {
-2442let conn = endpoint.connect(*id, NOOP_ALPN).await?;
-2443 conn.close(0u32.into(), b"done");
-2444 }
-2445let dt1 = t1.elapsed().as_secs_f64();
-2446
-2447assert!(dt0 / dt1 < 20.0, "First round: {dt0}s, second round {dt1}s");
-2448Ok(())
-2449 }
-2450}
\ No newline at end of file
+2390const NOOP_ALPN: &[u8] = b"noop";
+2391
+2392#[derive(Debug, Clone)]
+2393struct Noop;
+2394
+2395impl ProtocolHandler for Noop {
+2396async fn accept(&self, connection: Connection) -> Result<(), AcceptError> {
+2397 connection.closed().await;
+2398Ok(())
+2399 }
+2400 }
+2401
+2402async fn noop_server() -> Result<(Router, EndpointAddr)> {
+2403let endpoint = Endpoint::empty_builder(RelayMode::Disabled)
+2404 .bind()
+2405 .await
+2406.anyerr()?;
+2407let addr = endpoint.addr();
+2408let router = Router::builder(endpoint).accept(NOOP_ALPN, Noop).spawn();
+2409Ok((router, addr))
+2410 }
+2411
+2412let routers = stream::iter(0..n)
+2413 .map(|_| noop_server())
+2414 .buffered_unordered(32)
+2415 .collect::<Vec<_>>()
+2416 .await
+2417.into_iter()
+2418 .collect::<Result<Vec<_>, _>>()
+2419 .anyerr()?;
+2420
+2421let addrs = routers
+2422 .iter()
+2423 .map(|(_, addr)| addr.clone())
+2424 .collect::<Vec<_>>();
+2425let ids = addrs.iter().map(|addr| addr.id).collect::<Vec<_>>();
+2426let discovery = StaticProvider::from_endpoint_info(addrs);
+2427let endpoint = Endpoint::empty_builder(RelayMode::Disabled)
+2428 .discovery(discovery)
+2429 .bind()
+2430 .await
+2431.anyerr()?;
+2432// wait for the endpoint to be initialized. This should not be needed,
+2433 // but we don't want to measure endpoint init time but connection time
+2434 // from a fully initialized endpoint.
+2435endpoint.addr();
+2436let t0 = Instant::now();
+2437for id in &ids {
+2438let conn = endpoint.connect(*id, NOOP_ALPN).await?;
+2439 conn.close(0u32.into(), b"done");
+2440 }
+2441let dt0 = t0.elapsed().as_secs_f64();
+2442let t1 = Instant::now();
+2443for id in &ids {
+2444let conn = endpoint.connect(*id, NOOP_ALPN).await?;
+2445 conn.close(0u32.into(), b"done");
+2446 }
+2447let dt1 = t1.elapsed().as_secs_f64();
+2448
+2449assert!(dt0 / dt1 < 20.0, "First round: {dt0}s, second round {dt1}s");
+2450Ok(())
+2451 }
+2452}
\ No newline at end of file
diff --git a/pr/3666/docs/src/iroh/endpoint/connection.rs.html b/pr/3666/docs/src/iroh/endpoint/connection.rs.html
index 2c0628e95a..41bb9ac757 100644
--- a/pr/3666/docs/src/iroh/endpoint/connection.rs.html
+++ b/pr/3666/docs/src/iroh/endpoint/connection.rs.html
@@ -512,840 +512,841 @@
512 .inner
513 .into_0rtt()
514 .expect("incoming connections can always be converted to 0-RTT");
-515let accepted: BoxFuture<_> = Box::pin({
-516let quinn_conn = quinn_conn.clone();
-517async move {
-518 zrtt_accepted.await;
-519let conn = conn_from_quinn_conn(quinn_conn, &self.ep)?.await?;
-520Ok(conn)
-521 }
-522 });
-523let accepted = accepted.shared();
-524 IncomingZeroRttConnection {
-525 inner: quinn_conn,
-526 data: IncomingZeroRttData { accepted },
-527 }
-528 }
-529
-530/// Parameters negotiated during the handshake
-531pub async fn handshake_data(&mut self) -> Result<Box<dyn Any>, ConnectionError> {
-532self.inner.handshake_data().await
-533}
-534
-535/// Extracts the ALPN protocol from the peer's handshake data.
-536pub async fn alpn(&mut self) -> Result<Vec<u8>, AlpnError> {
-537 alpn_from_quinn_connecting(&mut self.inner).await
-538}
-539}
-540
-541impl Future for Accepting {
-542type Output = Result<Connection, ConnectingError>;
-543
-544fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
-545loop {
-546if let Some(fut) = &mut self.register_with_magicsock {
-547return fut.poll_unpin(cx).map_err(Into::into);
-548 } else {
-549let quinn_conn = std::task::ready!(self.inner.poll_unpin(cx)?);
-550match conn_from_quinn_conn(quinn_conn, &self.ep) {
-551Err(err) => return Poll::Ready(Err(err)),
-552Ok(fut) => self.register_with_magicsock = Some(Box::pin(fut.err_into())),
-553 };
-554 }
-555 }
-556 }
-557}
-558
-559/// The client side of a 0-RTT connection.
-560///
-561/// This is created using [`Connecting::into_0rtt`].
+515
+516let accepted: BoxFuture<_> = Box::pin({
+517let quinn_conn = quinn_conn.clone();
+518async move {
+519let _ = zrtt_accepted.await;
+520let conn = conn_from_quinn_conn(quinn_conn, &self.ep)?.await?;
+521Ok(conn)
+522 }
+523 });
+524let accepted = accepted.shared();
+525
+526 IncomingZeroRttConnection {
+527 inner: quinn_conn,
+528 data: IncomingZeroRttData { accepted },
+529 }
+530 }
+531
+532/// Parameters negotiated during the handshake
+533pub async fn handshake_data(&mut self) -> Result<Box<dyn Any>, ConnectionError> {
+534self.inner.handshake_data().await
+535}
+536
+537/// Extracts the ALPN protocol from the peer's handshake data.
+538pub async fn alpn(&mut self) -> Result<Vec<u8>, AlpnError> {
+539 alpn_from_quinn_connecting(&mut self.inner).await
+540}
+541}
+542
+543impl Future for Accepting {
+544type Output = Result<Connection, ConnectingError>;
+545
+546fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
+547loop {
+548if let Some(fut) = &mut self.register_with_magicsock {
+549return fut.poll_unpin(cx).map_err(Into::into);
+550 } else {
+551let quinn_conn = std::task::ready!(self.inner.poll_unpin(cx)?);
+552match conn_from_quinn_conn(quinn_conn, &self.ep) {
+553Err(err) => return Poll::Ready(Err(err)),
+554Ok(fut) => self.register_with_magicsock = Some(Box::pin(fut.err_into())),
+555 };
+556 }
+557 }
+558 }
+559}
+560
+561/// The client side of a 0-RTT connection.
562///
-563/// Creating a `OutgoingZeroRttConnection` means that the endpoint is capable
-564/// of attempting a 0-RTT connection with the remote. The remote may still
-565/// reject the 0-RTT connection. In which case, any data sent before the
-566/// handshake has completed may need to be resent.
-567///
-568/// Look at the [`OutgoingZeroRttConnection::handshake_completed`] method for
-569/// more details.
-570pub type OutgoingZeroRttConnection = Connection<OutgoingZeroRtt>;
-571
-572/// Returned from [`OutgoingZeroRttConnection::handshake_completed`].
-573#[derive(Debug, Clone)]
-574pub enum ZeroRttStatus {
-575/// If the 0-RTT data was accepted, you can continue to use any streams
-576 /// that were created before the handshake was completed.
-577Accepted(Connection),
-578/// If the 0-RTT data was rejected, any streams that were created before
-579 /// the handshake was completed will error and any data that was
-580 /// previously sent on those streams will need to be resent.
-581Rejected(Connection),
-582}
-583
-584/// A QUIC connection on the server-side that can possibly accept 0-RTT data.
-585///
-586/// It is very similar to a `Connection`, but the `IncomingZeroRttConnection::remote_id`
-587/// and `IncomingZeroRttConnection::alpn` may not be set yet, since the handshake has
-588/// not necessarily occurred yet.
-589///
-590/// If the `IncomingZeroRttConnection` has rejected 0-RTT or does not have enough information
-591/// to accept 0-RTT, any received 0-RTT packets will simply be dropped before
-592/// reaching any receive streams.
-593///
-594/// Any streams that are created to send or receive data can continue to be used
-595/// even after the handshake has completed and we are no longer in a 0-RTT
-596/// situation.
-597///
-598/// Use the [`IncomingZeroRttConnection::handshake_completed`] method to get a [`Connection`] from a
-599/// `IncomingZeroRttConnection`. This waits until 0-RTT connection has completed
-600/// the handshake and can now confidently derive the ALPN and the
-601/// [`EndpointId`] of the remote endpoint.
-602pub type IncomingZeroRttConnection = Connection<IncomingZeroRtt>;
-603
-604/// A QUIC connection.
-605///
-606/// If all references to a connection (including every clone of the Connection handle,
-607/// streams of incoming streams, and the various stream types) have been dropped, then the
-608/// connection will be automatically closed with an error_code of 0 and an empty reason. You
-609/// can also close the connection explicitly by calling [`Connection::close`].
-610///
-611/// Closing the connection immediately abandons efforts to deliver data to the peer. Upon
-612/// receiving CONNECTION_CLOSE the peer may drop any stream data not yet delivered to the
-613/// application. [`Connection::close`] describes in more detail how to gracefully close a
-614/// connection without losing application data.
-615///
-616/// May be cloned to obtain another handle to the same connection.
-617#[derive(Debug, Clone)]
-618pub struct Connection<State: ConnectionState = HandshakeCompleted> {
-619 inner: quinn::Connection,
-620/// State-specific information
-621data: State::Data,
-622}
-623
-624#[doc(hidden)]
-625#[derive(Debug, Clone)]
-626pub struct HandshakeCompletedData {
-627 info: StaticInfo,
-628 paths: PathsWatcher,
-629}
-630
-631/// Static info from a completed TLS handshake.
-632#[derive(Debug, Clone)]
-633struct StaticInfo {
-634 endpoint_id: EndpointId,
-635 alpn: Vec<u8>,
-636}
-637
-638#[doc(hidden)]
-639#[derive(Debug, Clone)]
-640pub struct IncomingZeroRttData {
-641 accepted: Shared<BoxFuture<Result<Connection, ConnectingError>>>,
-642}
-643
-644#[doc(hidden)]
-645#[derive(Debug, Clone)]
-646pub struct OutgoingZeroRttData {
-647 accepted: Shared<BoxFuture<Result<ZeroRttStatus, ConnectingError>>>,
-648}
-649
-650mod sealed {
-651pub trait Sealed {}
-652}
-653
-654/// Trait to track the state of a [`Connection`] at compile time.
-655pub trait ConnectionState: sealed::Sealed {
-656/// State-specific data stored in the [`Connection`].
-657type Data: std::fmt::Debug + Clone;
-658}
-659
-660/// Marker type for a connection that has completed the handshake.
-661#[derive(Debug, Clone)]
-662pub struct HandshakeCompleted;
-663
-664/// Marker type for a connection that is in the incoming 0-RTT state.
-665#[derive(Debug, Clone)]
-666pub struct IncomingZeroRtt;
-667
-668/// Marker type for a connection that is in the outgoing 0-RTT state.
-669#[derive(Debug, Clone)]
-670pub struct OutgoingZeroRtt;
-671
-672impl sealed::Sealed for HandshakeCompleted {}
-673impl ConnectionState for HandshakeCompleted {
-674type Data = HandshakeCompletedData;
-675}
-676
-677impl sealed::Sealed for IncomingZeroRtt {}
-678impl ConnectionState for IncomingZeroRtt {
-679type Data = IncomingZeroRttData;
-680}
-681
-682impl sealed::Sealed for OutgoingZeroRtt {}
-683impl ConnectionState for OutgoingZeroRtt {
-684type Data = OutgoingZeroRttData;
-685}
-686
-687#[allow(missing_docs)]
-688#[stack_error(add_meta, derive)]
-689#[error("Protocol error: no remote id available")]
-690#[derive(Clone)]
-691pub struct RemoteEndpointIdError;
-692
-693impl<T: ConnectionState> Connection<T> {
-694/// Initiates a new outgoing unidirectional stream.
-695 ///
-696 /// Streams are cheap and instantaneous to open unless blocked by flow control. As a
-697 /// consequence, the peer won’t be notified that a stream has been opened until the
-698 /// stream is actually used.
-699#[inline]
-700pub fn open_uni(&self) -> OpenUni<'_> {
-701self.inner.open_uni()
-702 }
-703
-704/// Initiates a new outgoing bidirectional stream.
-705 ///
-706 /// Streams are cheap and instantaneous to open unless blocked by flow control. As a
-707 /// consequence, the peer won't be notified that a stream has been opened until the
-708 /// stream is actually used. Calling [`open_bi`] then waiting on the [`RecvStream`]
-709 /// without writing anything to [`SendStream`] will never succeed.
-710 ///
-711 /// [`open_bi`]: Connection::open_bi
-712 /// [`SendStream`]: quinn::SendStream
-713 /// [`RecvStream`]: quinn::RecvStream
-714#[inline]
-715pub fn open_bi(&self) -> OpenBi<'_> {
-716self.inner.open_bi()
-717 }
-718
-719/// Accepts the next incoming uni-directional stream.
-720#[inline]
-721pub fn accept_uni(&self) -> AcceptUni<'_> {
-722self.inner.accept_uni()
-723 }
-724
-725/// Accept the next incoming bidirectional stream.
-726 ///
-727 /// **Important Note**: The peer that calls [`open_bi`] must write to its [`SendStream`]
-728 /// before the peer `Connection` is able to accept the stream using
-729 /// `accept_bi()`. Calling [`open_bi`] then waiting on the [`RecvStream`] without
-730 /// writing anything to the connected [`SendStream`] will never succeed.
-731 ///
-732 /// [`open_bi`]: Connection::open_bi
-733 /// [`SendStream`]: quinn::SendStream
-734 /// [`RecvStream`]: quinn::RecvStream
-735#[inline]
-736pub fn accept_bi(&self) -> AcceptBi<'_> {
-737self.inner.accept_bi()
-738 }
-739
-740/// Receives an application datagram.
-741#[inline]
-742pub fn read_datagram(&self) -> ReadDatagram<'_> {
-743self.inner.read_datagram()
-744 }
-745
-746/// Wait for the connection to be closed for any reason.
-747 ///
-748 /// Despite the return type's name, closed connections are often not an error condition
-749 /// at the application layer. Cases that might be routine include
-750 /// [`ConnectionError::LocallyClosed`] and [`ConnectionError::ApplicationClosed`].
-751#[inline]
-752pub async fn closed(&self) -> ConnectionError {
-753self.inner.closed().await
-754}
-755
-756/// If the connection is closed, the reason why.
-757 ///
-758 /// Returns `None` if the connection is still open.
-759#[inline]
-760pub fn close_reason(&self) -> Option<ConnectionError> {
-761self.inner.close_reason()
-762 }
-763
-764/// Closes the connection immediately.
-765 ///
-766 /// Pending operations will fail immediately with [`ConnectionError::LocallyClosed`]. No
-767 /// more data is sent to the peer and the peer may drop buffered data upon receiving the
-768 /// CONNECTION_CLOSE frame.
-769 ///
-770 /// `error_code` and `reason` are not interpreted, and are provided directly to the
-771 /// peer.
-772 ///
-773 /// `reason` will be truncated to fit in a single packet with overhead; to improve odds
-774 /// that it is preserved in full, it should be kept under 1KiB.
-775 ///
-776 /// # Gracefully closing a connection
-777 ///
-778 /// Only the peer last receiving application data can be certain that all data is
-779 /// delivered. The only reliable action it can then take is to close the connection,
-780 /// potentially with a custom error code. The delivery of the final CONNECTION_CLOSE
-781 /// frame is very likely if both endpoints stay online long enough, calling
-782 /// [`Endpoint::close`] will wait to provide sufficient time. Otherwise, the remote peer
-783 /// will time out the connection, provided that the idle timeout is not disabled.
-784 ///
-785 /// The sending side can not guarantee all stream data is delivered to the remote
-786 /// application. It only knows the data is delivered to the QUIC stack of the remote
-787 /// endpoint. Once the local side sends a CONNECTION_CLOSE frame in response to calling
-788 /// [`close`] the remote endpoint may drop any data it received but is as yet
-789 /// undelivered to the application, including data that was acknowledged as received to
-790 /// the local endpoint.
-791 ///
-792 /// [`close`]: Connection::close
-793#[inline]
-794pub fn close(&self, error_code: VarInt, reason: &[u8]) {
-795self.inner.close(error_code, reason)
-796 }
-797
-798/// Transmits `data` as an unreliable, unordered application datagram.
-799 ///
-800 /// Application datagrams are a low-level primitive. They may be lost or delivered out
-801 /// of order, and `data` must both fit inside a single QUIC packet and be smaller than
-802 /// the maximum dictated by the peer.
-803#[inline]
-804pub fn send_datagram(&self, data: bytes::Bytes) -> Result<(), SendDatagramError> {
-805self.inner.send_datagram(data)
-806 }
-807
-808// TODO: It seems `SendDatagram` is not yet exposed by quinn. This has been fixed
-809 // upstream and will be in the next release.
-810 // /// Transmits `data` as an unreliable, unordered application datagram
-811 // ///
-812 // /// Unlike [`send_datagram()`], this method will wait for buffer space during congestion
-813 // /// conditions, which effectively prioritizes old datagrams over new datagrams.
-814 // ///
-815 // /// See [`send_datagram()`] for details.
-816 // ///
-817 // /// [`send_datagram()`]: Connection::send_datagram
-818 // #[inline]
-819 // pub fn send_datagram_wait(&self, data: bytes::Bytes) -> SendDatagram<'_> {
-820 // self.inner.send_datagram_wait(data)
-821 // }
-822
-823/// Computes the maximum size of datagrams that may be passed to [`send_datagram`].
-824 ///
-825 /// Returns `None` if datagrams are unsupported by the peer or disabled locally.
-826 ///
-827 /// This may change over the lifetime of a connection according to variation in the path
-828 /// MTU estimate. The peer can also enforce an arbitrarily small fixed limit, but if the
-829 /// peer's limit is large this is guaranteed to be a little over a kilobyte at minimum.
-830 ///
-831 /// Not necessarily the maximum size of received datagrams.
-832 ///
-833 /// [`send_datagram`]: Self::send_datagram
-834#[inline]
-835pub fn max_datagram_size(&self) -> Option<usize> {
-836self.inner.max_datagram_size()
-837 }
-838
-839/// Bytes available in the outgoing datagram buffer.
-840 ///
-841 /// When greater than zero, calling [`send_datagram`] with a
-842 /// datagram of at most this size is guaranteed not to cause older datagrams to be
-843 /// dropped.
-844 ///
-845 /// [`send_datagram`]: Self::send_datagram
-846#[inline]
-847pub fn datagram_send_buffer_space(&self) -> usize {
-848self.inner.datagram_send_buffer_space()
-849 }
-850
-851/// Current best estimate of this connection's latency (round-trip-time).
-852#[inline]
-853pub fn rtt(&self) -> Duration {
-854self.inner.rtt()
-855 }
-856
-857/// Returns connection statistics.
-858#[inline]
-859pub fn stats(&self) -> ConnectionStats {
-860self.inner.stats()
-861 }
-862
-863/// Current state of the congestion control algorithm, for debugging purposes.
-864#[inline]
-865pub fn congestion_state(&self) -> Box<dyn quinn_proto::congestion::Controller> {
-866self.inner.congestion_state()
-867 }
-868
-869/// Parameters negotiated during the handshake.
-870 ///
-871 /// Guaranteed to return `Some` on fully established connections or after
-872 /// [`Connecting::handshake_data()`] succeeds. See that method's documentations for
-873 /// details on the returned value.
-874 ///
-875 /// [`Connection::handshake_data()`]: crate::endpoint::Connecting::handshake_data
-876#[inline]
-877pub fn handshake_data(&self) -> Option<Box<dyn Any>> {
-878self.inner.handshake_data()
-879 }
-880
-881/// Cryptographic identity of the peer.
-882 ///
-883 /// The dynamic type returned is determined by the configured [`Session`]. For the
-884 /// default `rustls` session, the return value can be [`downcast`] to a
-885 /// <code>Vec<[rustls::pki_types::CertificateDer]></code>
-886 ///
-887 /// [`Session`]: quinn_proto::crypto::Session
-888 /// [`downcast`]: Box::downcast
-889#[inline]
-890pub fn peer_identity(&self) -> Option<Box<dyn Any>> {
-891self.inner.peer_identity()
-892 }
-893
-894/// A stable identifier for this connection.
-895 ///
-896 /// Peer addresses and connection IDs can change, but this value will remain fixed for
-897 /// the lifetime of the connection.
-898#[inline]
-899pub fn stable_id(&self) -> usize {
-900self.inner.stable_id()
-901 }
-902
-903/// Derives keying material from this connection's TLS session secrets.
-904 ///
-905 /// When both peers call this method with the same `label` and `context`
-906 /// arguments and `output` buffers of equal length, they will get the
-907 /// same sequence of bytes in `output`. These bytes are cryptographically
-908 /// strong and pseudorandom, and are suitable for use as keying material.
-909 ///
-910 /// See [RFC5705](https://tools.ietf.org/html/rfc5705) for more information.
-911#[inline]
-912pub fn export_keying_material(
-913&self,
-914 output: &mut [u8],
-915 label: &[u8],
-916 context: &[u8],
-917 ) -> Result<(), quinn_proto::crypto::ExportKeyingMaterialError> {
-918self.inner.export_keying_material(output, label, context)
-919 }
-920
-921/// Modifies the number of unidirectional streams that may be concurrently opened.
-922 ///
-923 /// No streams may be opened by the peer unless fewer than `count` are already
-924 /// open. Large `count`s increase both minimum and worst-case memory consumption.
-925#[inline]
-926pub fn set_max_concurrent_uni_streams(&self, count: VarInt) {
-927self.inner.set_max_concurrent_uni_streams(count)
-928 }
-929
-930/// See [`quinn_proto::TransportConfig::receive_window`].
-931#[inline]
-932pub fn set_receive_window(&self, receive_window: VarInt) {
-933self.inner.set_receive_window(receive_window)
-934 }
-935
-936/// Modifies the number of bidirectional streams that may be concurrently opened.
-937 ///
-938 /// No streams may be opened by the peer unless fewer than `count` are already
-939 /// open. Large `count`s increase both minimum and worst-case memory consumption.
-940#[inline]
-941pub fn set_max_concurrent_bi_streams(&self, count: VarInt) {
-942self.inner.set_max_concurrent_bi_streams(count)
-943 }
-944}
-945
-946impl Connection<HandshakeCompleted> {
-947/// Extracts the ALPN protocol from the peer's handshake data.
-948pub fn alpn(&self) -> &[u8] {
-949&self.data.info.alpn
-950 }
-951
-952/// Returns the [`EndpointId`] from the peer's TLS certificate.
-953 ///
-954 /// The [`PublicKey`] of an endpoint is also known as an [`EndpointId`]. This [`PublicKey`] is
-955 /// included in the TLS certificate presented during the handshake when connecting.
-956 /// This function allows you to get the [`EndpointId`] of the remote endpoint of this
-957 /// connection.
-958 ///
-959 /// [`PublicKey`]: iroh_base::PublicKey
-960pub fn remote_id(&self) -> EndpointId {
-961self.data.info.endpoint_id
-962 }
-963
-964/// Returns a [`Watcher`] for the network paths of this connection.
-965 ///
-966 /// A connection can have several network paths to the remote endpoint, commonly there
-967 /// will be a path via the relay server and a holepunched path.
-968 ///
-969 /// The watcher is updated whenever a path is opened or closed, or when the path selected
-970 /// for transmission changes (see [`PathInfo::is_selected`]).
-971 ///
-972 /// The [`PathInfoList`] returned from the watcher contains a [`PathInfo`] for each
-973 /// transmission path.
-974 ///
-975 /// [`PathInfo::is_selected`]: crate::magicsock::PathInfo::is_selected
-976 /// [`PathInfo`]: crate::magicsock::PathInfo
-977pub fn paths(&self) -> impl Watcher<Value = PathInfoList> + Unpin + Send + Sync + 'static {
-978self.data.paths.clone()
-979 }
-980}
-981
-982impl Connection<IncomingZeroRtt> {
-983/// Extracts the ALPN protocol from the peer's handshake data.
-984pub fn alpn(&self) -> Option<Vec<u8>> {
-985 alpn_from_quinn_conn(&self.inner)
-986 }
-987
-988/// Waits until the full handshake occurs and then returns a [`Connection`].
-989 ///
-990 /// This may fail with [`ConnectingError::ConnectionError`], if there was
-991 /// some general failure with the connection, such as a network timeout since
-992 /// we accepted the connection.
-993 ///
-994 /// This may fail with [`ConnectingError::HandshakeFailure`], if the other side
-995 /// doesn't use the right TLS authentication, which usually every iroh endpoint
-996 /// uses and requires.
-997 ///
-998 /// Thus, those errors should only occur if someone connects to you with a
-999 /// modified iroh endpoint or with a plain QUIC client.
-1000pub async fn handshake_completed(&self) -> Result<Connection, ConnectingError> {
-1001self.data.accepted.clone().await
-1002}
-1003}
-1004
-1005impl Connection<OutgoingZeroRtt> {
-1006/// Extracts the ALPN protocol from the peer's handshake data.
-1007pub fn alpn(&self) -> Option<Vec<u8>> {
-1008 alpn_from_quinn_conn(&self.inner)
-1009 }
-1010
-1011/// Waits until the full handshake occurs and returns a [`ZeroRttStatus`].
-1012 ///
-1013 /// If `ZeroRttStatus::Accepted` is returned, than any streams created before
-1014 /// the handshake has completed can still be used.
-1015 ///
-1016 /// If `ZeroRttStatus::Rejected` is returned, than any streams created before
-1017 /// the handshake will error and any data sent should be re-sent on a
-1018 /// new stream.
-1019 ///
-1020 /// This may fail with [`ConnectingError::ConnectionError`], if there was
-1021 /// some general failure with the connection, such as a network timeout since
-1022 /// we initiated the connection.
-1023 ///
-1024 /// This may fail with [`ConnectingError::HandshakeFailure`], if the other side
-1025 /// doesn't use the right TLS authentication, which usually every iroh endpoint
-1026 /// uses and requires.
-1027 ///
-1028 /// Thus, those errors should only occur if someone connects to you with a
-1029 /// modified iroh endpoint or with a plain QUIC client.
-1030pub async fn handshake_completed(&self) -> Result<ZeroRttStatus, ConnectingError> {
-1031self.data.accepted.clone().await
-1032}
-1033}
-1034
-1035#[cfg(test)]
-1036mod tests {
-1037use std::time::Duration;
-1038
-1039use iroh_base::{EndpointAddr, SecretKey};
-1040use n0_error::{Result, StackResultExt, StdResultExt};
-1041use n0_future::StreamExt;
-1042use n0_watcher::Watcher;
-1043use rand::SeedableRng;
-1044use tracing::{Instrument, error_span, info, info_span, trace_span};
-1045use tracing_test::traced_test;
-1046
-1047use super::Endpoint;
-1048use crate::{
-1049 RelayMode,
-1050 endpoint::{ConnectOptions, Incoming, PathInfo, PathInfoList, ZeroRttStatus},
-1051 test_utils::run_relay_server,
-1052 };
-1053
-1054const TEST_ALPN: &[u8] = b"n0/iroh/test";
-1055
-1056async fn spawn_0rtt_server(secret_key: SecretKey, log_span: tracing::Span) -> Result<Endpoint> {
-1057let server = Endpoint::empty_builder(RelayMode::Disabled)
-1058 .secret_key(secret_key)
-1059 .alpns(vec![TEST_ALPN.to_vec()])
-1060 .bind()
-1061 .instrument(log_span.clone())
-1062 .await?;
-1063
-1064async fn handle_incoming(incoming: Incoming) -> Result {
-1065let accepting = incoming
-1066 .accept()
-1067 .std_context("Failed to accept incoming connection")?;
-1068
-1069// accept a possible 0-RTT connection
-1070let zrtt_conn = accepting.into_0rtt();
-1071
-1072let (mut send, mut recv) = zrtt_conn
-1073 .accept_bi()
-1074 .await
-1075.std_context("failed to accept bi stream")?;
-1076
-1077let data = recv
-1078 .read_to_end(10_000_000)
-1079 .await
-1080.std_context("Failed to read data")?;
-1081
-1082 send.write_all(&data)
-1083 .await
-1084.std_context("Failed to write data")?;
-1085 send.finish().std_context("Failed to finish send")?;
-1086
-1087// Stay alive until the other side closes the connection.
-1088zrtt_conn.closed().await;
-1089Ok(())
-1090 }
-1091
-1092// Gets aborted via the endpoint closing causing an `Err`
-1093 // a simple echo server
-1094tokio::spawn({
-1095let server = server.clone();
-1096async move {
-1097tracing::trace!("Server accept loop started");
-1098while let Some(incoming) = server.accept().await {
-1099tracing::trace!("Server received incoming connection");
-1100// Handle connection errors gracefully instead of exiting the task
-1101if let Err(e) = handle_incoming(incoming).await {
-1102tracing::warn!("Failure while handling connection: {e:#}");
-1103 }
-1104tracing::trace!("Connection closed, ready for next");
-1105 }
-1106tracing::trace!("Server accept loop exiting");
-1107 n0_error::Ok(())
-1108 }
-1109 .instrument(log_span)
-1110 });
-1111
-1112Ok(server)
-1113 }
-1114
-1115async fn connect_client_0rtt_expect_err(
-1116 client: &Endpoint,
-1117 server_addr: EndpointAddr,
-1118 ) -> Result {
-1119let conn = client
-1120 .connect_with_opts(server_addr, TEST_ALPN, ConnectOptions::new())
-1121 .await?
-1122.into_0rtt()
-1123 .expect_err("expected 0-RTT to fail")
-1124 .await?;
-1125
-1126let (mut send, mut recv) = conn.open_bi().await.anyerr()?;
-1127 send.write_all(b"hello").await.anyerr()?;
-1128 send.finish().anyerr()?;
-1129let received = recv.read_to_end(1_000).await.anyerr()?;
-1130assert_eq!(&received, b"hello");
-1131 conn.close(0u32.into(), b"thx");
-1132Ok(())
-1133 }
-1134
-1135async fn connect_client_0rtt_expect_ok(
-1136 client: &Endpoint,
-1137 server_addr: EndpointAddr,
-1138 expect_server_accepts: bool,
-1139 ) -> Result {
-1140tracing::trace!(?server_addr, "Client connecting with 0-RTT");
-1141let zrtt_conn = client
-1142 .connect_with_opts(server_addr, TEST_ALPN, ConnectOptions::new())
-1143 .await
-1144.context("connect")?
-1145.into_0rtt()
-1146 .ok()
-1147 .context("into_0rtt")?;
-1148
-1149tracing::trace!("Client established 0-RTT connection");
-1150// This is how we send data in 0-RTT:
-1151let (mut send, mut recv) = zrtt_conn.open_bi().await.anyerr()?;
-1152 send.write_all(b"hello").await.anyerr()?;
-1153 send.finish().anyerr()?;
-1154tracing::trace!("Client sent 0-RTT data, waiting for server response");
-1155// When this resolves, we've gotten a response from the server about whether the 0-RTT data above was accepted:
-1156let zrtt_res = zrtt_conn.handshake_completed().await;
-1157tracing::trace!(?zrtt_res, "Server responded to 0-RTT");
-1158let zrtt_res = zrtt_res.context("handshake completed")?;
-1159let conn = match zrtt_res {
-1160 ZeroRttStatus::Accepted(conn) => {
-1161assert!(expect_server_accepts);
-1162 conn
-1163 }
-1164 ZeroRttStatus::Rejected(conn) => {
-1165assert!(!expect_server_accepts);
-1166// in this case we need to re-send data by re-creating the stream.
-1167let (mut send, r) = conn.open_bi().await.anyerr()?;
-1168 send.write_all(b"hello").await.anyerr()?;
-1169 send.finish().anyerr()?;
-1170 recv = r;
-1171 conn
-1172 }
-1173 };
-1174let received = recv.read_to_end(1_000).await.anyerr()?;
-1175assert_eq!(&received, b"hello");
-1176 conn.close(0u32.into(), b"thx");
-1177Ok(())
-1178 }
-1179
-1180#[tokio::test]
-1181 #[traced_test]
-1182async fn test_0rtt() -> Result {
-1183let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42);
-1184let client = Endpoint::empty_builder(RelayMode::Disabled).bind().await?;
-1185let server = spawn_0rtt_server(SecretKey::generate(&mut rng), info_span!("server")).await?;
-1186
-1187 connect_client_0rtt_expect_err(&client, server.addr()).await?;
-1188// The second 0rtt attempt should work
-1189connect_client_0rtt_expect_ok(&client, server.addr(), true).await?;
-1190
-1191 client.close().await;
-1192 server.close().await;
-1193
-1194Ok(())
-1195 }
-1196
-1197// We have this test, as this would've failed at some point.
-1198 // This effectively tests that we correctly categorize the TLS session tickets we
-1199 // receive into the respective "bucket" for the recipient.
-1200#[tokio::test]
-1201 #[traced_test]
-1202async fn test_0rtt_non_consecutive() -> Result {
-1203let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42);
-1204let client = Endpoint::empty_builder(RelayMode::Disabled).bind().await?;
-1205let server = spawn_0rtt_server(SecretKey::generate(&mut rng), info_span!("server")).await?;
-1206
-1207 connect_client_0rtt_expect_err(&client, server.addr()).await?;
-1208
-1209// connecting with another endpoint should not interfere with our
-1210 // TLS session ticket cache for the first endpoint:
-1211let another =
-1212 spawn_0rtt_server(SecretKey::generate(&mut rng), info_span!("another")).await?;
-1213 connect_client_0rtt_expect_err(&client, another.addr()).await?;
-1214 another.close().await;
-1215
-1216 connect_client_0rtt_expect_ok(&client, server.addr(), true).await?;
-1217
-1218 client.close().await;
-1219 server.close().await;
-1220
-1221Ok(())
-1222 }
-1223
-1224// Test whether 0-RTT is possible after a restart:
-1225#[tokio::test]
-1226 #[traced_test]
-1227async fn test_0rtt_after_server_restart() -> Result {
-1228let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42);
-1229let client = Endpoint::empty_builder(RelayMode::Disabled)
-1230 .bind()
-1231 .instrument(info_span!("client"))
-1232 .await?;
-1233let server_key = SecretKey::generate(&mut rng);
-1234let server = spawn_0rtt_server(server_key.clone(), info_span!("server-initial")).await?;
-1235
-1236 connect_client_0rtt_expect_err(&client, server.addr())
-1237 .instrument(trace_span!("connect1"))
-1238 .await
-1239.context("client connect 1")?;
-1240 connect_client_0rtt_expect_ok(&client, server.addr(), true)
-1241 .instrument(trace_span!("connect2"))
-1242 .await
-1243.context("client connect 2")?;
-1244
-1245// adds time to the test, but we need to ensure the server is fully closed before spawning the next one.
-1246server.close().await;
-1247
-1248let server = spawn_0rtt_server(server_key, info_span!("server-restart")).await?;
-1249
-1250// we expect the client to *believe* it can 0-RTT connect to the server (hence expect_ok),
-1251 // but the server will reject the early data because it discarded necessary state
-1252 // to decrypt it when restarting.
-1253connect_client_0rtt_expect_ok(&client, server.addr(), false)
-1254 .instrument(trace_span!("connect3"))
-1255 .await
-1256.context("client connect 3")?;
-1257
-1258tokio::join!(client.close(), server.close());
-1259Ok(())
-1260 }
-1261
-1262#[tokio::test]
-1263 #[traced_test]
-1264async fn test_paths_watcher() -> Result {
-1265const ALPN: &[u8] = b"test";
-1266let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
-1267let (relay_map, _relay_map, _guard) = run_relay_server().await?;
-1268let server = Endpoint::empty_builder(RelayMode::Custom(relay_map.clone()))
-1269 .secret_key(SecretKey::generate(&mut rng))
-1270 .insecure_skip_relay_cert_verify(true)
-1271 .alpns(vec![ALPN.to_vec()])
-1272 .bind()
-1273 .await?;
-1274
-1275let client = Endpoint::empty_builder(RelayMode::Custom(relay_map.clone()))
-1276 .secret_key(SecretKey::generate(&mut rng))
-1277 .insecure_skip_relay_cert_verify(true)
-1278 .bind()
-1279 .await?;
-1280
-1281 server.online().await;
-1282let server_addr = server.addr();
-1283info!("server addr: {server_addr:?}");
-1284
-1285let (conn_client, conn_server) = tokio::join!(
-1286async { client.connect(server_addr, ALPN).await.unwrap() },
-1287async { server.accept().await.unwrap().await.unwrap() }
-1288 );
-1289info!("connected");
-1290let mut paths_client = conn_client.paths().stream();
-1291let mut paths_server = conn_server.paths().stream();
-1292
-1293/// Advances the path stream until at least one IP and one relay paths are available.
-1294 ///
-1295 /// Panics if the path stream finishes before that happens.
-1296async fn wait_for_paths(
-1297 stream: &mut n0_watcher::Stream<impl n0_watcher::Watcher<Value = PathInfoList> + Unpin>,
-1298 ) {
-1299loop {
-1300let paths = stream.next().await.expect("paths stream ended");
-1301info!(?paths, "paths");
-1302if paths.len() >= 2
-1303&& paths.iter().any(PathInfo::is_relay)
-1304 && paths.iter().any(PathInfo::is_ip)
-1305 {
-1306info!("break");
-1307return;
-1308 }
-1309 }
-1310 }
-1311
-1312// Verify that both connections are notified of path changes and get an IP and a relay path.
-1313tokio::join!(
-1314async {
-1315 tokio::time::timeout(Duration::from_secs(1), wait_for_paths(&mut paths_server))
-1316 .instrument(error_span!("paths-server"))
-1317 .await
-1318.unwrap()
-1319 },
-1320async {
-1321 tokio::time::timeout(Duration::from_secs(1), wait_for_paths(&mut paths_client))
-1322 .instrument(error_span!("paths-client"))
-1323 .await
-1324.unwrap()
-1325 }
-1326 );
-1327
-1328// Close the client connection.
-1329info!("close client conn");
-1330 conn_client.close(0u32.into(), b"");
-1331
-1332// Verify that the path watch streams close.
-1333assert_eq!(
-1334 tokio::time::timeout(Duration::from_secs(1), paths_client.next())
-1335 .await
-1336.unwrap(),
-1337None
-1338);
-1339assert_eq!(
-1340 tokio::time::timeout(Duration::from_secs(1), paths_server.next())
-1341 .await
-1342.unwrap(),
-1343None
-1344);
-1345
-1346 server.close().await;
-1347 client.close().await;
-1348
-1349Ok(())
-1350 }
-1351}
\ No newline at end of file
+563/// This is created using [`Connecting::into_0rtt`].
+564///
+565/// Creating a `OutgoingZeroRttConnection` means that the endpoint is capable
+566/// of attempting a 0-RTT connection with the remote. The remote may still
+567/// reject the 0-RTT connection. In which case, any data sent before the
+568/// handshake has completed may need to be resent.
+569///
+570/// Look at the [`OutgoingZeroRttConnection::handshake_completed`] method for
+571/// more details.
+572pub type OutgoingZeroRttConnection = Connection<OutgoingZeroRtt>;
+573
+574/// Returned from [`OutgoingZeroRttConnection::handshake_completed`].
+575#[derive(Debug, Clone)]
+576pub enum ZeroRttStatus {
+577/// If the 0-RTT data was accepted, you can continue to use any streams
+578 /// that were created before the handshake was completed.
+579Accepted(Connection),
+580/// If the 0-RTT data was rejected, any streams that were created before
+581 /// the handshake was completed will error and any data that was
+582 /// previously sent on those streams will need to be resent.
+583Rejected(Connection),
+584}
+585
+586/// A QUIC connection on the server-side that can possibly accept 0-RTT data.
+587///
+588/// It is very similar to a `Connection`, but the `IncomingZeroRttConnection::remote_id`
+589/// and `IncomingZeroRttConnection::alpn` may not be set yet, since the handshake has
+590/// not necessarily occurred yet.
+591///
+592/// If the `IncomingZeroRttConnection` has rejected 0-RTT or does not have enough information
+593/// to accept 0-RTT, any received 0-RTT packets will simply be dropped before
+594/// reaching any receive streams.
+595///
+596/// Any streams that are created to send or receive data can continue to be used
+597/// even after the handshake has completed and we are no longer in a 0-RTT
+598/// situation.
+599///
+600/// Use the [`IncomingZeroRttConnection::handshake_completed`] method to get a [`Connection`] from a
+601/// `IncomingZeroRttConnection`. This waits until 0-RTT connection has completed
+602/// the handshake and can now confidently derive the ALPN and the
+603/// [`EndpointId`] of the remote endpoint.
+604pub type IncomingZeroRttConnection = Connection<IncomingZeroRtt>;
+605
+606/// A QUIC connection.
+607///
+608/// If all references to a connection (including every clone of the Connection handle,
+609/// streams of incoming streams, and the various stream types) have been dropped, then the
+610/// connection will be automatically closed with an error_code of 0 and an empty reason. You
+611/// can also close the connection explicitly by calling [`Connection::close`].
+612///
+613/// Closing the connection immediately abandons efforts to deliver data to the peer. Upon
+614/// receiving CONNECTION_CLOSE the peer may drop any stream data not yet delivered to the
+615/// application. [`Connection::close`] describes in more detail how to gracefully close a
+616/// connection without losing application data.
+617///
+618/// May be cloned to obtain another handle to the same connection.
+619#[derive(Debug, Clone)]
+620pub struct Connection<State: ConnectionState = HandshakeCompleted> {
+621 inner: quinn::Connection,
+622/// State-specific information
+623data: State::Data,
+624}
+625
+626#[doc(hidden)]
+627#[derive(Debug, Clone)]
+628pub struct HandshakeCompletedData {
+629 info: StaticInfo,
+630 paths: PathsWatcher,
+631}
+632
+633/// Static info from a completed TLS handshake.
+634#[derive(Debug, Clone)]
+635struct StaticInfo {
+636 endpoint_id: EndpointId,
+637 alpn: Vec<u8>,
+638}
+639
+640#[doc(hidden)]
+641#[derive(Debug, Clone)]
+642pub struct IncomingZeroRttData {
+643 accepted: Shared<BoxFuture<Result<Connection, ConnectingError>>>,
+644}
+645
+646#[doc(hidden)]
+647#[derive(Debug, Clone)]
+648pub struct OutgoingZeroRttData {
+649 accepted: Shared<BoxFuture<Result<ZeroRttStatus, ConnectingError>>>,
+650}
+651
+652mod sealed {
+653pub trait Sealed {}
+654}
+655
+656/// Trait to track the state of a [`Connection`] at compile time.
+657pub trait ConnectionState: sealed::Sealed {
+658/// State-specific data stored in the [`Connection`].
+659type Data: std::fmt::Debug + Clone;
+660}
+661
+662/// Marker type for a connection that has completed the handshake.
+663#[derive(Debug, Clone)]
+664pub struct HandshakeCompleted;
+665
+666/// Marker type for a connection that is in the incoming 0-RTT state.
+667#[derive(Debug, Clone)]
+668pub struct IncomingZeroRtt;
+669
+670/// Marker type for a connection that is in the outgoing 0-RTT state.
+671#[derive(Debug, Clone)]
+672pub struct OutgoingZeroRtt;
+673
+674impl sealed::Sealed for HandshakeCompleted {}
+675impl ConnectionState for HandshakeCompleted {
+676type Data = HandshakeCompletedData;
+677}
+678impl sealed::Sealed for IncomingZeroRtt {}
+679impl ConnectionState for IncomingZeroRtt {
+680type Data = IncomingZeroRttData;
+681}
+682
+683impl sealed::Sealed for OutgoingZeroRtt {}
+684impl ConnectionState for OutgoingZeroRtt {
+685type Data = OutgoingZeroRttData;
+686}
+687
+688#[allow(missing_docs)]
+689#[stack_error(add_meta, derive)]
+690#[error("Protocol error: no remote id available")]
+691#[derive(Clone)]
+692pub struct RemoteEndpointIdError;
+693
+694impl<T: ConnectionState> Connection<T> {
+695/// Initiates a new outgoing unidirectional stream.
+696 ///
+697 /// Streams are cheap and instantaneous to open unless blocked by flow control. As a
+698 /// consequence, the peer won’t be notified that a stream has been opened until the
+699 /// stream is actually used.
+700#[inline]
+701pub fn open_uni(&self) -> OpenUni<'_> {
+702self.inner.open_uni()
+703 }
+704
+705/// Initiates a new outgoing bidirectional stream.
+706 ///
+707 /// Streams are cheap and instantaneous to open unless blocked by flow control. As a
+708 /// consequence, the peer won't be notified that a stream has been opened until the
+709 /// stream is actually used. Calling [`open_bi`] then waiting on the [`RecvStream`]
+710 /// without writing anything to [`SendStream`] will never succeed.
+711 ///
+712 /// [`open_bi`]: Connection::open_bi
+713 /// [`SendStream`]: quinn::SendStream
+714 /// [`RecvStream`]: quinn::RecvStream
+715#[inline]
+716pub fn open_bi(&self) -> OpenBi<'_> {
+717self.inner.open_bi()
+718 }
+719
+720/// Accepts the next incoming uni-directional stream.
+721#[inline]
+722pub fn accept_uni(&self) -> AcceptUni<'_> {
+723self.inner.accept_uni()
+724 }
+725
+726/// Accept the next incoming bidirectional stream.
+727 ///
+728 /// **Important Note**: The peer that calls [`open_bi`] must write to its [`SendStream`]
+729 /// before the peer `Connection` is able to accept the stream using
+730 /// `accept_bi()`. Calling [`open_bi`] then waiting on the [`RecvStream`] without
+731 /// writing anything to the connected [`SendStream`] will never succeed.
+732 ///
+733 /// [`open_bi`]: Connection::open_bi
+734 /// [`SendStream`]: quinn::SendStream
+735 /// [`RecvStream`]: quinn::RecvStream
+736#[inline]
+737pub fn accept_bi(&self) -> AcceptBi<'_> {
+738self.inner.accept_bi()
+739 }
+740
+741/// Receives an application datagram.
+742#[inline]
+743pub fn read_datagram(&self) -> ReadDatagram<'_> {
+744self.inner.read_datagram()
+745 }
+746
+747/// Wait for the connection to be closed for any reason.
+748 ///
+749 /// Despite the return type's name, closed connections are often not an error condition
+750 /// at the application layer. Cases that might be routine include
+751 /// [`ConnectionError::LocallyClosed`] and [`ConnectionError::ApplicationClosed`].
+752#[inline]
+753pub async fn closed(&self) -> ConnectionError {
+754self.inner.closed().await
+755}
+756
+757/// If the connection is closed, the reason why.
+758 ///
+759 /// Returns `None` if the connection is still open.
+760#[inline]
+761pub fn close_reason(&self) -> Option<ConnectionError> {
+762self.inner.close_reason()
+763 }
+764
+765/// Closes the connection immediately.
+766 ///
+767 /// Pending operations will fail immediately with [`ConnectionError::LocallyClosed`]. No
+768 /// more data is sent to the peer and the peer may drop buffered data upon receiving the
+769 /// CONNECTION_CLOSE frame.
+770 ///
+771 /// `error_code` and `reason` are not interpreted, and are provided directly to the
+772 /// peer.
+773 ///
+774 /// `reason` will be truncated to fit in a single packet with overhead; to improve odds
+775 /// that it is preserved in full, it should be kept under 1KiB.
+776 ///
+777 /// # Gracefully closing a connection
+778 ///
+779 /// Only the peer last receiving application data can be certain that all data is
+780 /// delivered. The only reliable action it can then take is to close the connection,
+781 /// potentially with a custom error code. The delivery of the final CONNECTION_CLOSE
+782 /// frame is very likely if both endpoints stay online long enough, calling
+783 /// [`Endpoint::close`] will wait to provide sufficient time. Otherwise, the remote peer
+784 /// will time out the connection, provided that the idle timeout is not disabled.
+785 ///
+786 /// The sending side can not guarantee all stream data is delivered to the remote
+787 /// application. It only knows the data is delivered to the QUIC stack of the remote
+788 /// endpoint. Once the local side sends a CONNECTION_CLOSE frame in response to calling
+789 /// [`close`] the remote endpoint may drop any data it received but is as yet
+790 /// undelivered to the application, including data that was acknowledged as received to
+791 /// the local endpoint.
+792 ///
+793 /// [`close`]: Connection::close
+794#[inline]
+795pub fn close(&self, error_code: VarInt, reason: &[u8]) {
+796self.inner.close(error_code, reason)
+797 }
+798
+799/// Transmits `data` as an unreliable, unordered application datagram.
+800 ///
+801 /// Application datagrams are a low-level primitive. They may be lost or delivered out
+802 /// of order, and `data` must both fit inside a single QUIC packet and be smaller than
+803 /// the maximum dictated by the peer.
+804#[inline]
+805pub fn send_datagram(&self, data: bytes::Bytes) -> Result<(), SendDatagramError> {
+806self.inner.send_datagram(data)
+807 }
+808
+809// TODO: It seems `SendDatagram` is not yet exposed by quinn. This has been fixed
+810 // upstream and will be in the next release.
+811 // /// Transmits `data` as an unreliable, unordered application datagram
+812 // ///
+813 // /// Unlike [`send_datagram()`], this method will wait for buffer space during congestion
+814 // /// conditions, which effectively prioritizes old datagrams over new datagrams.
+815 // ///
+816 // /// See [`send_datagram()`] for details.
+817 // ///
+818 // /// [`send_datagram()`]: Connection::send_datagram
+819 // #[inline]
+820 // pub fn send_datagram_wait(&self, data: bytes::Bytes) -> SendDatagram<'_> {
+821 // self.inner.send_datagram_wait(data)
+822 // }
+823
+824/// Computes the maximum size of datagrams that may be passed to [`send_datagram`].
+825 ///
+826 /// Returns `None` if datagrams are unsupported by the peer or disabled locally.
+827 ///
+828 /// This may change over the lifetime of a connection according to variation in the path
+829 /// MTU estimate. The peer can also enforce an arbitrarily small fixed limit, but if the
+830 /// peer's limit is large this is guaranteed to be a little over a kilobyte at minimum.
+831 ///
+832 /// Not necessarily the maximum size of received datagrams.
+833 ///
+834 /// [`send_datagram`]: Self::send_datagram
+835#[inline]
+836pub fn max_datagram_size(&self) -> Option<usize> {
+837self.inner.max_datagram_size()
+838 }
+839
+840/// Bytes available in the outgoing datagram buffer.
+841 ///
+842 /// When greater than zero, calling [`send_datagram`] with a
+843 /// datagram of at most this size is guaranteed not to cause older datagrams to be
+844 /// dropped.
+845 ///
+846 /// [`send_datagram`]: Self::send_datagram
+847#[inline]
+848pub fn datagram_send_buffer_space(&self) -> usize {
+849self.inner.datagram_send_buffer_space()
+850 }
+851
+852/// Current best estimate of this connection's latency (round-trip-time).
+853#[inline]
+854pub fn rtt(&self) -> Duration {
+855self.inner.rtt()
+856 }
+857
+858/// Returns connection statistics.
+859#[inline]
+860pub fn stats(&self) -> ConnectionStats {
+861self.inner.stats()
+862 }
+863
+864/// Current state of the congestion control algorithm, for debugging purposes.
+865#[inline]
+866pub fn congestion_state(&self) -> Box<dyn quinn_proto::congestion::Controller> {
+867self.inner.congestion_state()
+868 }
+869
+870/// Parameters negotiated during the handshake.
+871 ///
+872 /// Guaranteed to return `Some` on fully established connections or after
+873 /// [`Connecting::handshake_data()`] succeeds. See that method's documentations for
+874 /// details on the returned value.
+875 ///
+876 /// [`Connection::handshake_data()`]: crate::endpoint::Connecting::handshake_data
+877#[inline]
+878pub fn handshake_data(&self) -> Option<Box<dyn Any>> {
+879self.inner.handshake_data()
+880 }
+881
+882/// Cryptographic identity of the peer.
+883 ///
+884 /// The dynamic type returned is determined by the configured [`Session`]. For the
+885 /// default `rustls` session, the return value can be [`downcast`] to a
+886 /// <code>Vec<[rustls::pki_types::CertificateDer]></code>
+887 ///
+888 /// [`Session`]: quinn_proto::crypto::Session
+889 /// [`downcast`]: Box::downcast
+890#[inline]
+891pub fn peer_identity(&self) -> Option<Box<dyn Any>> {
+892self.inner.peer_identity()
+893 }
+894
+895/// A stable identifier for this connection.
+896 ///
+897 /// Peer addresses and connection IDs can change, but this value will remain fixed for
+898 /// the lifetime of the connection.
+899#[inline]
+900pub fn stable_id(&self) -> usize {
+901self.inner.stable_id()
+902 }
+903
+904/// Derives keying material from this connection's TLS session secrets.
+905 ///
+906 /// When both peers call this method with the same `label` and `context`
+907 /// arguments and `output` buffers of equal length, they will get the
+908 /// same sequence of bytes in `output`. These bytes are cryptographically
+909 /// strong and pseudorandom, and are suitable for use as keying material.
+910 ///
+911 /// See [RFC5705](https://tools.ietf.org/html/rfc5705) for more information.
+912#[inline]
+913pub fn export_keying_material(
+914&self,
+915 output: &mut [u8],
+916 label: &[u8],
+917 context: &[u8],
+918 ) -> Result<(), quinn_proto::crypto::ExportKeyingMaterialError> {
+919self.inner.export_keying_material(output, label, context)
+920 }
+921
+922/// Modifies the number of unidirectional streams that may be concurrently opened.
+923 ///
+924 /// No streams may be opened by the peer unless fewer than `count` are already
+925 /// open. Large `count`s increase both minimum and worst-case memory consumption.
+926#[inline]
+927pub fn set_max_concurrent_uni_streams(&self, count: VarInt) {
+928self.inner.set_max_concurrent_uni_streams(count)
+929 }
+930
+931/// See [`quinn_proto::TransportConfig::receive_window`].
+932#[inline]
+933pub fn set_receive_window(&self, receive_window: VarInt) {
+934self.inner.set_receive_window(receive_window)
+935 }
+936
+937/// Modifies the number of bidirectional streams that may be concurrently opened.
+938 ///
+939 /// No streams may be opened by the peer unless fewer than `count` are already
+940 /// open. Large `count`s increase both minimum and worst-case memory consumption.
+941#[inline]
+942pub fn set_max_concurrent_bi_streams(&self, count: VarInt) {
+943self.inner.set_max_concurrent_bi_streams(count)
+944 }
+945}
+946
+947impl Connection<HandshakeCompleted> {
+948/// Extracts the ALPN protocol from the peer's handshake data.
+949pub fn alpn(&self) -> &[u8] {
+950&self.data.info.alpn
+951 }
+952
+953/// Returns the [`EndpointId`] from the peer's TLS certificate.
+954 ///
+955 /// The [`PublicKey`] of an endpoint is also known as an [`EndpointId`]. This [`PublicKey`] is
+956 /// included in the TLS certificate presented during the handshake when connecting.
+957 /// This function allows you to get the [`EndpointId`] of the remote endpoint of this
+958 /// connection.
+959 ///
+960 /// [`PublicKey`]: iroh_base::PublicKey
+961pub fn remote_id(&self) -> EndpointId {
+962self.data.info.endpoint_id
+963 }
+964
+965/// Returns a [`Watcher`] for the network paths of this connection.
+966 ///
+967 /// A connection can have several network paths to the remote endpoint, commonly there
+968 /// will be a path via the relay server and a holepunched path.
+969 ///
+970 /// The watcher is updated whenever a path is opened or closed, or when the path selected
+971 /// for transmission changes (see [`PathInfo::is_selected`]).
+972 ///
+973 /// The [`PathInfoList`] returned from the watcher contains a [`PathInfo`] for each
+974 /// transmission path.
+975 ///
+976 /// [`PathInfo::is_selected`]: crate::magicsock::PathInfo::is_selected
+977 /// [`PathInfo`]: crate::magicsock::PathInfo
+978pub fn paths(&self) -> impl Watcher<Value = PathInfoList> + Unpin + Send + Sync + 'static {
+979self.data.paths.clone()
+980 }
+981}
+982
+983impl Connection<IncomingZeroRtt> {
+984/// Extracts the ALPN protocol from the peer's handshake data.
+985pub fn alpn(&self) -> Option<Vec<u8>> {
+986 alpn_from_quinn_conn(&self.inner)
+987 }
+988
+989/// Waits until the full handshake occurs and then returns a [`Connection`].
+990 ///
+991 /// This may fail with [`ConnectingError::ConnectionError`], if there was
+992 /// some general failure with the connection, such as a network timeout since
+993 /// we accepted the connection.
+994 ///
+995 /// This may fail with [`ConnectingError::HandshakeFailure`], if the other side
+996 /// doesn't use the right TLS authentication, which usually every iroh endpoint
+997 /// uses and requires.
+998 ///
+999 /// Thus, those errors should only occur if someone connects to you with a
+1000 /// modified iroh endpoint or with a plain QUIC client.
+1001pub async fn handshake_completed(&self) -> Result<Connection, ConnectingError> {
+1002self.data.accepted.clone().await
+1003}
+1004}
+1005
+1006impl Connection<OutgoingZeroRtt> {
+1007/// Extracts the ALPN protocol from the peer's handshake data.
+1008pub fn alpn(&self) -> Option<Vec<u8>> {
+1009 alpn_from_quinn_conn(&self.inner)
+1010 }
+1011
+1012/// Waits until the full handshake occurs and returns a [`ZeroRttStatus`].
+1013 ///
+1014 /// If `ZeroRttStatus::Accepted` is returned, than any streams created before
+1015 /// the handshake has completed can still be used.
+1016 ///
+1017 /// If `ZeroRttStatus::Rejected` is returned, than any streams created before
+1018 /// the handshake will error and any data sent should be re-sent on a
+1019 /// new stream.
+1020 ///
+1021 /// This may fail with [`ConnectingError::ConnectionError`], if there was
+1022 /// some general failure with the connection, such as a network timeout since
+1023 /// we initiated the connection.
+1024 ///
+1025 /// This may fail with [`ConnectingError::HandshakeFailure`], if the other side
+1026 /// doesn't use the right TLS authentication, which usually every iroh endpoint
+1027 /// uses and requires.
+1028 ///
+1029 /// Thus, those errors should only occur if someone connects to you with a
+1030 /// modified iroh endpoint or with a plain QUIC client.
+1031pub async fn handshake_completed(&self) -> Result<ZeroRttStatus, ConnectingError> {
+1032self.data.accepted.clone().await
+1033}
+1034}
+1035
+1036#[cfg(test)]
+1037mod tests {
+1038use std::time::Duration;
+1039
+1040use iroh_base::{EndpointAddr, SecretKey};
+1041use n0_error::{Result, StackResultExt, StdResultExt};
+1042use n0_future::StreamExt;
+1043use n0_watcher::Watcher;
+1044use rand::SeedableRng;
+1045use tracing::{Instrument, error_span, info, info_span, trace_span};
+1046use tracing_test::traced_test;
+1047
+1048use super::Endpoint;
+1049use crate::{
+1050 RelayMode,
+1051 endpoint::{ConnectOptions, Incoming, PathInfo, PathInfoList, ZeroRttStatus},
+1052 test_utils::run_relay_server,
+1053 };
+1054
+1055const TEST_ALPN: &[u8] = b"n0/iroh/test";
+1056
+1057async fn spawn_0rtt_server(secret_key: SecretKey, log_span: tracing::Span) -> Result<Endpoint> {
+1058let server = Endpoint::empty_builder(RelayMode::Disabled)
+1059 .secret_key(secret_key)
+1060 .alpns(vec![TEST_ALPN.to_vec()])
+1061 .bind()
+1062 .instrument(log_span.clone())
+1063 .await?;
+1064
+1065async fn handle_incoming(incoming: Incoming) -> Result {
+1066let accepting = incoming
+1067 .accept()
+1068 .std_context("Failed to accept incoming connection")?;
+1069
+1070// accept a possible 0-RTT connection
+1071let zrtt_conn = accepting.into_0rtt();
+1072
+1073let (mut send, mut recv) = zrtt_conn
+1074 .accept_bi()
+1075 .await
+1076.std_context("failed to accept bi stream")?;
+1077
+1078let data = recv
+1079 .read_to_end(10_000_000)
+1080 .await
+1081.std_context("Failed to read data")?;
+1082
+1083 send.write_all(&data)
+1084 .await
+1085.std_context("Failed to write data")?;
+1086 send.finish().std_context("Failed to finish send")?;
+1087
+1088// Stay alive until the other side closes the connection.
+1089zrtt_conn.closed().await;
+1090Ok(())
+1091 }
+1092
+1093// Gets aborted via the endpoint closing causing an `Err`
+1094 // a simple echo server
+1095tokio::spawn({
+1096let server = server.clone();
+1097async move {
+1098tracing::trace!("Server accept loop started");
+1099while let Some(incoming) = server.accept().await {
+1100tracing::trace!("Server received incoming connection");
+1101// Handle connection errors gracefully instead of exiting the task
+1102if let Err(e) = handle_incoming(incoming).await {
+1103tracing::warn!("Failure while handling connection: {e:#}");
+1104 }
+1105tracing::trace!("Connection closed, ready for next");
+1106 }
+1107tracing::trace!("Server accept loop exiting");
+1108 n0_error::Ok(())
+1109 }
+1110 .instrument(log_span)
+1111 });
+1112
+1113Ok(server)
+1114 }
+1115
+1116async fn connect_client_0rtt_expect_err(
+1117 client: &Endpoint,
+1118 server_addr: EndpointAddr,
+1119 ) -> Result {
+1120let conn = client
+1121 .connect_with_opts(server_addr, TEST_ALPN, ConnectOptions::new())
+1122 .await?
+1123.into_0rtt()
+1124 .expect_err("expected 0-RTT to fail")
+1125 .await?;
+1126
+1127let (mut send, mut recv) = conn.open_bi().await.anyerr()?;
+1128 send.write_all(b"hello").await.anyerr()?;
+1129 send.finish().anyerr()?;
+1130let received = recv.read_to_end(1_000).await.anyerr()?;
+1131assert_eq!(&received, b"hello");
+1132 conn.close(0u32.into(), b"thx");
+1133Ok(())
+1134 }
+1135
+1136async fn connect_client_0rtt_expect_ok(
+1137 client: &Endpoint,
+1138 server_addr: EndpointAddr,
+1139 expect_server_accepts: bool,
+1140 ) -> Result {
+1141tracing::trace!(?server_addr, "Client connecting with 0-RTT");
+1142let zrtt_conn = client
+1143 .connect_with_opts(server_addr, TEST_ALPN, ConnectOptions::new())
+1144 .await
+1145.context("connect")?
+1146.into_0rtt()
+1147 .ok()
+1148 .context("into_0rtt")?;
+1149
+1150tracing::trace!("Client established 0-RTT connection");
+1151// This is how we send data in 0-RTT:
+1152let (mut send, mut recv) = zrtt_conn.open_bi().await.anyerr()?;
+1153 send.write_all(b"hello").await.anyerr()?;
+1154 send.finish().anyerr()?;
+1155tracing::trace!("Client sent 0-RTT data, waiting for server response");
+1156// When this resolves, we've gotten a response from the server about whether the 0-RTT data above was accepted:
+1157let zrtt_res = zrtt_conn.handshake_completed().await;
+1158tracing::trace!(?zrtt_res, "Server responded to 0-RTT");
+1159let zrtt_res = zrtt_res.context("handshake completed")?;
+1160let conn = match zrtt_res {
+1161 ZeroRttStatus::Accepted(conn) => {
+1162assert!(expect_server_accepts);
+1163 conn
+1164 }
+1165 ZeroRttStatus::Rejected(conn) => {
+1166assert!(!expect_server_accepts);
+1167// in this case we need to re-send data by re-creating the stream.
+1168let (mut send, r) = conn.open_bi().await.anyerr()?;
+1169 send.write_all(b"hello").await.anyerr()?;
+1170 send.finish().anyerr()?;
+1171 recv = r;
+1172 conn
+1173 }
+1174 };
+1175let received = recv.read_to_end(1_000).await.anyerr()?;
+1176assert_eq!(&received, b"hello");
+1177 conn.close(0u32.into(), b"thx");
+1178Ok(())
+1179 }
+1180
+1181#[tokio::test]
+1182 #[traced_test]
+1183async fn test_0rtt() -> Result {
+1184let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42);
+1185let client = Endpoint::empty_builder(RelayMode::Disabled).bind().await?;
+1186let server = spawn_0rtt_server(SecretKey::generate(&mut rng), info_span!("server")).await?;
+1187
+1188 connect_client_0rtt_expect_err(&client, server.addr()).await?;
+1189// The second 0rtt attempt should work
+1190connect_client_0rtt_expect_ok(&client, server.addr(), true).await?;
+1191
+1192 client.close().await;
+1193 server.close().await;
+1194
+1195Ok(())
+1196 }
+1197
+1198// We have this test, as this would've failed at some point.
+1199 // This effectively tests that we correctly categorize the TLS session tickets we
+1200 // receive into the respective "bucket" for the recipient.
+1201#[tokio::test]
+1202 #[traced_test]
+1203async fn test_0rtt_non_consecutive() -> Result {
+1204let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42);
+1205let client = Endpoint::empty_builder(RelayMode::Disabled).bind().await?;
+1206let server = spawn_0rtt_server(SecretKey::generate(&mut rng), info_span!("server")).await?;
+1207
+1208 connect_client_0rtt_expect_err(&client, server.addr()).await?;
+1209
+1210// connecting with another endpoint should not interfere with our
+1211 // TLS session ticket cache for the first endpoint:
+1212let another =
+1213 spawn_0rtt_server(SecretKey::generate(&mut rng), info_span!("another")).await?;
+1214 connect_client_0rtt_expect_err(&client, another.addr()).await?;
+1215 another.close().await;
+1216
+1217 connect_client_0rtt_expect_ok(&client, server.addr(), true).await?;
+1218
+1219 client.close().await;
+1220 server.close().await;
+1221
+1222Ok(())
+1223 }
+1224
+1225// Test whether 0-RTT is possible after a restart:
+1226#[tokio::test]
+1227 #[traced_test]
+1228async fn test_0rtt_after_server_restart() -> Result {
+1229let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42);
+1230let client = Endpoint::empty_builder(RelayMode::Disabled)
+1231 .bind()
+1232 .instrument(info_span!("client"))
+1233 .await?;
+1234let server_key = SecretKey::generate(&mut rng);
+1235let server = spawn_0rtt_server(server_key.clone(), info_span!("server-initial")).await?;
+1236
+1237 connect_client_0rtt_expect_err(&client, server.addr())
+1238 .instrument(trace_span!("connect1"))
+1239 .await
+1240.context("client connect 1")?;
+1241 connect_client_0rtt_expect_ok(&client, server.addr(), true)
+1242 .instrument(trace_span!("connect2"))
+1243 .await
+1244.context("client connect 2")?;
+1245
+1246// adds time to the test, but we need to ensure the server is fully closed before spawning the next one.
+1247server.close().await;
+1248
+1249let server = spawn_0rtt_server(server_key, info_span!("server-restart")).await?;
+1250
+1251// we expect the client to *believe* it can 0-RTT connect to the server (hence expect_ok),
+1252 // but the server will reject the early data because it discarded necessary state
+1253 // to decrypt it when restarting.
+1254connect_client_0rtt_expect_ok(&client, server.addr(), false)
+1255 .instrument(trace_span!("connect3"))
+1256 .await
+1257.context("client connect 3")?;
+1258
+1259tokio::join!(client.close(), server.close());
+1260Ok(())
+1261 }
+1262
+1263#[tokio::test]
+1264 #[traced_test]
+1265async fn test_paths_watcher() -> Result {
+1266const ALPN: &[u8] = b"test";
+1267let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
+1268let (relay_map, _relay_map, _guard) = run_relay_server().await?;
+1269let server = Endpoint::empty_builder(RelayMode::Custom(relay_map.clone()))
+1270 .secret_key(SecretKey::generate(&mut rng))
+1271 .insecure_skip_relay_cert_verify(true)
+1272 .alpns(vec![ALPN.to_vec()])
+1273 .bind()
+1274 .await?;
+1275
+1276let client = Endpoint::empty_builder(RelayMode::Custom(relay_map.clone()))
+1277 .secret_key(SecretKey::generate(&mut rng))
+1278 .insecure_skip_relay_cert_verify(true)
+1279 .bind()
+1280 .await?;
+1281
+1282 server.online().await;
+1283let server_addr = server.addr();
+1284info!("server addr: {server_addr:?}");
+1285
+1286let (conn_client, conn_server) = tokio::join!(
+1287async { client.connect(server_addr, ALPN).await.unwrap() },
+1288async { server.accept().await.unwrap().await.unwrap() }
+1289 );
+1290info!("connected");
+1291let mut paths_client = conn_client.paths().stream();
+1292let mut paths_server = conn_server.paths().stream();
+1293
+1294/// Advances the path stream until at least one IP and one relay paths are available.
+1295 ///
+1296 /// Panics if the path stream finishes before that happens.
+1297async fn wait_for_paths(
+1298 stream: &mut n0_watcher::Stream<impl n0_watcher::Watcher<Value = PathInfoList> + Unpin>,
+1299 ) {
+1300loop {
+1301let paths = stream.next().await.expect("paths stream ended");
+1302info!(?paths, "paths");
+1303if paths.len() >= 2
+1304&& paths.iter().any(PathInfo::is_relay)
+1305 && paths.iter().any(PathInfo::is_ip)
+1306 {
+1307info!("break");
+1308return;
+1309 }
+1310 }
+1311 }
+1312
+1313// Verify that both connections are notified of path changes and get an IP and a relay path.
+1314tokio::join!(
+1315async {
+1316 tokio::time::timeout(Duration::from_secs(1), wait_for_paths(&mut paths_server))
+1317 .instrument(error_span!("paths-server"))
+1318 .await
+1319.unwrap()
+1320 },
+1321async {
+1322 tokio::time::timeout(Duration::from_secs(1), wait_for_paths(&mut paths_client))
+1323 .instrument(error_span!("paths-client"))
+1324 .await
+1325.unwrap()
+1326 }
+1327 );
+1328
+1329// Close the client connection.
+1330info!("close client conn");
+1331 conn_client.close(0u32.into(), b"");
+1332
+1333// Verify that the path watch streams close.
+1334assert_eq!(
+1335 tokio::time::timeout(Duration::from_secs(1), paths_client.next())
+1336 .await
+1337.unwrap(),
+1338None
+1339);
+1340assert_eq!(
+1341 tokio::time::timeout(Duration::from_secs(1), paths_server.next())
+1342 .await
+1343.unwrap(),
+1344None
+1345);
+1346
+1347 server.close().await;
+1348 client.close().await;
+1349
+1350Ok(())
+1351 }
+1352}
\ No newline at end of file
diff --git a/pr/3666/docs/src/iroh/key.rs.html b/pr/3666/docs/src/iroh/key.rs.html
deleted file mode 100644
index 835ebb14c4..0000000000
--- a/pr/3666/docs/src/iroh/key.rs.html
+++ /dev/null
@@ -1,158 +0,0 @@
-key.rs - source
1use iroh_metrics::{Counter, Histogram, MetricsGroup};
2use serde::{Deserialize, Serialize};
34/// Enum of metrics for the module
@@ -27,76 +27,64 @@
27/// Number of datagrams received using GRO
28pub recv_gro_datagrams: Counter,
29
-30// Disco packets
-31pub send_disco_udp: Counter,
-32pub send_disco_relay: Counter,
-33pub sent_disco_udp: Counter,
-34pub sent_disco_relay: Counter,
-35pub sent_disco_ping: Counter,
-36pub sent_disco_pong: Counter,
-37pub sent_disco_call_me_maybe: Counter,
-38pub recv_disco_bad_key: Counter,
-39pub recv_disco_bad_parse: Counter,
-40
-41pub recv_disco_udp: Counter,
-42pub recv_disco_relay: Counter,
-43pub recv_disco_ping: Counter,
-44pub recv_disco_pong: Counter,
-45pub recv_disco_call_me_maybe: Counter,
-46pub recv_disco_call_me_maybe_bad_disco: Counter,
-47
-48// How many times our relay home endpoint DI has changed from non-zero to a different non-zero.
-49pub relay_home_change: Counter,
+30// How many times our relay home endpoint DI has changed from non-zero to a different non-zero.
+31pub relay_home_change: Counter,
+32
+33/*
+34 * Holepunching metrics
+35 */
+36/// The number of NAT traversal attempts initiated.
+37pub nat_traversal: Counter,
+38
+39/*
+40 * Connection Metrics
+41 */
+42/// The number of direct connections we have made to peers.
+43pub num_direct_conns_added: Counter,
+44/// The number of direct connections we have lost to peers.
+45pub num_direct_conns_removed: Counter,
+46/// The number of connections to peers we have added over relay.
+47pub num_relay_conns_added: Counter,
+48/// The number of connections to peers we have removed over relay.
+49pub num_relay_conns_removed: Counter,
50
-51/*
-52 * Connection Metrics
-53 */
-54/// The number of direct connections we have made to peers.
-55pub num_direct_conns_added: Counter,
-56/// The number of direct connections we have lost to peers.
-57pub num_direct_conns_removed: Counter,
-58/// The number of connections to peers we have added over relay.
-59pub num_relay_conns_added: Counter,
-60/// The number of connections to peers we have removed over relay.
-61pub num_relay_conns_removed: Counter,
-62
-63pub actor_tick_main: Counter,
-64pub actor_tick_msg: Counter,
-65pub actor_tick_re_stun: Counter,
-66pub actor_tick_portmap_changed: Counter,
-67pub actor_tick_direct_addr_heartbeat: Counter,
-68pub actor_link_change: Counter,
-69pub actor_tick_other: Counter,
-70
-71/// Number of endpoints we have attempted to contact.
-72pub endpoints_contacted: Counter,
-73/// Number of endpoints we have managed to contact directly.
-74pub endpoints_contacted_directly: Counter,
-75
-76/// Number of connections with a successful handshake.
-77pub connection_handshake_success: Counter,
-78/// Number of connections with a successful handshake that became direct.
-79pub connection_became_direct: Counter,
-80/// Histogram of connection latency in milliseconds across all endpoint connections.
-81#[default(Histogram::new(vec![1.0, 5.0, 10.0, 25.0, 50.0, 100.0, 250.0, 500.0, 1000.0, f64::INFINITY]))]
-82pub connection_latency_ms: Histogram,
-83
-84/*
-85 * Path Congestion Metrics
-86 */
-87/// Number of times a path was marked as outdated due to consecutive ping failures.
-88pub path_marked_outdated: Counter,
-89/// Number of ping failures recorded across all paths.
-90pub path_ping_failures: Counter,
-91/// Number of consecutive failure resets (path recovered).
-92pub path_failure_resets: Counter,
-93/// Histogram of packet loss rates (0.0-1.0) observed on UDP paths.
-94#[default(Histogram::new(vec![0.0, 0.01, 0.05, 0.1, 0.2, 0.5, 1.0]))]
-95pub path_packet_loss_rate: Histogram,
-96/// Histogram of RTT variance (in milliseconds) as a congestion indicator.
-97#[default(Histogram::new(vec![0.0, 1.0, 5.0, 10.0, 20.0, 50.0, 100.0, 200.0]))]
-98pub path_rtt_variance_ms: Histogram,
-99/// Histogram of path quality scores (0.0-1.0).
-100#[default(Histogram::new(vec![0.0, 0.3, 0.5, 0.7, 0.85, 0.95, 1.0]))]
-101pub path_quality_score: Histogram,
-102}
\ No newline at end of file
+51pub actor_tick_main: Counter,
+52pub actor_tick_msg: Counter,
+53pub actor_tick_re_stun: Counter,
+54pub actor_tick_portmap_changed: Counter,
+55pub actor_tick_direct_addr_heartbeat: Counter,
+56pub actor_link_change: Counter,
+57pub actor_tick_other: Counter,
+58
+59/// Number of endpoints we have attempted to contact.
+60pub endpoints_contacted: Counter,
+61/// Number of endpoints we have managed to contact directly.
+62pub endpoints_contacted_directly: Counter,
+63
+64/// Number of connections with a successful handshake.
+65pub connection_handshake_success: Counter,
+66/// Number of connections with a successful handshake that became direct.
+67pub connection_became_direct: Counter,
+68/// Histogram of connection latency in milliseconds across all endpoint connections.
+69#[default(Histogram::new(vec![1.0, 5.0, 10.0, 25.0, 50.0, 100.0, 250.0, 500.0, 1000.0, f64::INFINITY]))]
+70pub connection_latency_ms: Histogram,
+71
+72/*
+73 * Path Congestion Metrics
+74 */
+75/// Number of times a path was marked as outdated due to consecutive ping failures.
+76pub path_marked_outdated: Counter,
+77/// Number of ping failures recorded across all paths.
+78pub path_ping_failures: Counter,
+79/// Number of consecutive failure resets (path recovered).
+80pub path_failure_resets: Counter,
+81/// Histogram of packet loss rates (0.0-1.0) observed on UDP paths.
+82#[default(Histogram::new(vec![0.0, 0.01, 0.05, 0.1, 0.2, 0.5, 1.0]))]
+83pub path_packet_loss_rate: Histogram,
+84/// Histogram of RTT variance (in milliseconds) as a congestion indicator.
+85#[default(Histogram::new(vec![0.0, 1.0, 5.0, 10.0, 20.0, 50.0, 100.0, 200.0]))]
+86pub path_rtt_variance_ms: Histogram,
+87/// Histogram of path quality scores (0.0-1.0).
+88#[default(Histogram::new(vec![0.0, 0.3, 0.5, 0.7, 0.85, 0.95, 1.0]))]
+89pub path_quality_score: Histogram,
+90}
\ No newline at end of file
diff --git a/pr/3666/docs/src/iroh/magicsock/remote_map.rs.html b/pr/3666/docs/src/iroh/magicsock/remote_map.rs.html
index 1640029f49..ba68852b7f 100644
--- a/pr/3666/docs/src/iroh/magicsock/remote_map.rs.html
+++ b/pr/3666/docs/src/iroh/magicsock/remote_map.rs.html
@@ -10,276 +10,230 @@
10use rustc_hash::FxHashMap;
11use serde::{Deserialize, Serialize};
12use tokio::sync::mpsc;
-13use tracing::warn;
-14
-15pub(crate) use self::remote_state::PathsWatcher;
-16pub(super) use self::remote_state::RemoteStateMessage;
-17pub use self::remote_state::{PathInfo, PathInfoList};
-18use self::remote_state::{RemoteStateActor, RemoteStateHandle};
-19use super::{
-20 DirectAddr, DiscoState, MagicsockMetrics,
-21 mapped_addrs::{AddrMap, EndpointIdMappedAddr, RelayMappedAddr},
-22 transports::{self, TransportsSender},
-23};
-24use crate::{disco, discovery::ConcurrentDiscovery};
-25
-26mod remote_state;
-27
-28/// Interval in which handles to closed [`RemoteStateActor`]s should be removed.
-29pub(super) const REMOTE_MAP_GC_INTERVAL: Duration = Duration::from_secs(60);
-30
-31// TODO: use this
-32// /// Number of endpoints that are inactive for which we keep info about. This limit is enforced
-33// /// periodically via [`NodeMap::prune_inactive`].
-34// const MAX_INACTIVE_NODES: usize = 30;
-35
-36/// Map containing all the state for endpoints.
-37///
-38/// - Has actors which each manage all the connection state for a remote endpoint.
-39///
-40/// - Has the mapped addresses we use to refer to non-IP transports destinations into IPv6
-41/// addressing space that is used by Quinn.
-42#[derive(Debug)]
-43pub(crate) struct RemoteMap {
-44//
-45 // State we keep about remote endpoints.
-46 //
-47/// The actors tracking each remote endpoint.
-48actor_handles: Mutex<FxHashMap<EndpointId, RemoteStateHandle>>,
-49/// The mapping between [`EndpointId`]s and [`EndpointIdMappedAddr`]s.
-50pub(super) endpoint_mapped_addrs: AddrMap<EndpointId, EndpointIdMappedAddr>,
-51/// The mapping between endpoints via a relay and their [`RelayMappedAddr`]s.
-52pub(super) relay_mapped_addrs: AddrMap<(RelayUrl, EndpointId), RelayMappedAddr>,
-53
-54//
-55 // State needed to start a new RemoteStateHandle.
-56 //
-57/// The endpoint ID of the local endpoint.
-58local_endpoint_id: EndpointId,
-59 metrics: Arc<MagicsockMetrics>,
-60/// The "direct" addresses known for our local endpoint
-61local_direct_addrs: n0_watcher::Direct<BTreeSet<DirectAddr>>,
-62 disco: DiscoState,
-63 sender: TransportsSender,
-64 discovery: ConcurrentDiscovery,
-65}
-66
-67impl RemoteMap {
-68/// Creates a new [`RemoteMap`].
-69pub(super) fn new(
-70 local_endpoint_id: EndpointId,
-71 metrics: Arc<MagicsockMetrics>,
-72
-73 local_direct_addrs: n0_watcher::Direct<BTreeSet<DirectAddr>>,
-74 disco: DiscoState,
-75 sender: TransportsSender,
-76 discovery: ConcurrentDiscovery,
-77 ) -> Self {
-78Self {
-79 actor_handles: Mutex::new(FxHashMap::default()),
-80 endpoint_mapped_addrs: Default::default(),
-81 relay_mapped_addrs: Default::default(),
-82 local_endpoint_id,
-83 metrics,
-84 local_direct_addrs,
-85 disco,
-86 sender,
-87 discovery,
-88 }
-89 }
-90
-91pub(super) fn endpoint_mapped_addr(&self, eid: EndpointId) -> EndpointIdMappedAddr {
-92self.endpoint_mapped_addrs.get(&eid)
-93 }
-94
-95/// Removes the handles for terminated [`RemoteStateActor`]s from the endpoint map.
-96 ///
-97 /// This should be called periodically to remove handles to endpoint state actors
-98 /// that have shutdown after their idle timeout expired.
-99pub(super) fn remove_closed_remote_state_actors(&self) {
-100let mut handles = self.actor_handles.lock().expect("poisoned");
-101 handles.retain(|_eid, handle| !handle.sender.is_closed())
-102 }
-103
-104/// Returns the sender for the [`RemoteStateActor`].
-105 ///
-106 /// If needed a new actor is started on demand.
-107 ///
-108 /// [`RemoteStateActor`]: remote_state::RemoteStateActor
-109pub(super) fn remote_state_actor(&self, eid: EndpointId) -> mpsc::Sender<RemoteStateMessage> {
-110let mut handles = self.actor_handles.lock().expect("poisoned");
-111match handles.entry(eid) {
-112 hash_map::Entry::Occupied(mut entry) => {
-113if let Some(sender) = entry.get().sender.get() {
+13
+14pub(crate) use self::remote_state::PathsWatcher;
+15pub(super) use self::remote_state::RemoteStateMessage;
+16pub use self::remote_state::{PathInfo, PathInfoList};
+17use self::remote_state::{RemoteStateActor, RemoteStateHandle};
+18use super::{
+19 DirectAddr, MagicsockMetrics,
+20 mapped_addrs::{AddrMap, EndpointIdMappedAddr, RelayMappedAddr},
+21 transports::TransportsSender,
+22};
+23use crate::discovery::ConcurrentDiscovery;
+24
+25mod remote_state;
+26
+27/// Interval in which handles to closed [`RemoteStateActor`]s should be removed.
+28pub(super) const REMOTE_MAP_GC_INTERVAL: Duration = Duration::from_secs(60);
+29
+30// TODO: use this
+31// /// Number of endpoints that are inactive for which we keep info about. This limit is enforced
+32// /// periodically via [`NodeMap::prune_inactive`].
+33// const MAX_INACTIVE_NODES: usize = 30;
+34
+35/// Map containing all the state for endpoints.
+36///
+37/// - Has actors which each manage all the connection state for a remote endpoint.
+38///
+39/// - Has the mapped addresses we use to refer to non-IP transports destinations into IPv6
+40/// addressing space that is used by Quinn.
+41#[derive(Debug)]
+42pub(crate) struct RemoteMap {
+43//
+44 // State we keep about remote endpoints.
+45 //
+46/// The actors tracking each remote endpoint.
+47actor_handles: Mutex<FxHashMap<EndpointId, RemoteStateHandle>>,
+48/// The mapping between [`EndpointId`]s and [`EndpointIdMappedAddr`]s.
+49pub(super) endpoint_mapped_addrs: AddrMap<EndpointId, EndpointIdMappedAddr>,
+50/// The mapping between endpoints via a relay and their [`RelayMappedAddr`]s.
+51pub(super) relay_mapped_addrs: AddrMap<(RelayUrl, EndpointId), RelayMappedAddr>,
+52
+53//
+54 // State needed to start a new RemoteStateHandle.
+55 //
+56/// The endpoint ID of the local endpoint.
+57local_endpoint_id: EndpointId,
+58 metrics: Arc<MagicsockMetrics>,
+59/// The "direct" addresses known for our local endpoint
+60local_direct_addrs: n0_watcher::Direct<BTreeSet<DirectAddr>>,
+61 sender: TransportsSender,
+62 discovery: ConcurrentDiscovery,
+63}
+64
+65impl RemoteMap {
+66/// Creates a new [`RemoteMap`].
+67pub(super) fn new(
+68 local_endpoint_id: EndpointId,
+69 metrics: Arc<MagicsockMetrics>,
+70 local_direct_addrs: n0_watcher::Direct<BTreeSet<DirectAddr>>,
+71 sender: TransportsSender,
+72 discovery: ConcurrentDiscovery,
+73 ) -> Self {
+74Self {
+75 actor_handles: Mutex::new(FxHashMap::default()),
+76 endpoint_mapped_addrs: Default::default(),
+77 relay_mapped_addrs: Default::default(),
+78 local_endpoint_id,
+79 metrics,
+80 local_direct_addrs,
+81 sender,
+82 discovery,
+83 }
+84 }
+85
+86pub(super) fn endpoint_mapped_addr(&self, eid: EndpointId) -> EndpointIdMappedAddr {
+87self.endpoint_mapped_addrs.get(&eid)
+88 }
+89
+90/// Removes the handles for terminated [`RemoteStateActor`]s from the endpoint map.
+91 ///
+92 /// This should be called periodically to remove handles to endpoint state actors
+93 /// that have shutdown after their idle timeout expired.
+94pub(super) fn remove_closed_remote_state_actors(&self) {
+95let mut handles = self.actor_handles.lock().expect("poisoned");
+96 handles.retain(|_eid, handle| !handle.sender.is_closed())
+97 }
+98
+99/// Returns the sender for the [`RemoteStateActor`].
+100 ///
+101 /// If needed a new actor is started on demand.
+102 ///
+103 /// [`RemoteStateActor`]: remote_state::RemoteStateActor
+104pub(super) fn remote_state_actor(&self, eid: EndpointId) -> mpsc::Sender<RemoteStateMessage> {
+105let mut handles = self.actor_handles.lock().expect("poisoned");
+106match handles.entry(eid) {
+107 hash_map::Entry::Occupied(mut entry) => {
+108if let Some(sender) = entry.get().sender.get() {
+109 sender
+110 } else {
+111// The actor is dead: Start a new actor.
+112let (handle, sender) = self.start_remote_state_actor(eid);
+113 entry.insert(handle);
114 sender
-115 } else {
-116// The actor is dead: Start a new actor.
-117let (handle, sender) = self.start_remote_state_actor(eid);
-118 entry.insert(handle);
-119 sender
-120 }
+115 }
+116 }
+117 hash_map::Entry::Vacant(entry) => {
+118let (handle, sender) = self.start_remote_state_actor(eid);
+119 entry.insert(handle);
+120 sender
121 }
-122 hash_map::Entry::Vacant(entry) => {
-123let (handle, sender) = self.start_remote_state_actor(eid);
-124 entry.insert(handle);
-125 sender
-126 }
-127 }
-128 }
-129
-130/// Starts a new remote state actor and returns a handle and a sender.
-131 ///
-132 /// The handle is not inserted into the endpoint map, this must be done by the caller of this function.
-133fn start_remote_state_actor(
-134&self,
-135 eid: EndpointId,
-136 ) -> (RemoteStateHandle, mpsc::Sender<RemoteStateMessage>) {
-137// Ensure there is a RemoteMappedAddr for this EndpointId.
-138self.endpoint_mapped_addrs.get(&eid);
-139let handle = RemoteStateActor::new(
-140 eid,
-141self.local_endpoint_id,
-142self.local_direct_addrs.clone(),
-143self.disco.clone(),
-144self.relay_mapped_addrs.clone(),
-145self.metrics.clone(),
-146self.sender.clone(),
-147self.discovery.clone(),
-148 )
-149 .start();
-150let sender = handle.sender.get().expect("just created");
-151 (handle, sender)
-152 }
-153
-154pub(super) fn handle_ping(&self, msg: disco::Ping, sender: EndpointId, src: transports::Addr) {
-155if msg.endpoint_key != sender {
-156warn!("DISCO Ping EndpointId mismatch, ignoring ping");
-157return;
-158 }
-159let remote_state = self.remote_state_actor(sender);
-160if let Err(err) = remote_state.try_send(RemoteStateMessage::PingReceived(msg, src)) {
-161// TODO: This is really, really bad and will drop pings under load. But
-162 // DISCO pings are going away with QUIC-NAT-TRAVERSAL so I don't care.
-163warn!("DISCO Ping dropped: {err:#}");
-164 }
-165 }
-166
-167pub(super) fn handle_pong(&self, msg: disco::Pong, sender: EndpointId, src: transports::Addr) {
-168let actor = self.remote_state_actor(sender);
-169if let Err(err) = actor.try_send(RemoteStateMessage::PongReceived(msg, src)) {
-170// TODO: This is really, really bad and will drop pongs under load. But
-171 // DISCO pongs are going away with QUIC-NAT-TRAVERSAL so I don't care.
-172warn!("DISCO Pong dropped: {err:#}");
-173 }
-174 }
-175
-176pub(super) fn handle_call_me_maybe(
-177&self,
-178 msg: disco::CallMeMaybe,
-179 sender: EndpointId,
-180 src: transports::Addr,
-181 ) {
-182if !src.is_relay() {
-183warn!("DISCO CallMeMaybe packets should only come via relay");
-184return;
-185 }
-186let actor = self.remote_state_actor(sender);
-187if let Err(err) = actor.try_send(RemoteStateMessage::CallMeMaybeReceived(msg)) {
-188// TODO: This is bad and will drop call-me-maybe's under load. But
-189 // DISCO CallMeMaybe going away with QUIC-NAT-TRAVERSAL so I don't care.
-190warn!("DISCO CallMeMaybe dropped: {err:#}");
-191 }
-192 }
-193}
-194
-195/// The origin or *source* through which an address associated with a remote endpoint
-196/// was discovered.
-197///
-198/// An aggregate of the [`Source`]s of all the addresses of an endpoint describe the
-199/// [`Source`]s of the endpoint itself.
-200///
-201/// A [`Source`] helps track how and where an address was learned. Multiple
-202/// sources can be associated with a single address, if we have discovered this
-203/// address through multiple means.
-204#[derive(Serialize, Deserialize, strum::Display, Debug, Clone, Eq, PartialEq, Hash)]
-205#[strum(serialize_all = "kebab-case")]
-206#[allow(private_interfaces)]
-207pub enum Source {
-208/// An endpoint communicated with us first via UDP.
-209Udp,
-210/// An endpoint communicated with us first via relay.
-211Relay,
-212/// Application layer added the address directly.
-213App,
-214/// The address was discovered by a discovery service.
-215#[strum(serialize = "{name}")]
-216Discovery {
-217/// The name of the discovery service that discovered the address.
-218name: String,
-219 },
-220/// Application layer with a specific name added the endpoint directly.
-221#[strum(serialize = "{name}")]
-222NamedApp {
-223/// The name of the application that added the endpoint
-224name: String,
-225 },
-226/// The address was advertised by a call-me-maybe DISCO message.
-227#[strum(serialize = "CallMeMaybe")]
-228CallMeMaybe {
-229/// private marker
-230_0: Private,
-231 },
-232/// We received a ping on the path.
-233#[strum(serialize = "Ping")]
-234Ping {
-235/// private marker
-236_0: Private,
-237 },
-238/// We established a connection on this address.
-239#[strum(serialize = "Connection")]
-240Connection {
-241/// private marker
-242_0: Private,
-243 },
-244}
-245
-246/// Helper to ensure certain `Source` variants can not be constructed externally.
-247#[derive(Serialize, Deserialize, Debug, Clone, Copy, Eq, PartialEq, Hash)]
-248struct Private;
-249
-250/// An (Ip, Port) pair.
-251///
-252/// NOTE: storing an [`IpPort`] is safer than storing a [`SocketAddr`] because for IPv6 socket
-253/// addresses include fields that can't be assumed consistent even within a single connection.
-254#[derive(Debug, derive_more::Display, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
-255#[display("{}", SocketAddr::from(*self))]
-256pub struct IpPort {
-257 ip: IpAddr,
-258 port: u16,
-259}
-260
-261impl From<SocketAddr> for IpPort {
-262fn from(socket_addr: SocketAddr) -> Self {
-263Self {
-264 ip: socket_addr.ip(),
-265 port: socket_addr.port(),
-266 }
-267 }
-268}
-269
-270impl From<IpPort> for SocketAddr {
-271fn from(ip_port: IpPort) -> Self {
-272let IpPort { ip, port } = ip_port;
-273 (ip, port).into()
-274 }
-275}
-276
-277impl IpPort {
-278pub fn ip(&self) -> &IpAddr {
-279&self.ip
-280 }
-281
-282pub fn port(&self) -> u16 {
-283self.port
-284 }
-285}
\ No newline at end of file
+122 }
+123 }
+124
+125/// Starts a new remote state actor and returns a handle and a sender.
+126 ///
+127 /// The handle is not inserted into the endpoint map, this must be done by the caller of this function.
+128fn start_remote_state_actor(
+129&self,
+130 eid: EndpointId,
+131 ) -> (RemoteStateHandle, mpsc::Sender<RemoteStateMessage>) {
+132// Ensure there is a RemoteMappedAddr for this EndpointId.
+133self.endpoint_mapped_addrs.get(&eid);
+134let handle = RemoteStateActor::new(
+135 eid,
+136self.local_endpoint_id,
+137self.local_direct_addrs.clone(),
+138self.relay_mapped_addrs.clone(),
+139self.metrics.clone(),
+140self.sender.clone(),
+141self.discovery.clone(),
+142 )
+143 .start();
+144let sender = handle.sender.get().expect("just created");
+145 (handle, sender)
+146 }
+147}
+148
+149/// The origin or *source* through which an address associated with a remote endpoint
+150/// was discovered.
+151///
+152/// An aggregate of the [`Source`]s of all the addresses of an endpoint describe the
+153/// [`Source`]s of the endpoint itself.
+154///
+155/// A [`Source`] helps track how and where an address was learned. Multiple
+156/// sources can be associated with a single address, if we have discovered this
+157/// address through multiple means.
+158#[derive(Serialize, Deserialize, strum::Display, Debug, Clone, Eq, PartialEq, Hash)]
+159#[strum(serialize_all = "kebab-case")]
+160#[allow(private_interfaces)]
+161pub enum Source {
+162/// An endpoint communicated with us first via UDP.
+163Udp,
+164/// An endpoint communicated with us first via relay.
+165Relay,
+166/// Application layer added the address directly.
+167App,
+168/// The address was discovered by a discovery service.
+169#[strum(serialize = "{name}")]
+170Discovery {
+171/// The name of the discovery service that discovered the address.
+172name: String,
+173 },
+174/// Application layer with a specific name added the endpoint directly.
+175#[strum(serialize = "{name}")]
+176NamedApp {
+177/// The name of the application that added the endpoint
+178name: String,
+179 },
+180/// The address was advertised by a call-me-maybe DISCO message.
+181#[strum(serialize = "CallMeMaybe")]
+182CallMeMaybe {
+183/// private marker
+184_0: Private,
+185 },
+186/// We received a ping on the path.
+187#[strum(serialize = "Ping")]
+188Ping {
+189/// private marker
+190_0: Private,
+191 },
+192/// We established a connection on this address.
+193#[strum(serialize = "Connection")]
+194Connection {
+195/// private marker
+196_0: Private,
+197 },
+198}
+199
+200/// Helper to ensure certain `Source` variants can not be constructed externally.
+201#[derive(Serialize, Deserialize, Debug, Clone, Copy, Eq, PartialEq, Hash)]
+202struct Private;
+203
+204/// An (Ip, Port) pair.
+205///
+206/// NOTE: storing an [`IpPort`] is safer than storing a [`SocketAddr`] because for IPv6 socket
+207/// addresses include fields that can't be assumed consistent even within a single connection.
+208#[derive(Debug, derive_more::Display, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
+209#[display("{}", SocketAddr::from(*self))]
+210pub struct IpPort {
+211 ip: IpAddr,
+212 port: u16,
+213}
+214
+215impl From<SocketAddr> for IpPort {
+216fn from(socket_addr: SocketAddr) -> Self {
+217Self {
+218 ip: socket_addr.ip(),
+219 port: socket_addr.port(),
+220 }
+221 }
+222}
+223
+224impl From<IpPort> for SocketAddr {
+225fn from(ip_port: IpPort) -> Self {
+226let IpPort { ip, port } = ip_port;
+227 (ip, port).into()
+228 }
+229}
+230
+231impl IpPort {
+232pub fn ip(&self) -> &IpAddr {
+233&self.ip
+234 }
+235
+236pub fn port(&self) -> u16 {
+237self.port
+238 }
+239}
\ No newline at end of file
diff --git a/pr/3666/docs/src/iroh/magicsock/remote_map/remote_state.rs.html b/pr/3666/docs/src/iroh/magicsock/remote_map/remote_state.rs.html
index 87b3cdff37..23541c8828 100644
--- a/pr/3666/docs/src/iroh/magicsock/remote_map/remote_state.rs.html
+++ b/pr/3666/docs/src/iroh/magicsock/remote_map/remote_state.rs.html
@@ -16,7 +16,7 @@
16};
17use n0_watcher::{Watchable, Watcher};
18use quinn::{PathStats, WeakConnectionHandle};
-19use quinn_proto::{PathError, PathEvent, PathId, PathStatus};
+19use quinn_proto::{PathError, PathEvent, PathId, PathStatus, iroh_hp};
20use rustc_hash::FxHashMap;
21use smallvec::SmallVec;
22use sync_wrapper::SyncStream;
@@ -30,1423 +30,1319 @@
30};
31use super::Source;
32use crate::{
-33 disco::{self},
-34 discovery::{ConcurrentDiscovery, Discovery, DiscoveryError, DiscoveryItem},
-35 endpoint::DirectAddr,
-36 magicsock::{
-37 DiscoState, HEARTBEAT_INTERVAL, MagicsockMetrics, PATH_MAX_IDLE_TIMEOUT,
-38 mapped_addrs::{AddrMap, MappedAddr, RelayMappedAddr},
-39 remote_map::Private,
-40 transports::{self, OwnedTransmit, TransportsSender},
-41 },
-42 util::MaybeFuture,
-43};
-44
-45mod guarded_channel;
-46mod path_state;
-47
-48// TODO: use this
-49// /// The latency at or under which we don't try to upgrade to a better path.
-50// const GOOD_ENOUGH_LATENCY: Duration = Duration::from_millis(5);
-51
-52// TODO: use this
-53// /// How long since the last activity we try to keep an established endpoint peering alive.
-54// ///
-55// /// It's also the idle time at which we stop doing QAD queries to keep NAT mappings alive.
-56// pub(super) const SESSION_ACTIVE_TIMEOUT: Duration = Duration::from_secs(45);
-57
-58// TODO: use this
-59// /// How often we try to upgrade to a better path.
-60// ///
-61// /// Even if we have some non-relay route that works.
-62// const UPGRADE_INTERVAL: Duration = Duration::from_secs(60);
-63
-64/// The value which we close paths.
-65// TODO: Quinn should just do this. Also, I made this value up.
-66const APPLICATION_ABANDON_PATH: u8 = 30;
-67
-68/// The time after which an idle [`RemoteStateActor`] stops.
-69///
-70/// The actor only enters the idle state if no connections are active and no inbox senders exist
-71/// apart from the one stored in the endpoint map. Stopping and restarting the actor in this state
-72/// is not an issue; a timeout here serves the purpose of not stopping-and-recreating actors
-73/// in a high frequency, and to keep data about previous path around for subsequent connections.
-74const ACTOR_MAX_IDLE_TIMEOUT: Duration = Duration::from_secs(60);
-75
-76/// A stream of events from all paths for all connections.
-77///
-78/// The connection is identified using [`ConnId`]. The event `Err` variant happens when the
-79/// actor has lagged processing the events, which is rather critical for us.
-80type PathEvents = MergeUnbounded<
-81 Pin<
-82 Box<dyn Stream<Item = (ConnId, Result<PathEvent, BroadcastStreamRecvError>)> + Send + Sync>,
-83 >,
-84>;
-85
-86/// Either a stream of incoming results from [`ConcurrentDiscovery::resolve`] or infinitely pending.
-87///
-88/// Set to [`Either::Left`] with an always-pending stream while discovery is not running, and to
-89/// [`Either::Right`] while discovery is running.
-90///
-91/// The stream returned from [`ConcurrentDiscovery::resolve`] is `!Sync`. We use the (safe) [`SyncStream`]
-92/// wrapper to make it `Sync` so that the [`RemoteStateActor::run`] future stays `Send`.
-93type DiscoveryStream = Either<
-94 n0_future::stream::Pending<Result<DiscoveryItem, DiscoveryError>>,
-95 SyncStream<BoxStream<Result<DiscoveryItem, DiscoveryError>>>,
-96>;
-97
-98/// List of addrs and path ids for open paths in a connection.
-99pub(crate) type PathAddrList = SmallVec<[(TransportAddr, PathId); 4]>;
-100
-101/// The state we need to know about a single remote endpoint.
-102///
-103/// This actor manages all connections to the remote endpoint. It will trigger holepunching
-104/// and select the best path etc.
-105pub(super) struct RemoteStateActor {
-106/// The endpoint ID of the remote endpoint.
-107endpoint_id: EndpointId,
-108/// The endpoint ID of the local endpoint.
-109local_endpoint_id: EndpointId,
-110
-111// Hooks into the rest of the MagicSocket.
-112 //
-113/// Metrics.
-114metrics: Arc<MagicsockMetrics>,
-115 sender: TransportsSender,
-116/// Our local addresses.
-117 ///
-118 /// These are our local addresses and any reflexive transport addresses.
-119 /// They are called "direct addresses" in the magic socket actor.
-120local_direct_addrs: n0_watcher::Direct<BTreeSet<DirectAddr>>,
-121/// Shared state to allow to encrypt DISCO messages to peers.
-122disco: DiscoState,
-123/// The mapping between endpoints via a relay and their [`RelayMappedAddr`]s.
-124relay_mapped_addrs: AddrMap<(RelayUrl, EndpointId), RelayMappedAddr>,
-125/// Discovery service, cloned from the magicsock.
-126discovery: ConcurrentDiscovery,
-127
-128// Internal state - Quinn Connections we are managing.
-129 //
-130/// All connections we have to this remote endpoint.
-131connections: FxHashMap<ConnId, ConnectionState>,
-132/// Notifications when connections are closed.
-133connections_close: FuturesUnordered<OnClosed>,
-134/// Events emitted by Quinn about path changes, for all paths, all connections.
-135path_events: PathEvents,
-136
-137// Internal state - Holepunching and path state.
-138 //
-139/// All possible paths we are aware of.
-140 ///
-141 /// These paths might be entirely impossible to use, since they are added by discovery
-142 /// mechanisms. The are only potentially usable.
-143paths: RemotePathState,
-144/// Information about the last holepunching attempt.
-145last_holepunch: Option<HolepunchAttempt>,
-146/// The path we currently consider the preferred path to the remote endpoint.
-147 ///
-148 /// **We expect this path to work.** If we become aware this path is broken then it is
-149 /// set back to `None`. Having a selected path does not mean we may not be able to get
-150 /// a better path: e.g. when the selected path is a relay path we still need to trigger
-151 /// holepunching regularly.
-152 ///
-153 /// We only select a path once the path is functional in Quinn.
-154selected_path: Watchable<Option<transports::Addr>>,
-155/// Time at which we should schedule the next holepunch attempt.
-156scheduled_holepunch: Option<Instant>,
-157/// When to next attempt opening paths in [`Self::pending_open_paths`].
-158scheduled_open_path: Option<Instant>,
-159/// Paths which we still need to open.
-160 ///
-161 /// They failed to open because we did not have enough CIDs issued by the remote.
-162pending_open_paths: VecDeque<transports::Addr>,
-163
-164// Internal state - Discovery
-165 //
-166/// Stream of discovery results, or always pending if discovery is not running.
-167discovery_stream: DiscoveryStream,
-168}
-169
-170impl RemoteStateActor {
-171#[allow(clippy::too_many_arguments)]
-172pub(super) fn new(
-173 endpoint_id: EndpointId,
-174 local_endpoint_id: EndpointId,
-175 local_direct_addrs: n0_watcher::Direct<BTreeSet<DirectAddr>>,
-176 disco: DiscoState,
-177 relay_mapped_addrs: AddrMap<(RelayUrl, EndpointId), RelayMappedAddr>,
-178 metrics: Arc<MagicsockMetrics>,
-179 sender: TransportsSender,
-180 discovery: ConcurrentDiscovery,
-181 ) -> Self {
-182Self {
-183 endpoint_id,
-184 local_endpoint_id,
-185 metrics,
-186 local_direct_addrs,
-187 relay_mapped_addrs,
-188 discovery,
-189 disco,
-190 connections: FxHashMap::default(),
-191 connections_close: Default::default(),
-192 path_events: Default::default(),
-193 paths: Default::default(),
-194 last_holepunch: None,
-195 selected_path: Default::default(),
-196 scheduled_holepunch: None,
-197 scheduled_open_path: None,
-198 pending_open_paths: VecDeque::new(),
-199 sender,
-200 discovery_stream: Either::Left(n0_future::stream::pending()),
-201 }
-202 }
-203
-204pub(super) fn start(self) -> RemoteStateHandle {
-205let (tx, rx) = guarded_channel(16);
-206let me = self.local_endpoint_id;
-207let endpoint_id = self.endpoint_id;
-208
-209// Ideally we'd use the endpoint span as parent. We'd have to plug that span into
-210 // here somehow. Instead we have no parent and explicitly set the me attribute. If
-211 // we don't explicitly set a span we get the spans from whatever call happens to
-212 // first create the actor, which is often very confusing as it then keeps those
-213 // spans for all logging of the actor.
-214let task = task::spawn(self.run(rx).instrument(info_span!(
-215 parent: None,
-216"RemoteStateActor",
-217 me = %me.fmt_short(),
-218 remote = %endpoint_id.fmt_short(),
-219 )));
-220 RemoteStateHandle {
-221 sender: tx,
-222 _task: AbortOnDropHandle::new(task),
-223 }
-224 }
-225
-226/// Runs the main loop of the actor.
-227 ///
-228 /// Note that the actor uses async handlers for tasks from the main loop. The actor is
-229 /// not processing items from the inbox while waiting on any async calls. So some
-230 /// discipline is needed to not turn pending for a long time.
-231async fn run(mut self, mut inbox: GuardedReceiver<RemoteStateMessage>) {
-232trace!("actor started");
-233let idle_timeout = time::sleep(ACTOR_MAX_IDLE_TIMEOUT);
-234n0_future::pin!(idle_timeout);
-235loop {
-236let scheduled_path_open = match self.scheduled_open_path {
-237Some(when) => MaybeFuture::Some(time::sleep_until(when)),
-238None => MaybeFuture::None,
-239 };
-240n0_future::pin!(scheduled_path_open);
-241let scheduled_hp = match self.scheduled_holepunch {
-242Some(when) => MaybeFuture::Some(time::sleep_until(when)),
-243None => MaybeFuture::None,
-244 };
-245n0_future::pin!(scheduled_hp);
-246if !inbox.is_idle() || !self.connections.is_empty() {
-247 idle_timeout
-248 .as_mut()
-249 .reset(Instant::now() + ACTOR_MAX_IDLE_TIMEOUT);
-250 }
-251tokio::select! {
-252 biased;
-253 msg = inbox.recv() => {
-254match msg {
-255Some(msg) => self.handle_message(msg).await,
-256None => break,
-257 }
-258 }
-259Some((id, evt)) = self.path_events.next() => {
-260self.handle_path_event(id, evt);
-261 }
-262Some(conn_id) = self.connections_close.next(), if !self.connections_close.is_empty() => {
-263self.connections.remove(&conn_id);
-264if self.connections.is_empty() {
-265trace!("last connection closed - clearing selected_path");
-266self.selected_path.set(None).ok();
-267 }
-268 }
-269 res = self.local_direct_addrs.updated() => {
-270if let Err(n0_watcher::Disconnected) = res {
-271trace!("direct address watcher disconnected, shutting down");
-272break;
+33 discovery::{ConcurrentDiscovery, Discovery, DiscoveryError, DiscoveryItem},
+34 endpoint::DirectAddr,
+35 magicsock::{
+36 HEARTBEAT_INTERVAL, MagicsockMetrics, PATH_MAX_IDLE_TIMEOUT,
+37 mapped_addrs::{AddrMap, MappedAddr, RelayMappedAddr},
+38 remote_map::Private,
+39 transports::{self, OwnedTransmit, TransportsSender},
+40 },
+41 util::MaybeFuture,
+42};
+43
+44/// How often to attempt holepunching.
+45///
+46/// If there have been no changes to the NAT address candidates, holepunching will not be
+47/// attempted more frequently than at this interval.
+48const HOLEPUNCH_ATTEMPTS_INTERVAL: Duration = Duration::from_secs(5);
+49
+50mod guarded_channel;
+51mod path_state;
+52
+53// TODO: use this
+54// /// The latency at or under which we don't try to upgrade to a better path.
+55// const GOOD_ENOUGH_LATENCY: Duration = Duration::from_millis(5);
+56
+57// TODO: use this
+58// /// How long since the last activity we try to keep an established endpoint peering alive.
+59// ///
+60// /// It's also the idle time at which we stop doing QAD queries to keep NAT mappings alive.
+61// pub(super) const SESSION_ACTIVE_TIMEOUT: Duration = Duration::from_secs(45);
+62
+63// TODO: use this
+64// /// How often we try to upgrade to a better path.
+65// ///
+66// /// Even if we have some non-relay route that works.
+67// const UPGRADE_INTERVAL: Duration = Duration::from_secs(60);
+68
+69/// The value which we close paths.
+70// TODO: Quinn should just do this. Also, I made this value up.
+71const APPLICATION_ABANDON_PATH: u8 = 30;
+72
+73/// The time after which an idle [`RemoteStateActor`] stops.
+74///
+75/// The actor only enters the idle state if no connections are active and no inbox senders exist
+76/// apart from the one stored in the endpoint map. Stopping and restarting the actor in this state
+77/// is not an issue; a timeout here serves the purpose of not stopping-and-recreating actors
+78/// in a high frequency, and to keep data about previous path around for subsequent connections.
+79const ACTOR_MAX_IDLE_TIMEOUT: Duration = Duration::from_secs(60);
+80
+81/// A stream of events from all paths for all connections.
+82///
+83/// The connection is identified using [`ConnId`]. The event `Err` variant happens when the
+84/// actor has lagged processing the events, which is rather critical for us.
+85type PathEvents = MergeUnbounded<
+86 Pin<
+87 Box<dyn Stream<Item = (ConnId, Result<PathEvent, BroadcastStreamRecvError>)> + Send + Sync>,
+88 >,
+89>;
+90
+91/// A stream of events of announced NAT traversal candidate addresses for all connections.
+92///
+93/// The connection is identified using [`ConnId`].
+94type AddrEvents = MergeUnbounded<
+95 Pin<
+96 Box<
+97dyn Stream<Item = (ConnId, Result<iroh_hp::Event, BroadcastStreamRecvError>)>
+98 + Send
+99 + Sync,
+100 >,
+101 >,
+102>;
+103
+104/// Either a stream of incoming results from [`ConcurrentDiscovery::resolve`] or infinitely pending.
+105///
+106/// Set to [`Either::Left`] with an always-pending stream while discovery is not running, and to
+107/// [`Either::Right`] while discovery is running.
+108///
+109/// The stream returned from [`ConcurrentDiscovery::resolve`] is `!Sync`. We use the (safe) [`SyncStream`]
+110/// wrapper to make it `Sync` so that the [`RemoteStateActor::run`] future stays `Send`.
+111type DiscoveryStream = Either<
+112 n0_future::stream::Pending<Result<DiscoveryItem, DiscoveryError>>,
+113 SyncStream<BoxStream<Result<DiscoveryItem, DiscoveryError>>>,
+114>;
+115
+116/// List of addrs and path ids for open paths in a connection.
+117pub(crate) type PathAddrList = SmallVec<[(TransportAddr, PathId); 4]>;
+118
+119/// The state we need to know about a single remote endpoint.
+120///
+121/// This actor manages all connections to the remote endpoint. It will trigger holepunching
+122/// and select the best path etc.
+123pub(super) struct RemoteStateActor {
+124/// The endpoint ID of the remote endpoint.
+125endpoint_id: EndpointId,
+126/// The endpoint ID of the local endpoint.
+127local_endpoint_id: EndpointId,
+128
+129// Hooks into the rest of the MagicSocket.
+130 //
+131/// Metrics.
+132metrics: Arc<MagicsockMetrics>,
+133 sender: TransportsSender,
+134/// Our local addresses.
+135 ///
+136 /// These are our local addresses and any reflexive transport addresses.
+137local_direct_addrs: n0_watcher::Direct<BTreeSet<DirectAddr>>,
+138/// The mapping between endpoints via a relay and their [`RelayMappedAddr`]s.
+139relay_mapped_addrs: AddrMap<(RelayUrl, EndpointId), RelayMappedAddr>,
+140/// Discovery service, cloned from the magicsock.
+141discovery: ConcurrentDiscovery,
+142
+143// Internal state - Quinn Connections we are managing.
+144 //
+145/// All connections we have to this remote endpoint.
+146connections: FxHashMap<ConnId, ConnectionState>,
+147/// Notifications when connections are closed.
+148connections_close: FuturesUnordered<OnClosed>,
+149/// Events emitted by Quinn about path changes, for all paths, all connections.
+150path_events: PathEvents,
+151/// A stream of events of announced NAT traversal candidate addresses for all connections.
+152addr_events: AddrEvents,
+153
+154// Internal state - Holepunching and path state.
+155 //
+156/// All possible paths we are aware of.
+157 ///
+158 /// These paths might be entirely impossible to use, since they are added by discovery
+159 /// mechanisms. The are only potentially usable.
+160paths: RemotePathState,
+161/// Information about the last holepunching attempt.
+162last_holepunch: Option<HolepunchAttempt>,
+163/// The path we currently consider the preferred path to the remote endpoint.
+164 ///
+165 /// **We expect this path to work.** If we become aware this path is broken then it is
+166 /// set back to `None`. Having a selected path does not mean we may not be able to get
+167 /// a better path: e.g. when the selected path is a relay path we still need to trigger
+168 /// holepunching regularly.
+169 ///
+170 /// We only select a path once the path is functional in Quinn.
+171selected_path: Watchable<Option<transports::Addr>>,
+172/// Time at which we should schedule the next holepunch attempt.
+173scheduled_holepunch: Option<Instant>,
+174/// When to next attempt opening paths in [`Self::pending_open_paths`].
+175scheduled_open_path: Option<Instant>,
+176/// Paths which we still need to open.
+177 ///
+178 /// They failed to open because we did not have enough CIDs issued by the remote.
+179pending_open_paths: VecDeque<transports::Addr>,
+180
+181// Internal state - Discovery
+182 //
+183/// Stream of discovery results, or always pending if discovery is not running.
+184discovery_stream: DiscoveryStream,
+185}
+186
+187impl RemoteStateActor {
+188#[allow(clippy::too_many_arguments)]
+189pub(super) fn new(
+190 endpoint_id: EndpointId,
+191 local_endpoint_id: EndpointId,
+192 local_direct_addrs: n0_watcher::Direct<BTreeSet<DirectAddr>>,
+193 relay_mapped_addrs: AddrMap<(RelayUrl, EndpointId), RelayMappedAddr>,
+194 metrics: Arc<MagicsockMetrics>,
+195 sender: TransportsSender,
+196 discovery: ConcurrentDiscovery,
+197 ) -> Self {
+198Self {
+199 endpoint_id,
+200 local_endpoint_id,
+201 metrics,
+202 local_direct_addrs,
+203 relay_mapped_addrs,
+204 discovery,
+205 connections: FxHashMap::default(),
+206 connections_close: Default::default(),
+207 path_events: Default::default(),
+208 addr_events: Default::default(),
+209 paths: Default::default(),
+210 last_holepunch: None,
+211 selected_path: Default::default(),
+212 scheduled_holepunch: None,
+213 scheduled_open_path: None,
+214 pending_open_paths: VecDeque::new(),
+215 sender,
+216 discovery_stream: Either::Left(n0_future::stream::pending()),
+217 }
+218 }
+219
+220pub(super) fn start(self) -> RemoteStateHandle {
+221let (tx, rx) = guarded_channel(16);
+222let me = self.local_endpoint_id;
+223let endpoint_id = self.endpoint_id;
+224
+225// Ideally we'd use the endpoint span as parent. We'd have to plug that span into
+226 // here somehow. Instead we have no parent and explicitly set the me attribute. If
+227 // we don't explicitly set a span we get the spans from whatever call happens to
+228 // first create the actor, which is often very confusing as it then keeps those
+229 // spans for all logging of the actor.
+230let task = task::spawn(self.run(rx).instrument(info_span!(
+231 parent: None,
+232"RemoteStateActor",
+233 me = %me.fmt_short(),
+234 remote = %endpoint_id.fmt_short(),
+235 )));
+236 RemoteStateHandle {
+237 sender: tx,
+238 _task: AbortOnDropHandle::new(task),
+239 }
+240 }
+241
+242/// Runs the main loop of the actor.
+243 ///
+244 /// Note that the actor uses async handlers for tasks from the main loop. The actor is
+245 /// not processing items from the inbox while waiting on any async calls. So some
+246 /// discipline is needed to not turn pending for a long time.
+247async fn run(mut self, mut inbox: GuardedReceiver<RemoteStateMessage>) {
+248trace!("actor started");
+249let idle_timeout = time::sleep(ACTOR_MAX_IDLE_TIMEOUT);
+250n0_future::pin!(idle_timeout);
+251loop {
+252let scheduled_path_open = match self.scheduled_open_path {
+253Some(when) => MaybeFuture::Some(time::sleep_until(when)),
+254None => MaybeFuture::None,
+255 };
+256n0_future::pin!(scheduled_path_open);
+257let scheduled_hp = match self.scheduled_holepunch {
+258Some(when) => MaybeFuture::Some(time::sleep_until(when)),
+259None => MaybeFuture::None,
+260 };
+261n0_future::pin!(scheduled_hp);
+262if !inbox.is_idle() || !self.connections.is_empty() {
+263 idle_timeout
+264 .as_mut()
+265 .reset(Instant::now() + ACTOR_MAX_IDLE_TIMEOUT);
+266 }
+267tokio::select! {
+268 biased;
+269 msg = inbox.recv() => {
+270match msg {
+271Some(msg) => self.handle_message(msg).await,
+272None => break,
273 }
-274trace!("local addrs updated, triggering holepunching");
-275self.trigger_holepunching().await;
-276 }
-277_ = &mut scheduled_path_open => {
-278trace!("triggering scheduled path_open");
-279self.scheduled_open_path = None;
-280let mut addrs = std::mem::take(&mut self.pending_open_paths);
-281while let Some(addr) = addrs.pop_front() {
-282self.open_path(&addr);
-283 }
-284 }
-285_ = &mut scheduled_hp => {
-286trace!("triggering scheduled holepunching");
-287self.scheduled_holepunch = None;
-288self.trigger_holepunching().await;
-289 }
-290 item = self.discovery_stream.next() => {
-291self.handle_discovery_item(item);
-292 }
-293_ = &mut idle_timeout => {
-294if self.connections.is_empty() && inbox.close_if_idle() {
-295trace!("idle timeout expired and still idle: terminate actor");
-296break;
-297 } else {
-298// Seems like we weren't really idle, so we reset
-299idle_timeout.as_mut().reset(Instant::now() + ACTOR_MAX_IDLE_TIMEOUT);
-300 }
-301 }
-302 }
-303 }
-304trace!("actor terminating");
-305 }
-306
-307/// Handles an actor message.
-308 ///
-309 /// Error returns are fatal and kill the actor.
-310#[instrument(skip(self))]
-311async fn handle_message(&mut self, msg: RemoteStateMessage) {
-312// trace!("handling message");
-313match msg {
-314 RemoteStateMessage::SendDatagram(transmit) => {
-315self.handle_msg_send_datagram(transmit).await;
-316 }
-317 RemoteStateMessage::AddConnection(handle, tx) => {
-318self.handle_msg_add_connection(handle, tx).await;
-319 }
-320 RemoteStateMessage::CallMeMaybeReceived(msg) => {
-321self.handle_msg_call_me_maybe_received(msg).await;
-322 }
-323 RemoteStateMessage::PingReceived(ping, src) => {
-324self.handle_msg_ping_received(ping, src).await;
-325 }
-326 RemoteStateMessage::PongReceived(pong, src) => {
-327self.handle_msg_pong_received(pong, src);
-328 }
-329 RemoteStateMessage::ResolveRemote(addrs, tx) => {
-330self.handle_msg_resolve_remote(addrs, tx);
-331 }
-332 RemoteStateMessage::Latency(tx) => {
-333self.handle_msg_latency(tx);
-334 }
-335 }
-336 }
-337
-338async fn send_datagram(
-339&self,
-340 dst: transports::Addr,
-341 owned_transmit: OwnedTransmit,
-342 ) -> n0_error::Result<()> {
-343let transmit = transports::Transmit {
-344 ecn: owned_transmit.ecn,
-345 contents: owned_transmit.contents.as_ref(),
-346 segment_size: owned_transmit.segment_size,
-347 };
-348self.sender
-349 .send(&dst, None, &transmit)
-350 .await
-351.with_context(|_| format!("failed to send datagram to {dst:?}"))?;
-352Ok(())
-353 }
-354
-355/// Handles [`RemoteStateMessage::SendDatagram`].
-356async fn handle_msg_send_datagram(&mut self, transmit: OwnedTransmit) {
-357// Sending datagrams might fail, e.g. because we don't have the right transports set
-358 // up to handle sending this owned transmit to.
-359 // After all, we try every single path that we know (relay URL, IP address), even
-360 // though we might not have a relay transport or ip-capable transport set up.
-361 // So these errors must not be fatal for this actor (or even this operation).
-362
-363if let Some(addr) = self.selected_path.get() {
-364trace!(?addr, "sending datagram to selected path");
-365
-366if let Err(err) = self.send_datagram(addr.clone(), transmit).await {
-367debug!(?addr, "failed to send datagram on selected_path: {err:#}");
-368 }
-369 } else {
-370trace!(
-371 paths = ?self.paths.addrs().collect::<Vec<_>>(),
-372"sending datagram to all known paths",
-373 );
-374if self.paths.is_empty() {
-375warn!("Cannot send datagrams: No paths to remote endpoint known");
-376 }
-377for addr in self.paths.addrs() {
-378// We never want to send to our local addresses.
-379 // The local address set is updated in the main loop so we can use `peek` here.
-380if let transports::Addr::Ip(sockaddr) = addr
-381 && self
-382.local_direct_addrs
-383 .peek()
-384 .iter()
-385 .any(|a| a.addr == *sockaddr)
-386 {
-387trace!(%sockaddr, "not sending datagram to our own address");
-388 } else if let Err(err) = self.send_datagram(addr.clone(), transmit.clone()).await {
-389debug!(?addr, "failed to send datagram: {err:#}");
-390 }
-391 }
-392// This message is received *before* a connection is added. So we do
-393 // not yet have a connection to holepunch. Instead we trigger
-394 // holepunching when AddConnection is received.
-395}
-396 }
-397
-398/// Handles [`RemoteStateMessage::AddConnection`].
-399 ///
-400 /// Error returns are fatal and kill the actor.
-401async fn handle_msg_add_connection(
-402&mut self,
-403 handle: WeakConnectionHandle,
-404 tx: oneshot::Sender<PathsWatcher>,
-405 ) {
-406let pub_open_paths = Watchable::default();
-407if let Some(conn) = handle.upgrade() {
-408// Remove any conflicting stable_ids from the local state.
-409let conn_id = ConnId(conn.stable_id());
-410self.connections.remove(&conn_id);
-411
-412// Store the connection and hook up paths events stream.
-413let events = BroadcastStream::new(conn.path_events());
-414let stream = events.map(move |evt| (conn_id, evt));
-415self.path_events.push(Box::pin(stream));
-416self.connections_close.push(OnClosed::new(&conn));
-417let conn_state = self
-418.connections
-419 .entry(conn_id)
-420 .insert_entry(ConnectionState {
-421 handle: handle.clone(),
-422 pub_open_paths: pub_open_paths.clone(),
-423 paths: Default::default(),
-424 open_paths: Default::default(),
-425 path_ids: Default::default(),
-426 })
-427 .into_mut();
-428
-429// Store PathId(0), set path_status and select best path, check if holepunching
-430 // is needed.
-431if let Some(path) = conn.path(PathId::ZERO)
-432 && let Ok(socketaddr) = path.remote_address()
-433 && let Some(path_remote) = self.relay_mapped_addrs.to_transport_addr(socketaddr)
-434 {
-435trace!(?path_remote, "added new connection");
-436let path_remote_is_ip = path_remote.is_ip();
-437let status = match path_remote {
-438 transports::Addr::Ip(_) => PathStatus::Available,
-439 transports::Addr::Relay(_, _) => PathStatus::Backup,
-440 };
-441 path.set_status(status).ok();
-442 conn_state.add_open_path(path_remote.clone(), PathId::ZERO);
-443self.paths
-444 .insert(path_remote, Source::Connection { _0: Private });
-445self.select_path();
-446self.prune_ip_paths();
-447
-448if path_remote_is_ip {
-449// We may have raced this with a relay address. Try and add any
-450 // relay addresses we have back.
-451let relays = self
-452.paths
-453 .addrs()
-454 .filter(|a| a.is_relay())
-455 .cloned()
-456 .collect::<Vec<_>>();
-457for remote in relays {
-458self.open_path(&remote);
-459 }
-460 }
-461 }
-462self.trigger_holepunching().await;
-463 }
-464 tx.send(PathsWatcher::new(
-465 pub_open_paths.watch(),
-466self.selected_path.watch(),
-467 handle,
-468 ))
-469 .ok();
-470 }
-471
-472/// Handles [`RemoteStateMessage::CallMeMaybeReceived`].
-473async fn handle_msg_call_me_maybe_received(&mut self, msg: disco::CallMeMaybe) {
-474event!(
-475 target: "iroh::_events::call_me_maybe::recv",
-476 Level::DEBUG,
-477 remote = %self.endpoint_id.fmt_short(),
-478 addrs = ?msg.my_numbers,
-479 );
-480for addr in msg.my_numbers {
-481let dst = transports::Addr::Ip(addr);
-482let ping = disco::Ping::new(self.local_endpoint_id);
-483
-484self.paths
-485 .insert(dst.clone(), Source::CallMeMaybe { _0: Private });
-486self.paths.disco_ping_sent(dst.clone(), ping.tx_id);
-487
-488event!(
-489 target: "iroh::_events::ping::sent",
-490 Level::DEBUG,
-491 remote = %self.endpoint_id.fmt_short(),
-492?dst,
-493 );
-494self.send_disco_message(dst, disco::Message::Ping(ping))
-495 .await;
-496 }
-497// prune any unused/inactive paths, now that we have added potential
-498 // new ones
-499self.prune_ip_paths()
-500 }
-501
-502/// Handles [`RemoteStateMessage::PingReceived`].
-503async fn handle_msg_ping_received(&mut self, ping: disco::Ping, src: transports::Addr) {
-504let transports::Addr::Ip(addr) = src else {
-505warn!("received ping via relay transport, ignored");
-506return;
-507 };
-508event!(
-509 target: "iroh::_events::ping::recv",
-510 Level::DEBUG,
-511 remote = %self.endpoint_id.fmt_short(),
-512?src,
-513 txn = ?ping.tx_id,
-514 );
-515let pong = disco::Pong {
-516 tx_id: ping.tx_id,
-517 ping_observed_addr: addr.into(),
-518 };
-519event!(
-520 target: "iroh::_events::pong::sent",
-521 Level::DEBUG,
-522 remote = %self.endpoint_id.fmt_short(),
-523 dst = ?src,
-524 txn = ?pong.tx_id,
-525 );
-526self.send_disco_message(src.clone(), disco::Message::Pong(pong))
-527 .await;
-528
-529self.paths.insert(src, Source::Ping { _0: Private });
-530
-531trace!("ping received, triggering holepunching");
-532self.trigger_holepunching().await;
-533self.prune_ip_paths();
+274 }
+275Some((id, evt)) = self.path_events.next() => {
+276self.handle_path_event(id, evt);
+277 }
+278Some((id, _)) = self.addr_events.next() => {
+279trace!(?id, "remote addrs updated, triggering holepunching");
+280self.trigger_holepunching().await;
+281 }
+282Some(conn_id) = self.connections_close.next(), if !self.connections_close.is_empty() => {
+283self.connections.remove(&conn_id);
+284if self.connections.is_empty() {
+285trace!("last connection closed - clearing selected_path");
+286self.selected_path.set(None).ok();
+287 }
+288 }
+289 res = self.local_direct_addrs.updated() => {
+290if let Err(n0_watcher::Disconnected) = res {
+291trace!("direct address watcher disconnected, shutting down");
+292break;
+293 }
+294self.local_addrs_updated();
+295trace!("local addrs updated, triggering holepunching");
+296self.trigger_holepunching().await;
+297 }
+298_ = &mut scheduled_path_open => {
+299trace!("triggering scheduled path_open");
+300self.scheduled_open_path = None;
+301let mut addrs = std::mem::take(&mut self.pending_open_paths);
+302while let Some(addr) = addrs.pop_front() {
+303self.open_path(&addr);
+304 }
+305 }
+306_ = &mut scheduled_hp => {
+307trace!("triggering scheduled holepunching");
+308self.scheduled_holepunch = None;
+309self.trigger_holepunching().await;
+310 }
+311 item = self.discovery_stream.next() => {
+312self.handle_discovery_item(item);
+313 }
+314_ = &mut idle_timeout => {
+315if self.connections.is_empty() && inbox.close_if_idle() {
+316trace!("idle timeout expired and still idle: terminate actor");
+317break;
+318 } else {
+319// Seems like we weren't really idle, so we reset
+320idle_timeout.as_mut().reset(Instant::now() + ACTOR_MAX_IDLE_TIMEOUT);
+321 }
+322 }
+323 }
+324 }
+325trace!("actor terminating");
+326 }
+327
+328/// Handles an actor message.
+329 ///
+330 /// Error returns are fatal and kill the actor.
+331#[instrument(skip(self))]
+332async fn handle_message(&mut self, msg: RemoteStateMessage) {
+333// trace!("handling message");
+334match msg {
+335 RemoteStateMessage::SendDatagram(transmit) => {
+336self.handle_msg_send_datagram(transmit).await;
+337 }
+338 RemoteStateMessage::AddConnection(handle, tx) => {
+339self.handle_msg_add_connection(handle, tx).await;
+340 }
+341 RemoteStateMessage::ResolveRemote(addrs, tx) => {
+342self.handle_msg_resolve_remote(addrs, tx);
+343 }
+344 RemoteStateMessage::Latency(tx) => {
+345self.handle_msg_latency(tx);
+346 }
+347 }
+348 }
+349
+350async fn send_datagram(
+351&self,
+352 dst: transports::Addr,
+353 owned_transmit: OwnedTransmit,
+354 ) -> n0_error::Result<()> {
+355let transmit = transports::Transmit {
+356 ecn: owned_transmit.ecn,
+357 contents: owned_transmit.contents.as_ref(),
+358 segment_size: owned_transmit.segment_size,
+359 };
+360self.sender
+361 .send(&dst, None, &transmit)
+362 .await
+363.with_context(|_| format!("failed to send datagram to {dst:?}"))?;
+364Ok(())
+365 }
+366
+367/// Handles [`RemoteStateMessage::SendDatagram`].
+368async fn handle_msg_send_datagram(&mut self, transmit: OwnedTransmit) {
+369// Sending datagrams might fail, e.g. because we don't have the right transports set
+370 // up to handle sending this owned transmit to.
+371 // After all, we try every single path that we know (relay URL, IP address), even
+372 // though we might not have a relay transport or ip-capable transport set up.
+373 // So these errors must not be fatal for this actor (or even this operation).
+374
+375if let Some(addr) = self.selected_path.get() {
+376trace!(?addr, "sending datagram to selected path");
+377
+378if let Err(err) = self.send_datagram(addr.clone(), transmit).await {
+379debug!(?addr, "failed to send datagram on selected_path: {err:#}");
+380 }
+381 } else {
+382trace!(
+383 paths = ?self.paths.addrs().collect::<Vec<_>>(),
+384"sending datagram to all known paths",
+385 );
+386if self.paths.is_empty() {
+387warn!("Cannot send datagrams: No paths to remote endpoint known");
+388 }
+389for addr in self.paths.addrs() {
+390// We never want to send to our local addresses.
+391 // The local address set is updated in the main loop so we can use `peek` here.
+392if let transports::Addr::Ip(sockaddr) = addr
+393 && self
+394.local_direct_addrs
+395 .peek()
+396 .iter()
+397 .any(|a| a.addr == *sockaddr)
+398 {
+399trace!(%sockaddr, "not sending datagram to our own address");
+400 } else if let Err(err) = self.send_datagram(addr.clone(), transmit.clone()).await {
+401debug!(?addr, "failed to send datagram: {err:#}");
+402 }
+403 }
+404// This message is received *before* a connection is added. So we do
+405 // not yet have a connection to holepunch. Instead we trigger
+406 // holepunching when AddConnection is received.
+407}
+408 }
+409
+410/// Handles [`RemoteStateMessage::AddConnection`].
+411 ///
+412 /// Error returns are fatal and kill the actor.
+413async fn handle_msg_add_connection(
+414&mut self,
+415 handle: WeakConnectionHandle,
+416 tx: oneshot::Sender<PathsWatcher>,
+417 ) {
+418let pub_open_paths = Watchable::default();
+419if let Some(conn) = handle.upgrade() {
+420// Remove any conflicting stable_ids from the local state.
+421let conn_id = ConnId(conn.stable_id());
+422self.connections.remove(&conn_id);
+423
+424// Hook up paths, NAT addresses and connection closed event streams.
+425self.path_events.push(Box::pin(
+426 BroadcastStream::new(conn.path_events()).map(move |evt| (conn_id, evt)),
+427 ));
+428self.addr_events.push(Box::pin(
+429 BroadcastStream::new(conn.nat_traversal_updates()).map(move |evt| (conn_id, evt)),
+430 ));
+431self.connections_close.push(OnClosed::new(&conn));
+432
+433// Add local addrs to the connection
+434let local_addrs = self
+435.local_direct_addrs
+436 .get()
+437 .iter()
+438 .map(|d| d.addr)
+439 .collect::<BTreeSet<_>>();
+440Self::set_local_addrs(&conn, &local_addrs);
+441
+442// Store the connection
+443let conn_state = self
+444.connections
+445 .entry(conn_id)
+446 .insert_entry(ConnectionState {
+447 handle: handle.clone(),
+448 pub_open_paths: pub_open_paths.clone(),
+449 paths: Default::default(),
+450 open_paths: Default::default(),
+451 path_ids: Default::default(),
+452 })
+453 .into_mut();
+454
+455// Store PathId(0), set path_status and select best path, check if holepunching
+456 // is needed.
+457if let Some(path) = conn.path(PathId::ZERO)
+458 && let Ok(socketaddr) = path.remote_address()
+459 && let Some(path_remote) = self.relay_mapped_addrs.to_transport_addr(socketaddr)
+460 {
+461trace!(?path_remote, "added new connection");
+462let path_remote_is_ip = path_remote.is_ip();
+463let status = match path_remote {
+464 transports::Addr::Ip(_) => PathStatus::Available,
+465 transports::Addr::Relay(_, _) => PathStatus::Backup,
+466 };
+467 path.set_status(status).ok();
+468 conn_state.add_open_path(path_remote.clone(), PathId::ZERO);
+469self.paths
+470 .insert(path_remote.clone(), Source::Connection { _0: Private });
+471self.paths.opened_path(&path_remote);
+472self.select_path();
+473self.prune_paths();
+474
+475if path_remote_is_ip {
+476// We may have raced this with a relay address. Try and add any
+477 // relay addresses we have back.
+478let relays = self
+479.paths
+480 .addrs()
+481 .filter(|a| a.is_relay())
+482 .cloned()
+483 .collect::<Vec<_>>();
+484for remote in relays {
+485self.open_path(&remote);
+486 }
+487 }
+488 }
+489self.trigger_holepunching().await;
+490 }
+491 tx.send(PathsWatcher::new(
+492 pub_open_paths.watch(),
+493self.selected_path.watch(),
+494 handle,
+495 ))
+496 .ok();
+497 }
+498
+499/// Handles [`RemoteStateMessage::ResolveRemote`].
+500fn handle_msg_resolve_remote(
+501&mut self,
+502 addrs: BTreeSet<TransportAddr>,
+503 tx: oneshot::Sender<Result<(), DiscoveryError>>,
+504 ) {
+505let addrs = to_transports_addr(self.endpoint_id, addrs);
+506self.paths.insert_multiple(addrs, Source::App);
+507self.paths.resolve_remote(tx);
+508// Start discovery if we have no selected path.
+509self.trigger_discovery();
+510self.prune_paths();
+511 }
+512
+513/// Handles [`RemoteStateMessage::Latency`].
+514fn handle_msg_latency(&self, tx: oneshot::Sender<Option<Duration>>) {
+515let rtt = self.selected_path.get().and_then(|addr| {
+516for conn_state in self.connections.values() {
+517let Some(path_id) = conn_state.path_ids.get(&addr) else {
+518continue;
+519 };
+520if !conn_state.open_paths.contains_key(path_id) {
+521continue;
+522 }
+523if let Some(rtt) = conn_state
+524 .handle
+525 .upgrade()
+526 .and_then(|conn| conn.path_stats(*path_id).map(|stats| stats.rtt))
+527 {
+528return Some(rtt);
+529 }
+530 }
+531None
+532});
+533 tx.send(rtt).ok();
534 }
535
-536/// Handles [`RemoteStateMessage::PongReceived`].
-537fn handle_msg_pong_received(&mut self, pong: disco::Pong, src: transports::Addr) {
-538if self.paths.disco_pong_received(&src, pong.tx_id) {
-539event!(
-540 target: "iroh::_events::pong::recv",
-541 Level::DEBUG,
-542 remote_endpoint = %self.endpoint_id.fmt_short(),
-543?src,
-544 txn = ?pong.tx_id,
-545 );
-546// mark that this path has been holepunched
-547self.paths.holepunched(&src);
-548self.open_path(&src);
-549 }
-550 }
-551
-552/// Handles [`RemoteStateMessage::ResolveRemote`].
-553fn handle_msg_resolve_remote(
-554&mut self,
-555 addrs: BTreeSet<TransportAddr>,
-556 tx: oneshot::Sender<Result<(), DiscoveryError>>,
-557 ) {
-558let addrs = to_transports_addr(self.endpoint_id, addrs);
-559self.paths.insert_multiple(addrs, Source::App);
-560self.paths.resolve_remote(tx);
-561// Start discovery if we have no selected path.
-562self.trigger_discovery();
-563 }
-564
-565/// Handles [`RemoteStateMessage::Latency`].
-566fn handle_msg_latency(&self, tx: oneshot::Sender<Option<Duration>>) {
-567let rtt = self.selected_path.get().and_then(|addr| {
-568for conn_state in self.connections.values() {
-569let Some(path_id) = conn_state.path_ids.get(&addr) else {
-570continue;
-571 };
-572if !conn_state.open_paths.contains_key(path_id) {
-573continue;
-574 }
-575if let Some(rtt) = conn_state
-576 .handle
-577 .upgrade()
-578 .and_then(|conn| conn.path_stats(*path_id).map(|stats| stats.rtt))
-579 {
-580return Some(rtt);
-581 }
-582 }
-583None
-584});
-585 tx.send(rtt).ok();
-586 }
-587
-588fn handle_discovery_item(&mut self, item: Option<Result<DiscoveryItem, DiscoveryError>>) {
-589match item {
-590None => {
-591self.discovery_stream = Either::Left(n0_future::stream::pending());
-592self.paths.discovery_finished(Ok(()));
-593 }
-594Some(Err(err)) => {
-595warn!("Discovery failed: {err:#}");
-596self.discovery_stream = Either::Left(n0_future::stream::pending());
-597self.paths.discovery_finished(Err(err));
+536fn handle_discovery_item(&mut self, item: Option<Result<DiscoveryItem, DiscoveryError>>) {
+537match item {
+538None => {
+539self.discovery_stream = Either::Left(n0_future::stream::pending());
+540self.paths.discovery_finished(Ok(()));
+541 }
+542Some(Err(err)) => {
+543warn!("Discovery failed: {err:#}");
+544self.discovery_stream = Either::Left(n0_future::stream::pending());
+545self.paths.discovery_finished(Err(err));
+546 }
+547Some(Ok(item)) => {
+548if item.endpoint_id() != self.endpoint_id {
+549warn!(?item, "Discovery emitted item for wrong remote endpoint");
+550 } else {
+551let source = Source::Discovery {
+552 name: item.provenance().to_string(),
+553 };
+554let addrs =
+555 to_transports_addr(self.endpoint_id, item.into_endpoint_addr().addrs);
+556self.paths.insert_multiple(addrs, source);
+557self.prune_paths();
+558 }
+559 }
+560 }
+561 }
+562
+563/// Triggers discovery for the remote endpoint, if needed.
+564 ///
+565 /// Does not start discovery if we have a selected path or if discovery is currently running.
+566fn trigger_discovery(&mut self) {
+567if self.selected_path.get().is_some() || matches!(self.discovery_stream, Either::Right(_)) {
+568return;
+569 }
+570match self.discovery.resolve(self.endpoint_id) {
+571Some(stream) => self.discovery_stream = Either::Right(SyncStream::new(stream)),
+572None => self.paths.discovery_finished(Ok(())),
+573 }
+574 }
+575
+576/// Sets the current local addresses to QNT's state to all connections
+577fn local_addrs_updated(&mut self) {
+578let local_addrs = self
+579.local_direct_addrs
+580 .get()
+581 .iter()
+582 .map(|d| d.addr)
+583 .collect::<BTreeSet<_>>();
+584
+585for conn in self.connections.values().filter_map(|s| s.handle.upgrade()) {
+586Self::set_local_addrs(&conn, &local_addrs);
+587 }
+588// todo: trace
+589}
+590
+591/// Sets the current local addresses to QNT's state
+592fn set_local_addrs(conn: &quinn::Connection, local_addrs: &BTreeSet<SocketAddr>) {
+593let quinn_local_addrs = match conn.get_local_nat_traversal_addresses() {
+594Ok(addrs) => BTreeSet::from_iter(addrs),
+595Err(err) => {
+596warn!("failed to get local nat candidates: {err:#}");
+597return;
598 }
-599Some(Ok(item)) => {
-600if item.endpoint_id() != self.endpoint_id {
-601warn!(?item, "Discovery emitted item for wrong remote endpoint");
-602 } else {
-603let source = Source::Discovery {
-604 name: item.provenance().to_string(),
-605 };
-606let addrs =
-607 to_transports_addr(self.endpoint_id, item.into_endpoint_addr().addrs);
-608self.paths.insert_multiple(addrs, source);
-609 }
-610 }
-611 }
-612 }
-613
-614/// Triggers discovery for the remote endpoint, if needed.
-615 ///
-616 /// Does not start discovery if we have a selected path or if discovery is currently running.
-617fn trigger_discovery(&mut self) {
-618if self.selected_path.get().is_some() || matches!(self.discovery_stream, Either::Right(_)) {
-619return;
-620 }
-621match self.discovery.resolve(self.endpoint_id) {
-622Some(stream) => self.discovery_stream = Either::Right(SyncStream::new(stream)),
-623None => self.paths.discovery_finished(Ok(())),
-624 }
-625 }
-626
-627/// Triggers holepunching to the remote endpoint.
-628 ///
-629 /// This will manage the entire process of holepunching with the remote endpoint.
-630 ///
-631 /// - If there already is a direct connection, nothing happens.
-632 /// - If there is no relay address known, nothing happens.
-633 /// - If there was a recent attempt, it will schedule holepunching instead.
-634 /// - Unless there are new addresses to try.
-635 /// - The scheduled attempt will only run if holepunching has not yet succeeded by
-636 /// then.
-637 /// - DISCO pings will be sent to addresses recently advertised in a call-me-maybe
-638 /// message.
-639 /// - A DISCO call-me-maybe message advertising our own addresses will be sent.
-640 ///
-641 /// If a next trigger needs to be scheduled the delay until when to call this again is
-642 /// returned.
-643async fn trigger_holepunching(&mut self) {
-644const HOLEPUNCH_ATTEMPTS_INTERVAL: Duration = Duration::from_secs(5);
-645
-646if self.connections.is_empty() {
-647trace!("not holepunching: no connections");
-648return;
-649 }
-650
-651if self
-652.selected_path
-653 .get()
-654 .map(|addr| addr.is_ip())
-655 .unwrap_or_default()
-656 {
-657// TODO: We should ping this path to make sure it still works. Because we now
-658 // know things could be broken.
-659trace!("not holepunching: already have a direct connection");
-660// TODO: If the latency is kind of bad we should retry holepunching at times.
-661return;
-662 }
-663
-664let remote_addrs: BTreeSet<SocketAddr> = self.remote_hp_addrs();
-665let local_addrs: BTreeSet<SocketAddr> = self
-666.local_direct_addrs
-667 .get()
-668 .iter()
-669 .map(|daddr| daddr.addr)
-670 .collect();
-671let new_addrs = self
-672.last_holepunch
-673 .as_ref()
-674 .map(|last_hp| {
-675// Addrs are allowed to disappear, but if there are new ones we need to
-676 // holepunch again.
-677trace!(?last_hp, ?local_addrs, ?remote_addrs, "addrs to holepunch?");
-678 !remote_addrs.is_subset(&last_hp.remote_addrs)
-679 || !local_addrs.is_subset(&last_hp.local_addrs)
-680 })
-681 .unwrap_or(true);
-682if !new_addrs {
-683if let Some(ref last_hp) = self.last_holepunch {
-684let next_hp = last_hp.when + HOLEPUNCH_ATTEMPTS_INTERVAL;
-685let now = Instant::now();
-686if next_hp > now {
-687trace!(scheduled_in = ?(next_hp - now), "not holepunching: no new addresses");
-688self.scheduled_holepunch = Some(next_hp);
-689return;
-690 }
-691 }
-692 }
-693
-694self.do_holepunching().await;
-695 }
-696
-697/// Returns the remote addresses to holepunch against.
-698fn remote_hp_addrs(&self) -> BTreeSet<SocketAddr> {
-699const CALL_ME_MAYBE_VALIDITY: Duration = Duration::from_secs(30);
-700
-701self.paths
-702 .iter()
-703 .filter_map(|(addr, state)| match addr {
-704 transports::Addr::Ip(socket_addr) => Some((socket_addr, state)),
-705 transports::Addr::Relay(_, _) => None,
-706 })
-707 .filter_map(|(addr, state)| {
-708if state
-709 .sources
-710 .get(&Source::CallMeMaybe { _0: Private })
-711 .map(|when| when.elapsed() <= CALL_ME_MAYBE_VALIDITY)
-712 .unwrap_or_default()
-713 || state
-714 .sources
-715 .get(&Source::Ping { _0: Private })
-716 .map(|when| when.elapsed() <= CALL_ME_MAYBE_VALIDITY)
-717 .unwrap_or_default()
-718 {
-719Some(*addr)
-720 } else {
-721None
-722}
-723 })
-724 .collect()
-725 }
-726
-727/// Unconditionally perform holepunching.
-728 ///
-729 /// - DISCO pings will be sent to addresses recently advertised in a call-me-maybe
-730 /// message.
-731 /// - A DISCO call-me-maybe message advertising our own addresses will be sent.
-732#[instrument(skip_all)]
-733async fn do_holepunching(&mut self) {
-734let Some(relay_addr) = self.paths.addrs().find(|addr| addr.is_relay()).cloned() else {
-735warn!("holepunching requested but have no relay address");
-736return;
-737 };
-738let remote_addrs = self.remote_hp_addrs();
-739
-740// Send DISCO Ping messages to all CallMeMaybe-advertised paths.
-741for dst in remote_addrs.iter() {
-742let msg = disco::Ping::new(self.local_endpoint_id);
-743event!(
-744 target: "iroh::_events::ping::sent",
-745 Level::DEBUG,
-746 remote = %self.endpoint_id.fmt_short(),
-747?dst,
-748 txn = ?msg.tx_id,
-749 );
-750let addr = transports::Addr::Ip(*dst);
-751self.paths.disco_ping_sent(addr.clone(), msg.tx_id);
-752self.send_disco_message(addr, disco::Message::Ping(msg))
-753 .await;
-754 }
-755
-756// Send the DISCO CallMeMaybe message over the relay.
-757let my_numbers: Vec<SocketAddr> = self
-758.local_direct_addrs
-759 .get()
-760 .iter()
-761 .map(|daddr| daddr.addr)
-762 .collect();
-763let local_addrs: BTreeSet<SocketAddr> = my_numbers.iter().copied().collect();
-764let msg = disco::CallMeMaybe { my_numbers };
-765event!(
-766 target: "iroh::_events::call_me_maybe::sent",
-767 Level::DEBUG,
-768 remote = %self.endpoint_id.fmt_short(),
-769 dst = ?relay_addr,
-770 my_numbers = ?msg.my_numbers,
-771 );
-772self.send_disco_message(relay_addr, disco::Message::CallMeMaybe(msg))
-773 .await;
-774
-775self.last_holepunch = Some(HolepunchAttempt {
-776 when: Instant::now(),
-777 local_addrs,
-778 remote_addrs,
-779 });
-780 }
-781
-782/// Sends a DISCO message to the remote endpoint this actor manages.
-783#[instrument(skip(self), fields(remote = %self.endpoint_id.fmt_short()))]
-784async fn send_disco_message(&self, dst: transports::Addr, msg: disco::Message) {
-785let pkt = self.disco.encode_and_seal(self.endpoint_id, &msg);
-786let transmit = transports::OwnedTransmit {
-787 ecn: None,
-788 contents: pkt,
-789 segment_size: None,
-790 };
-791let counter = match dst {
-792 transports::Addr::Ip(_) => &self.metrics.send_disco_udp,
-793 transports::Addr::Relay(_, _) => &self.metrics.send_disco_relay,
-794 };
-795match self.send_datagram(dst, transmit).await {
-796Ok(()) => {
-797trace!("sent");
-798 counter.inc();
-799 }
-800Err(err) => {
-801warn!("failed to send disco message: {err:#}");
-802 }
-803 }
-804 }
-805
-806/// Open the path on all connections.
-807 ///
-808 /// This goes through all the connections for which we are the client, and makes sure
-809 /// the path exists, or opens it.
-810#[instrument(level = "warn", skip(self))]
-811fn open_path(&mut self, open_addr: &transports::Addr) {
-812let path_status = match open_addr {
-813 transports::Addr::Ip(_) => PathStatus::Available,
-814 transports::Addr::Relay(_, _) => PathStatus::Backup,
-815 };
-816let quic_addr = match &open_addr {
-817 transports::Addr::Ip(socket_addr) => *socket_addr,
-818 transports::Addr::Relay(relay_url, eid) => self
-819.relay_mapped_addrs
-820 .get(&(relay_url.clone(), *eid))
-821 .private_socket_addr(),
-822 };
-823
-824for (conn_id, conn_state) in self.connections.iter_mut() {
-825if conn_state.path_ids.contains_key(open_addr) {
-826continue;
-827 }
-828let Some(conn) = conn_state.handle.upgrade() else {
-829continue;
-830 };
-831if conn.side().is_server() {
-832continue;
-833 }
-834let fut = conn.open_path_ensure(quic_addr, path_status);
-835match fut.path_id() {
-836Some(path_id) => {
-837trace!(?conn_id, ?path_id, "opening new path");
-838 conn_state.add_path(open_addr.clone(), path_id);
-839 }
-840None => {
-841let ret = now_or_never(fut);
-842match ret {
-843Some(Err(PathError::RemoteCidsExhausted)) => {
-844self.scheduled_open_path =
-845Some(Instant::now() + Duration::from_millis(333));
-846self.pending_open_paths.push_back(open_addr.clone());
-847trace!(?open_addr, "scheduling open_path");
-848 }
-849_ => warn!(?ret, "Opening path failed"),
-850 }
-851 }
-852 }
-853 }
-854 }
-855
-856#[instrument(skip(self))]
-857fn handle_path_event(
-858&mut self,
-859 conn_id: ConnId,
-860 event: Result<PathEvent, BroadcastStreamRecvError>,
-861 ) {
-862let Ok(event) = event else {
-863warn!("missed a PathEvent, RemoteStateActor lagging");
-864// TODO: Is it possible to recover using the sync APIs to figure out what the
-865 // state of the connection and it's paths are?
-866return;
-867 };
-868let Some(conn_state) = self.connections.get_mut(&conn_id) else {
-869trace!("event for removed connection");
-870return;
-871 };
-872let Some(conn) = conn_state.handle.upgrade() else {
-873trace!("event for closed connection");
-874return;
-875 };
-876trace!("path event");
-877match event {
-878 PathEvent::Opened { id: path_id } => {
-879let Some(path) = conn.path(path_id) else {
-880trace!("path open event for unknown path");
-881return;
-882 };
-883// TODO: We configure this as defaults when we setup the endpoint, do we
-884 // really need to duplicate this?
-885path.set_keep_alive_interval(Some(HEARTBEAT_INTERVAL)).ok();
-886 path.set_max_idle_timeout(Some(PATH_MAX_IDLE_TIMEOUT)).ok();
-887
-888if let Ok(socketaddr) = path.remote_address()
-889 && let Some(path_remote) = self.relay_mapped_addrs.to_transport_addr(socketaddr)
-890 {
-891event!(
-892 target: "iroh::_events::path::open",
-893 Level::DEBUG,
-894 remote = %self.endpoint_id.fmt_short(),
-895?path_remote,
-896?conn_id,
-897?path_id,
-898 );
-899 conn_state.add_open_path(path_remote.clone(), path_id);
-900self.paths
-901 .insert(path_remote.clone(), Source::Connection { _0: Private });
-902self.paths.holepunched(&path_remote);
-903 }
-904
-905self.select_path();
-906self.prune_ip_paths();
-907 }
-908 PathEvent::Abandoned { id, path_stats } => {
-909trace!(?path_stats, "path abandoned");
-910// This is the last event for this path.
-911conn_state.remove_path(&id);
-912 }
-913 PathEvent::Closed { id, .. } | PathEvent::LocallyClosed { id, .. } => {
-914let Some(path_remote) = conn_state.paths.get(&id).cloned() else {
-915debug!("path not in path_id_map");
-916return;
-917 };
-918event!(
-919 target: "iroh::_events::path::closed",
-920 Level::DEBUG,
-921 remote = %self.endpoint_id.fmt_short(),
-922?path_remote,
-923?conn_id,
-924 path_id = ?id,
-925 );
-926 conn_state.remove_open_path(&id);
-927
-928// If one connection closes this path, close it on all connections.
-929for (conn_id, conn_state) in self.connections.iter_mut() {
-930let Some(path_id) = conn_state.path_ids.get(&path_remote) else {
-931continue;
-932 };
-933let Some(conn) = conn_state.handle.upgrade() else {
-934continue;
-935 };
-936if let Some(path) = conn.path(*path_id) {
-937trace!(?path_remote, ?conn_id, ?path_id, "closing path");
-938if let Err(err) = path.close(APPLICATION_ABANDON_PATH.into()) {
-939trace!(
-940?path_remote,
-941?conn_id,
-942?path_id,
-943"path close failed: {err:#}"
-944);
-945 }
-946 }
-947 }
-948 }
-949 PathEvent::RemoteStatus { .. } | PathEvent::ObservedAddr { .. } => {
-950// Nothing to do for these events.
-951}
-952 }
-953 }
-954
-955/// Selects the path with the lowest RTT, prefers direct paths.
-956 ///
-957 /// If there are direct paths, this selects the direct path with the lowest RTT. If
-958 /// there are only relay paths, the relay path with the lowest RTT is chosen.
-959 ///
-960 /// The selected path is added to any connections which do not yet have it. Any unused
-961 /// direct paths are closed for all connections.
-962#[instrument(skip_all)]
-963fn select_path(&mut self) {
-964// Find the lowest RTT across all connections for each open path. The long way, so
-965 // we get to log *all* RTTs.
-966let mut all_path_rtts: FxHashMap<transports::Addr, Vec<Duration>> = FxHashMap::default();
-967for conn_state in self.connections.values() {
-968let Some(conn) = conn_state.handle.upgrade() else {
-969continue;
-970 };
-971for (path_id, addr) in conn_state.open_paths.iter() {
-972if let Some(stats) = conn.path_stats(*path_id) {
-973 all_path_rtts
-974 .entry(addr.clone())
-975 .or_default()
-976 .push(stats.rtt);
-977 }
-978 }
-979 }
-980trace!(?all_path_rtts, "dumping all path RTTs");
-981let path_rtts: FxHashMap<transports::Addr, Duration> = all_path_rtts
-982 .into_iter()
-983 .filter_map(|(addr, rtts)| rtts.into_iter().min().map(|rtt| (addr, rtt)))
-984 .collect();
-985
-986// Find the fastest direct or relay path.
-987const IPV6_RTT_ADVANTAGE: Duration = Duration::from_millis(3);
-988let direct_path = path_rtts
-989 .iter()
-990 .filter(|(addr, _rtt)| addr.is_ip())
-991 .map(|(addr, rtt)| {
-992if addr.is_ipv4() {
-993 (*rtt + IPV6_RTT_ADVANTAGE, addr)
-994 } else {
-995 (*rtt, addr)
-996 }
-997 })
-998 .min();
-999let selected_path = direct_path.or_else(|| {
-1000// Find the fasted relay path.
-1001path_rtts
-1002 .iter()
-1003 .filter(|(addr, _rtt)| addr.is_relay())
-1004 .map(|(addr, rtt)| (*rtt, addr))
-1005 .min()
-1006 });
-1007if let Some((rtt, addr)) = selected_path {
-1008let prev = self.selected_path.set(Some(addr.clone()));
-1009if prev.is_ok() {
-1010debug!(?addr, ?rtt, ?prev, "selected new path");
-1011 }
-1012self.open_path(addr);
-1013self.close_redundant_paths(addr);
-1014 }
-1015 }
-1016
-1017/// Closes any direct paths not selected.
-1018 ///
-1019 /// Makes sure not to close the last direct path. Relay paths are never closed
-1020 /// currently, because we only have one relay path at this time.
-1021// TODO: Need to handle this on a timer as well probably. In .select_path() we open new
-1022 // paths and immediately call this. But the new paths are probably not yet open on
-1023 // all connections.
-1024fn close_redundant_paths(&mut self, selected_path: &transports::Addr) {
-1025debug_assert_eq!(self.selected_path.get().as_ref(), Some(selected_path),);
-1026
-1027for (conn_id, conn_state) in self.connections.iter() {
-1028for (path_id, path_remote) in conn_state
-1029 .open_paths
-1030 .iter()
-1031 .filter(|(_, addr)| addr.is_ip())
-1032 .filter(|(_, addr)| *addr != selected_path)
-1033 {
-1034if conn_state.open_paths.values().filter(|a| a.is_ip()).count() <= 1 {
-1035continue; // Do not close the last direct path.
-1036}
-1037if let Some(path) = conn_state
-1038 .handle
-1039 .upgrade()
-1040 .and_then(|conn| conn.path(*path_id))
-1041 {
-1042trace!(?path_remote, ?conn_id, ?path_id, "closing direct path");
-1043match path.close(APPLICATION_ABANDON_PATH.into()) {
-1044Err(quinn_proto::ClosePathError::LastOpenPath) => {
-1045error!("could not close last open path");
-1046 }
-1047Err(quinn_proto::ClosePathError::ClosedPath) => {
-1048// We already closed this.
-1049}
-1050Ok(_fut) => {
-1051// We will handle the event in Self::handle_path_events.
-1052}
-1053 }
-1054 }
-1055 }
-1056 }
-1057 }
-1058
-1059/// TODO: fix up docs once review indicates this is actually
-1060 /// the criteria for pruning.
-1061fn prune_ip_paths(&mut self) {
-1062let open_paths = self
-1063.connections
-1064 .values()
-1065 .flat_map(|state| state.open_paths.values());
-1066self.paths.prune_ip_paths(
-1067&self.pending_open_paths,
-1068&self.selected_path.get(),
-1069 open_paths,
-1070 );
-1071 }
-1072}
-1073
-1074/// Messages to send to the [`RemoteStateActor`].
-1075#[derive(derive_more::Debug)]
-1076pub(crate) enum RemoteStateMessage {
-1077/// Sends a datagram to all known paths.
-1078 ///
-1079 /// Used to send QUIC Initial packets. If there is no working direct path this will
-1080 /// trigger holepunching.
-1081 ///
-1082 /// This is not acceptable to use on the normal send path, as it is an async send
-1083 /// operation with a bunch more copying. So it should only be used for sending QUIC
-1084 /// Initial packets.
-1085#[debug("SendDatagram(..)")]
-1086SendDatagram(OwnedTransmit),
-1087/// Adds an active connection to this remote endpoint.
-1088 ///
-1089 /// The connection will now be managed by this actor. Holepunching will happen when
-1090 /// needed, any new paths discovered via holepunching will be added. And closed paths
-1091 /// will be removed etc.
-1092#[debug("AddConnection(..)")]
-1093AddConnection(WeakConnectionHandle, oneshot::Sender<PathsWatcher>),
-1094/// Process a received DISCO CallMeMaybe message.
-1095CallMeMaybeReceived(disco::CallMeMaybe),
-1096/// Process a received DISCO Ping message.
-1097#[debug("PingReceived({:?}, src: {_1:?})", _0.tx_id)]
-1098PingReceived(disco::Ping, transports::Addr),
-1099/// Process a received DISCO Pong message.
-1100#[debug("PongReceived({:?}, src: {_1:?})", _0.tx_id)]
-1101PongReceived(disco::Pong, transports::Addr),
-1102/// Ensure we have at least one transport address for a remote.
-1103 ///
-1104 /// This adds the provided transport addresses to the list of potential paths for this remote
-1105 /// and starts discovery if needed.
-1106 ///
-1107 /// Returns `Ok` immediately if the provided address list is non-empy or we have are other known paths.
-1108 /// Otherwise returns `Ok` once discovery produces a result, or the discovery error if discovery fails
-1109 /// or produces no results,
-1110#[debug("ResolveRemote(..)")]
-1111ResolveRemote(
-1112 BTreeSet<TransportAddr>,
-1113 oneshot::Sender<Result<(), DiscoveryError>>,
-1114 ),
-1115/// Returns the current latency to the remote endpoint.
-1116 ///
-1117 /// TODO: This is more of a placeholder message currently. Check MagicSock::latency.
-1118#[debug("Latency(..)")]
-1119Latency(oneshot::Sender<Option<Duration>>),
-1120}
+599 };
+600for addr in local_addrs.difference(&quinn_local_addrs) {
+601if let Err(err) = conn.add_nat_traversal_address(*addr) {
+602warn!("failed adding local addr: {err:#}",);
+603 }
+604 }
+605for addr in quinn_local_addrs.difference(local_addrs) {
+606if let Err(err) = conn.remove_nat_traversal_address(*addr) {
+607warn!("failed removing local addr: {err:#}");
+608 }
+609 }
+610trace!(?local_addrs, "updated local QNT addresses");
+611 }
+612
+613/// Triggers holepunching to the remote endpoint.
+614 ///
+615 /// This will manage the entire process of holepunching with the remote endpoint.
+616 ///
+617 /// - Holepunching happens on the Connection with the lowest [`ConnId`] which is a
+618 /// client.
+619 /// - Both endpoints may initiate holepunching if both have a client connection.
+620 /// - Any opened paths are opened on all other connections without holepunching.
+621 /// - If there are no changes in local or remote candidate addresses since the
+622 /// last attempt **and** there was a recent attempt, a trigger_holepunching call
+623 /// will be scheduled instead.
+624async fn trigger_holepunching(&mut self) {
+625if self.connections.is_empty() {
+626trace!("not holepunching: no connections");
+627return;
+628 }
+629
+630let Some(conn) = self
+631.connections
+632 .iter()
+633 .filter_map(|(id, state)| state.handle.upgrade().map(|conn| (*id, conn)))
+634 .filter(|(_, conn)| conn.side().is_client())
+635 .min_by_key(|(id, _)| *id)
+636 .map(|(_, conn)| conn)
+637else {
+638trace!("not holepunching: no client connection");
+639return;
+640 };
+641let remote_candidates = match conn.get_remote_nat_traversal_addresses() {
+642Ok(addrs) => BTreeSet::from_iter(addrs),
+643Err(err) => {
+644warn!("failed to get nat candidate addresses: {err:#}");
+645return;
+646 }
+647 };
+648let local_candidates: BTreeSet<SocketAddr> = self
+649.local_direct_addrs
+650 .get()
+651 .iter()
+652 .map(|daddr| daddr.addr)
+653 .collect();
+654let new_candidates = self
+655.last_holepunch
+656 .as_ref()
+657 .map(|last_hp| {
+658// Addrs are allowed to disappear, but if there are new ones we need to
+659 // holepunch again.
+660trace!(
+661?last_hp,
+662?local_candidates,
+663?remote_candidates,
+664"candidates to holepunch?"
+665);
+666 !remote_candidates.is_subset(&last_hp.remote_candidates)
+667 || !local_candidates.is_subset(&last_hp.local_candidates)
+668 })
+669 .unwrap_or(true);
+670if !new_candidates {
+671if let Some(ref last_hp) = self.last_holepunch {
+672let next_hp = last_hp.when + HOLEPUNCH_ATTEMPTS_INTERVAL;
+673let now = Instant::now();
+674if next_hp > now {
+675trace!(scheduled_in = ?(next_hp - now), "not holepunching: no new addresses");
+676self.scheduled_holepunch = Some(next_hp);
+677return;
+678 }
+679 }
+680 }
+681
+682self.do_holepunching(conn).await;
+683 }
+684
+685/// Unconditionally perform holepunching.
+686#[instrument(skip_all)]
+687async fn do_holepunching(&mut self, conn: quinn::Connection) {
+688self.metrics.nat_traversal.inc();
+689let local_candidates = self
+690.local_direct_addrs
+691 .get()
+692 .iter()
+693 .map(|daddr| daddr.addr)
+694 .collect::<BTreeSet<_>>();
+695match conn.initiate_nat_traversal_round() {
+696Ok(remote_candidates) => {
+697trace!(
+698?local_candidates,
+699?remote_candidates,
+700"nat traversal initiated"
+701);
+702self.last_holepunch = Some(HolepunchAttempt {
+703 when: Instant::now(),
+704 local_candidates,
+705 remote_candidates: BTreeSet::from_iter(remote_candidates),
+706 });
+707 }
+708Err(err) => {
+709warn!("failed to initiate NAT traversal: {err:#}");
+710 }
+711 }
+712 }
+713
+714/// Open the path on all connections.
+715 ///
+716 /// This goes through all the connections for which we are the client, and makes sure
+717 /// the path exists, or opens it.
+718#[instrument(level = "warn", skip(self))]
+719fn open_path(&mut self, open_addr: &transports::Addr) {
+720let path_status = match open_addr {
+721 transports::Addr::Ip(_) => PathStatus::Available,
+722 transports::Addr::Relay(_, _) => PathStatus::Backup,
+723 };
+724let quic_addr = match &open_addr {
+725 transports::Addr::Ip(socket_addr) => *socket_addr,
+726 transports::Addr::Relay(relay_url, eid) => self
+727.relay_mapped_addrs
+728 .get(&(relay_url.clone(), *eid))
+729 .private_socket_addr(),
+730 };
+731
+732for (conn_id, conn_state) in self.connections.iter_mut() {
+733if conn_state.path_ids.contains_key(open_addr) {
+734continue;
+735 }
+736let Some(conn) = conn_state.handle.upgrade() else {
+737continue;
+738 };
+739if conn.side().is_server() {
+740continue;
+741 }
+742let fut = conn.open_path_ensure(quic_addr, path_status);
+743match fut.path_id() {
+744Some(path_id) => {
+745trace!(?conn_id, ?path_id, "opening new path");
+746 conn_state.add_path(open_addr.clone(), path_id);
+747 }
+748None => {
+749let ret = now_or_never(fut);
+750match ret {
+751Some(Err(PathError::RemoteCidsExhausted)) => {
+752self.scheduled_open_path =
+753Some(Instant::now() + Duration::from_millis(333));
+754self.pending_open_paths.push_back(open_addr.clone());
+755trace!(?open_addr, "scheduling open_path");
+756 }
+757_ => warn!(?ret, "Opening path failed"),
+758 }
+759 }
+760 }
+761 }
+762 }
+763
+764#[instrument(skip(self))]
+765fn handle_path_event(
+766&mut self,
+767 conn_id: ConnId,
+768 event: Result<PathEvent, BroadcastStreamRecvError>,
+769 ) {
+770let Ok(event) = event else {
+771warn!("missed a PathEvent, RemoteStateActor lagging");
+772// TODO: Is it possible to recover using the sync APIs to figure out what the
+773 // state of the connection and it's paths are?
+774return;
+775 };
+776let Some(conn_state) = self.connections.get_mut(&conn_id) else {
+777trace!("event for removed connection");
+778return;
+779 };
+780let Some(conn) = conn_state.handle.upgrade() else {
+781trace!("event for closed connection");
+782return;
+783 };
+784trace!("path event");
+785match event {
+786 PathEvent::Opened { id: path_id } => {
+787let Some(path) = conn.path(path_id) else {
+788trace!("path open event for unknown path");
+789return;
+790 };
+791// TODO: We configure this as defaults when we setup the endpoint, do we
+792 // really need to duplicate this?
+793path.set_keep_alive_interval(Some(HEARTBEAT_INTERVAL)).ok();
+794 path.set_max_idle_timeout(Some(PATH_MAX_IDLE_TIMEOUT)).ok();
+795
+796if let Ok(socketaddr) = path.remote_address()
+797 && let Some(path_remote) = self.relay_mapped_addrs.to_transport_addr(socketaddr)
+798 {
+799event!(
+800 target: "iroh::_events::path::open",
+801 Level::DEBUG,
+802 remote = %self.endpoint_id.fmt_short(),
+803?path_remote,
+804?conn_id,
+805?path_id,
+806 );
+807 conn_state.add_open_path(path_remote.clone(), path_id);
+808self.paths
+809 .insert(path_remote.clone(), Source::Connection { _0: Private });
+810self.paths.opened_path(&path_remote);
+811 }
+812
+813self.select_path();
+814self.prune_paths();
+815 }
+816 PathEvent::Abandoned { id, path_stats } => {
+817trace!(?path_stats, "path abandoned");
+818// This is the last event for this path.
+819if let Some(addr) = conn_state.remove_path(&id) {
+820self.paths.abandoned_path(&addr);
+821 }
+822 }
+823 PathEvent::Closed { id, .. } | PathEvent::LocallyClosed { id, .. } => {
+824let Some(path_remote) = conn_state.paths.get(&id).cloned() else {
+825debug!("path not in path_id_map");
+826return;
+827 };
+828event!(
+829 target: "iroh::_events::path::closed",
+830 Level::DEBUG,
+831 remote = %self.endpoint_id.fmt_short(),
+832?path_remote,
+833?conn_id,
+834 path_id = ?id,
+835 );
+836 conn_state.remove_open_path(&id);
+837
+838// If one connection closes this path, close it on all connections.
+839for (conn_id, conn_state) in self.connections.iter_mut() {
+840let Some(path_id) = conn_state.path_ids.get(&path_remote) else {
+841continue;
+842 };
+843let Some(conn) = conn_state.handle.upgrade() else {
+844continue;
+845 };
+846if let Some(path) = conn.path(*path_id) {
+847trace!(?path_remote, ?conn_id, ?path_id, "closing path");
+848if let Err(err) = path.close(APPLICATION_ABANDON_PATH.into()) {
+849trace!(
+850?path_remote,
+851?conn_id,
+852?path_id,
+853"path close failed: {err:#}"
+854);
+855 }
+856 }
+857 }
+858 }
+859 PathEvent::RemoteStatus { .. } | PathEvent::ObservedAddr { .. } => {
+860// Nothing to do for these events.
+861}
+862 }
+863 }
+864
+865/// Selects the path with the lowest RTT, prefers direct paths.
+866 ///
+867 /// If there are direct paths, this selects the direct path with the lowest RTT. If
+868 /// there are only relay paths, the relay path with the lowest RTT is chosen.
+869 ///
+870 /// The selected path is added to any connections which do not yet have it. Any unused
+871 /// direct paths are closed for all connections.
+872#[instrument(skip_all)]
+873fn select_path(&mut self) {
+874// Find the lowest RTT across all connections for each open path. The long way, so
+875 // we get to log *all* RTTs.
+876let mut all_path_rtts: FxHashMap<transports::Addr, Vec<Duration>> = FxHashMap::default();
+877for conn_state in self.connections.values() {
+878let Some(conn) = conn_state.handle.upgrade() else {
+879continue;
+880 };
+881for (path_id, addr) in conn_state.open_paths.iter() {
+882if let Some(stats) = conn.path_stats(*path_id) {
+883 all_path_rtts
+884 .entry(addr.clone())
+885 .or_default()
+886 .push(stats.rtt);
+887 }
+888 }
+889 }
+890trace!(?all_path_rtts, "dumping all path RTTs");
+891let path_rtts: FxHashMap<transports::Addr, Duration> = all_path_rtts
+892 .into_iter()
+893 .filter_map(|(addr, rtts)| rtts.into_iter().min().map(|rtt| (addr, rtt)))
+894 .collect();
+895
+896// Find the fastest direct or relay path.
+897const IPV6_RTT_ADVANTAGE: Duration = Duration::from_millis(3);
+898let direct_path = path_rtts
+899 .iter()
+900 .filter(|(addr, _rtt)| addr.is_ip())
+901 .map(|(addr, rtt)| {
+902if addr.is_ipv4() {
+903 (*rtt + IPV6_RTT_ADVANTAGE, addr)
+904 } else {
+905 (*rtt, addr)
+906 }
+907 })
+908 .min();
+909let selected_path = direct_path.or_else(|| {
+910// Find the fasted relay path.
+911path_rtts
+912 .iter()
+913 .filter(|(addr, _rtt)| addr.is_relay())
+914 .map(|(addr, rtt)| (*rtt, addr))
+915 .min()
+916 });
+917if let Some((rtt, addr)) = selected_path {
+918let prev = self.selected_path.set(Some(addr.clone()));
+919if prev.is_ok() {
+920debug!(?addr, ?rtt, ?prev, "selected new path");
+921 }
+922self.open_path(addr);
+923self.close_redundant_paths(addr);
+924 }
+925 }
+926
+927/// Closes any direct paths not selected.
+928 ///
+929 /// Makes sure not to close the last direct path. Relay paths are never closed
+930 /// currently, because we only have one relay path at this time.
+931// TODO: Need to handle this on a timer as well probably. In .select_path() we open new
+932 // paths and immediately call this. But the new paths are probably not yet open on
+933 // all connections.
+934fn close_redundant_paths(&mut self, selected_path: &transports::Addr) {
+935debug_assert_eq!(self.selected_path.get().as_ref(), Some(selected_path),);
+936
+937for (conn_id, conn_state) in self.connections.iter() {
+938for (path_id, path_remote) in conn_state
+939 .open_paths
+940 .iter()
+941 .filter(|(_, addr)| addr.is_ip())
+942 .filter(|(_, addr)| *addr != selected_path)
+943 {
+944if conn_state.open_paths.values().filter(|a| a.is_ip()).count() <= 1 {
+945continue; // Do not close the last direct path.
+946}
+947if let Some(path) = conn_state
+948 .handle
+949 .upgrade()
+950 .and_then(|conn| conn.path(*path_id))
+951 {
+952trace!(?path_remote, ?conn_id, ?path_id, "closing direct path");
+953match path.close(APPLICATION_ABANDON_PATH.into()) {
+954Err(quinn_proto::ClosePathError::LastOpenPath) => {
+955error!("could not close last open path");
+956 }
+957Err(quinn_proto::ClosePathError::ClosedPath) => {
+958// We already closed this.
+959}
+960Ok(_fut) => {
+961// We will handle the event in Self::handle_path_events.
+962}
+963 }
+964 }
+965 }
+966 }
+967 }
+968
+969/// TODO: fix up docs once review indicates this is actually
+970 /// the criteria for pruning.
+971fn prune_paths(&mut self) {
+972self.paths.prune_paths();
+973 }
+974}
+975
+976/// Messages to send to the [`RemoteStateActor`].
+977#[derive(derive_more::Debug)]
+978pub(crate) enum RemoteStateMessage {
+979/// Sends a datagram to all known paths.
+980 ///
+981 /// Used to send QUIC Initial packets. If there is no working direct path this will
+982 /// trigger holepunching.
+983 ///
+984 /// This is not acceptable to use on the normal send path, as it is an async send
+985 /// operation with a bunch more copying. So it should only be used for sending QUIC
+986 /// Initial packets.
+987#[debug("SendDatagram(..)")]
+988SendDatagram(OwnedTransmit),
+989/// Adds an active connection to this remote endpoint.
+990 ///
+991 /// The connection will now be managed by this actor. Holepunching will happen when
+992 /// needed, any new paths discovered via holepunching will be added. And closed paths
+993 /// will be removed etc.
+994#[debug("AddConnection(..)")]
+995AddConnection(WeakConnectionHandle, oneshot::Sender<PathsWatcher>),
+996/// Asks if there is any possible path that could be used.
+997 ///
+998 /// This adds the provided transport addresses to the list of potential paths for this remote
+999 /// and starts discovery if needed.
+1000 ///
+1001 /// Returns `Ok` immediately if the provided address list is non-empy or we have are other known paths.
+1002 /// Otherwise returns `Ok` once discovery produces a result, or the discovery error if discovery fails
+1003 /// or produces no results,
+1004#[debug("ResolveRemote(..)")]
+1005ResolveRemote(
+1006 BTreeSet<TransportAddr>,
+1007 oneshot::Sender<Result<(), DiscoveryError>>,
+1008 ),
+1009/// Returns the current latency to the remote endpoint.
+1010 ///
+1011 /// TODO: This is more of a placeholder message currently. Check MagicSock::latency.
+1012#[debug("Latency(..)")]
+1013Latency(oneshot::Sender<Option<Duration>>),
+1014}
+1015
+1016/// A handle to a [`RemoteStateActor`].
+1017///
+1018/// Dropping this will stop the actor. The actor will also stop after an idle timeout
+1019/// if it has no connections, an empty inbox, and no other senders than the one stored
+1020/// in the endpoint map exist.
+1021#[derive(Debug)]
+1022pub(super) struct RemoteStateHandle {
+1023/// Sender for the channel into the [`RemoteStateActor`].
+1024 ///
+1025 /// This is a [`GuardedSender`], from which we can get a sender but only if the receiver
+1026 /// hasn't been closed.
+1027pub(super) sender: GuardedSender<RemoteStateMessage>,
+1028 _task: AbortOnDropHandle<()>,
+1029}
+1030
+1031/// Information about a holepunch attempt.
+1032#[derive(Debug)]
+1033struct HolepunchAttempt {
+1034 when: Instant,
+1035/// The set of local addresses which could take part in holepunching.
+1036 ///
+1037 /// This does not mean every address here participated in the holepunching. E.g. we
+1038 /// could have tried only a sub-set of the addresses because a previous attempt already
+1039 /// covered part of the range.
+1040 ///
+1041 /// We do not store this as a [`DirectAddr`] because this is checked for equality and we
+1042 /// do not want to compare the sources of these addresses.
+1043local_candidates: BTreeSet<SocketAddr>,
+1044/// The set of remote addresses which could take part in holepunching.
+1045 ///
+1046 /// Like [`Self::local_candidates`] we may not have used them.
+1047remote_candidates: BTreeSet<SocketAddr>,
+1048}
+1049
+1050/// Newtype to track Connections.
+1051///
+1052/// The wrapped value is the [`quinn::Connection::stable_id`] value, and is thus only valid
+1053/// for active connections.
+1054#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
+1055struct ConnId(usize);
+1056
+1057/// State about one connection.
+1058#[derive(Debug)]
+1059struct ConnectionState {
+1060/// Weak handle to the connection.
+1061handle: WeakConnectionHandle,
+1062/// The information we publish to users about the paths used in this connection.
+1063pub_open_paths: Watchable<PathAddrList>,
+1064/// The paths that exist on this connection.
+1065 ///
+1066 /// This could be in any state, e.g. while still validating the path or already closed
+1067 /// but not yet fully removed from the connection. This exists as long as Quinn knows
+1068 /// about the [`PathId`].
+1069paths: FxHashMap<PathId, transports::Addr>,
+1070/// The open paths on this connection, a subset of [`Self::paths`].
+1071open_paths: FxHashMap<PathId, transports::Addr>,
+1072/// Reverse map of [`Self::paths].
+1073path_ids: FxHashMap<transports::Addr, PathId>,
+1074}
+1075
+1076impl ConnectionState {
+1077/// Tracks a path for the connection.
+1078fn add_path(&mut self, remote: transports::Addr, path_id: PathId) {
+1079self.paths.insert(path_id, remote.clone());
+1080self.path_ids.insert(remote, path_id);
+1081 }
+1082
+1083/// Tracks an open path for the connection.
+1084fn add_open_path(&mut self, remote: transports::Addr, path_id: PathId) {
+1085self.paths.insert(path_id, remote.clone());
+1086self.open_paths.insert(path_id, remote.clone());
+1087self.path_ids.insert(remote, path_id);
+1088
+1089self.update_pub_path_info();
+1090 }
+1091
+1092/// Completely removes a path from this connection.
+1093fn remove_path(&mut self, path_id: &PathId) -> Option<transports::Addr> {
+1094let addr = self.paths.remove(path_id);
+1095if let Some(ref addr) = addr {
+1096self.path_ids.remove(addr);
+1097 }
+1098self.open_paths.remove(path_id);
+1099 addr
+1100 }
+1101
+1102/// Removes the path from the open paths.
+1103fn remove_open_path(&mut self, path_id: &PathId) {
+1104self.open_paths.remove(path_id);
+1105
+1106self.update_pub_path_info();
+1107 }
+1108
+1109/// Sets the new [`PathInfo`] structs for the public [`Connection`].
+1110 ///
+1111 /// [`Connection`]: crate::endpoint::Connection
+1112fn update_pub_path_info(&self) {
+1113let new = self
+1114.open_paths
+1115 .iter()
+1116 .map(|(path_id, remote)| {
+1117let remote = TransportAddr::from(remote.clone());
+1118 (remote, *path_id)
+1119 })
+1120 .collect::<PathAddrList>();
1121
-1122/// A handle to a [`RemoteStateActor`].
-1123///
-1124/// Dropping this will stop the actor. The actor will also stop after an idle timeout
-1125/// if it has no connections, an empty inbox, and no other senders than the one stored
-1126/// in the endpoint map exist.
-1127#[derive(Debug)]
-1128pub(super) struct RemoteStateHandle {
-1129/// Sender for the channel into the [`RemoteStateActor`].
-1130 ///
-1131 /// This is a [`GuardedSender`], from which we can get a sender but only if the receiver
-1132 /// hasn't been closed.
-1133pub(super) sender: GuardedSender<RemoteStateMessage>,
-1134 _task: AbortOnDropHandle<()>,
-1135}
-1136
-1137/// Information about a holepunch attempt.
-1138#[derive(Debug)]
-1139struct HolepunchAttempt {
-1140 when: Instant,
-1141/// The set of local addresses which could take part in holepunching.
-1142 ///
-1143 /// This does not mean every address here participated in the holepunching. E.g. we
-1144 /// could have tried only a sub-set of the addresses because a previous attempt already
-1145 /// covered part of the range.
-1146 ///
-1147 /// We do not store this as a [`DirectAddr`] because this is checked for equality and we
-1148 /// do not want to compare the sources of these addresses.
-1149local_addrs: BTreeSet<SocketAddr>,
-1150/// The set of remote addresses which could take part in holepunching.
-1151 ///
-1152 /// Like `local_addrs` we may not have used them.
-1153remote_addrs: BTreeSet<SocketAddr>,
-1154}
-1155
-1156/// Newtype to track Connections.
-1157///
-1158/// The wrapped value is the [`quinn::Connection::stable_id`] value, and is thus only valid
-1159/// for active connections.
-1160#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
-1161struct ConnId(usize);
-1162
-1163/// State about one connection.
-1164#[derive(Debug)]
-1165struct ConnectionState {
-1166/// Weak handle to the connection.
-1167handle: WeakConnectionHandle,
-1168/// The information we publish to users about the paths used in this connection.
-1169pub_open_paths: Watchable<PathAddrList>,
-1170/// The paths that exist on this connection.
-1171 ///
-1172 /// This could be in any state, e.g. while still validating the path or already closed
-1173 /// but not yet fully removed from the connection. This exists as long as Quinn knows
-1174 /// about the [`PathId`].
-1175paths: FxHashMap<PathId, transports::Addr>,
-1176/// The open paths on this connection, a subset of [`Self::paths`].
-1177open_paths: FxHashMap<PathId, transports::Addr>,
-1178/// Reverse map of [`Self::paths].
-1179path_ids: FxHashMap<transports::Addr, PathId>,
-1180}
-1181
-1182impl ConnectionState {
-1183/// Tracks a path for the connection.
-1184fn add_path(&mut self, remote: transports::Addr, path_id: PathId) {
-1185self.paths.insert(path_id, remote.clone());
-1186self.path_ids.insert(remote, path_id);
-1187 }
-1188
-1189/// Tracks an open path for the connection.
-1190fn add_open_path(&mut self, remote: transports::Addr, path_id: PathId) {
-1191self.paths.insert(path_id, remote.clone());
-1192self.open_paths.insert(path_id, remote.clone());
-1193self.path_ids.insert(remote, path_id);
-1194
-1195self.update_pub_path_info();
-1196 }
-1197
-1198/// Completely removes a path from this connection.
-1199fn remove_path(&mut self, path_id: &PathId) {
-1200if let Some(addr) = self.paths.remove(path_id) {
-1201self.path_ids.remove(&addr);
-1202 }
-1203self.open_paths.remove(path_id);
-1204 }
+1122self.pub_open_paths.set(new).ok();
+1123 }
+1124}
+1125
+1126/// Watcher for the open paths and selected transmission path in a connection.
+1127///
+1128/// This is stored in the [`Connection`], and the watchables are set from within the endpoint state actor.
+1129///
+1130/// Internally, this contains a boxed-mapped-joined watcher over the open paths in the connection and the
+1131/// selected path to the remote endpoint. The watcher is boxed because the mapped-joined watcher with
+1132/// `SmallVec<PathInfoList>` has a size of over 800 bytes, which we don't want to put upon the [`Connection`].
+1133///
+1134/// [`Connection`]: crate::endpoint::Connection
+1135#[derive(Clone, derive_more::Debug)]
+1136#[debug("PathsWatcher")]
+1137#[allow(clippy::type_complexity)]
+1138pub(crate) struct PathsWatcher(
+1139 Box<
+1140 n0_watcher::Map<
+1141 n0_watcher::Tuple<
+1142 n0_watcher::Direct<PathAddrList>,
+1143 n0_watcher::Direct<Option<transports::Addr>>,
+1144 >,
+1145 PathInfoList,
+1146 >,
+1147 >,
+1148);
+1149
+1150impl n0_watcher::Watcher for PathsWatcher {
+1151type Value = PathInfoList;
+1152
+1153fn update(&mut self) -> bool {
+1154self.0.update()
+1155 }
+1156
+1157fn peek(&self) -> &Self::Value {
+1158self.0.peek()
+1159 }
+1160
+1161fn is_connected(&self) -> bool {
+1162self.0.is_connected()
+1163 }
+1164
+1165fn poll_updated(
+1166&mut self,
+1167 cx: &mut std::task::Context<'_>,
+1168 ) -> Poll<Result<(), n0_watcher::Disconnected>> {
+1169self.0.poll_updated(cx)
+1170 }
+1171}
+1172
+1173impl PathsWatcher {
+1174fn new(
+1175 open_paths: n0_watcher::Direct<PathAddrList>,
+1176 selected_path: n0_watcher::Direct<Option<transports::Addr>>,
+1177 conn_handle: WeakConnectionHandle,
+1178 ) -> Self {
+1179Self(Box::new(open_paths.or(selected_path).map(
+1180move |(open_paths, selected_path)| {
+1181let selected_path: Option<TransportAddr> = selected_path.map(Into::into);
+1182let Some(conn) = conn_handle.upgrade() else {
+1183return PathInfoList(Default::default());
+1184 };
+1185let list = open_paths
+1186 .into_iter()
+1187 .flat_map(move |(remote, path_id)| {
+1188 PathInfo::new(path_id, &conn, remote, selected_path.as_ref())
+1189 })
+1190 .collect();
+1191 PathInfoList(list)
+1192 },
+1193 )))
+1194 }
+1195}
+1196
+1197/// List of [`PathInfo`] for the network paths of a [`Connection`].
+1198///
+1199/// This struct implements [`IntoIterator`].
+1200///
+1201/// [`Connection`]: crate::endpoint::Connection
+1202#[derive(derive_more::Debug, derive_more::IntoIterator, Eq, PartialEq, Clone)]
+1203#[debug("{_0:?}")]
+1204pub struct PathInfoList(SmallVec<[PathInfo; 4]>);
1205
-1206/// Removes the path from the open paths.
-1207fn remove_open_path(&mut self, path_id: &PathId) {
-1208self.open_paths.remove(path_id);
-1209
-1210self.update_pub_path_info();
-1211 }
-1212
-1213/// Sets the new [`PathInfo`] structs for the public [`Connection`].
-1214 ///
-1215 /// [`Connection`]: crate::endpoint::Connection
-1216fn update_pub_path_info(&self) {
-1217let new = self
-1218.open_paths
-1219 .iter()
-1220 .map(|(path_id, remote)| {
-1221let remote = TransportAddr::from(remote.clone());
-1222 (remote, *path_id)
-1223 })
-1224 .collect::<PathAddrList>();
-1225
-1226self.pub_open_paths.set(new).ok();
-1227 }
-1228}
-1229
-1230/// Watcher for the open paths and selected transmission path in a connection.
-1231///
-1232/// This is stored in the [`Connection`], and the watchables are set from within the endpoint state actor.
-1233///
-1234/// Internally, this contains a boxed-mapped-joined watcher over the open paths in the connection and the
-1235/// selected path to the remote endpoint. The watcher is boxed because the mapped-joined watcher with
-1236/// `SmallVec<PathInfoList>` has a size of over 800 bytes, which we don't want to put upon the [`Connection`].
-1237///
-1238/// [`Connection`]: crate::endpoint::Connection
-1239#[derive(Clone, derive_more::Debug)]
-1240#[debug("PathsWatcher")]
-1241#[allow(clippy::type_complexity)]
-1242pub(crate) struct PathsWatcher(
-1243 Box<
-1244 n0_watcher::Map<
-1245 n0_watcher::Tuple<
-1246 n0_watcher::Direct<PathAddrList>,
-1247 n0_watcher::Direct<Option<transports::Addr>>,
-1248 >,
-1249 PathInfoList,
-1250 >,
-1251 >,
-1252);
-1253
-1254impl n0_watcher::Watcher for PathsWatcher {
-1255type Value = PathInfoList;
-1256
-1257fn update(&mut self) -> bool {
-1258self.0.update()
-1259 }
-1260
-1261fn peek(&self) -> &Self::Value {
-1262self.0.peek()
-1263 }
-1264
-1265fn is_connected(&self) -> bool {
-1266self.0.is_connected()
-1267 }
-1268
-1269fn poll_updated(
-1270&mut self,
-1271 cx: &mut std::task::Context<'_>,
-1272 ) -> Poll<Result<(), n0_watcher::Disconnected>> {
-1273self.0.poll_updated(cx)
-1274 }
-1275}
-1276
-1277impl PathsWatcher {
-1278fn new(
-1279 open_paths: n0_watcher::Direct<PathAddrList>,
-1280 selected_path: n0_watcher::Direct<Option<transports::Addr>>,
-1281 conn_handle: WeakConnectionHandle,
-1282 ) -> Self {
-1283Self(Box::new(open_paths.or(selected_path).map(
-1284move |(open_paths, selected_path)| {
-1285let selected_path: Option<TransportAddr> = selected_path.map(Into::into);
-1286let Some(conn) = conn_handle.upgrade() else {
-1287return PathInfoList(Default::default());
-1288 };
-1289let list = open_paths
-1290 .into_iter()
-1291 .flat_map(move |(remote, path_id)| {
-1292 PathInfo::new(path_id, &conn, remote, selected_path.as_ref())
-1293 })
-1294 .collect();
-1295 PathInfoList(list)
-1296 },
-1297 )))
-1298 }
-1299}
-1300
-1301/// List of [`PathInfo`] for the network paths of a [`Connection`].
-1302///
-1303/// This struct implements [`IntoIterator`].
-1304///
-1305/// [`Connection`]: crate::endpoint::Connection
-1306#[derive(derive_more::Debug, derive_more::IntoIterator, Eq, PartialEq, Clone)]
-1307#[debug("{_0:?}")]
-1308pub struct PathInfoList(SmallVec<[PathInfo; 4]>);
-1309
-1310impl PathInfoList {
-1311/// Returns an iterator over the path infos.
-1312pub fn iter(&self) -> impl Iterator<Item = &PathInfo> {
-1313self.0.iter()
-1314 }
-1315
-1316/// Returns `true` if the list is empty.
-1317pub fn is_empty(&self) -> bool {
-1318self.0.is_empty()
-1319 }
-1320
-1321/// Returns the number of paths.
-1322pub fn len(&self) -> usize {
-1323self.0.len()
-1324 }
-1325}
-1326
-1327/// Information about a network path used by a [`Connection`].
-1328///
-1329/// [`Connection`]: crate::endpoint::Connection
-1330#[derive(derive_more::Debug, Clone)]
-1331pub struct PathInfo {
-1332 path_id: PathId,
-1333#[debug(skip)]
-1334handle: WeakConnectionHandle,
-1335 stats: PathStats,
-1336 remote: TransportAddr,
-1337 is_selected: bool,
-1338}
-1339
-1340impl PartialEq for PathInfo {
-1341fn eq(&self, other: &Self) -> bool {
-1342self.path_id == other.path_id
-1343 && self.remote == other.remote
-1344 && self.is_selected == other.is_selected
-1345 }
-1346}
-1347
-1348impl Eq for PathInfo {}
-1349
-1350impl PathInfo {
-1351fn new(
-1352 path_id: PathId,
-1353 conn: &quinn::Connection,
-1354 remote: TransportAddr,
-1355 selected_path: Option<&TransportAddr>,
-1356 ) -> Option<Self> {
-1357let stats = conn.path_stats(path_id)?;
-1358Some(Self {
-1359 path_id,
-1360 handle: conn.weak_handle(),
-1361 is_selected: Some(&remote) == selected_path,
-1362 remote,
-1363 stats,
-1364 })
-1365 }
-1366
-1367/// The remote transport address used by this network path.
-1368pub fn remote_addr(&self) -> &TransportAddr {
-1369&self.remote
-1370 }
-1371
-1372/// Returns `true` if this path is currently the main transmission path for this [`Connection`].
-1373 ///
-1374 /// [`Connection`]: crate::endpoint::Connection
-1375pub fn is_selected(&self) -> bool {
-1376self.is_selected
-1377 }
-1378
-1379/// Whether this is an IP transport address.
-1380pub fn is_ip(&self) -> bool {
-1381self.remote.is_ip()
-1382 }
-1383
-1384/// Whether this is a transport address via a relay server.
-1385pub fn is_relay(&self) -> bool {
-1386self.remote.is_relay()
-1387 }
-1388
-1389/// Returns stats for this transmission path.
-1390pub fn stats(&self) -> PathStats {
-1391self.handle
-1392 .upgrade()
-1393 .and_then(|conn| conn.path_stats(self.path_id))
-1394 .unwrap_or(self.stats)
-1395 }
-1396
-1397/// Current best estimate of this paths's latency (round-trip-time)
-1398pub fn rtt(&self) -> Duration {
-1399self.stats().rtt
-1400 }
-1401}
-1402
-1403/// Poll a future once, like n0_future::future::poll_once but sync.
-1404fn now_or_never<T, F: Future<Output = T>>(fut: F) -> Option<T> {
-1405let fut = std::pin::pin!(fut);
-1406match fut.poll(&mut std::task::Context::from_waker(std::task::Waker::noop())) {
-1407 Poll::Ready(res) => Some(res),
-1408 Poll::Pending => None,
-1409 }
-1410}
-1411
-1412/// Future that resolves to the `conn_id` once a connection is closed.
-1413///
-1414/// This uses [`quinn::Connection::on_closed`], which does not keep the connection alive
-1415/// while awaiting the future.
-1416struct OnClosed {
-1417 conn_id: ConnId,
-1418 inner: quinn::OnClosed,
-1419}
-1420
-1421impl OnClosed {
-1422fn new(conn: &quinn::Connection) -> Self {
-1423Self {
-1424 conn_id: ConnId(conn.stable_id()),
-1425 inner: conn.on_closed(),
-1426 }
-1427 }
-1428}
-1429
-1430impl Future for OnClosed {
-1431type Output = ConnId;
-1432
-1433fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
-1434let (_close_reason, _stats) = std::task::ready!(Pin::new(&mut self.inner).poll(cx));
-1435 Poll::Ready(self.conn_id)
-1436 }
-1437}
-1438
-1439/// Converts an iterator of [`TransportAddr'] into an iterator of [`transports::Addr`].
-1440fn to_transports_addr(
-1441 endpoint_id: EndpointId,
-1442 addrs: impl IntoIterator<Item = TransportAddr>,
-1443) -> impl Iterator<Item = transports::Addr> {
-1444 addrs.into_iter().filter_map(move |addr| match addr {
-1445 TransportAddr::Relay(relay_url) => Some(transports::Addr::from((relay_url, endpoint_id))),
-1446 TransportAddr::Ip(sockaddr) => Some(transports::Addr::from(sockaddr)),
-1447_ => {
-1448warn!(?addr, "Unsupported TransportAddr");
-1449None
-1450}
-1451 })
-1452}