diff --git a/pr/3836/docs/iroh/discovery/enum.DiscoveryError.html b/pr/3836/docs/iroh/discovery/enum.DiscoveryError.html index c7abe234c1..a9aa917022 100644 --- a/pr/3836/docs/iroh/discovery/enum.DiscoveryError.html +++ b/pr/3836/docs/iroh/discovery/enum.DiscoveryError.html @@ -26,7 +26,7 @@ provenance: &'static str, source: impl Into<AnyError>, ) -> Self

Creates a new user error from an arbitrary error type that can be converted into [AnyError].

-

Trait Implementations§

Source§

impl Clone for DiscoveryError

Source§

fn clone(&self) -> DiscoveryError

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

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

Performs copy-assignment from source. Read more
Source§

impl Debug for DiscoveryError

Source§

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

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

impl Display for DiscoveryError

Source§

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

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

impl Error for DiscoveryError

Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl From<DiscoveryError> for AnyError

Source§

fn from(value: DiscoveryError) -> AnyError

Converts to this type from the input type.
Source§

impl From<DiscoveryError> for ConnectWithOptsError

Source§

fn from(source: DiscoveryError) -> Self

Converts to this type from the input type.
Source§

impl From<PkarrError> for DiscoveryError

Source§

fn from(err: PkarrError) -> Self

Converts to this type from the input type.
Source§

impl StackError for DiscoveryError

Source§

fn as_std(&self) -> &(dyn Error + Send + Sync + 'static)

Returns this error as a std error reference.
Source§

fn into_std(self: Box<Self>) -> Box<dyn Error + Send + Sync>

Returns this error as a std error.
Source§

fn as_dyn(&self) -> &dyn StackError

Returns this error as a dyn StackError.
Source§

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

Returns the next source in the chain, if any.
Source§

fn meta(&self) -> Option<&Meta>

Returns metadata captured at creation time, if available.
Source§

fn source(&self) -> Option<ErrorRef<'_>>

Returns the next source in the chain, if any.
Source§

fn is_transparent(&self) -> bool

Returns whether this error is transparent and should be skipped in reports.
§

fn as_ref(&self) -> ErrorRef<'_>

Returns this error as an [ErrorRef]. Read more
§

fn stack(&self) -> Chain<'_>

Returns an iterator over this error followed by its sources.
§

fn sources(&self) -> Chain<'_>

Returns an iterator over sources of this error (skipping self).
§

fn report(&self) -> Report<'_>

Returns a [Report] to output the error with configurable formatting.

Auto Trait Implementations§

§

impl Freeze for DiscoveryError

§

impl !RefUnwindSafe for DiscoveryError

§

impl Send for DiscoveryError

§

impl Sync for DiscoveryError

§

impl Unpin for DiscoveryError

§

impl !UnwindSafe for DiscoveryError

Blanket Implementations§

Source§

impl<T> Any for T
where +

Trait Implementations§

Source§

impl Clone for DiscoveryError

Source§

fn clone(&self) -> DiscoveryError

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

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

Performs copy-assignment from source. Read more
Source§

impl Debug for DiscoveryError

Source§

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

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

impl Display for DiscoveryError

Source§

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

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

impl Error for DiscoveryError

Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl From<DiscoveryError> for AnyError

Source§

fn from(value: DiscoveryError) -> AnyError

Converts to this type from the input type.
Source§

impl From<DiscoveryError> for ConnectWithOptsError

Source§

fn from(source: DiscoveryError) -> Self

Converts to this type from the input type.
Source§

impl From<PkarrError> for DiscoveryError

Source§

fn from(err: PkarrError) -> Self

Converts to this type from the input type.
Source§

impl StackError for DiscoveryError

Source§

fn as_std(&self) -> &(dyn Error + Send + Sync + 'static)

Returns this error as a std error reference.
Source§

fn into_std(self: Box<Self>) -> Box<dyn Error + Send + Sync>

Returns this error as a std error.
Source§

fn as_dyn(&self) -> &dyn StackError

Returns this error as a dyn StackError.
Source§

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

Returns the next source in the chain, if any.
Source§

fn meta(&self) -> Option<&Meta>

Returns metadata captured at creation time, if available.
Source§

fn source(&self) -> Option<ErrorRef<'_>>

Returns the next source in the chain, if any.
Source§

fn is_transparent(&self) -> bool

Returns whether this error is transparent and should be skipped in reports.
§

fn as_ref(&self) -> ErrorRef<'_>

Returns this error as an [ErrorRef]. Read more
§

fn stack(&self) -> Chain<'_>

Returns an iterator over this error followed by its sources.
§

fn sources(&self) -> Chain<'_>

Returns an iterator over sources of this error (skipping self).
§

fn report(&self) -> Report<'_>

Returns a [Report] to output the error with configurable formatting.

Auto Trait Implementations§

§

impl Freeze for DiscoveryError

§

impl !RefUnwindSafe for DiscoveryError

§

impl Send for DiscoveryError

§

impl Sync for DiscoveryError

§

impl Unpin for DiscoveryError

§

impl !UnwindSafe for DiscoveryError

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

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

§

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

§

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

§

fn implicit( diff --git a/pr/3836/docs/iroh/discovery/enum.IntoDiscoveryError.html b/pr/3836/docs/iroh/discovery/enum.IntoDiscoveryError.html index e89b1c5bf9..992eb5d4c1 100644 --- a/pr/3836/docs/iroh/discovery/enum.IntoDiscoveryError.html +++ b/pr/3836/docs/iroh/discovery/enum.IntoDiscoveryError.html @@ -14,7 +14,7 @@ provenance: &'static str, source: Box<dyn Error + Send + Sync + 'static>, ) -> Self

Creates a new user error from an arbitrary boxed error type.

-

Trait Implementations§

Source§

impl Debug for IntoDiscoveryError

Source§

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

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

impl Display for IntoDiscoveryError

Source§

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

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

impl Error for IntoDiscoveryError

Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl From<IntoDiscoveryError> for AnyError

Source§

fn from(value: IntoDiscoveryError) -> AnyError

Converts to this type from the input type.
Source§

impl From<IntoDiscoveryError> for BindError

Source§

fn from(source: IntoDiscoveryError) -> Self

Converts to this type from the input type.
Source§

impl StackError for IntoDiscoveryError

Source§

fn as_std(&self) -> &(dyn Error + Send + Sync + 'static)

Returns this error as a std error reference.
Source§

fn into_std(self: Box<Self>) -> Box<dyn Error + Send + Sync>

Returns this error as a std error.
Source§

fn as_dyn(&self) -> &dyn StackError

Returns this error as a dyn StackError.
Source§

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

Returns the next source in the chain, if any.
Source§

fn meta(&self) -> Option<&Meta>

Returns metadata captured at creation time, if available.
Source§

fn source(&self) -> Option<ErrorRef<'_>>

Returns the next source in the chain, if any.
Source§

fn is_transparent(&self) -> bool

Returns whether this error is transparent and should be skipped in reports.
§

fn as_ref(&self) -> ErrorRef<'_>

Returns this error as an [ErrorRef]. Read more
§

fn stack(&self) -> Chain<'_>

Returns an iterator over this error followed by its sources.
§

fn sources(&self) -> Chain<'_>

Returns an iterator over sources of this error (skipping self).
§

fn report(&self) -> Report<'_>

Returns a [Report] to output the error with configurable formatting.

Auto Trait Implementations§

§

impl Freeze for IntoDiscoveryError

§

impl !RefUnwindSafe for IntoDiscoveryError

§

impl Send for IntoDiscoveryError

§

impl Sync for IntoDiscoveryError

§

impl Unpin for IntoDiscoveryError

§

impl !UnwindSafe for IntoDiscoveryError

Blanket Implementations§

Source§

impl<T> Any for T
where +

Trait Implementations§

Source§

impl Debug for IntoDiscoveryError

Source§

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

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

impl Display for IntoDiscoveryError

Source§

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

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

impl Error for IntoDiscoveryError

Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl From<IntoDiscoveryError> for AnyError

Source§

fn from(value: IntoDiscoveryError) -> AnyError

Converts to this type from the input type.
Source§

impl From<IntoDiscoveryError> for BindError

Source§

fn from(source: IntoDiscoveryError) -> Self

Converts to this type from the input type.
Source§

impl StackError for IntoDiscoveryError

Source§

fn as_std(&self) -> &(dyn Error + Send + Sync + 'static)

Returns this error as a std error reference.
Source§

fn into_std(self: Box<Self>) -> Box<dyn Error + Send + Sync>

Returns this error as a std error.
Source§

fn as_dyn(&self) -> &dyn StackError

Returns this error as a dyn StackError.
Source§

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

Returns the next source in the chain, if any.
Source§

fn meta(&self) -> Option<&Meta>

Returns metadata captured at creation time, if available.
Source§

fn source(&self) -> Option<ErrorRef<'_>>

Returns the next source in the chain, if any.
Source§

fn is_transparent(&self) -> bool

Returns whether this error is transparent and should be skipped in reports.
§

fn as_ref(&self) -> ErrorRef<'_>

Returns this error as an [ErrorRef]. Read more
§

fn stack(&self) -> Chain<'_>

Returns an iterator over this error followed by its sources.
§

fn sources(&self) -> Chain<'_>

Returns an iterator over sources of this error (skipping self).
§

fn report(&self) -> Report<'_>

Returns a [Report] to output the error with configurable formatting.

Auto Trait Implementations§

§

impl Freeze for IntoDiscoveryError

§

impl !RefUnwindSafe for IntoDiscoveryError

§

impl Send for IntoDiscoveryError

§

impl Sync for IntoDiscoveryError

§

impl Unpin for IntoDiscoveryError

§

impl !UnwindSafe for IntoDiscoveryError

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

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

§

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

§

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

§

fn implicit( diff --git a/pr/3836/docs/iroh/endpoint/constant.ENV_FORCE_STAGING_RELAYS.html b/pr/3836/docs/iroh/endpoint/constant.ENV_FORCE_STAGING_RELAYS.html index ed8da9bec6..9efc491834 100644 --- a/pr/3836/docs/iroh/endpoint/constant.ENV_FORCE_STAGING_RELAYS.html +++ b/pr/3836/docs/iroh/endpoint/constant.ENV_FORCE_STAGING_RELAYS.html @@ -1,2 +1,2 @@ -ENV_FORCE_STAGING_RELAYS in iroh::endpoint - Rust

ENV_FORCE_STAGING_RELAYS

Constant ENV_FORCE_STAGING_RELAYS 

Source
pub const ENV_FORCE_STAGING_RELAYS: &str = "IROH_FORCE_STAGING_RELAYS";
Expand description

Environment variable to force the use of staging relays.

+ENV_FORCE_STAGING_RELAYS in iroh::endpoint - Rust

ENV_FORCE_STAGING_RELAYS

Constant ENV_FORCE_STAGING_RELAYS 

Source
pub const ENV_FORCE_STAGING_RELAYS: &str = "IROH_FORCE_STAGING_RELAYS";
Expand description

Environment variable to force the use of staging relays.

\ No newline at end of file diff --git a/pr/3836/docs/iroh/endpoint/enum.BindError.html b/pr/3836/docs/iroh/endpoint/enum.BindError.html index 2c307f6a3d..bc09766ec5 100644 --- a/pr/3836/docs/iroh/endpoint/enum.BindError.html +++ b/pr/3836/docs/iroh/endpoint/enum.BindError.html @@ -1,4 +1,4 @@ -BindError in iroh::endpoint - Rust

BindError

Enum BindError 

Source
#[non_exhaustive]
pub enum BindError { +BindError in iroh::endpoint - Rust

BindError

Enum BindError 

Source
#[non_exhaustive]
pub enum BindError { MagicSpawn { source: CreateHandleError, meta: Meta, @@ -9,7 +9,7 @@ }, }

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
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.
§

MagicSpawn

Fields

§source: CreateHandleError
§meta: Meta

Captured call-site metadata

§

Discovery

Fields

§meta: Meta

Captured call-site metadata

-

Trait Implementations§

Source§

impl Debug for BindError

Source§

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

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

impl Display for BindError

Source§

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

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

impl Error for BindError

Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl From<BindError> for AnyError

Source§

fn from(value: BindError) -> AnyError

Converts to this type from the input type.
Source§

impl From<IntoDiscoveryError> for BindError

Source§

fn from(source: IntoDiscoveryError) -> Self

Converts to this type from the input type.
Source§

impl StackError for BindError

Source§

fn as_std(&self) -> &(dyn Error + Send + Sync + 'static)

Returns this error as a std error reference.
Source§

fn into_std(self: Box<Self>) -> Box<dyn Error + Send + Sync>

Returns this error as a std error.
Source§

fn as_dyn(&self) -> &dyn StackError

Returns this error as a dyn StackError.
Source§

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

Returns the next source in the chain, if any.
Source§

fn meta(&self) -> Option<&Meta>

Returns metadata captured at creation time, if available.
Source§

fn source(&self) -> Option<ErrorRef<'_>>

Returns the next source in the chain, if any.
Source§

fn is_transparent(&self) -> bool

Returns whether this error is transparent and should be skipped in reports.
§

fn as_ref(&self) -> ErrorRef<'_>

Returns this error as an [ErrorRef]. Read more
§

fn stack(&self) -> Chain<'_>

Returns an iterator over this error followed by its sources.
§

fn sources(&self) -> Chain<'_>

Returns an iterator over sources of this error (skipping self).
§

fn report(&self) -> Report<'_>

Returns a [Report] to output the error with configurable formatting.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +

Trait Implementations§

Source§

impl Debug for BindError

Source§

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

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

impl Display for BindError

Source§

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

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

impl Error for BindError

Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl From<BindError> for AnyError

Source§

fn from(value: BindError) -> AnyError

Converts to this type from the input type.
Source§

impl From<IntoDiscoveryError> for BindError

Source§

fn from(source: IntoDiscoveryError) -> Self

Converts to this type from the input type.
Source§

impl StackError for BindError

Source§

fn as_std(&self) -> &(dyn Error + Send + Sync + 'static)

Returns this error as a std error reference.
Source§

fn into_std(self: Box<Self>) -> Box<dyn Error + Send + Sync>

Returns this error as a std error.
Source§

fn as_dyn(&self) -> &dyn StackError

Returns this error as a dyn StackError.
Source§

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

Returns the next source in the chain, if any.
Source§

fn meta(&self) -> Option<&Meta>

Returns metadata captured at creation time, if available.
Source§

fn source(&self) -> Option<ErrorRef<'_>>

Returns the next source in the chain, if any.
Source§

fn is_transparent(&self) -> bool

Returns whether this error is transparent and should be skipped in reports.
§

fn as_ref(&self) -> ErrorRef<'_>

Returns this error as an [ErrorRef]. Read more
§

fn stack(&self) -> Chain<'_>

Returns an iterator over this error followed by its sources.
§

fn sources(&self) -> Chain<'_>

Returns an iterator over sources of this error (skipping self).
§

fn report(&self) -> Report<'_>

Returns a [Report] to output the error with configurable formatting.

Auto Trait Implementations§

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

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

§

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

§

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

§

fn implicit( diff --git a/pr/3836/docs/iroh/endpoint/enum.ConnectError.html b/pr/3836/docs/iroh/endpoint/enum.ConnectError.html index 6c99952bc8..d20e61af7f 100644 --- a/pr/3836/docs/iroh/endpoint/enum.ConnectError.html +++ b/pr/3836/docs/iroh/endpoint/enum.ConnectError.html @@ -1,4 +1,4 @@ -ConnectError in iroh::endpoint - Rust

ConnectError

Enum ConnectError 

Source
#[non_exhaustive]
pub enum ConnectError { +ConnectError in iroh::endpoint - Rust

ConnectError

Enum ConnectError 

Source
#[non_exhaustive]
pub enum ConnectError { Connect { source: ConnectWithOptsError, meta: Meta, @@ -14,7 +14,7 @@ }

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
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.
§

Connect

Fields

§meta: Meta

Captured call-site metadata

§

Connecting

Fields

§meta: Meta

Captured call-site metadata

§

Connection

Fields

§meta: Meta

Captured call-site metadata

-

Trait Implementations§

Source§

impl Debug for ConnectError

Source§

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

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

impl Display for ConnectError

Source§

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

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

impl Error for ConnectError

Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl From<ConnectError> for AnyError

Source§

fn from(value: ConnectError) -> AnyError

Converts to this type from the input type.
Source§

impl From<ConnectWithOptsError> for ConnectError

Source§

fn from(source: ConnectWithOptsError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectingError> for ConnectError

Source§

fn from(source: ConnectingError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectionError> for ConnectError

Source§

fn from(source: ConnectionError) -> Self

Converts to this type from the input type.
Source§

impl StackError for ConnectError

Source§

fn as_std(&self) -> &(dyn Error + Send + Sync + 'static)

Returns this error as a std error reference.
Source§

fn into_std(self: Box<Self>) -> Box<dyn Error + Send + Sync>

Returns this error as a std error.
Source§

fn as_dyn(&self) -> &dyn StackError

Returns this error as a dyn StackError.
Source§

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

Returns the next source in the chain, if any.
Source§

fn meta(&self) -> Option<&Meta>

Returns metadata captured at creation time, if available.
Source§

fn source(&self) -> Option<ErrorRef<'_>>

Returns the next source in the chain, if any.
Source§

fn is_transparent(&self) -> bool

Returns whether this error is transparent and should be skipped in reports.
§

fn as_ref(&self) -> ErrorRef<'_>

Returns this error as an [ErrorRef]. Read more
§

fn stack(&self) -> Chain<'_>

Returns an iterator over this error followed by its sources.
§

fn sources(&self) -> Chain<'_>

Returns an iterator over sources of this error (skipping self).
§

fn report(&self) -> Report<'_>

Returns a [Report] to output the error with configurable formatting.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +

Trait Implementations§

Source§

impl Debug for ConnectError

Source§

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

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

impl Display for ConnectError

Source§

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

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

impl Error for ConnectError

Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl From<ConnectError> for AnyError

Source§

fn from(value: ConnectError) -> AnyError

Converts to this type from the input type.
Source§

impl From<ConnectWithOptsError> for ConnectError

Source§

fn from(source: ConnectWithOptsError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectingError> for ConnectError

Source§

fn from(source: ConnectingError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectionError> for ConnectError

Source§

fn from(source: ConnectionError) -> Self

Converts to this type from the input type.
Source§

impl StackError for ConnectError

Source§

fn as_std(&self) -> &(dyn Error + Send + Sync + 'static)

Returns this error as a std error reference.
Source§

fn into_std(self: Box<Self>) -> Box<dyn Error + Send + Sync>

Returns this error as a std error.
Source§

fn as_dyn(&self) -> &dyn StackError

Returns this error as a dyn StackError.
Source§

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

Returns the next source in the chain, if any.
Source§

fn meta(&self) -> Option<&Meta>

Returns metadata captured at creation time, if available.
Source§

fn source(&self) -> Option<ErrorRef<'_>>

Returns the next source in the chain, if any.
Source§

fn is_transparent(&self) -> bool

Returns whether this error is transparent and should be skipped in reports.
§

fn as_ref(&self) -> ErrorRef<'_>

Returns this error as an [ErrorRef]. Read more
§

fn stack(&self) -> Chain<'_>

Returns an iterator over this error followed by its sources.
§

fn sources(&self) -> Chain<'_>

Returns an iterator over sources of this error (skipping self).
§

fn report(&self) -> Report<'_>

Returns a [Report] to output the error with configurable formatting.

Auto Trait Implementations§

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

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

§

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

§

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

§

fn implicit( diff --git a/pr/3836/docs/iroh/endpoint/enum.ConnectWithOptsError.html b/pr/3836/docs/iroh/endpoint/enum.ConnectWithOptsError.html index 13d575a68b..2f6119df22 100644 --- a/pr/3836/docs/iroh/endpoint/enum.ConnectWithOptsError.html +++ b/pr/3836/docs/iroh/endpoint/enum.ConnectWithOptsError.html @@ -1,4 +1,4 @@ -ConnectWithOptsError in iroh::endpoint - Rust

ConnectWithOptsError

Enum ConnectWithOptsError 

Source
#[non_exhaustive]
pub enum ConnectWithOptsError { +ConnectWithOptsError in iroh::endpoint - Rust

ConnectWithOptsError

Enum ConnectWithOptsError 

Source
#[non_exhaustive]
pub enum ConnectWithOptsError { SelfConnect { meta: Meta, }, @@ -23,7 +23,7 @@

§

InternalConsistencyError

Fields

§source: RemoteStateActorStoppedError

Private source type, cannot be created publicly.

§meta: Meta

Captured call-site metadata

§

LocallyRejected

Fields

§meta: Meta

Captured call-site metadata

-

Trait Implementations§

Source§

impl Debug for ConnectWithOptsError

Source§

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

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

impl Display for ConnectWithOptsError

Source§

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

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

impl Error for ConnectWithOptsError

Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl From<ConnectError> for ConnectWithOptsError

Source§

fn from(source: QuicConnectError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectWithOptsError> for AnyError

Source§

fn from(value: ConnectWithOptsError) -> AnyError

Converts to this type from the input type.
Source§

impl From<ConnectWithOptsError> for ConnectError

Source§

fn from(source: ConnectWithOptsError) -> Self

Converts to this type from the input type.
Source§

impl From<DiscoveryError> for ConnectWithOptsError

Source§

fn from(source: DiscoveryError) -> Self

Converts to this type from the input type.
Source§

impl StackError for ConnectWithOptsError

Source§

fn as_std(&self) -> &(dyn Error + Send + Sync + 'static)

Returns this error as a std error reference.
Source§

fn into_std(self: Box<Self>) -> Box<dyn Error + Send + Sync>

Returns this error as a std error.
Source§

fn as_dyn(&self) -> &dyn StackError

Returns this error as a dyn StackError.
Source§

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

Returns the next source in the chain, if any.
Source§

fn meta(&self) -> Option<&Meta>

Returns metadata captured at creation time, if available.
Source§

fn source(&self) -> Option<ErrorRef<'_>>

Returns the next source in the chain, if any.
Source§

fn is_transparent(&self) -> bool

Returns whether this error is transparent and should be skipped in reports.
§

fn as_ref(&self) -> ErrorRef<'_>

Returns this error as an [ErrorRef]. Read more
§

fn stack(&self) -> Chain<'_>

Returns an iterator over this error followed by its sources.
§

fn sources(&self) -> Chain<'_>

Returns an iterator over sources of this error (skipping self).
§

fn report(&self) -> Report<'_>

Returns a [Report] to output the error with configurable formatting.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +

Trait Implementations§

Source§

impl Debug for ConnectWithOptsError

Source§

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

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

impl Display for ConnectWithOptsError

Source§

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

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

impl Error for ConnectWithOptsError

Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl From<ConnectError> for ConnectWithOptsError

Source§

fn from(source: QuicConnectError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectWithOptsError> for AnyError

Source§

fn from(value: ConnectWithOptsError) -> AnyError

Converts to this type from the input type.
Source§

impl From<ConnectWithOptsError> for ConnectError

Source§

fn from(source: ConnectWithOptsError) -> Self

Converts to this type from the input type.
Source§

impl From<DiscoveryError> for ConnectWithOptsError

Source§

fn from(source: DiscoveryError) -> Self

Converts to this type from the input type.
Source§

impl StackError for ConnectWithOptsError

Source§

fn as_std(&self) -> &(dyn Error + Send + Sync + 'static)

Returns this error as a std error reference.
Source§

fn into_std(self: Box<Self>) -> Box<dyn Error + Send + Sync>

Returns this error as a std error.
Source§

fn as_dyn(&self) -> &dyn StackError

Returns this error as a dyn StackError.
Source§

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

Returns the next source in the chain, if any.
Source§

fn meta(&self) -> Option<&Meta>

Returns metadata captured at creation time, if available.
Source§

fn source(&self) -> Option<ErrorRef<'_>>

Returns the next source in the chain, if any.
Source§

fn is_transparent(&self) -> bool

Returns whether this error is transparent and should be skipped in reports.
§

fn as_ref(&self) -> ErrorRef<'_>

Returns this error as an [ErrorRef]. Read more
§

fn stack(&self) -> Chain<'_>

Returns an iterator over this error followed by its sources.
§

fn sources(&self) -> Chain<'_>

Returns an iterator over sources of this error (skipping self).
§

fn report(&self) -> Report<'_>

Returns a [Report] to output the error with configurable formatting.

Auto Trait Implementations§

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

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

§

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

§

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

§

fn implicit( diff --git a/pr/3836/docs/iroh/endpoint/enum.ConnectingError.html b/pr/3836/docs/iroh/endpoint/enum.ConnectingError.html index 6533c6fb62..ed0b8086c2 100644 --- a/pr/3836/docs/iroh/endpoint/enum.ConnectingError.html +++ b/pr/3836/docs/iroh/endpoint/enum.ConnectingError.html @@ -19,7 +19,7 @@

§

InternalConsistencyError

Fields

§source: RemoteStateActorStoppedError

Private source type, cannot be created publicly.

§meta: Meta

Captured call-site metadata

§

LocallyRejected

Fields

§meta: Meta

Captured call-site metadata

-

Trait Implementations§

Source§

impl Clone for ConnectingError

Source§

fn clone(&self) -> ConnectingError

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

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

Performs copy-assignment from source. Read more
Source§

impl Debug for ConnectingError

Source§

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

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

impl Display for ConnectingError

Source§

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

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

impl Error for ConnectingError

Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl From<AuthenticationError> for ConnectingError

Source§

fn from(source: AuthenticationError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectingError> for AcceptError

Source§

fn from(source: ConnectingError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectingError> for AnyError

Source§

fn from(value: ConnectingError) -> AnyError

Converts to this type from the input type.
Source§

impl From<ConnectingError> for ConnectError

Source§

fn from(source: ConnectingError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectionError> for ConnectingError

Source§

fn from(source: ConnectionError) -> Self

Converts to this type from the input type.
Source§

impl StackError for ConnectingError

Source§

fn as_std(&self) -> &(dyn Error + Send + Sync + 'static)

Returns this error as a std error reference.
Source§

fn into_std(self: Box<Self>) -> Box<dyn Error + Send + Sync>

Returns this error as a std error.
Source§

fn as_dyn(&self) -> &dyn StackError

Returns this error as a dyn StackError.
Source§

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

Returns the next source in the chain, if any.
Source§

fn meta(&self) -> Option<&Meta>

Returns metadata captured at creation time, if available.
Source§

fn source(&self) -> Option<ErrorRef<'_>>

Returns the next source in the chain, if any.
Source§

fn is_transparent(&self) -> bool

Returns whether this error is transparent and should be skipped in reports.
§

fn as_ref(&self) -> ErrorRef<'_>

Returns this error as an [ErrorRef]. Read more
§

fn stack(&self) -> Chain<'_>

Returns an iterator over this error followed by its sources.
§

fn sources(&self) -> Chain<'_>

Returns an iterator over sources of this error (skipping self).
§

fn report(&self) -> Report<'_>

Returns a [Report] to output the error with configurable formatting.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +

Trait Implementations§

Source§

impl Clone for ConnectingError

Source§

fn clone(&self) -> ConnectingError

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

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

Performs copy-assignment from source. Read more
Source§

impl Debug for ConnectingError

Source§

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

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

impl Display for ConnectingError

Source§

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

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

impl Error for ConnectingError

Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl From<AuthenticationError> for ConnectingError

Source§

fn from(source: AuthenticationError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectingError> for AcceptError

Source§

fn from(source: ConnectingError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectingError> for AnyError

Source§

fn from(value: ConnectingError) -> AnyError

Converts to this type from the input type.
Source§

impl From<ConnectingError> for ConnectError

Source§

fn from(source: ConnectingError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectionError> for ConnectingError

Source§

fn from(source: ConnectionError) -> Self

Converts to this type from the input type.
Source§

impl StackError for ConnectingError

Source§

fn as_std(&self) -> &(dyn Error + Send + Sync + 'static)

Returns this error as a std error reference.
Source§

fn into_std(self: Box<Self>) -> Box<dyn Error + Send + Sync>

Returns this error as a std error.
Source§

fn as_dyn(&self) -> &dyn StackError

Returns this error as a dyn StackError.
Source§

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

Returns the next source in the chain, if any.
Source§

fn meta(&self) -> Option<&Meta>

Returns metadata captured at creation time, if available.
Source§

fn source(&self) -> Option<ErrorRef<'_>>

Returns the next source in the chain, if any.
Source§

fn is_transparent(&self) -> bool

Returns whether this error is transparent and should be skipped in reports.
§

fn as_ref(&self) -> ErrorRef<'_>

Returns this error as an [ErrorRef]. Read more
§

fn stack(&self) -> Chain<'_>

Returns an iterator over this error followed by its sources.
§

fn sources(&self) -> Chain<'_>

Returns an iterator over sources of this error (skipping self).
§

fn report(&self) -> Report<'_>

Returns a [Report] to output the error with configurable formatting.

Auto Trait Implementations§

§

impl !Freeze for ConnectingError

§

impl !RefUnwindSafe for ConnectingError

§

impl Send for ConnectingError

§

impl Sync for ConnectingError

§

impl Unpin for ConnectingError

§

impl !UnwindSafe for ConnectingError

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

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

§

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

§

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

§

fn implicit( diff --git a/pr/3836/docs/iroh/endpoint/enum.ConnectionError.html b/pr/3836/docs/iroh/endpoint/enum.ConnectionError.html index c9cee82fc1..8672b90674 100644 --- a/pr/3836/docs/iroh/endpoint/enum.ConnectionError.html +++ b/pr/3836/docs/iroh/endpoint/enum.ConnectionError.html @@ -21,7 +21,7 @@ and [TransportConfig::keep_alive_interval()].

§

LocallyClosed

The local application closed the connection

§

CidsExhausted

The connection could not be created because not enough of the CID space is available

Try using longer connection IDs.

-

Trait Implementations§

§

impl Clone for ConnectionError

§

fn clone(&self) -> ConnectionError

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

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

Performs copy-assignment from source. Read more
§

impl Debug for ConnectionError

§

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

Formats the value using the given formatter. Read more
§

impl Display for ConnectionError

§

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

Formats the value using the given formatter. Read more
§

impl Error for ConnectionError

§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
§

impl From<Close> for ConnectionError

§

fn from(x: Close) -> ConnectionError

Converts to this type from the input type.
§

impl From<CloseReason> for ConnectionError

§

fn from(value: CloseReason) -> ConnectionError

Converts to this type from the input type.
Source§

impl From<ConnectionError> for AcceptError

Source§

fn from(source: ConnectionError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectionError> for AlpnError

Source§

fn from(source: ConnectionError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectionError> for ConnectError

Source§

fn from(source: ConnectionError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectionError> for ConnectingError

Source§

fn from(source: ConnectionError) -> Self

Converts to this type from the input type.
§

impl From<ConnectionError> for ReadError

§

fn from(source: ConnectionError) -> ReadError

Converts to this type from the input type.
§

impl From<ConnectionError> for ResetError

§

fn from(source: ConnectionError) -> ResetError

Converts to this type from the input type.
§

impl From<ConnectionError> for SendDatagramError

§

fn from(source: ConnectionError) -> SendDatagramError

Converts to this type from the input type.
§

impl From<ConnectionError> for StoppedError

§

fn from(source: ConnectionError) -> StoppedError

Converts to this type from the input type.
§

impl From<ConnectionError> for WriteError

§

fn from(source: ConnectionError) -> WriteError

Converts to this type from the input type.
§

impl From<Error> for ConnectionError

§

fn from(source: Error) -> ConnectionError

Converts to this type from the input type.
§

impl PartialEq for ConnectionError

§

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

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

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

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

Trait Implementations§

§

impl Clone for ConnectionError

§

fn clone(&self) -> ConnectionError

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

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

Performs copy-assignment from source. Read more
§

impl Debug for ConnectionError

§

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

Formats the value using the given formatter. Read more
§

impl Display for ConnectionError

§

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

Formats the value using the given formatter. Read more
§

impl Error for ConnectionError

§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
§

impl From<Close> for ConnectionError

§

fn from(x: Close) -> ConnectionError

Converts to this type from the input type.
§

impl From<CloseReason> for ConnectionError

§

fn from(value: CloseReason) -> ConnectionError

Converts to this type from the input type.
Source§

impl From<ConnectionError> for AcceptError

Source§

fn from(source: ConnectionError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectionError> for AlpnError

Source§

fn from(source: ConnectionError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectionError> for ConnectError

Source§

fn from(source: ConnectionError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectionError> for ConnectingError

Source§

fn from(source: ConnectionError) -> Self

Converts to this type from the input type.
§

impl From<ConnectionError> for ReadError

§

fn from(source: ConnectionError) -> ReadError

Converts to this type from the input type.
§

impl From<ConnectionError> for ResetError

§

fn from(source: ConnectionError) -> ResetError

Converts to this type from the input type.
§

impl From<ConnectionError> for SendDatagramError

§

fn from(source: ConnectionError) -> SendDatagramError

Converts to this type from the input type.
§

impl From<ConnectionError> for StoppedError

§

fn from(source: ConnectionError) -> StoppedError

Converts to this type from the input type.
§

impl From<ConnectionError> for WriteError

§

fn from(source: ConnectionError) -> WriteError

Converts to this type from the input type.
§

impl From<Error> for ConnectionError

§

fn from(source: Error) -> ConnectionError

Converts to this type from the input type.
§

impl PartialEq for ConnectionError

§

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

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

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

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

impl Eq for ConnectionError

§

impl StructuralPartialEq for ConnectionError

Auto Trait Implementations§

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

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

§

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

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where diff --git a/pr/3836/docs/iroh/endpoint/enum.QuicConnectError.html b/pr/3836/docs/iroh/endpoint/enum.QuicConnectError.html index 9227ed9437..7d826297ef 100644 --- a/pr/3836/docs/iroh/endpoint/enum.QuicConnectError.html +++ b/pr/3836/docs/iroh/endpoint/enum.QuicConnectError.html @@ -18,7 +18,7 @@ Errors in the parameters being used to create a new connection

§

NoDefaultClientConfig

No default client configuration was set up

Use Endpoint::connect_with to specify a client configuration.

§

UnsupportedVersion

The local endpoint does not support the QUIC version specified in the client configuration

-

Trait Implementations§

§

impl Clone for ConnectError

§

fn clone(&self) -> ConnectError

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

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

Performs copy-assignment from source. Read more
§

impl Debug for ConnectError

§

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

Formats the value using the given formatter. Read more
§

impl Display for ConnectError

§

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

Formats the value using the given formatter. Read more
§

impl Error for ConnectError

1.30.0 · Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl From<ConnectError> for ConnectWithOptsError

Source§

fn from(source: QuicConnectError) -> Self

Converts to this type from the input type.
§

impl From<UnsupportedVersion> for ConnectError

§

fn from(_: UnsupportedVersion) -> ConnectError

Converts to this type from the input type.
§

impl PartialEq for ConnectError

§

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

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

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

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

Trait Implementations§

§

impl Clone for ConnectError

§

fn clone(&self) -> ConnectError

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

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

Performs copy-assignment from source. Read more
§

impl Debug for ConnectError

§

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

Formats the value using the given formatter. Read more
§

impl Display for ConnectError

§

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

Formats the value using the given formatter. Read more
§

impl Error for ConnectError

1.30.0 · Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl From<ConnectError> for ConnectWithOptsError

Source§

fn from(source: QuicConnectError) -> Self

Converts to this type from the input type.
§

impl From<UnsupportedVersion> for ConnectError

§

fn from(_: UnsupportedVersion) -> ConnectError

Converts to this type from the input type.
§

impl PartialEq for ConnectError

§

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

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

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

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

impl Eq for ConnectError

§

impl StructuralPartialEq for ConnectError

Auto Trait Implementations§

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

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

§

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

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where diff --git a/pr/3836/docs/iroh/endpoint/enum.RelayMode.html b/pr/3836/docs/iroh/endpoint/enum.RelayMode.html index 55374ba570..c0d8934eee 100644 --- a/pr/3836/docs/iroh/endpoint/enum.RelayMode.html +++ b/pr/3836/docs/iroh/endpoint/enum.RelayMode.html @@ -1,4 +1,4 @@ -RelayMode in iroh::endpoint - Rust

RelayMode

Enum RelayMode 

Source
pub enum RelayMode {
+RelayMode in iroh::endpoint - Rust

RelayMode

Enum RelayMode 

Source
pub enum RelayMode {
     Disabled,
     Default,
     Staging,
@@ -10,14 +10,14 @@ This means that neither listening nor dialing relays will be available.

See crate::defaults::prod for the severs used.

§

Staging

Use the staging relay servers from n0.

§

Custom(RelayMap)

Use a custom relay map.

-

Implementations§

Source§

impl RelayMode

Source

pub fn relay_map(&self) -> RelayMap

Returns the relay map for this mode.

-
Source

pub fn custom(map: impl IntoIterator<Item = RelayUrl>) -> Self

Create a custom relay mode from a list of RelayUrls.

+

Implementations§

Source§

impl RelayMode

Source

pub fn relay_map(&self) -> RelayMap

Returns the relay map for this mode.

+
Source

pub fn custom(map: impl IntoIterator<Item = RelayUrl>) -> Self

Create a custom relay mode from a list of RelayUrls.

§Example
RelayMode::custom([
     "https://use1-1.relay.n0.iroh-canary.iroh.link.".parse()?,
     "https://euw-1.relay.n0.iroh-canary.iroh.link.".parse()?,
-]);

Trait Implementations§

Source§

impl Clone for RelayMode

Source§

fn clone(&self) -> RelayMode

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

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

Performs copy-assignment from source. Read more
Source§

impl Debug for RelayMode

Source§

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

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

impl From<RelayMode> for Option<TransportConfig>

Source§

fn from(mode: RelayMode) -> Self

Converts to this type from the input type.
Source§

impl PartialEq for RelayMode

Source§

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

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

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

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

impl Eq for RelayMode

Source§

impl StructuralPartialEq for RelayMode

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +]);

Trait Implementations§

Source§

impl Clone for RelayMode

Source§

fn clone(&self) -> RelayMode

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

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

Performs copy-assignment from source. Read more
Source§

impl Debug for RelayMode

Source§

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

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

impl From<RelayMode> for Option<TransportConfig>

Source§

fn from(mode: RelayMode) -> Self

Converts to this type from the input type.
Source§

impl PartialEq for RelayMode

Source§

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

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

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

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

impl Eq for RelayMode

Source§

impl StructuralPartialEq for RelayMode

Auto Trait Implementations§

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

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

§

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

§

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

§

fn implicit( diff --git a/pr/3836/docs/iroh/endpoint/fn.default_relay_mode.html b/pr/3836/docs/iroh/endpoint/fn.default_relay_mode.html index 204e538489..4d369a0824 100644 --- a/pr/3836/docs/iroh/endpoint/fn.default_relay_mode.html +++ b/pr/3836/docs/iroh/endpoint/fn.default_relay_mode.html @@ -1,4 +1,4 @@ -default_relay_mode in iroh::endpoint - Rust

default_relay_mode

Function default_relay_mode 

Source
pub fn default_relay_mode() -> RelayMode
Expand description

Returns the default relay mode.

+default_relay_mode in iroh::endpoint - Rust

default_relay_mode

Function default_relay_mode 

Source
pub fn default_relay_mode() -> RelayMode
Expand description

Returns the default relay mode.

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/3836/docs/iroh/endpoint/fn.force_staging_infra.html b/pr/3836/docs/iroh/endpoint/fn.force_staging_infra.html index a6d32a1148..8a2ac0fd8b 100644 --- a/pr/3836/docs/iroh/endpoint/fn.force_staging_infra.html +++ b/pr/3836/docs/iroh/endpoint/fn.force_staging_infra.html @@ -1,2 +1,2 @@ -force_staging_infra in iroh::endpoint - Rust

force_staging_infra

Function force_staging_infra 

Source
pub fn force_staging_infra() -> bool
Expand description

Returns true if the use of staging relays is forced.

+force_staging_infra in iroh::endpoint - Rust

force_staging_infra

Function force_staging_infra 

Source
pub fn force_staging_infra() -> bool
Expand description

Returns true if the use of staging relays is forced.

\ No newline at end of file diff --git a/pr/3836/docs/iroh/endpoint/index.html b/pr/3836/docs/iroh/endpoint/index.html index 1613c249be..4b6c177798 100644 --- a/pr/3836/docs/iroh/endpoint/index.html +++ b/pr/3836/docs/iroh/endpoint/index.html @@ -1,4 +1,4 @@ -iroh::endpoint - Rust

Module endpoint

Module endpoint 

Source
Expand description

The Endpoint allows establishing connections to other iroh endpoints.

+iroh::endpoint - Rust

Module endpoint

Module endpoint 

Source
Expand description

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/3836/docs/iroh/endpoint/struct.Builder.html b/pr/3836/docs/iroh/endpoint/struct.Builder.html index 1cabe176fd..896640ce37 100644 --- a/pr/3836/docs/iroh/endpoint/struct.Builder.html +++ b/pr/3836/docs/iroh/endpoint/struct.Builder.html @@ -2,7 +2,7 @@

By default the endpoint will generate a new random SecretKey, which will result in a new EndpointId.

To create the Endpoint call Builder::bind.

-

Implementations§

Source§

impl Builder

Source

pub fn new<P: Preset>(preset: P) -> Self

Creates a new Builder using the given Preset.

+

Implementations§

Source§

impl Builder

Source

pub fn new<P: Preset>(preset: P) -> Self

Creates a new Builder using the given Preset.

See presets for more.

Source

pub fn preset<P: Preset>(self, preset: P) -> Self

Applies the given Preset.

Source

pub fn empty(relay_mode: RelayMode) -> Self

Creates an empty builder with no discovery services.

@@ -47,7 +47,7 @@ port 0 in the socket address assigns a random free port.

.bind_addr("127.0.0.1:1234")? .bind_addr("[::1]:1235")? .bind() - .await?;
Source

pub fn bind_addr_with_opts<A>( + .await?;

Source

pub fn bind_addr_with_opts<A>( self, addr: A, opts: BindOpts, @@ -97,24 +97,25 @@ socket should be bound or the routing will be non-deterministic. Prefer using is, they are in response to an incoming datagram. In this case the outgoing datagram will be sent over the same socket as the incoming datagram was received on, and the routing with the prefix length and default route as described above does not apply.

-

If the port specified is already in use, binding the endpoint will fail. Using -port 0 in the socket address assigns a random free port.

+

Using port 0 in the socket address assigns a random free port.

+

If the port specified is already in use, binding the endpoint will fail, unless +BindOpts::set_is_required is set to false

§Example
let endpoint = Endpoint::builder()
     .clear_ip_transports()
     .bind_addr_with_opts("127.0.0.1:1234", BindOpts::default().set_prefix_len(24))?
     .bind_addr_with_opts("[::1]:1235", BindOpts::default().set_prefix_len(48))?
     .bind()
-    .await?;
Source

pub fn clear_ip_transports(self) -> Self

Available on non-wasm_browser only.

Removes all IP based transports.

-
Source

pub fn clear_relay_transports(self) -> Self

Removes all relay based transports.

-
Source

pub fn secret_key(self, secret_key: SecretKey) -> Self

Sets a secret key to authenticate with other peers.

+ .await?;
Source

pub fn clear_ip_transports(self) -> Self

Available on non-wasm_browser only.

Removes all IP based transports.

+
Source

pub fn clear_relay_transports(self) -> Self

Removes all relay based transports.

+
Source

pub fn secret_key(self, secret_key: SecretKey) -> Self

Sets a secret key to authenticate with other peers.

This secret key’s public key will be the PublicKey of this endpoint and thus also its EndpointId

If not set, a new secret key will be generated.

-
Source

pub fn alpns(self, alpn_protocols: Vec<Vec<u8>>) -> Self

Sets the ALPN protocols that this endpoint will accept on incoming connections.

+
Source

pub fn alpns(self, alpn_protocols: Vec<Vec<u8>>) -> Self

Sets the ALPN protocols that this endpoint will accept on incoming connections.

Not setting this will still allow creating connections, but to accept incoming connections at least one ALPN must be set.

-
Source

pub fn relay_mode(self, relay_mode: RelayMode) -> Self

Sets the relay servers to assist in establishing connectivity.

+
Source

pub fn relay_mode(self, relay_mode: RelayMode) -> Self

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.

@@ -122,11 +123,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.

-
Source

pub fn clear_discovery(self) -> Self

Removes all discovery services from the builder.

+
Source

pub fn clear_discovery(self) -> Self

Removes all discovery services from the builder.

If no discovery service is set, connecting to an endpoint without providing its direct addresses or relay URLs will fail.

See the documentation of the crate::discovery::Discovery trait for details.

-
Source

pub fn discovery(self, discovery: impl IntoDiscovery) -> Self

Adds an additional discovery mechanism for this endpoint.

+
Source

pub fn discovery(self, discovery: impl IntoDiscovery) -> Self

Adds an additional discovery mechanism for this endpoint.

Once the endpoint is created the provided IntoDiscovery::into_discovery will be called. This allows discovery services to finalize their configuration by e.g. using the secret key from the endpoint which can be needed to sign published information.

@@ -137,13 +138,13 @@ will be combined using an internal instance of the

If no discovery service is set, connecting to an endpoint without providing its direct addresses or relay URLs will fail.

See the documentation of the crate::discovery::Discovery trait for details.

-
Source

pub fn user_data_for_discovery(self, user_data: UserData) -> Self

Sets the initial user-defined data to be published in discovery services for this node.

+
Source

pub fn user_data_for_discovery(self, user_data: UserData) -> Self

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.

-
Source

pub fn transport_config(self, transport_config: QuicTransportConfig) -> Self

Sets a custom QuicTransportConfig for this endpoint.

+
Source

pub fn transport_config(self, transport_config: QuicTransportConfig) -> Self

Sets a custom QuicTransportConfig for this endpoint.

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 @@ -151,33 +152,33 @@ 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.

-
Source

pub fn dns_resolver(self, dns_resolver: DnsResolver) -> Self

Available on non-wasm_browser only.

Optionally sets a custom DNS resolver to use for this endpoint.

+
Source

pub fn dns_resolver(self, dns_resolver: DnsResolver) -> Self

Available on non-wasm_browser only.

Optionally sets a custom DNS resolver to use for this endpoint.

The DNS resolver is used to resolve relay hostnames, and endpoint addresses if crate::discovery::dns::DnsDiscovery is configured.

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.

-
Source

pub fn proxy_url(self, url: Url) -> Self

Sets an explicit proxy url to proxy all HTTP(S) traffic through.

-
Source

pub fn proxy_from_env(self) -> Self

Sets the proxy url from the environment, in this order:

+
Source

pub fn proxy_url(self, url: Url) -> Self

Sets an explicit proxy url to proxy all HTTP(S) traffic through.

+
Source

pub fn proxy_from_env(self) -> Self

Sets the proxy url from the environment, in this order:

  • HTTP_PROXY
  • http_proxy
  • HTTPS_PROXY
  • https_proxy
-
Source

pub fn keylog(self, keylog: bool) -> Self

Enables saving the TLS pre-master key for connections.

+
Source

pub fn keylog(self, keylog: bool) -> Self

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.

-
Source

pub fn insecure_skip_relay_cert_verify(self, skip_verify: bool) -> Self

Available on crate features test-utils only.

Skip verification of SSL certificates from relay servers

+
Source

pub fn insecure_skip_relay_cert_verify(self, skip_verify: bool) -> Self

Available on crate features test-utils only.

Skip verification of SSL certificates from relay servers

May only be used in tests.

-
Source

pub fn max_tls_tickets(self, n: usize) -> Self

Set the maximum number of TLS tickets to cache.

+
Source

pub fn max_tls_tickets(self, n: usize) -> Self

Set the maximum number of TLS tickets to cache.

Set this to a larger value if you want to do 0rtt connections to a large number of clients.

The default is 256, taking about 150 KiB in memory.

-
Source

pub fn hooks(self, hooks: impl EndpointHooks + 'static) -> Self

Install hooks onto the endpoint.

+
Source

pub fn hooks(self, hooks: impl EndpointHooks + 'static) -> Self

Install hooks onto the endpoint.

Endpoint hooks intercept the connection establishment process of an Endpoint.

You can install multiple EndpointHooks by calling this function multiple times. Order matters: hooks are invoked in the order they were installed onto the endpoint diff --git a/pr/3836/docs/iroh/endpoint/struct.ConnectOptions.html b/pr/3836/docs/iroh/endpoint/struct.ConnectOptions.html index 1cb2f5649f..e0f89bf3ec 100644 --- a/pr/3836/docs/iroh/endpoint/struct.ConnectOptions.html +++ b/pr/3836/docs/iroh/endpoint/struct.ConnectOptions.html @@ -1,12 +1,12 @@ -ConnectOptions in iroh::endpoint - Rust

ConnectOptions

Struct ConnectOptions 

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

Options for the Endpoint::connect_with_opts function.

-

Implementations§

Source§

impl ConnectOptions

Source

pub fn new() -> Self

Initializes new connection options.

+ConnectOptions in iroh::endpoint - Rust

ConnectOptions

Struct ConnectOptions 

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

Options for the Endpoint::connect_with_opts function.

+

Implementations§

Source§

impl ConnectOptions

Source

pub fn new() -> Self

Initializes new connection options.

By default, the connection will use the same options as Endpoint::connect, e.g. a default QuicTransportConfig.

-
Source

pub fn with_transport_config( +

Source

pub fn with_transport_config( self, transport_config: QuicTransportConfig, ) -> Self

Sets the QUIC transport config options for this connection.

-
Source

pub fn with_additional_alpns(self, alpns: Vec<Vec<u8>>) -> Self

Sets ALPN identifiers that should be signaled as supported on connection, in +

Source

pub fn with_additional_alpns(self, alpns: Vec<Vec<u8>>) -> Self

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.

-

Trait Implementations§

Source§

impl Clone for ConnectOptions

Source§

fn clone(&self) -> ConnectOptions

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

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

Performs copy-assignment from source. Read more
Source§

impl Debug for ConnectOptions

Source§

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

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

impl Default for ConnectOptions

Source§

fn default() -> ConnectOptions

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

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +

Trait Implementations§

Source§

impl Clone for ConnectOptions

Source§

fn clone(&self) -> ConnectOptions

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

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

Performs copy-assignment from source. Read more
Source§

impl Debug for ConnectOptions

Source§

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

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

impl Default for ConnectOptions

Source§

fn default() -> ConnectOptions

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

Auto Trait Implementations§

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

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

§

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

§

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

§

fn implicit( diff --git a/pr/3836/docs/iroh/endpoint/struct.Endpoint.html b/pr/3836/docs/iroh/endpoint/struct.Endpoint.html index 329ebd0149..e909effbb4 100644 --- a/pr/3836/docs/iroh/endpoint/struct.Endpoint.html +++ b/pr/3836/docs/iroh/endpoint/struct.Endpoint.html @@ -1,4 +1,4 @@ -Endpoint in iroh::endpoint - Rust

Endpoint

Struct Endpoint 

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

Controls an iroh endpoint, establishing connections with other endpoints.

+Endpoint in iroh::endpoint - Rust

Endpoint

Struct Endpoint 

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

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.

-

Implementations§

Source§

impl Endpoint

Source

pub fn builder() -> Builder

Returns the builder for an Endpoint, with a production configuration.

+

Implementations§

Source§

impl Endpoint

Source

pub fn builder() -> Builder

Returns the builder for an Endpoint, with a production configuration.

This uses the presets::N0 as the configuration.

-
Source

pub fn empty_builder(relay_mode: RelayMode) -> Builder

Returns the builder for an Endpoint, with an empty configuration.

+
Source

pub fn empty_builder(relay_mode: RelayMode) -> Builder

Returns the builder for an Endpoint, with an empty configuration.

See Builder::empty for details.

-
Source

pub async fn bind() -> Result<Self, BindError>

Constructs a default Endpoint and binds it immediately.

+
Source

pub async fn bind() -> Result<Self, BindError>

Constructs a default Endpoint and binds it immediately.

Uses the presets::N0 as configuration.

-
Source

pub fn set_alpns(&self, alpns: Vec<Vec<u8>>)

Sets the list of accepted ALPN protocols.

+
Source

pub fn set_alpns(&self, alpns: Vec<Vec<u8>>)

Sets the list of accepted ALPN protocols.

This will only affect new incoming connections. Note that this overrides the current list of ALPNs.

-
Source

pub async fn insert_relay( +

Source

pub async fn insert_relay( &self, relay: RelayUrl, config: Arc<RelayConfig>, ) -> Option<Arc<RelayConfig>>

Adds the provided configuration to the RelayMap.

Replacing and returning any existing configuration for RelayUrl.

-
Source

pub async fn remove_relay(&self, relay: &RelayUrl) -> Option<Arc<RelayConfig>>

Removes the configuration from the RelayMap for the provided RelayUrl.

+
Source

pub async fn remove_relay(&self, relay: &RelayUrl) -> Option<Arc<RelayConfig>>

Removes the configuration from the RelayMap for the provided RelayUrl.

Returns any existing configuration.

-
Source

pub async fn connect( +

Source

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.

-

Source

pub async fn connect_with_opts( +

Source

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. -

Source

pub fn accept(&self) -> Accept<'_> ⓘ

Accepts an incoming connection on the endpoint.

+
Source

pub fn accept(&self) -> Accept<'_> ⓘ

Accepts an incoming connection on the endpoint.

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.

-
Source

pub fn secret_key(&self) -> &SecretKey

Returns the secret_key of this endpoint.

-
Source

pub fn id(&self) -> EndpointId

Returns the endpoint id of this endpoint.

+
Source

pub fn secret_key(&self) -> &SecretKey

Returns the secret_key of this endpoint.

+
Source

pub fn id(&self) -> EndpointId

Returns the endpoint id of this endpoint.

This ID is the unique addressing information of this endpoint and other peers must know it to be able to connect to this endpoint.

-
Source

pub fn addr(&self) -> EndpointAddr

Returns the current EndpointAddr. +

Source

pub fn addr(&self) -> EndpointAddr

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.

-
Source

pub fn watch_addr(&self) -> impl Watcher<Value = EndpointAddr> + use<>

Available on non-wasm_browser only.

Returns a Watcher for the current EndpointAddr for this endpoint.

+
Source

pub fn watch_addr(&self) -> impl Watcher<Value = EndpointAddr> + use<>

Available on non-wasm_browser only.

Returns a Watcher for the current EndpointAddr for this endpoint.

The observed EndpointAddr will have the current RelayUrl and direct addresses.

use iroh::{Endpoint, Watcher};
@@ -117,7 +117,7 @@ on the internet.

  • the endpoint changes its preferred relay server
  • more addresses are discovered for this endpoint
  • -
    Source

    pub async fn online(&self)

    A convenience method that waits for the endpoint to be considered “online”.

    +
    Source

    pub async fn online(&self)

    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. Even if no relays are configured, this will still wait for a relay connection.

    @@ -150,14 +150,14 @@ let endpoint = Endpoint::bind().await; // After this await returns we have a connection to at least one relay // and holepunching should work as expected. endpoint.online().await; -}
    Source

    pub fn bound_sockets(&self) -> Vec<SocketAddr>

    Available on non-wasm_browser only.

    Returns the local socket addresses on which the underlying sockets are bound.

    +}

    Source

    pub fn bound_sockets(&self) -> Vec<SocketAddr>

    Available on non-wasm_browser only.

    Returns the local socket addresses on which the underlying sockets are bound.

    The Endpoint always binds on an IPv4 address and also tries to bind on an IPv6 address if available.

    -
    Source

    pub fn dns_resolver(&self) -> &DnsResolver

    Available on non-wasm_browser only.

    Returns the DNS resolver used in this Endpoint.

    +
    Source

    pub fn dns_resolver(&self) -> &DnsResolver

    Available on non-wasm_browser only.

    Returns the DNS resolver used in this Endpoint.

    See Builder::dns_resolver.

    -
    Source

    pub fn discovery(&self) -> &ConcurrentDiscovery

    Returns the discovery mechanism, if configured.

    +
    Source

    pub fn discovery(&self) -> &ConcurrentDiscovery

    Returns the discovery mechanism, if configured.

    See Builder::discovery.

    -
    Source

    pub fn metrics(&self) -> &EndpointMetrics

    Available on crate feature metrics only.

    Returns metrics collected for this endpoint.

    +
    Source

    pub fn metrics(&self) -> &EndpointMetrics

    Available on crate feature metrics only.

    Returns metrics collected for this endpoint.

    The endpoint internally collects various metrics about its operation. The returned EndpointMetrics struct contains all of these metrics.

    You can access individual metrics directly by using the public fields:

    @@ -227,13 +227,13 @@ registry.write().unwrap().register_all(endpoint.metrics()); .std_context("text")?; assert!(res.contains(r#"TYPE magicsock_recv_datagrams counter"#)); -assert!(res.contains(r#"magicsock_recv_datagrams_total 0"#));
    Source

    pub async fn remote_info(&self, endpoint_id: EndpointId) -> Option<RemoteInfo>

    Returns addressing information about a recently used remote endpoint.

    +assert!(res.contains(r#"magicsock_recv_datagrams_total 0"#));
    Source

    pub async fn remote_info(&self, endpoint_id: EndpointId) -> Option<RemoteInfo>

    Returns addressing information about a recently used remote endpoint.

    The returned RemoteInfo contains a list of all transport addresses for the remote that we know about. This is a snapshot in time and not a watcher.

    Returns None if the endpoint doesn’t have information about the remote. When remote endpoints are no longer used, our endpoint will keep information around for a little while, and then drop it. Afterwards, this will return None.

    -
    Source

    pub async fn network_change(&self)

    Notifies the system of potential network changes.

    +
    Source

    pub async fn network_change(&self)

    Notifies the system of potential network changes.

    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 @@ -241,12 +241,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.

    -
    Source

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

    Sets the initial user-defined data to be published in discovery services for this endpoint.

    +
    Source

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

    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.

    See also Builder::user_data_for_discovery for setting an initial value when building the endpoint.

    -
    Source

    pub async fn close(&self)

    Closes the QUIC endpoint and the magic socket.

    +
    Source

    pub async fn close(&self)

    Closes the QUIC endpoint and the magic socket.

    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.

    @@ -272,14 +272,14 @@ 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.

    -
    Source

    pub fn is_closed(&self) -> bool

    Check if this endpoint is still alive, or already closed.

    -
    Source

    pub fn create_server_config_builder( +

    Source

    pub fn is_closed(&self) -> bool

    Check if this endpoint is still alive, or already closed.

    +
    Source

    pub fn create_server_config_builder( &self, alpns: Vec<Vec<u8>>, ) -> ServerConfigBuilder

    Create a ServerConfigBuilder for this endpoint that includes the given alpns.

    Use the ServerConfigBuilder to customize the ServerConfig connection configuration for a connection accepted using the Incoming::accept_with method.

    -

    Trait Implementations§

    Source§

    impl Clone for Endpoint

    Source§

    fn clone(&self) -> Endpoint

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

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

    Performs copy-assignment from source. Read more
    Source§

    impl Debug for Endpoint

    Source§

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

    Formats the value using the given formatter. Read more

    Auto Trait Implementations§

    §

    impl Freeze for Endpoint

    §

    impl !RefUnwindSafe for Endpoint

    §

    impl Send for Endpoint

    §

    impl Sync for Endpoint

    §

    impl Unpin for Endpoint

    §

    impl !UnwindSafe for Endpoint

    Blanket Implementations§

    Source§

    impl<T> Any for T
    where +

    Trait Implementations§

    Source§

    impl Clone for Endpoint

    Source§

    fn clone(&self) -> Endpoint

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

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

    Performs copy-assignment from source. Read more
    Source§

    impl Debug for Endpoint

    Source§

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

    Formats the value using the given formatter. Read more

    Auto Trait Implementations§

    §

    impl Freeze for Endpoint

    §

    impl !RefUnwindSafe for Endpoint

    §

    impl Send for Endpoint

    §

    impl Sync for Endpoint

    §

    impl Unpin for Endpoint

    §

    impl !UnwindSafe for Endpoint

    Blanket Implementations§

    Source§

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

    Source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    §

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

    §

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

    §

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

    §

    fn implicit( diff --git a/pr/3836/docs/iroh_relay/client/struct.ClientBuilder.html b/pr/3836/docs/iroh_relay/client/struct.ClientBuilder.html index e3a4484114..8ae7d5bfbf 100644 --- a/pr/3836/docs/iroh_relay/client/struct.ClientBuilder.html +++ b/pr/3836/docs/iroh_relay/client/struct.ClientBuilder.html @@ -1,7 +1,7 @@ ClientBuilder in iroh_relay::client - Rust

    ClientBuilder

    Struct ClientBuilder 

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

    Build a Client.

    Implementations§

    Source§

    impl ClientBuilder

    Source

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

    Create a new ClientBuilder

    Source

    pub fn address_family_selector<S>(self, selector: S) -> Self
    where diff --git a/pr/3836/docs/iroh_relay/dns/struct.DnsResolver.html b/pr/3836/docs/iroh_relay/dns/struct.DnsResolver.html index 1160624ab9..ec70f157ed 100644 --- a/pr/3836/docs/iroh_relay/dns/struct.DnsResolver.html +++ b/pr/3836/docs/iroh_relay/dns/struct.DnsResolver.html @@ -73,9 +73,9 @@ at T+0ms, T+200ms and T+300ms. The timeout is applied as stated in summary of all errors otherwise.

    Source

    pub async fn lookup_endpoint_by_id( &self, - endpoint_id: &EndpointId, + endpoint_id: &EndpointId, origin: &str, -) -> Result<EndpointInfo, LookupError>

    Looks up endpoint info by EndpointId and origin domain name.

    +) -> Result<EndpointInfo, LookupError>

    Looks up endpoint info by [EndpointId] and origin domain name.

    To lookup endpoints that published their endpoint info to the DNS servers run by n0, pass N0_DNS_ENDPOINT_ORIGIN_PROD as origin.

    Source

    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.

    Source

    pub async fn lookup_endpoint_by_id_staggered( &self, - endpoint_id: &EndpointId, + endpoint_id: &EndpointId, origin: &str, delays_ms: &[u64], -) -> Result<EndpointInfo, StaggeredError<LookupError>>

    Looks up endpoint info by EndpointId and origin domain name.

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

    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 diff --git a/pr/3836/docs/iroh_relay/endpoint_info/enum.DecodingError.html b/pr/3836/docs/iroh_relay/endpoint_info/enum.DecodingError.html index f94d666796..f605341e85 100644 --- a/pr/3836/docs/iroh_relay/endpoint_info/enum.DecodingError.html +++ b/pr/3836/docs/iroh_relay/endpoint_info/enum.DecodingError.html @@ -8,12 +8,12 @@ meta: Meta, }, InvalidKey { - source: KeyParsingError, + source: KeyParsingError, meta: Meta, }, }

    Variants (Non-exhaustive)§

    This enum is marked as non-exhaustive
    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.
    §

    InvalidEncodingZ32

    Fields

    §source: Z32Error
    §meta: Meta

    Captured call-site metadata

    §

    InvalidLength

    Fields

    §len: usize
    §meta: Meta

    Captured call-site metadata

    -
    §

    InvalidKey

    Fields

    §meta: Meta

    Captured call-site metadata

    +
    §

    InvalidKey

    Fields

    §source: KeyParsingError
    §meta: Meta

    Captured call-site metadata

    Trait Implementations§

    Source§

    impl Debug for DecodingError

    Source§

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

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

    impl Display for DecodingError

    Source§

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

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

    impl Error for DecodingError

    Source§

    fn source(&self) -> Option<&(dyn Error + 'static)>

    Returns the lower-level source of this error, if any. Read more
    1.0.0 · Source§

    fn description(&self) -> &str

    👎Deprecated since 1.42.0: use the Display impl or to_string()
    1.0.0 · Source§

    fn cause(&self) -> Option<&dyn Error>

    👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
    Source§

    fn provide<'a>(&'a self, request: &mut Request<'a>)

    🔬This is a nightly-only experimental API. (error_generic_member_access)
    Provides type-based access to context intended for error reports. Read more
    Source§

    impl From<DecodingError> for AnyError

    Source§

    fn from(value: DecodingError) -> AnyError

    Converts to this type from the input type.
    Source§

    impl From<DecodingError> for ParseError

    Source§

    fn from(source: DecodingError) -> Self

    Converts to this type from the input type.
    Source§

    impl StackError for DecodingError

    Source§

    fn as_std(&self) -> &(dyn Error + Send + Sync + 'static)

    Returns this error as a std error reference.
    Source§

    fn into_std(self: Box<Self>) -> Box<dyn Error + Send + Sync>

    Returns this error as a std error.
    Source§

    fn as_dyn(&self) -> &dyn StackError

    Returns this error as a dyn StackError.
    Source§

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

    Returns the next source in the chain, if any.
    Source§

    fn meta(&self) -> Option<&Meta>

    Returns metadata captured at creation time, if available.
    Source§

    fn source(&self) -> Option<ErrorRef<'_>>

    Returns the next source in the chain, if any.
    Source§

    fn is_transparent(&self) -> bool

    Returns whether this error is transparent and should be skipped in reports.
    §

    fn as_ref(&self) -> ErrorRef<'_>

    Returns this error as an [ErrorRef]. Read more
    §

    fn stack(&self) -> Chain<'_>

    Returns an iterator over this error followed by its sources.
    §

    fn sources(&self) -> Chain<'_>

    Returns an iterator over sources of this error (skipping self).
    §

    fn report(&self) -> Report<'_>

    Returns a [Report] to output the error with configurable formatting.

    Auto Trait Implementations§

    Blanket Implementations§

    Source§

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

    Source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    §

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

    §

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

    §

    impl<'a, T, E> AsTaggedImplicit<'a, E> for T
    where diff --git a/pr/3836/docs/iroh_relay/endpoint_info/index.html b/pr/3836/docs/iroh_relay/endpoint_info/index.html index 9de61c4142..4a43824b7c 100644 --- a/pr/3836/docs/iroh_relay/endpoint_info/index.html +++ b/pr/3836/docs/iroh_relay/endpoint_info/index.html @@ -1,5 +1,5 @@ -iroh_relay::endpoint_info - Rust

    Module endpoint_info

    Module endpoint_info 

    Source
    Expand description

    Support for handling DNS resource records for dialing by EndpointId.

    -

    Dialing by EndpointId is supported by iroh endpoints publishing Pkarr records to DNS +iroh_relay::endpoint_info - Rust

    Module endpoint_info

    Module endpoint_info 

    Source
    Expand description

    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.

    +

    <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:

    • -

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

      +

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

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

    -
  • Structs§

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

    Enums§

    DecodingError
    EncodingError
    ParseError

    Constants§

    IROH_TXT_NAME
    The DNS name for the iroh TXT record.

    Traits§

    EndpointIdExt
    Extension methods for EndpointId to encode to and decode from [z32], +

    Structs§

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

    Enums§

    DecodingError
    EncodingError
    ParseError

    Constants§

    IROH_TXT_NAME
    The DNS name for the iroh TXT record.

    Traits§

    EndpointIdExt
    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/3836/docs/iroh_relay/endpoint_info/struct.EndpointData.html b/pr/3836/docs/iroh_relay/endpoint_info/struct.EndpointData.html index e4c7d8a31c..2b64a61e3e 100644 --- a/pr/3836/docs/iroh_relay/endpoint_info/struct.EndpointData.html +++ b/pr/3836/docs/iroh_relay/endpoint_info/struct.EndpointData.html @@ -1,23 +1,23 @@ EndpointData in iroh_relay::endpoint_info - Rust

    EndpointData

    Struct EndpointData 

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

    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 +

    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.

    -

    Implementations§

    Source§

    impl EndpointData

    Source

    pub fn new(addrs: impl IntoIterator<Item = TransportAddr>) -> Self

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

    -
    Source

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

    Sets the relay URL and returns the updated 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.

    +

    Implementations§

    Source§

    impl EndpointData

    Source

    pub fn new(addrs: impl IntoIterator<Item = TransportAddr>) -> Self

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

    +
    Source

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

    Sets the relay URL and returns the updated endpoint data.

    Source

    pub fn with_ip_addrs(self, addresses: BTreeSet<SocketAddr>) -> Self

    Sets the direct addresses and returns the updated endpoint data.

    Source

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

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

    -
    Source

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

    Returns the relay URL of the endpoint.

    +
    Source

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

    Returns the relay URL of the endpoint.

    Source

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

    Returns the optional user-defined data of the endpoint.

    Source

    pub fn ip_addrs(&self) -> impl Iterator<Item = &SocketAddr>

    Returns the direct addresses of the endpoint.

    Source

    pub fn clear_ip_addrs(&mut self)

    Removes all direct addresses from the endpoint data.

    Source

    pub fn clear_relay_urls(&mut self)

    Removes all direct addresses from the endpoint data.

    -
    Source

    pub fn add_addrs(&mut self, addrs: impl IntoIterator<Item = TransportAddr>)

    Add addresses to the endpoint data.

    +
    Source

    pub fn add_addrs(&mut self, addrs: impl IntoIterator<Item = TransportAddr>)

    Add addresses to the endpoint data.

    Source

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

    Sets the user-defined data of the endpoint data.

    -
    Source

    pub fn addrs(&self) -> impl Iterator<Item = &TransportAddr>

    Returns the full list of all known addresses

    +
    Source

    pub fn addrs(&self) -> impl Iterator<Item = &TransportAddr>

    Returns the full list of all known addresses

    Source

    pub fn has_addrs(&self) -> bool

    Does this have any addresses?

    -

    Trait Implementations§

    Source§

    impl Clone for EndpointData

    Source§

    fn clone(&self) -> EndpointData

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

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

    Performs copy-assignment from source. Read more
    Source§

    impl Debug for EndpointData

    Source§

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

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

    impl Default for EndpointData

    Source§

    fn default() -> EndpointData

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

    impl From<EndpointAddr> for EndpointData

    Source§

    fn from(endpoint_addr: EndpointAddr) -> Self

    Converts to this type from the input type.
    Source§

    impl PartialEq for EndpointData

    Source§

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

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

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

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

    Trait Implementations§

    Source§

    impl Clone for EndpointData

    Source§

    fn clone(&self) -> EndpointData

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

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

    Performs copy-assignment from source. Read more
    Source§

    impl Debug for EndpointData

    Source§

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

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

    impl Default for EndpointData

    Source§

    fn default() -> EndpointData

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

    impl From<EndpointAddr> for EndpointData

    Source§

    fn from(endpoint_addr: EndpointAddr) -> Self

    Converts to this type from the input type.
    Source§

    impl PartialEq for EndpointData

    Source§

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

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

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

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

    impl Eq for EndpointData

    Source§

    impl StructuralPartialEq for EndpointData

    Auto Trait Implementations§

    Blanket Implementations§

    Source§

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

    Source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    §

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

    §

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

    §

    impl<'a, T, E> AsTaggedImplicit<'a, E> for T
    where diff --git a/pr/3836/docs/iroh_relay/endpoint_info/struct.EndpointInfo.html b/pr/3836/docs/iroh_relay/endpoint_info/struct.EndpointInfo.html index cebd590faf..6593679505 100644 --- a/pr/3836/docs/iroh_relay/endpoint_info/struct.EndpointInfo.html +++ b/pr/3836/docs/iroh_relay/endpoint_info/struct.EndpointInfo.html @@ -1,17 +1,17 @@ EndpointInfo in iroh_relay::endpoint_info - Rust

    EndpointInfo

    Struct EndpointInfo 

    Source
    pub struct EndpointInfo {
    -    pub endpoint_id: EndpointId,
    +    pub endpoint_id: EndpointId,
         pub data: EndpointData,
     }
    Expand description

    Information about an endpoint that may be published to and resolved from discovery services.

    -

    This struct couples a EndpointId with its associated EndpointData.

    -

    Fields§

    §endpoint_id: EndpointId

    The EndpointId of the endpoint this is about.

    +

    This struct couples a [EndpointId] with its associated EndpointData.

    +

    Fields§

    §endpoint_id: EndpointId

    The [EndpointId] of the endpoint this is about.

    §data: EndpointData

    The information published about the endpoint.

    -

    Implementations§

    Source§

    impl EndpointInfo

    Source

    pub fn new(endpoint_id: EndpointId) -> Self

    Creates a new EndpointInfo with an empty EndpointData.

    -
    Source

    pub fn from_parts(endpoint_id: EndpointId, data: EndpointData) -> Self

    Creates a new EndpointInfo from its parts.

    -
    Source

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

    Sets the relay URL and returns the updated endpoint info.

    +

    Implementations§

    Source§

    impl EndpointInfo

    Source

    pub fn new(endpoint_id: EndpointId) -> Self

    Creates a new EndpointInfo with an empty EndpointData.

    +
    Source

    pub fn from_parts(endpoint_id: EndpointId, data: EndpointData) -> Self

    Creates a new EndpointInfo from its parts.

    +
    Source

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

    Sets the relay URL and returns the updated endpoint info.

    Source

    pub fn with_ip_addrs(self, addrs: BTreeSet<SocketAddr>) -> Self

    Sets the IP based addresses and returns the updated endpoint info.

    Source

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

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

    -
    Source

    pub fn to_endpoint_addr(&self) -> EndpointAddr

    Converts into a EndpointAddr by cloning the needed fields.

    -
    Source

    pub fn into_endpoint_addr(self) -> EndpointAddr

    Converts into a EndpointAddr without cloning.

    +
    Source

    pub fn to_endpoint_addr(&self) -> EndpointAddr

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

    +
    Source

    pub fn into_endpoint_addr(self) -> EndpointAddr

    Converts into a [EndpointAddr] without cloning.

    Source

    pub fn from_txt_lookup( domain_name: String, lookup: impl Iterator<Item = TxtRecordData>, @@ -21,21 +21,21 @@ ) -> Result<Self, ParseError>

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

    Source

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

    Creates a [pkarr::SignedPacket].

    -

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

    +

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

    Source

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

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

    -

    Methods from Deref<Target = EndpointData>§

    Source

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

    Returns the relay URL of the endpoint.

    +

    Methods from Deref<Target = EndpointData>§

    Source

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

    Returns the relay URL of the endpoint.

    Source

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

    Returns the optional user-defined data of the endpoint.

    Source

    pub fn ip_addrs(&self) -> impl Iterator<Item = &SocketAddr>

    Returns the direct addresses of the endpoint.

    Source

    pub fn clear_ip_addrs(&mut self)

    Removes all direct addresses from the endpoint data.

    Source

    pub fn clear_relay_urls(&mut self)

    Removes all direct addresses from the endpoint data.

    -
    Source

    pub fn add_addrs(&mut self, addrs: impl IntoIterator<Item = TransportAddr>)

    Add addresses to the endpoint data.

    +
    Source

    pub fn add_addrs(&mut self, addrs: impl IntoIterator<Item = TransportAddr>)

    Add addresses to the endpoint data.

    Source

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

    Sets the user-defined data of the endpoint data.

    -
    Source

    pub fn addrs(&self) -> impl Iterator<Item = &TransportAddr>

    Returns the full list of all known addresses

    +
    Source

    pub fn addrs(&self) -> impl Iterator<Item = &TransportAddr>

    Returns the full list of all known addresses

    Source

    pub fn has_addrs(&self) -> bool

    Does this have any addresses?

    -

    Trait Implementations§

    Source§

    impl Clone for EndpointInfo

    Source§

    fn clone(&self) -> EndpointInfo

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

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

    Performs copy-assignment from source. Read more
    Source§

    impl Debug for EndpointInfo

    Source§

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

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

    impl Deref for EndpointInfo

    Source§

    type Target = EndpointData

    The resulting type after dereferencing.
    Source§

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

    Dereferences the value.
    Source§

    impl DerefMut for EndpointInfo

    Source§

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

    Mutably dereferences the value.
    Source§

    impl From<EndpointAddr> for EndpointInfo

    Source§

    fn from(addr: EndpointAddr) -> Self

    Converts to this type from the input type.
    Source§

    impl From<EndpointInfo> for EndpointAddr

    Source§

    fn from(value: EndpointInfo) -> Self

    Converts to this type from the input type.
    Source§

    impl PartialEq for EndpointInfo

    Source§

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

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

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

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

    Trait Implementations§

    Source§

    impl Clone for EndpointInfo

    Source§

    fn clone(&self) -> EndpointInfo

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

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

    Performs copy-assignment from source. Read more
    Source§

    impl Debug for EndpointInfo

    Source§

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

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

    impl Deref for EndpointInfo

    Source§

    type Target = EndpointData

    The resulting type after dereferencing.
    Source§

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

    Dereferences the value.
    Source§

    impl DerefMut for EndpointInfo

    Source§

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

    Mutably dereferences the value.
    Source§

    impl From<EndpointAddr> for EndpointInfo

    Source§

    fn from(addr: EndpointAddr) -> Self

    Converts to this type from the input type.
    Source§

    impl From<EndpointInfo> for EndpointAddr

    Source§

    fn from(value: EndpointInfo) -> Self

    Converts to this type from the input type.
    Source§

    impl PartialEq for EndpointInfo

    Source§

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

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

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

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

    impl Eq for EndpointInfo

    Source§

    impl StructuralPartialEq for EndpointInfo

    Auto Trait Implementations§

    Blanket Implementations§

    Source§

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

    Source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    §

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

    §

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

    §

    impl<'a, T, E> AsTaggedImplicit<'a, E> for T
    where diff --git a/pr/3836/docs/iroh_relay/endpoint_info/trait.EndpointIdExt.html b/pr/3836/docs/iroh_relay/endpoint_info/trait.EndpointIdExt.html index 103efb1882..2cfafe8d14 100644 --- a/pr/3836/docs/iroh_relay/endpoint_info/trait.EndpointIdExt.html +++ b/pr/3836/docs/iroh_relay/endpoint_info/trait.EndpointIdExt.html @@ -1,9 +1,9 @@ EndpointIdExt in iroh_relay::endpoint_info - Rust

    EndpointIdExt

    Trait EndpointIdExt 

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

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

    Expand description

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

    -

    Required Methods§

    Source

    fn to_z32(&self) -> String

    Encodes a EndpointId in z-base-32 encoding.

    -
    Source

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

    Parses a EndpointId from z-base-32 encoding.

    -

    Dyn Compatibility§

    This trait is not dyn compatible.

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

    Implementations on Foreign Types§

    Source§

    impl EndpointIdExt for EndpointId

    Implementors§

    \ No newline at end of file +

    Required Methods§

    Source

    fn to_z32(&self) -> String

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

    +
    Source

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

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

    +

    Dyn Compatibility§

    This trait is not dyn compatible.

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

    Implementations on Foreign Types§

    Source§

    impl EndpointIdExt for EndpointId

    Source§

    fn to_z32(&self) -> String

    Source§

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

    Implementors§

    \ No newline at end of file diff --git a/pr/3836/docs/iroh_relay/index.html b/pr/3836/docs/iroh_relay/index.html index d16544ab4a..9fd890b801 100644 --- a/pr/3836/docs/iroh_relay/index.html +++ b/pr/3836/docs/iroh_relay/index.html @@ -25,6 +25,6 @@ Tailscale.

    QAD support and expose metrics.

    -

    Re-exports§

    pub use protos::relay::MAX_PACKET_SIZE;

    Modules§

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

    Re-exports§

    pub use protos::relay::MAX_PACKET_SIZE;

    Modules§

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

    Structs§

    PingTracker
    Tracks pings on a single relay connection.
    RelayConfig
    Information on a specific relay server.
    RelayMap
    List of relay server configurations to be used in an iroh endpoint.
    RelayQuicConfig
    Configuration for speaking to the QUIC endpoint on the relay server to do QUIC address discovery.
    \ No newline at end of file diff --git a/pr/3836/docs/iroh_relay/protos/relay/enum.ClientToRelayMsg.html b/pr/3836/docs/iroh_relay/protos/relay/enum.ClientToRelayMsg.html index c60049e552..6602f3a4ad 100644 --- a/pr/3836/docs/iroh_relay/protos/relay/enum.ClientToRelayMsg.html +++ b/pr/3836/docs/iroh_relay/protos/relay/enum.ClientToRelayMsg.html @@ -2,7 +2,7 @@ Ping([u8; 8]), Pong([u8; 8]), Datagrams { - dst_endpoint_id: EndpointId, + dst_endpoint_id: EndpointId, datagrams: Datagrams, }, }
    Expand description

    Messages that clients send to relays.

    @@ -11,7 +11,7 @@ other side with a §

    Pong([u8; 8])

    Reply to a RelayToClientMsg::Ping from a server with the payload sent previously in the ping.

    §

    Datagrams

    Request from the client to relay datagrams to given remote endpoint.

    -

    Fields

    §dst_endpoint_id: EndpointId

    The remote endpoint to relay to.

    +

    Fields

    §dst_endpoint_id: EndpointId

    The remote endpoint to relay to.

    §datagrams: Datagrams

    The datagrams and related metadata to relay.

    Trait Implementations§

    Source§

    impl Clone for ClientToRelayMsg

    Source§

    fn clone(&self) -> ClientToRelayMsg

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

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

    Performs copy-assignment from source. Read more
    Source§

    impl Debug for ClientToRelayMsg

    Source§

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

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

    impl PartialEq for ClientToRelayMsg

    Source§

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

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

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

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

    impl Sink<ClientToRelayMsg> for Client

    Source§

    type Error = SendError

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

    fn poll_ready( diff --git a/pr/3836/docs/iroh_relay/protos/relay/enum.Error.html b/pr/3836/docs/iroh_relay/protos/relay/enum.Error.html index d9b34d6d28..90193843dc 100644 --- a/pr/3836/docs/iroh_relay/protos/relay/enum.Error.html +++ b/pr/3836/docs/iroh_relay/protos/relay/enum.Error.html @@ -17,7 +17,7 @@ meta: Meta, }, InvalidPublicKey { - source: KeyParsingError, + source: KeyParsingError, meta: Meta, }, InvalidFrame { @@ -39,12 +39,12 @@

    §

    FrameTooLarge

    Fields

    §frame_len: usize
    §meta: Meta

    Captured call-site metadata

    §

    SerDe

    Fields

    §source: Error
    §meta: Meta

    Captured call-site metadata

    §

    FrameTypeError

    Fields

    §meta: Meta

    Captured call-site metadata

    -
    §

    InvalidPublicKey

    Fields

    §meta: Meta

    Captured call-site metadata

    +
    §

    InvalidPublicKey

    Fields

    §source: KeyParsingError
    §meta: Meta

    Captured call-site metadata

    §

    InvalidFrame

    Fields

    §meta: Meta

    Captured call-site metadata

    §

    InvalidFrameType

    Fields

    §frame_type: FrameType
    §meta: Meta

    Captured call-site metadata

    §

    InvalidProtocolMessageEncoding

    Fields

    §source: Utf8Error
    §meta: Meta

    Captured call-site metadata

    §

    TooSmall

    Fields

    §meta: Meta

    Captured call-site metadata

    -

    Trait Implementations§

    Source§

    impl Debug for Error

    Source§

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

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

    impl Display for Error

    Source§

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

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

    impl Error for Error

    Source§

    fn source(&self) -> Option<&(dyn Error + 'static)>

    Returns the lower-level source of this error, if any. Read more
    1.0.0 · Source§

    fn description(&self) -> &str

    👎Deprecated since 1.42.0: use the Display impl or to_string()
    1.0.0 · Source§

    fn cause(&self) -> Option<&dyn Error>

    👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
    Source§

    fn provide<'a>(&'a self, request: &mut Request<'a>)

    🔬This is a nightly-only experimental API. (error_generic_member_access)
    Provides type-based access to context intended for error reports. Read more
    Source§

    impl From<Error> for AnyError

    Source§

    fn from(value: Error) -> AnyError

    Converts to this type from the input type.
    Source§

    impl From<Error> for Error

    Source§

    fn from(source: Error) -> Self

    Converts to this type from the input type.
    Source§

    impl From<Error> for RecvError

    Source§

    fn from(source: ProtoError) -> Self

    Converts to this type from the input type.
    Source§

    impl From<FrameTypeError> for Error

    Source§

    fn from(source: FrameTypeError) -> Self

    Converts to this type from the input type.
    Source§

    impl From<KeyParsingError> for Error

    Source§

    fn from(source: KeyParsingError) -> Self

    Converts to this type from the input type.
    Source§

    impl From<Utf8Error> for Error

    Source§

    fn from(source: Utf8Error) -> Self

    Converts to this type from the input type.
    Source§

    impl StackError for Error

    Source§

    fn as_std(&self) -> &(dyn Error + Send + Sync + 'static)

    Returns this error as a std error reference.
    Source§

    fn into_std(self: Box<Self>) -> Box<dyn Error + Send + Sync>

    Returns this error as a std error.
    Source§

    fn as_dyn(&self) -> &dyn StackError

    Returns this error as a dyn StackError.
    Source§

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

    Returns the next source in the chain, if any.
    Source§

    fn meta(&self) -> Option<&Meta>

    Returns metadata captured at creation time, if available.
    Source§

    fn source(&self) -> Option<ErrorRef<'_>>

    Returns the next source in the chain, if any.
    Source§

    fn is_transparent(&self) -> bool

    Returns whether this error is transparent and should be skipped in reports.
    §

    fn as_ref(&self) -> ErrorRef<'_>

    Returns this error as an [ErrorRef]. Read more
    §

    fn stack(&self) -> Chain<'_>

    Returns an iterator over this error followed by its sources.
    §

    fn sources(&self) -> Chain<'_>

    Returns an iterator over sources of this error (skipping self).
    §

    fn report(&self) -> Report<'_>

    Returns a [Report] to output the error with configurable formatting.

    Auto Trait Implementations§

    §

    impl Freeze for Error

    §

    impl !RefUnwindSafe for Error

    §

    impl Send for Error

    §

    impl Sync for Error

    §

    impl Unpin for Error

    §

    impl !UnwindSafe for Error

    Blanket Implementations§

    Source§

    impl<T> Any for T
    where +

    Trait Implementations§

    Source§

    impl Debug for Error

    Source§

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

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

    impl Display for Error

    Source§

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

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

    impl Error for Error

    Source§

    fn source(&self) -> Option<&(dyn Error + 'static)>

    Returns the lower-level source of this error, if any. Read more
    1.0.0 · Source§

    fn description(&self) -> &str

    👎Deprecated since 1.42.0: use the Display impl or to_string()
    1.0.0 · Source§

    fn cause(&self) -> Option<&dyn Error>

    👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
    Source§

    fn provide<'a>(&'a self, request: &mut Request<'a>)

    🔬This is a nightly-only experimental API. (error_generic_member_access)
    Provides type-based access to context intended for error reports. Read more
    Source§

    impl From<Error> for AnyError

    Source§

    fn from(value: Error) -> AnyError

    Converts to this type from the input type.
    Source§

    impl From<Error> for Error

    Source§

    fn from(source: Error) -> Self

    Converts to this type from the input type.
    Source§

    impl From<Error> for RecvError

    Source§

    fn from(source: ProtoError) -> Self

    Converts to this type from the input type.
    Source§

    impl From<FrameTypeError> for Error

    Source§

    fn from(source: FrameTypeError) -> Self

    Converts to this type from the input type.
    Source§

    impl From<KeyParsingError> for Error

    Source§

    fn from(source: KeyParsingError) -> Self

    Converts to this type from the input type.
    Source§

    impl From<Utf8Error> for Error

    Source§

    fn from(source: Utf8Error) -> Self

    Converts to this type from the input type.
    Source§

    impl StackError for Error

    Source§

    fn as_std(&self) -> &(dyn Error + Send + Sync + 'static)

    Returns this error as a std error reference.
    Source§

    fn into_std(self: Box<Self>) -> Box<dyn Error + Send + Sync>

    Returns this error as a std error.
    Source§

    fn as_dyn(&self) -> &dyn StackError

    Returns this error as a dyn StackError.
    Source§

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

    Returns the next source in the chain, if any.
    Source§

    fn meta(&self) -> Option<&Meta>

    Returns metadata captured at creation time, if available.
    Source§

    fn source(&self) -> Option<ErrorRef<'_>>

    Returns the next source in the chain, if any.
    Source§

    fn is_transparent(&self) -> bool

    Returns whether this error is transparent and should be skipped in reports.
    §

    fn as_ref(&self) -> ErrorRef<'_>

    Returns this error as an [ErrorRef]. Read more
    §

    fn stack(&self) -> Chain<'_>

    Returns an iterator over this error followed by its sources.
    §

    fn sources(&self) -> Chain<'_>

    Returns an iterator over sources of this error (skipping self).
    §

    fn report(&self) -> Report<'_>

    Returns a [Report] to output the error with configurable formatting.

    Auto Trait Implementations§

    §

    impl Freeze for Error

    §

    impl !RefUnwindSafe for Error

    §

    impl Send for Error

    §

    impl Sync for Error

    §

    impl Unpin for Error

    §

    impl !UnwindSafe for Error

    Blanket Implementations§

    Source§

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

    Source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    §

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

    §

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

    §

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

    §

    fn implicit( diff --git a/pr/3836/docs/iroh_relay/protos/relay/enum.RelayToClientMsg.html b/pr/3836/docs/iroh_relay/protos/relay/enum.RelayToClientMsg.html index b57e2ccf80..80fa796d28 100644 --- a/pr/3836/docs/iroh_relay/protos/relay/enum.RelayToClientMsg.html +++ b/pr/3836/docs/iroh_relay/protos/relay/enum.RelayToClientMsg.html @@ -1,9 +1,9 @@ RelayToClientMsg in iroh_relay::protos::relay - Rust

    RelayToClientMsg

    Enum RelayToClientMsg 

    Source
    pub enum RelayToClientMsg {
         Datagrams {
    -        remote_endpoint_id: EndpointId,
    +        remote_endpoint_id: EndpointId,
             datagrams: Datagrams,
         },
    -    EndpointGone(EndpointId),
    +    EndpointGone(EndpointId),
         Health {
             problem: String,
         },
    @@ -15,9 +15,9 @@
         Pong([u8; 8]),
     }
    Expand description

    The messages that a relay sends to clients or the clients receive from the relay.

    Variants§

    §

    Datagrams

    Represents datagrams sent from relays (originally sent to them by another client).

    -

    Fields

    §remote_endpoint_id: EndpointId

    The EndpointId of the original sender.

    +

    Fields

    §remote_endpoint_id: EndpointId

    The [EndpointId] of the original sender.

    §datagrams: Datagrams

    The datagrams and related metadata.

    -
    §

    EndpointGone(EndpointId)

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

    §

    EndpointGone(EndpointId)

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

    §

    Health

    A one-way message from relay to client, declaring the connection health state.

    Fields

    §problem: String

    If set, is a description of why the connection is unhealthy.

    diff --git a/pr/3836/docs/iroh_relay/server/enum.AccessConfig.html b/pr/3836/docs/iroh_relay/server/enum.AccessConfig.html index 3e668e71a3..6b01bd9031 100644 --- a/pr/3836/docs/iroh_relay/server/enum.AccessConfig.html +++ b/pr/3836/docs/iroh_relay/server/enum.AccessConfig.html @@ -1,10 +1,10 @@ AccessConfig in iroh_relay::server - Rust

    AccessConfig

    Enum AccessConfig 

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

    Controls which endpoints are allowed to use the relay.

    Variants§

    §

    Everyone

    Everyone

    -
    §

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

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

    -

    Implementations§

    Source§

    impl AccessConfig

    Source

    pub async fn is_allowed(&self, endpoint: EndpointId) -> bool

    Is this endpoint allowed?

    +
    §

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

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

    +

    Implementations§

    Source§

    impl AccessConfig

    Source

    pub async fn is_allowed(&self, endpoint: EndpointId) -> bool

    Is this endpoint allowed?

    Trait Implementations§

    Source§

    impl Debug for AccessConfig

    Source§

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

    Formats the value using the given formatter. Read more

    Auto Trait Implementations§

    Blanket Implementations§

    Source§

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

    Source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    §

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

    §

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

    §

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

    Source

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

    The socket address the HTTP server is listening on.

    Source

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

    The socket address the QUIC server is listening on.

    Source

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

    The certificates chain if configured with manual TLS certificates.

    -
    Source

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

    Available on crate feature test-utils only.

    Get the server’s https RelayUrl.

    +
    Source

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

    Available on crate feature test-utils only.

    Get the server’s https [RelayUrl].

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

    -
    Source

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

    Available on crate feature test-utils only.

    Get the server’s http RelayUrl.

    +
    Source

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

    Available on crate feature test-utils only.

    Get the server’s http [RelayUrl].

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

    Source

    pub fn metrics(&self) -> &RelayMetrics

    Returns the metrics collected in the relay server.

    Trait Implementations§

    Source§

    impl Debug for Server

    Source§

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

    Formats the value using the given formatter. Read more

    Auto Trait Implementations§

    §

    impl Freeze for Server

    §

    impl RefUnwindSafe for Server

    §

    impl Send for Server

    §

    impl Sync for Server

    §

    impl Unpin for Server

    §

    impl UnwindSafe for Server

    Blanket Implementations§

    Source§

    impl<T> Any for T
    where diff --git a/pr/3836/docs/iroh_relay/struct.RelayConfig.html b/pr/3836/docs/iroh_relay/struct.RelayConfig.html index f856f6e45f..a342140c9f 100644 --- a/pr/3836/docs/iroh_relay/struct.RelayConfig.html +++ b/pr/3836/docs/iroh_relay/struct.RelayConfig.html @@ -1,14 +1,14 @@ RelayConfig in iroh_relay - Rust

    RelayConfig

    Struct RelayConfig 

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

    Information on a specific relay server.

    Includes the Url where it can be dialed.

    -

    Fields§

    §url: RelayUrl

    The RelayUrl where this relay server can be dialed.

    +

    Fields§

    §url: RelayUrl

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

    §quic: Option<RelayQuicConfig>

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

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

    Trait Implementations§

    Source§

    impl Clone for RelayConfig

    Source§

    fn clone(&self) -> RelayConfig

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

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

    Performs copy-assignment from source. Read more
    Source§

    impl Debug for RelayConfig

    Source§

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

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

    impl<'de> Deserialize<'de> for RelayConfig

    Source§

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

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

    impl Display for RelayConfig

    Source§

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

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

    impl From<RelayConfig> for RelayMap

    Source§

    fn from(value: RelayConfig) -> Self

    Converts to this type from the input type.
    Source§

    impl From<RelayUrl> for RelayConfig

    Source§

    fn from(value: RelayUrl) -> Self

    Converts to this type from the input type.
    Source§

    impl FromIterator<RelayConfig> for RelayMap

    Source§

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

    Creates a value from an iterator. Read more
    Source§

    impl Ord for RelayConfig

    Source§

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

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

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

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

    impl Display for RelayConfig

    Source§

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

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

    impl From<RelayConfig> for RelayMap

    Source§

    fn from(value: RelayConfig) -> Self

    Converts to this type from the input type.
    Source§

    impl From<RelayUrl> for RelayConfig

    Source§

    fn from(value: RelayUrl) -> Self

    Converts to this type from the input type.
    Source§

    impl FromIterator<RelayConfig> for RelayMap

    Source§

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

    Creates a value from an iterator. Read more
    Source§

    impl Ord for RelayConfig

    Source§

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

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

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

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

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

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

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

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

    impl PartialEq for RelayConfig

    Source§

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

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

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

    Tests for !=. The default implementation is almost always sufficient, diff --git a/pr/3836/docs/iroh_relay/struct.RelayMap.html b/pr/3836/docs/iroh_relay/struct.RelayMap.html index abbb65dbe9..ad5b9cfe51 100644 --- a/pr/3836/docs/iroh_relay/struct.RelayMap.html +++ b/pr/3836/docs/iroh_relay/struct.RelayMap.html @@ -9,34 +9,34 @@ or by creating an empty relay map with let map = RelayMap::from_iter(vec![relay1, relay2]);

    Implementations§

    Source§

    impl RelayMap

    Source

    pub fn empty() -> Self

    Creates an empty relay map.

    Source

    pub fn try_from_iter<'a, T: IntoIterator<Item = &'a str>>( urls: T, -) -> Result<Self, RelayUrlParseError>

    Creates a RelayMap from an iterator.

    +) -> Result<Self, RelayUrlParseError>

    Creates a RelayMap from an iterator.

    The conversion from a URL to a RelayConfig is done the same as when parsing it directly, which means it is assumed to run QUIC on default settings as defined in RelayQuicConfig::default.

    §Example
    let map =
         RelayMap::try_from_iter(["https://relay_0.cool.com", "https://relay_1.cool.com"]).unwrap();
    Source

    pub fn urls<T>(&self) -> T
    where - T: FromIterator<RelayUrl>,

    Returns the URLs of all servers in this relay map.

    + T: FromIterator<RelayUrl>,

    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>.

    Source

    pub fn relays<T>(&self) -> T

    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>.

    -
    Source

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

    Returns true if a relay with url is contained in this this relay map.

    -
    Source

    pub fn get(&self, url: &RelayUrl) -> Option<Arc<RelayConfig>>

    Returns the config for a relay.

    +
    Source

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

    Returns true if a relay with url is contained in this this relay map.

    +
    Source

    pub fn get(&self, url: &RelayUrl) -> Option<Arc<RelayConfig>>

    Returns the config for a relay.

    Source

    pub fn len(&self) -> usize

    Returns the number of relays in this relay map.

    Source

    pub fn is_empty(&self) -> bool

    Returns true if this relay map is empty.

    Source

    pub fn insert( &self, - url: RelayUrl, + url: RelayUrl, endpoint: Arc<RelayConfig>, ) -> Option<Arc<RelayConfig>>

    Inserts a new relay into the relay map.

    -
    Source

    pub fn remove(&self, url: &RelayUrl) -> Option<Arc<RelayConfig>>

    Removes an existing relay by its URL.

    +
    Source

    pub fn remove(&self, url: &RelayUrl) -> Option<Arc<RelayConfig>>

    Removes an existing relay by its URL.

    Source

    pub fn extend(&self, other: &RelayMap)

    Extends this RelayMap with another one.

    -

    Trait Implementations§

    Source§

    impl Clone for RelayMap

    Source§

    fn clone(&self) -> RelayMap

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

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

    Performs copy-assignment from source. Read more
    Source§

    impl Debug for RelayMap

    Source§

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

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

    impl Display for RelayMap

    Source§

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

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

    impl From<RelayConfig> for RelayMap

    Source§

    fn from(value: RelayConfig) -> Self

    Converts to this type from the input type.
    Source§

    impl From<RelayUrl> for RelayMap

    Source§

    fn from(value: RelayUrl) -> Self

    Creates a RelayMap from a RelayUrl.

    +

    Trait Implementations§

    Source§

    impl Clone for RelayMap

    Source§

    fn clone(&self) -> RelayMap

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

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

    Performs copy-assignment from source. Read more
    Source§

    impl Debug for RelayMap

    Source§

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

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

    impl Display for RelayMap

    Source§

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

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

    impl From<RelayConfig> for RelayMap

    Source§

    fn from(value: RelayConfig) -> Self

    Converts to this type from the input type.
    Source§

    impl From<RelayUrl> for RelayMap

    Source§

    fn from(value: RelayUrl) -> Self

    Creates a RelayMap from a [RelayUrl].

    The RelayConfigs in the RelayMap will have the default QUIC address discovery ports.

    -
    Source§

    impl FromIterator<Arc<RelayConfig>> for RelayMap

    Source§

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

    Creates a value from an iterator. Read more
    Source§

    impl FromIterator<RelayConfig> for RelayMap

    Source§

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

    Creates a value from an iterator. Read more
    Source§

    impl FromIterator<RelayUrl> for RelayMap

    Source§

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

    Creates a RelayMap from an iterator of RelayUrl.

    +
    Source§

    impl FromIterator<Arc<RelayConfig>> for RelayMap

    Source§

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

    Creates a value from an iterator. Read more
    Source§

    impl FromIterator<RelayConfig> for RelayMap

    Source§

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

    Creates a value from an iterator. Read more
    Source§

    impl FromIterator<RelayUrl> for RelayMap

    Source§

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

    Creates a RelayMap from an iterator of [RelayUrl].

    The RelayConfigs in the RelayMap will have the default QUIC address discovery ports.

    Source§

    impl PartialEq for RelayMap

    Source§

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

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

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

    Tests for !=. The default implementation is almost always sufficient, diff --git a/pr/3836/docs/search.index/path/5d099ff8fd72.js b/pr/3836/docs/search.index/path/5d099ff8fd72.js new file mode 100644 index 0000000000..38e5dd5d0c --- /dev/null +++ b/pr/3836/docs/search.index/path/5d099ff8fd72.js @@ -0,0 +1 @@ +rd_("f[1,\"\"]0Al[10,\"core::cmp\",\"core::cmp\"]Al[10,\"core::ops\",\"core::ops\"]Ce[5,\"clap_builder::util::id\",\"clap_builder::util::id\"]Bd[15,\"iroh_relay::client::DialError\"]Cg[5,\"iroh::endpoint::presets\",\"iroh::endpoint::presets\"]Eg[5,\"tower_http::follow_redirect::policy::or\",\"tower_http::follow_redirect::policy::or\"]66Ei[5,\"tower_http::follow_redirect::policy::and\",\"tower_http::follow_redirect::policy::and\"]A`[10,\"core::any\"]Ao[5,\"alloc::sync\",\"alloc::sync\"]Ba[5,\"alloc::boxed\",\"alloc::boxed\"]Cb[10,\"bytes::buf::buf_impl\",\"bytes::buf::buf_impl\"]Ad[6,\"iroh::endpoint\"]8g[17,\"\"]Am[5,\"n0_watcher\",\"n0_watcher\"]Ae[10,\"core::ops::bit\"]Am[5,\"iroh_bench\",\"iroh_bench\"]Bg[5,\"iroh_bench::s2n\",\"iroh_bench::s2n\"]A`[10,\"core::cmp\"]Ak[5,\"core::pin\",\"core::pin\"]Bg[15,\"iroh_relay::client::ConnectError\"]o[5,\"url\",\"url\"]Am[5,\"alloc::vec\",\"alloc::vec\"]Al[2,\"iroh::discovery::pkarr\"]j[2,\"iroh\"]Ae[2,\"iroh::discovery\"]A`[2,\"iroh_relay\"]Ae[2,\"iroh_dns_server\"]f[1,\"\"]00o[2,\"iroh_base\"]f[0,\"\"]A`[2,\"iroh_bench\"]3Ak[2,\"iroh_dns_server::http\"]444Ak[10,\"clap_builder::derive\"]=Af[10,\"core::ops::drop\"]Ad[10,\"core::convert\"]Aa[10,\"core::hash\"]1g[17,\"\"]Ad[5,\"iroh::endpoint\"]Be[5,\"n0_error::meta\",\"n0_error::meta\"]Cc[5,\"reqwest::dns::resolve\",\"reqwest::dns::resolve\"]Dg[5,\"hickory_proto::rr::domain::name\",\"hickory_proto::rr::domain::name\"]Ak[5,\"std::path\",\"std::path\"]Am[15,\"iroh::endpoint::Source\"]Bi[6,\"core::task::poll\",\"core::task::poll\"]Bb[10,\"core::marker\",\"core::marker\"]Ad[6,\"iroh::endpoint\"]Ac[10,\"futures_sink\"]2Bf[15,\"iroh::discovery::DiscoveryError\"]Bj[15,\"iroh::discovery::IntoDiscoveryError\"]Bb[15,\"iroh::protocol::AcceptError\"]Bb[15,\"iroh::discovery::ParseError\"]Bl[15,\"iroh_relay::endpoint_info::ParseError\"]Ah[10,\"ppv_lite86::types\"]Ad[2,\"iroh::endpoint\"]f[1,\"\"]f[3,\"\"]Ah[2,\"iroh_relay::client\"]A`[2,\"iroh_relay\"]Ae[2,\"iroh_dns_server\"]A`[2,\"iroh_bench\"]4Ae[2,\"iroh::discovery\"]Ad[2,\"iroh::defaults\"]Af[2,\"iroh::test_utils\"]An[2,\"iroh_quinn_proto::config\"]:6Bk[2,\"iroh_quinn_proto::connection::streams\"]::Bd[10,\"core::convert\",\"core::convert\"]Ca[8,\"futures_lite::future\",\"futures_lite::future\"]Ca[8,\"futures_lite::stream\",\"futures_lite::stream\"]Ba[5,\"bytes::bytes\",\"bytes::bytes\"]Ad[5,\"iroh::endpoint\"]Ab[10,\"core::clone\"]Cg[6,\"iroh_quinn_proto::frame\",\"iroh_quinn_proto::frame\"]A`[10,\"core::fmt\"]Ag[10,\"core::ops::deref\"]Ak[5,\"core::fmt\",\"core::fmt\"]Ab[10,\"core::error\"]Be[5,\"std::io::error\",\"std::io::error\"]Ba[8,\"clap_builder\",\"clap_builder\"]Bi[5,\"signature::error\",\"signature::error\"]Af[2,\"iroh_relay::quic\"]Bc[2,\"iroh_relay::protos::handshake\"]Ao[2,\"iroh_relay::protos::relay\"]Ba[5,\"hyper::error\",\"hyper::error\"]Ee[6,\"iroh_quinn_proto::transport_parameters\",\"iroh_quinn_proto::transport_parameters\"]Be[5,\"reqwest::error\",\"reqwest::error\"]Bg[6,\"postcard::error\",\"postcard::error\"]Cg[6,\"tokio_websockets::error\",\"tokio_websockets::error\"]Bi[6,\"iroh_relay::quic\",\"iroh_relay::quic\"]Dc[6,\"iroh_relay::protos::handshake\",\"iroh_relay::protos::handshake\"]Ck[6,\"iroh_relay::protos::relay\",\"iroh_relay::protos::relay\"]Bk[15,\"iroh::endpoint::ConnectWithOptsError\"]Bg[15,\"iroh_relay::protos::relay::Error\"]Bb[10,\"core::marker\",\"core::marker\"]Bk[5,\"iroh_bench::stats\",\"iroh_bench::stats\"]Am[5,\"n0_watcher\",\"n0_watcher\"]2g[17,\"\"]Ah[10,\"std::io\",\"std::io\"]f[1,\"\"]Af[2,\"iroh_quinn_proto\"]Ad[2,\"iroh::endpoint\"]Bb[2,\"iroh_quinn_proto::connection\"]Ae[2,\"iroh::discovery\"]A`[2,\"iroh_bench\"]Ah[2,\"iroh_relay::protos\"]6Ae[2,\"iroh_dns_server\"]240677Ca[5,\"iroh::endpoint\",\"iroh::endpoint::connection\"]Bm[6,\"iroh_relay::server\",\"iroh_relay::server\"]Ac[10,\"core::borrow\"]C`[10,\"bytes::buf::buf_mut\",\"bytes::buf::buf_mut\"]Bc[5,\"pkarr::client\",\"pkarr::client\"]Bm[5,\"iroh_relay::client\",\"iroh_relay::client\"]Ba[5,\"async_compat\",\"async_compat\"]Cg[5,\"iroh_dns_server::config\",\"iroh_dns_server::config\"]Cb[10,\"core::future::future\",\"core::future::future\"]Ca[5,\"iroh_dns_server::dns\",\"iroh_dns_server::dns\"]An[10,\"core::hash\",\"core::hash\"]Cb[15,\"iroh_relay::protos::relay::RelayToClientMsg\"]Bm[6,\"core::net::ip_addr\",\"core::net::ip_addr\"]Bm[5,\"iroh_relay::server\",\"iroh_relay::server\"]Bh[10,\"reloadable_core\",\"reloadable_core\"]Be[15,\"iroh_relay::server::CertConfig\"]Bj[15,\"iroh::endpoint::AuthenticationError\"]Ad[5,\"iroh::endpoint\"]Ba[6,\"core::option\",\"core::option\"]g[17,\"\"]2E`[10,\"tower_http::follow_redirect::policy\",\"tower_http::follow_redirect::policy\"]Ch[10,\"iroh::endpoint::presets\",\"iroh::endpoint::presets\"]Co[5,\"hickory_proto::rr::resource\",\"hickory_proto::rr::resource\"]Bl[15,\"iroh::endpoint::AfterHandshakeOutcome\"]Ak[8,\"core::fmt\",\"core::fmt\"]Ba[6,\"core::result\",\"core::result\"]Be[8,\"std::io::error\",\"std::io::error\"]Ai[8,\"n0_error\",\"n0_error\"]Be[5,\"iroh::protocol\",\"iroh::protocol\"]Cg[5,\"iroh_dns_server::server\",\"iroh_dns_server::server\"]Bm[5,\"iroh_relay::server\",\"iroh_relay::server\"]Ad[2,\"iroh::endpoint\"]Cb[6,\"iroh::endpoint\",\"iroh::magicsock::remote_map\"]Ak[10,\"futures_core::stream\"]Am[5,\"n0_watcher\",\"n0_watcher\"]Bc[5,\"alloc::string\",\"alloc::string\"]Ak[5,\"core::any\",\"core::any\"]Ci[5,\"iroh_quinn_proto::varint\",\"iroh_quinn_proto::varint\"]Ad[5,\"iroh::endpoint\"]Bi[15,\"iroh::discovery::pkarr::PkarrError\"]A`[2,\"iroh_relay\"]Ah[2,\"iroh_relay::protos\"]Af[2,\"iroh_quinn_proto\"]Ae[2,\"iroh_dns_server\"]13301Ae[10,\"iroh::endpoint\"]Bg[8,\"iroh_relay::dns\",\"iroh_relay::dns\"]Be[5,\"iroh::endpoint\",\"iroh::endpoint\"]Co[5,\"iroh::discovery::pkarr::dht\",\"iroh::discovery::pkarr::dht\"]Bg[5,\"iroh_relay::dns\",\"iroh_relay::dns\"]De[5,\"clap_builder::builder::command\",\"clap_builder::builder::command\"]Bc[15,\"iroh::endpoint::ConnectError\"]An[15,\"iroh_relay::quic::Error\"]Bi[5,\"core::task::wake\",\"core::task::wake\"]Cc[5,\"iroh_metrics::metrics\",\"iroh_metrics::metrics\"]Ad[10,\"core::default\"]A`[10,\"core::fmt\"]Bm[5,\"tokio::time::error\",\"tokio::time::error\"]Bl[15,\"iroh::discovery::mdns::DiscoveryEvent\"]Bc[10,\"axum_core::extract::from_ref\"]Ah[10,\"core::str::traits\"]Ak[5,\"std::time\",\"std::time\"]Ci[5,\"iroh_quinn_proto::crypto\",\"iroh_quinn_proto::crypto\"]Bj[15,\"iroh_relay::server::SupervisorError\"]Ci[5,\"iroh_dns_server::metrics\",\"iroh_dns_server::metrics\"]Cf[5,\"iroh_relay::server\",\"iroh_relay::server::metrics\"]Am[5,\"n0_watcher\",\"n0_watcher\"]Ad[5,\"iroh::endpoint\"]Ak[5,\"std::path\",\"std::path\"]Bk[5,\"dyn_clone::sealed\",\"dyn_clone::sealed\"]Bo[5,\"tokio::io::read_buf\",\"tokio::io::read_buf\"]Eg[5,\"hickory_server::server::request_handler\",\"hickory_server::server::request_handler\"]B`[15,\"iroh_relay::dns::DnsError\"]Al[10,\"reqwest::dns::resolve\"]Cg[5,\"tokio::runtime::runtime\",\"tokio::runtime::runtime\"]Bd[15,\"iroh_relay::client::DialError\"]3Ad[10,\"alloc::borrow\"]Ad[10,\"core::convert\"]0Bg[15,\"iroh_relay::client::ConnectError\"]k[10,\"iroh\"]330 /// will be sent over the same socket as the incoming datagram was received on, and the 331 /// routing with the prefix length and default route as described above does not apply. 332 /// -333 /// If the port specified is already in use, binding the endpoint will fail. Using -334 /// port `0` in the socket address assigns a random free port. -335 /// -336 /// # Example -337 /// ``` -338 /// # #[tokio::main] -339 /// # async fn main() -> n0_error::Result<()> { -340 /// # use iroh::{Endpoint, endpoint::BindOpts}; -341 /// let endpoint = Endpoint::builder() -342 /// .clear_ip_transports() -343 /// .bind_addr_with_opts("127.0.0.1:1234", BindOpts::default().set_prefix_len(24))? -344 /// .bind_addr_with_opts("[::1]:1235", BindOpts::default().set_prefix_len(48))? -345 /// .bind() -346 /// .await?; -347 /// # Ok(()) } -348 /// ``` -349 #[cfg(not(wasm_browser))] -350 pub fn bind_addr_with_opts<A>( -351 mut self, -352 addr: A, -353 opts: BindOpts, -354 ) -> Result<Self, InvalidSocketAddr> -355 where -356 A: ToSocketAddr, -357 <A as ToSocketAddr>::Err: Into<InvalidSocketAddr>, -358 { -359 let addr = addr.to_socket_addr().map_err(Into::into)?; -360 match addr { -361 SocketAddr::V4(addr) => { -362 if self -363 .transports -364 .iter() -365 .any(|t| t.is_ipv4_default() && t.is_user_defined()) -366 { -367 bail!(InvalidSocketAddr::DuplicateDefaultAddr); -368 } -369 -370 self.transports.push(TransportConfig::Ip { -371 config: IpConfig::V4 { -372 ip_net: Ipv4Net::new(*addr.ip(), opts.prefix_len())?, -373 port: addr.port(), -374 is_required: opts.is_required(), -375 is_default: opts.is_default_route(), -376 }, -377 is_user_defined: true, -378 }); -379 } -380 SocketAddr::V6(addr) => { -381 if self -382 .transports -383 .iter() -384 .any(|t| t.is_ipv6_default() && t.is_user_defined()) -385 { -386 bail!(InvalidSocketAddr::DuplicateDefaultAddr); -387 } -388 -389 self.transports.push(TransportConfig::Ip { -390 config: IpConfig::V6 { -391 ip_net: Ipv6Net::new(*addr.ip(), opts.prefix_len())?, -392 scope_id: addr.scope_id(), -393 port: addr.port(), -394 is_required: opts.is_required(), -395 is_default: opts.is_default_route(), -396 }, -397 is_user_defined: true, -398 }); -399 } -400 } -401 Ok(self) -402 } -403 -404 /// Removes all IP based transports. -405 #[cfg(not(wasm_browser))] -406 pub fn clear_ip_transports(mut self) -> Self { -407 self.transports -408 .retain(|t| !matches!(t, TransportConfig::Ip { .. })); -409 self -410 } -411 -412 /// Removes all relay based transports. -413 pub fn clear_relay_transports(mut self) -> Self { -414 self.transports -415 .retain(|t| !matches!(t, TransportConfig::Relay { .. })); -416 self -417 } -418 -419 /// Sets a secret key to authenticate with other peers. -420 /// -421 /// This secret key's public key will be the [`PublicKey`] of this endpoint and thus -422 /// also its [`EndpointId`] -423 /// -424 /// If not set, a new secret key will be generated. +333 /// Using port `0` in the socket address assigns a random free port. +334 /// +335 /// If the port specified is already in use, binding the endpoint will fail, unless +336 /// [`BindOpts::set_is_required`] is set to `false` +337 /// +338 /// # Example +339 /// ``` +340 /// # #[tokio::main] +341 /// # async fn main() -> n0_error::Result<()> { +342 /// # use iroh::{Endpoint, endpoint::BindOpts}; +343 /// let endpoint = Endpoint::builder() +344 /// .clear_ip_transports() +345 /// .bind_addr_with_opts("127.0.0.1:1234", BindOpts::default().set_prefix_len(24))? +346 /// .bind_addr_with_opts("[::1]:1235", BindOpts::default().set_prefix_len(48))? +347 /// .bind() +348 /// .await?; +349 /// # Ok(()) } +350 /// ``` +351 #[cfg(not(wasm_browser))] +352 pub fn bind_addr_with_opts<A>( +353 mut self, +354 addr: A, +355 opts: BindOpts, +356 ) -> Result<Self, InvalidSocketAddr> +357 where +358 A: ToSocketAddr, +359 <A as ToSocketAddr>::Err: Into<InvalidSocketAddr>, +360 { +361 let addr = addr.to_socket_addr().map_err(Into::into)?; +362 match addr { +363 SocketAddr::V4(addr) => { +364 if self +365 .transports +366 .iter() +367 .any(|t| t.is_ipv4_default() && t.is_user_defined()) +368 { +369 bail!(InvalidSocketAddr::DuplicateDefaultAddr); +370 } +371 +372 self.transports.push(TransportConfig::Ip { +373 config: IpConfig::V4 { +374 ip_net: Ipv4Net::new(*addr.ip(), opts.prefix_len())?, +375 port: addr.port(), +376 is_required: opts.is_required(), +377 is_default: opts.is_default_route(), +378 }, +379 is_user_defined: true, +380 }); +381 } +382 SocketAddr::V6(addr) => { +383 if self +384 .transports +385 .iter() +386 .any(|t| t.is_ipv6_default() && t.is_user_defined()) +387 { +388 bail!(InvalidSocketAddr::DuplicateDefaultAddr); +389 } +390 +391 self.transports.push(TransportConfig::Ip { +392 config: IpConfig::V6 { +393 ip_net: Ipv6Net::new(*addr.ip(), opts.prefix_len())?, +394 scope_id: addr.scope_id(), +395 port: addr.port(), +396 is_required: opts.is_required(), +397 is_default: opts.is_default_route(), +398 }, +399 is_user_defined: true, +400 }); +401 } +402 } +403 Ok(self) +404 } +405 +406 /// Removes all IP based transports. +407 #[cfg(not(wasm_browser))] +408 pub fn clear_ip_transports(mut self) -> Self { +409 self.transports +410 .retain(|t| !matches!(t, TransportConfig::Ip { .. })); +411 self +412 } +413 +414 /// Removes all relay based transports. +415 pub fn clear_relay_transports(mut self) -> Self { +416 self.transports +417 .retain(|t| !matches!(t, TransportConfig::Relay { .. })); +418 self +419 } +420 +421 /// Sets a secret key to authenticate with other peers. +422 /// +423 /// This secret key's public key will be the [`PublicKey`] of this endpoint and thus +424 /// also its [`EndpointId`] 425 /// -426 /// [`PublicKey`]: iroh_base::PublicKey -427 pub fn secret_key(mut self, secret_key: SecretKey) -> Self { -428 self.secret_key = Some(secret_key); -429 self -430 } -431 -432 /// Sets the [ALPN] protocols that this endpoint will accept on incoming connections. -433 /// -434 /// Not setting this will still allow creating connections, but to accept incoming -435 /// connections at least one [ALPN] must be set. -436 /// -437 /// [ALPN]: https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation -438 pub fn alpns(mut self, alpn_protocols: Vec<Vec<u8>>) -> Self { -439 self.alpn_protocols = alpn_protocols; -440 self -441 } -442 -443 // # Methods for common customisation items. +426 /// If not set, a new secret key will be generated. +427 /// +428 /// [`PublicKey`]: iroh_base::PublicKey +429 pub fn secret_key(mut self, secret_key: SecretKey) -> Self { +430 self.secret_key = Some(secret_key); +431 self +432 } +433 +434 /// Sets the [ALPN] protocols that this endpoint will accept on incoming connections. +435 /// +436 /// Not setting this will still allow creating connections, but to accept incoming +437 /// connections at least one [ALPN] must be set. +438 /// +439 /// [ALPN]: https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation +440 pub fn alpns(mut self, alpn_protocols: Vec<Vec<u8>>) -> Self { +441 self.alpn_protocols = alpn_protocols; +442 self +443 } 444 -445 /// Sets the relay servers to assist in establishing connectivity. -446 /// -447 /// Relay servers are used to establish initial connection with another iroh endpoint. -448 /// They also perform various functions related to hole punching, see the [crate docs] -449 /// for more details. -450 /// -451 /// By default the [number 0] relay servers are used, see [`RelayMode::Default`]. +445 // # Methods for common customisation items. +446 +447 /// Sets the relay servers to assist in establishing connectivity. +448 /// +449 /// Relay servers are used to establish initial connection with another iroh endpoint. +450 /// They also perform various functions related to hole punching, see the [crate docs] +451 /// for more details. 452 /// -453 /// When using [RelayMode::Custom], the provided `relay_map` must contain at least one -454 /// configured relay endpoint. If an invalid RelayMap is provided [`bind`] -455 /// will result in an error. -456 /// -457 /// [`bind`]: Builder::bind -458 /// [crate docs]: crate -459 /// [number 0]: https://n0.computer -460 pub fn relay_mode(mut self, relay_mode: RelayMode) -> Self { -461 let transport: Option<_> = relay_mode.into(); -462 match transport { -463 Some(transport) => { -464 if let Some(og) = self -465 .transports -466 .iter_mut() -467 .find(|t| matches!(t, TransportConfig::Relay { .. })) -468 { -469 *og = transport; -470 } else { -471 self.transports.push(transport); -472 } -473 } -474 None => { -475 self.transports -476 .retain(|t| !matches!(t, TransportConfig::Relay { .. })); -477 } -478 } -479 self -480 } -481 -482 /// Removes all discovery services from the builder. -483 /// -484 /// If no discovery service is set, connecting to an endpoint without providing its -485 /// direct addresses or relay URLs will fail. -486 /// -487 /// See the documentation of the [`crate::discovery::Discovery`] trait for details. -488 pub fn clear_discovery(mut self) -> Self { -489 self.discovery.clear(); -490 self -491 } -492 -493 /// Adds an additional discovery mechanism for this endpoint. -494 /// -495 /// Once the endpoint is created the provided [`IntoDiscovery::into_discovery`] will be -496 /// called. This allows discovery services to finalize their configuration by e.g. using -497 /// the secret key from the endpoint which can be needed to sign published information. -498 /// -499 /// This method can be called multiple times and all the discovery services passed in -500 /// will be combined using an internal instance of the -501 /// [`crate::discovery::ConcurrentDiscovery`]. To clear all discovery services, use -502 /// [`Self::clear_discovery`]. -503 /// -504 /// If no discovery service is set, connecting to an endpoint without providing its -505 /// direct addresses or relay URLs will fail. -506 /// -507 /// See the documentation of the [`crate::discovery::Discovery`] trait for details. -508 pub fn discovery(mut self, discovery: impl IntoDiscovery) -> Self { -509 self.discovery.push(Box::new(discovery)); -510 self -511 } -512 -513 /// Sets the initial user-defined data to be published in discovery services for this node. -514 /// -515 /// When using discovery services, this string of [`UserData`] will be published together -516 /// with the endpoint's addresses and relay URL. When other endpoints discover this endpoint, -517 /// they retrieve the [`UserData`] in addition to the addressing info. -518 /// -519 /// Iroh itself does not interpret the user-defined data in any way, it is purely left -520 /// for applications to parse and use. -521 pub fn user_data_for_discovery(mut self, user_data: UserData) -> Self { -522 self.discovery_user_data = Some(user_data); -523 self -524 } -525 -526 // # Methods for more specialist customisation. +453 /// By default the [number 0] relay servers are used, see [`RelayMode::Default`]. +454 /// +455 /// When using [RelayMode::Custom], the provided `relay_map` must contain at least one +456 /// configured relay endpoint. If an invalid RelayMap is provided [`bind`] +457 /// will result in an error. +458 /// +459 /// [`bind`]: Builder::bind +460 /// [crate docs]: crate +461 /// [number 0]: https://n0.computer +462 pub fn relay_mode(mut self, relay_mode: RelayMode) -> Self { +463 let transport: Option<_> = relay_mode.into(); +464 match transport { +465 Some(transport) => { +466 if let Some(og) = self +467 .transports +468 .iter_mut() +469 .find(|t| matches!(t, TransportConfig::Relay { .. })) +470 { +471 *og = transport; +472 } else { +473 self.transports.push(transport); +474 } +475 } +476 None => { +477 self.transports +478 .retain(|t| !matches!(t, TransportConfig::Relay { .. })); +479 } +480 } +481 self +482 } +483 +484 /// Removes all discovery services from the builder. +485 /// +486 /// If no discovery service is set, connecting to an endpoint without providing its +487 /// direct addresses or relay URLs will fail. +488 /// +489 /// See the documentation of the [`crate::discovery::Discovery`] trait for details. +490 pub fn clear_discovery(mut self) -> Self { +491 self.discovery.clear(); +492 self +493 } +494 +495 /// Adds an additional discovery mechanism for this endpoint. +496 /// +497 /// Once the endpoint is created the provided [`IntoDiscovery::into_discovery`] will be +498 /// called. This allows discovery services to finalize their configuration by e.g. using +499 /// the secret key from the endpoint which can be needed to sign published information. +500 /// +501 /// This method can be called multiple times and all the discovery services passed in +502 /// will be combined using an internal instance of the +503 /// [`crate::discovery::ConcurrentDiscovery`]. To clear all discovery services, use +504 /// [`Self::clear_discovery`]. +505 /// +506 /// If no discovery service is set, connecting to an endpoint without providing its +507 /// direct addresses or relay URLs will fail. +508 /// +509 /// See the documentation of the [`crate::discovery::Discovery`] trait for details. +510 pub fn discovery(mut self, discovery: impl IntoDiscovery) -> Self { +511 self.discovery.push(Box::new(discovery)); +512 self +513 } +514 +515 /// Sets the initial user-defined data to be published in discovery services for this node. +516 /// +517 /// When using discovery services, this string of [`UserData`] will be published together +518 /// with the endpoint's addresses and relay URL. When other endpoints discover this endpoint, +519 /// they retrieve the [`UserData`] in addition to the addressing info. +520 /// +521 /// Iroh itself does not interpret the user-defined data in any way, it is purely left +522 /// for applications to parse and use. +523 pub fn user_data_for_discovery(mut self, user_data: UserData) -> Self { +524 self.discovery_user_data = Some(user_data); +525 self +526 } 527 -528 /// Sets a custom [`QuicTransportConfig`] for this endpoint. -529 /// -530 /// The transport config contains parameters governing the QUIC state machine. +528 // # Methods for more specialist customisation. +529 +530 /// Sets a custom [`QuicTransportConfig`] for this endpoint. 531 /// -532 /// If unset, the default config is used. Default values should be suitable for most -533 /// internet applications. Applications protocols which forbid remotely-initiated -534 /// streams should set `max_concurrent_bidi_streams` and `max_concurrent_uni_streams` to -535 /// zero. -536 /// -537 /// Please be aware that changing some settings may have adverse effects on establishing -538 /// and maintaining direct connections. -539 pub fn transport_config(mut self, transport_config: QuicTransportConfig) -> Self { -540 self.transport_config = transport_config; -541 self -542 } -543 -544 /// Optionally sets a custom DNS resolver to use for this endpoint. -545 /// -546 /// The DNS resolver is used to resolve relay hostnames, and endpoint addresses if -547 /// [`crate::discovery::dns::DnsDiscovery`] is configured. -548 /// -549 /// By default, a new DNS resolver is created which is configured to use the -550 /// host system's DNS configuration. You can pass a custom instance of [`DnsResolver`] -551 /// here to use a differently configured DNS resolver for this endpoint, or to share -552 /// a [`DnsResolver`] between multiple endpoints. -553 #[cfg(not(wasm_browser))] -554 pub fn dns_resolver(mut self, dns_resolver: DnsResolver) -> Self { -555 self.dns_resolver = Some(dns_resolver); -556 self -557 } -558 -559 /// Sets an explicit proxy url to proxy all HTTP(S) traffic through. -560 pub fn proxy_url(mut self, url: Url) -> Self { -561 self.proxy_url.replace(url); -562 self -563 } -564 -565 /// Sets the proxy url from the environment, in this order: -566 /// -567 /// - `HTTP_PROXY` -568 /// - `http_proxy` -569 /// - `HTTPS_PROXY` -570 /// - `https_proxy` -571 pub fn proxy_from_env(mut self) -> Self { -572 self.proxy_url = proxy_url_from_env(); -573 self -574 } -575 -576 /// Enables saving the TLS pre-master key for connections. -577 /// -578 /// This key should normally remain secret but can be useful to debug networking issues -579 /// by decrypting captured traffic. -580 /// -581 /// If *keylog* is `true` then setting the `SSLKEYLOGFILE` environment variable to a -582 /// filename will result in this file being used to log the TLS pre-master keys. -583 pub fn keylog(mut self, keylog: bool) -> Self { -584 self.keylog = keylog; -585 self -586 } -587 -588 /// Skip verification of SSL certificates from relay servers -589 /// -590 /// May only be used in tests. -591 #[cfg(any(test, feature = "test-utils"))] -592 pub fn insecure_skip_relay_cert_verify(mut self, skip_verify: bool) -> Self { -593 self.insecure_skip_relay_cert_verify = skip_verify; -594 self -595 } -596 -597 /// Set the maximum number of TLS tickets to cache. -598 /// -599 /// Set this to a larger value if you want to do 0rtt connections to a large -600 /// number of clients. -601 /// -602 /// The default is 256, taking about 150 KiB in memory. -603 pub fn max_tls_tickets(mut self, n: usize) -> Self { -604 self.max_tls_tickets = n; -605 self -606 } -607 -608 /// Install hooks onto the endpoint. -609 /// -610 /// Endpoint hooks intercept the connection establishment process of an [`Endpoint`]. +532 /// The transport config contains parameters governing the QUIC state machine. +533 /// +534 /// If unset, the default config is used. Default values should be suitable for most +535 /// internet applications. Applications protocols which forbid remotely-initiated +536 /// streams should set `max_concurrent_bidi_streams` and `max_concurrent_uni_streams` to +537 /// zero. +538 /// +539 /// Please be aware that changing some settings may have adverse effects on establishing +540 /// and maintaining direct connections. +541 pub fn transport_config(mut self, transport_config: QuicTransportConfig) -> Self { +542 self.transport_config = transport_config; +543 self +544 } +545 +546 /// Optionally sets a custom DNS resolver to use for this endpoint. +547 /// +548 /// The DNS resolver is used to resolve relay hostnames, and endpoint addresses if +549 /// [`crate::discovery::dns::DnsDiscovery`] is configured. +550 /// +551 /// By default, a new DNS resolver is created which is configured to use the +552 /// host system's DNS configuration. You can pass a custom instance of [`DnsResolver`] +553 /// here to use a differently configured DNS resolver for this endpoint, or to share +554 /// a [`DnsResolver`] between multiple endpoints. +555 #[cfg(not(wasm_browser))] +556 pub fn dns_resolver(mut self, dns_resolver: DnsResolver) -> Self { +557 self.dns_resolver = Some(dns_resolver); +558 self +559 } +560 +561 /// Sets an explicit proxy url to proxy all HTTP(S) traffic through. +562 pub fn proxy_url(mut self, url: Url) -> Self { +563 self.proxy_url.replace(url); +564 self +565 } +566 +567 /// Sets the proxy url from the environment, in this order: +568 /// +569 /// - `HTTP_PROXY` +570 /// - `http_proxy` +571 /// - `HTTPS_PROXY` +572 /// - `https_proxy` +573 pub fn proxy_from_env(mut self) -> Self { +574 self.proxy_url = proxy_url_from_env(); +575 self +576 } +577 +578 /// Enables saving the TLS pre-master key for connections. +579 /// +580 /// This key should normally remain secret but can be useful to debug networking issues +581 /// by decrypting captured traffic. +582 /// +583 /// If *keylog* is `true` then setting the `SSLKEYLOGFILE` environment variable to a +584 /// filename will result in this file being used to log the TLS pre-master keys. +585 pub fn keylog(mut self, keylog: bool) -> Self { +586 self.keylog = keylog; +587 self +588 } +589 +590 /// Skip verification of SSL certificates from relay servers +591 /// +592 /// May only be used in tests. +593 #[cfg(any(test, feature = "test-utils"))] +594 pub fn insecure_skip_relay_cert_verify(mut self, skip_verify: bool) -> Self { +595 self.insecure_skip_relay_cert_verify = skip_verify; +596 self +597 } +598 +599 /// Set the maximum number of TLS tickets to cache. +600 /// +601 /// Set this to a larger value if you want to do 0rtt connections to a large +602 /// number of clients. +603 /// +604 /// The default is 256, taking about 150 KiB in memory. +605 pub fn max_tls_tickets(mut self, n: usize) -> Self { +606 self.max_tls_tickets = n; +607 self +608 } +609 +610 /// Install hooks onto the endpoint. 611 /// -612 /// You can install multiple [`EndpointHooks`] by calling this function multiple times. -613 /// Order matters: hooks are invoked in the order they were installed onto the endpoint -614 /// builder. Once a hook returns reject, further processing -615 /// is aborted and other hooks won't be invoked. -616 /// -617 /// See [`EndpointHooks`] for details on the possible interception points in the connection lifecycle. -618 pub fn hooks(mut self, hooks: impl EndpointHooks + 'static) -> Self { -619 self.hooks.push(hooks); -620 self -621 } -622} -623 -624/// Configuration for a [`quinn::Endpoint`] that cannot be changed at runtime. -625#[derive(Debug)] -626struct StaticConfig { -627 tls_config: tls::TlsConfig, -628 transport_config: QuicTransportConfig, -629 keylog: bool, -630} -631 -632impl StaticConfig { -633 /// Create a [`ServerConfig`] with the specified ALPN protocols. -634 fn create_server_config(&self, alpn_protocols: Vec<Vec<u8>>) -> quinn_proto::ServerConfig { -635 let quic_server_config = self -636 .tls_config -637 .make_server_config(alpn_protocols, self.keylog); -638 let mut inner = quinn::ServerConfig::with_crypto(Arc::new(quic_server_config)); -639 inner.transport_config(self.transport_config.to_inner_arc()); -640 inner -641 } -642} -643 -644/// Controls an iroh endpoint, establishing connections with other endpoints. -645/// -646/// This is the main API interface to create connections to, and accept connections from -647/// other iroh endpoints. The connections are peer-to-peer and encrypted, a Relay server is -648/// used to make the connections reliable. See the [crate docs] for a more detailed -649/// overview of iroh. -650/// -651/// It is recommended to only create a single instance per application. This ensures all -652/// the connections made share the same peer-to-peer connections to other iroh endpoints, -653/// while still remaining independent connections. This will result in more optimal network -654/// behaviour. -655/// -656/// The endpoint is created using the [`Builder`], which can be created using -657/// [`Endpoint::builder`]. -658/// -659/// Once an endpoint exists, new connections are typically created using the -660/// [`Endpoint::connect`] and [`Endpoint::accept`] methods. Once established, the -661/// [`Connection`] gives access to most [QUIC] features. Individual streams to send data to -662/// the peer are created using the [`Connection::open_bi`], [`Connection::accept_bi`], -663/// [`Connection::open_uni`] and [`Connection::open_bi`] functions. -664/// -665/// Note that due to the light-weight properties of streams a stream will only be accepted -666/// once the initiating peer has sent some data on it. -667/// -668/// [QUIC]: https://quicwg.org -669#[derive(Clone, Debug)] -670pub struct Endpoint { -671 /// Handle to the magicsocket/actor -672 pub(crate) msock: Handle, -673 /// Configuration structs for quinn, holds the transport config, certificate setup, secret key etc. -674 static_config: Arc<StaticConfig>, -675} -676 -677#[allow(missing_docs)] -678#[stack_error(derive, add_meta, from_sources)] -679#[non_exhaustive] -680#[allow(private_interfaces)] -681pub enum ConnectWithOptsError { -682 #[error("Connecting to ourself is not supported")] -683 SelfConnect, -684 #[error("No addressing information available")] -685 NoAddress { source: DiscoveryError }, -686 #[error("Unable to connect to remote")] -687 Quinn { -688 #[error(std_err)] -689 source: QuicConnectError, -690 }, -691 #[error("Internal consistency error")] -692 InternalConsistencyError { -693 /// Private source type, cannot be created publicly. -694 source: RemoteStateActorStoppedError, -695 }, -696 #[error("Connection was rejected locally")] -697 LocallyRejected, -698} -699 -700#[allow(missing_docs)] -701#[stack_error(derive, add_meta, from_sources)] -702#[non_exhaustive] -703pub enum ConnectError { -704 #[error(transparent)] -705 Connect { source: ConnectWithOptsError }, +612 /// Endpoint hooks intercept the connection establishment process of an [`Endpoint`]. +613 /// +614 /// You can install multiple [`EndpointHooks`] by calling this function multiple times. +615 /// Order matters: hooks are invoked in the order they were installed onto the endpoint +616 /// builder. Once a hook returns reject, further processing +617 /// is aborted and other hooks won't be invoked. +618 /// +619 /// See [`EndpointHooks`] for details on the possible interception points in the connection lifecycle. +620 pub fn hooks(mut self, hooks: impl EndpointHooks + 'static) -> Self { +621 self.hooks.push(hooks); +622 self +623 } +624} +625 +626/// Configuration for a [`quinn::Endpoint`] that cannot be changed at runtime. +627#[derive(Debug)] +628struct StaticConfig { +629 tls_config: tls::TlsConfig, +630 transport_config: QuicTransportConfig, +631 keylog: bool, +632} +633 +634impl StaticConfig { +635 /// Create a [`ServerConfig`] with the specified ALPN protocols. +636 fn create_server_config(&self, alpn_protocols: Vec<Vec<u8>>) -> quinn_proto::ServerConfig { +637 let quic_server_config = self +638 .tls_config +639 .make_server_config(alpn_protocols, self.keylog); +640 let mut inner = quinn::ServerConfig::with_crypto(Arc::new(quic_server_config)); +641 inner.transport_config(self.transport_config.to_inner_arc()); +642 inner +643 } +644} +645 +646/// Controls an iroh endpoint, establishing connections with other endpoints. +647/// +648/// This is the main API interface to create connections to, and accept connections from +649/// other iroh endpoints. The connections are peer-to-peer and encrypted, a Relay server is +650/// used to make the connections reliable. See the [crate docs] for a more detailed +651/// overview of iroh. +652/// +653/// It is recommended to only create a single instance per application. This ensures all +654/// the connections made share the same peer-to-peer connections to other iroh endpoints, +655/// while still remaining independent connections. This will result in more optimal network +656/// behaviour. +657/// +658/// The endpoint is created using the [`Builder`], which can be created using +659/// [`Endpoint::builder`]. +660/// +661/// Once an endpoint exists, new connections are typically created using the +662/// [`Endpoint::connect`] and [`Endpoint::accept`] methods. Once established, the +663/// [`Connection`] gives access to most [QUIC] features. Individual streams to send data to +664/// the peer are created using the [`Connection::open_bi`], [`Connection::accept_bi`], +665/// [`Connection::open_uni`] and [`Connection::open_bi`] functions. +666/// +667/// Note that due to the light-weight properties of streams a stream will only be accepted +668/// once the initiating peer has sent some data on it. +669/// +670/// [QUIC]: https://quicwg.org +671#[derive(Clone, Debug)] +672pub struct Endpoint { +673 /// Handle to the magicsocket/actor +674 pub(crate) msock: Handle, +675 /// Configuration structs for quinn, holds the transport config, certificate setup, secret key etc. +676 static_config: Arc<StaticConfig>, +677} +678 +679#[allow(missing_docs)] +680#[stack_error(derive, add_meta, from_sources)] +681#[non_exhaustive] +682#[allow(private_interfaces)] +683pub enum ConnectWithOptsError { +684 #[error("Connecting to ourself is not supported")] +685 SelfConnect, +686 #[error("No addressing information available")] +687 NoAddress { source: DiscoveryError }, +688 #[error("Unable to connect to remote")] +689 Quinn { +690 #[error(std_err)] +691 source: QuicConnectError, +692 }, +693 #[error("Internal consistency error")] +694 InternalConsistencyError { +695 /// Private source type, cannot be created publicly. +696 source: RemoteStateActorStoppedError, +697 }, +698 #[error("Connection was rejected locally")] +699 LocallyRejected, +700} +701 +702#[allow(missing_docs)] +703#[stack_error(derive, add_meta, from_sources)] +704#[non_exhaustive] +705pub enum ConnectError { 706 #[error(transparent)] -707 Connecting { source: ConnectingError }, +707 Connect { source: ConnectWithOptsError }, 708 #[error(transparent)] -709 Connection { -710 #[error(std_err)] -711 source: ConnectionError, -712 }, -713} -714 -715#[allow(missing_docs)] -716#[stack_error(derive, add_meta, from_sources)] -717#[non_exhaustive] -718pub enum BindError { -719 #[error(transparent)] -720 MagicSpawn { -721 source: magicsock::CreateHandleError, -722 }, -723 #[error(transparent)] -724 Discovery { -725 source: crate::discovery::IntoDiscoveryError, -726 }, -727} -728 -729impl Endpoint { -730 // The ordering of public methods is reflected directly in the documentation. This is -731 // roughly ordered by what is most commonly needed by users, but grouped in similar -732 // items. -733 -734 // # Methods relating to construction. +709 Connecting { source: ConnectingError }, +710 #[error(transparent)] +711 Connection { +712 #[error(std_err)] +713 source: ConnectionError, +714 }, +715} +716 +717#[allow(missing_docs)] +718#[stack_error(derive, add_meta, from_sources)] +719#[non_exhaustive] +720pub enum BindError { +721 #[error(transparent)] +722 MagicSpawn { +723 source: magicsock::CreateHandleError, +724 }, +725 #[error(transparent)] +726 Discovery { +727 source: crate::discovery::IntoDiscoveryError, +728 }, +729} +730 +731impl Endpoint { +732 // The ordering of public methods is reflected directly in the documentation. This is +733 // roughly ordered by what is most commonly needed by users, but grouped in similar +734 // items. 735 -736 /// Returns the builder for an [`Endpoint`], with a production configuration. -737 /// -738 /// This uses the [`presets::N0`] as the configuration. -739 pub fn builder() -> Builder { -740 Builder::new(presets::N0) -741 } -742 -743 /// Returns the builder for an [`Endpoint`], with an empty configuration. -744 /// -745 /// See [`Builder::empty`] for details. -746 pub fn empty_builder(relay_mode: RelayMode) -> Builder { -747 Builder::empty(relay_mode) -748 } -749 -750 /// Constructs a default [`Endpoint`] and binds it immediately. -751 /// -752 /// Uses the [`presets::N0`] as configuration. -753 pub async fn bind() -> Result<Self, BindError> { -754 Self::builder().bind().await -755 } -756 -757 /// Sets the list of accepted ALPN protocols. -758 /// -759 /// This will only affect new incoming connections. -760 /// Note that this *overrides* the current list of ALPNs. -761 pub fn set_alpns(&self, alpns: Vec<Vec<u8>>) { -762 let server_config = self.static_config.create_server_config(alpns); -763 self.msock.endpoint().set_server_config(Some(server_config)); -764 } -765 -766 /// Adds the provided configuration to the [`RelayMap`]. -767 /// -768 /// Replacing and returning any existing configuration for [`RelayUrl`]. -769 pub async fn insert_relay( -770 &self, -771 relay: RelayUrl, -772 config: Arc<RelayConfig>, -773 ) -> Option<Arc<RelayConfig>> { -774 self.msock.insert_relay(relay, config).await -775 } -776 -777 /// Removes the configuration from the [`RelayMap`] for the provided [`RelayUrl`]. -778 /// -779 /// Returns any existing configuration. -780 pub async fn remove_relay(&self, relay: &RelayUrl) -> Option<Arc<RelayConfig>> { -781 self.msock.remove_relay(relay).await -782 } -783 -784 // # Methods for establishing connectivity. +736 // # Methods relating to construction. +737 +738 /// Returns the builder for an [`Endpoint`], with a production configuration. +739 /// +740 /// This uses the [`presets::N0`] as the configuration. +741 pub fn builder() -> Builder { +742 Builder::new(presets::N0) +743 } +744 +745 /// Returns the builder for an [`Endpoint`], with an empty configuration. +746 /// +747 /// See [`Builder::empty`] for details. +748 pub fn empty_builder(relay_mode: RelayMode) -> Builder { +749 Builder::empty(relay_mode) +750 } +751 +752 /// Constructs a default [`Endpoint`] and binds it immediately. +753 /// +754 /// Uses the [`presets::N0`] as configuration. +755 pub async fn bind() -> Result<Self, BindError> { +756 Self::builder().bind().await +757 } +758 +759 /// Sets the list of accepted ALPN protocols. +760 /// +761 /// This will only affect new incoming connections. +762 /// Note that this *overrides* the current list of ALPNs. +763 pub fn set_alpns(&self, alpns: Vec<Vec<u8>>) { +764 let server_config = self.static_config.create_server_config(alpns); +765 self.msock.endpoint().set_server_config(Some(server_config)); +766 } +767 +768 /// Adds the provided configuration to the [`RelayMap`]. +769 /// +770 /// Replacing and returning any existing configuration for [`RelayUrl`]. +771 pub async fn insert_relay( +772 &self, +773 relay: RelayUrl, +774 config: Arc<RelayConfig>, +775 ) -> Option<Arc<RelayConfig>> { +776 self.msock.insert_relay(relay, config).await +777 } +778 +779 /// Removes the configuration from the [`RelayMap`] for the provided [`RelayUrl`]. +780 /// +781 /// Returns any existing configuration. +782 pub async fn remove_relay(&self, relay: &RelayUrl) -> Option<Arc<RelayConfig>> { +783 self.msock.remove_relay(relay).await +784 } 785 -786 /// Connects to a remote [`Endpoint`]. -787 /// -788 /// A value that can be converted into an [`EndpointAddr`] is required. This can be either an -789 /// [`EndpointAddr`] or an [`EndpointId`]. -790 /// -791 /// The [`EndpointAddr`] must contain the [`EndpointId`] to dial and may also contain a [`RelayUrl`] -792 /// and direct addresses. If direct addresses are provided, they will be used to try and -793 /// establish a direct connection without involving a relay server. -794 /// -795 /// If neither a [`RelayUrl`] or direct addresses are configured in the [`EndpointAddr`] it -796 /// may still be possible a connection can be established. This depends on which, if any, -797 /// [`crate::discovery::Discovery`] services were configured using [`Builder::discovery`]. The discovery -798 /// service will also be used if the remote endpoint is not reachable on the provided direct -799 /// addresses and there is no [`RelayUrl`]. -800 /// -801 /// If addresses or relay servers are neither provided nor can be discovered, the -802 /// connection attempt will fail with an error. -803 /// -804 /// The `alpn`, or application-level protocol identifier, is also required. The remote -805 /// endpoint must support this `alpn`, otherwise the connection attempt will fail with -806 /// an error. -807 /// -808 /// [`RelayUrl`]: crate::RelayUrl -809 pub async fn connect( -810 &self, -811 endpoint_addr: impl Into<EndpointAddr>, -812 alpn: &[u8], -813 ) -> Result<Connection, ConnectError> { -814 let endpoint_addr = endpoint_addr.into(); -815 let remote = endpoint_addr.id; -816 let connecting = self -817 .connect_with_opts(endpoint_addr, alpn, Default::default()) -818 .await?; -819 let conn = connecting.await?; -820 -821 debug!( -822 me = %self.id().fmt_short(), -823 remote = %remote.fmt_short(), -824 alpn = %String::from_utf8_lossy(alpn), -825 "Connection established." -826 ); -827 Ok(conn) -828 } -829 -830 /// Starts a connection attempt with a remote [`Endpoint`]. -831 /// -832 /// Like [`Endpoint::connect`] (see also its docs for general details), but allows for a more -833 /// advanced connection setup with more customization in two aspects: -834 /// 1. The returned future resolves to a [`Connecting`], which can be further processed into -835 /// a [`Connection`] by awaiting, or alternatively allows connecting with 0-RTT via -836 /// [`Connecting::into_0rtt`]. -837 /// **Note:** Please read the documentation for `into_0rtt` carefully to assess -838 /// security concerns. -839 /// 2. The [`QuicTransportConfig`] for the connection can be modified via the provided -840 /// [`ConnectOptions`]. -841 /// **Note:** Please be aware that changing transport config settings may have adverse effects on -842 /// establishing and maintaining direct connections. Carefully test settings you use and -843 /// consider this currently as still rather experimental. -844 #[instrument(name = "connect", skip_all, fields( -845 me = %self.id().fmt_short(), -846 remote = tracing::field::Empty, -847 alpn = String::from_utf8_lossy(alpn).to_string(), -848 ))] -849 pub async fn connect_with_opts( -850 &self, -851 endpoint_addr: impl Into<EndpointAddr>, -852 alpn: &[u8], -853 options: ConnectOptions, -854 ) -> Result<Connecting, ConnectWithOptsError> { -855 let endpoint_addr: EndpointAddr = endpoint_addr.into(); -856 if let BeforeConnectOutcome::Reject = -857 self.msock.hooks.before_connect(&endpoint_addr, alpn).await -858 { -859 return Err(e!(ConnectWithOptsError::LocallyRejected)); -860 } -861 let endpoint_id = endpoint_addr.id; -862 -863 tracing::Span::current().record("remote", tracing::field::display(endpoint_id.fmt_short())); +786 // # Methods for establishing connectivity. +787 +788 /// Connects to a remote [`Endpoint`]. +789 /// +790 /// A value that can be converted into an [`EndpointAddr`] is required. This can be either an +791 /// [`EndpointAddr`] or an [`EndpointId`]. +792 /// +793 /// The [`EndpointAddr`] must contain the [`EndpointId`] to dial and may also contain a [`RelayUrl`] +794 /// and direct addresses. If direct addresses are provided, they will be used to try and +795 /// establish a direct connection without involving a relay server. +796 /// +797 /// If neither a [`RelayUrl`] or direct addresses are configured in the [`EndpointAddr`] it +798 /// may still be possible a connection can be established. This depends on which, if any, +799 /// [`crate::discovery::Discovery`] services were configured using [`Builder::discovery`]. The discovery +800 /// service will also be used if the remote endpoint is not reachable on the provided direct +801 /// addresses and there is no [`RelayUrl`]. +802 /// +803 /// If addresses or relay servers are neither provided nor can be discovered, the +804 /// connection attempt will fail with an error. +805 /// +806 /// The `alpn`, or application-level protocol identifier, is also required. The remote +807 /// endpoint must support this `alpn`, otherwise the connection attempt will fail with +808 /// an error. +809 /// +810 /// [`RelayUrl`]: crate::RelayUrl +811 pub async fn connect( +812 &self, +813 endpoint_addr: impl Into<EndpointAddr>, +814 alpn: &[u8], +815 ) -> Result<Connection, ConnectError> { +816 let endpoint_addr = endpoint_addr.into(); +817 let remote = endpoint_addr.id; +818 let connecting = self +819 .connect_with_opts(endpoint_addr, alpn, Default::default()) +820 .await?; +821 let conn = connecting.await?; +822 +823 debug!( +824 me = %self.id().fmt_short(), +825 remote = %remote.fmt_short(), +826 alpn = %String::from_utf8_lossy(alpn), +827 "Connection established." +828 ); +829 Ok(conn) +830 } +831 +832 /// Starts a connection attempt with a remote [`Endpoint`]. +833 /// +834 /// Like [`Endpoint::connect`] (see also its docs for general details), but allows for a more +835 /// advanced connection setup with more customization in two aspects: +836 /// 1. The returned future resolves to a [`Connecting`], which can be further processed into +837 /// a [`Connection`] by awaiting, or alternatively allows connecting with 0-RTT via +838 /// [`Connecting::into_0rtt`]. +839 /// **Note:** Please read the documentation for `into_0rtt` carefully to assess +840 /// security concerns. +841 /// 2. The [`QuicTransportConfig`] for the connection can be modified via the provided +842 /// [`ConnectOptions`]. +843 /// **Note:** Please be aware that changing transport config settings may have adverse effects on +844 /// establishing and maintaining direct connections. Carefully test settings you use and +845 /// consider this currently as still rather experimental. +846 #[instrument(name = "connect", skip_all, fields( +847 me = %self.id().fmt_short(), +848 remote = tracing::field::Empty, +849 alpn = String::from_utf8_lossy(alpn).to_string(), +850 ))] +851 pub async fn connect_with_opts( +852 &self, +853 endpoint_addr: impl Into<EndpointAddr>, +854 alpn: &[u8], +855 options: ConnectOptions, +856 ) -> Result<Connecting, ConnectWithOptsError> { +857 let endpoint_addr: EndpointAddr = endpoint_addr.into(); +858 if let BeforeConnectOutcome::Reject = +859 self.msock.hooks.before_connect(&endpoint_addr, alpn).await +860 { +861 return Err(e!(ConnectWithOptsError::LocallyRejected)); +862 } +863 let endpoint_id = endpoint_addr.id; 864 -865 // Connecting to ourselves is not supported. -866 ensure!(endpoint_id != self.id(), ConnectWithOptsError::SelfConnect); -867 -868 trace!( -869 dst_endpoint_id = %endpoint_id.fmt_short(), -870 relay_url = ?endpoint_addr.relay_urls().next().cloned(), -871 ip_addresses = ?endpoint_addr.ip_addrs().cloned().collect::<Vec<_>>(), -872 "connecting", -873 ); -874 -875 let mapped_addr = self.msock.resolve_remote(endpoint_addr).await??; +865 tracing::Span::current().record("remote", tracing::field::display(endpoint_id.fmt_short())); +866 +867 // Connecting to ourselves is not supported. +868 ensure!(endpoint_id != self.id(), ConnectWithOptsError::SelfConnect); +869 +870 trace!( +871 dst_endpoint_id = %endpoint_id.fmt_short(), +872 relay_url = ?endpoint_addr.relay_urls().next().cloned(), +873 ip_addresses = ?endpoint_addr.ip_addrs().cloned().collect::<Vec<_>>(), +874 "connecting", +875 ); 876 -877 let transport_config = options -878 .transport_config -879 .map(|cfg| cfg.to_inner_arc()) -880 .unwrap_or(self.static_config.transport_config.to_inner_arc()); -881 -882 // Start connecting via quinn. This will time out after 10 seconds if no reachable -883 // address is available. -884 -885 let client_config = { -886 let mut alpn_protocols = vec![alpn.to_vec()]; -887 alpn_protocols.extend(options.additional_alpns); -888 let quic_client_config = self -889 .static_config -890 .tls_config -891 .make_client_config(alpn_protocols, self.static_config.keylog); -892 let mut client_config = quinn::ClientConfig::new(Arc::new(quic_client_config)); -893 client_config.transport_config(transport_config.clone()); -894 client_config -895 }; -896 -897 let dest_addr = mapped_addr.private_socket_addr(); -898 let server_name = &tls::name::encode(endpoint_id); -899 let connect = self -900 .msock -901 .endpoint() -902 .connect_with(client_config, dest_addr, server_name)?; -903 -904 Ok(Connecting::new(connect, self.clone(), endpoint_id)) -905 } -906 -907 /// Accepts an incoming connection on the endpoint. -908 /// -909 /// Only connections with the ALPNs configured in [`Builder::alpns`] will be accepted. -910 /// If multiple ALPNs have been configured the ALPN can be inspected before accepting -911 /// the connection using [`Connecting::alpn`]. -912 /// -913 /// The returned future will yield `None` if the endpoint is closed by calling -914 /// [`Endpoint::close`]. -915 pub fn accept(&self) -> Accept<'_> { -916 Accept { -917 inner: self.msock.endpoint().accept(), -918 ep: self.clone(), -919 } -920 } -921 -922 // # Getter methods for properties of this Endpoint itself. +877 let mapped_addr = self.msock.resolve_remote(endpoint_addr).await??; +878 +879 let transport_config = options +880 .transport_config +881 .map(|cfg| cfg.to_inner_arc()) +882 .unwrap_or(self.static_config.transport_config.to_inner_arc()); +883 +884 // Start connecting via quinn. This will time out after 10 seconds if no reachable +885 // address is available. +886 +887 let client_config = { +888 let mut alpn_protocols = vec![alpn.to_vec()]; +889 alpn_protocols.extend(options.additional_alpns); +890 let quic_client_config = self +891 .static_config +892 .tls_config +893 .make_client_config(alpn_protocols, self.static_config.keylog); +894 let mut client_config = quinn::ClientConfig::new(Arc::new(quic_client_config)); +895 client_config.transport_config(transport_config.clone()); +896 client_config +897 }; +898 +899 let dest_addr = mapped_addr.private_socket_addr(); +900 let server_name = &tls::name::encode(endpoint_id); +901 let connect = self +902 .msock +903 .endpoint() +904 .connect_with(client_config, dest_addr, server_name)?; +905 +906 Ok(Connecting::new(connect, self.clone(), endpoint_id)) +907 } +908 +909 /// Accepts an incoming connection on the endpoint. +910 /// +911 /// Only connections with the ALPNs configured in [`Builder::alpns`] will be accepted. +912 /// If multiple ALPNs have been configured the ALPN can be inspected before accepting +913 /// the connection using [`Connecting::alpn`]. +914 /// +915 /// The returned future will yield `None` if the endpoint is closed by calling +916 /// [`Endpoint::close`]. +917 pub fn accept(&self) -> Accept<'_> { +918 Accept { +919 inner: self.msock.endpoint().accept(), +920 ep: self.clone(), +921 } +922 } 923 -924 /// Returns the secret_key of this endpoint. -925 pub fn secret_key(&self) -> &SecretKey { -926 &self.static_config.tls_config.secret_key -927 } -928 -929 /// Returns the endpoint id of this endpoint. -930 /// -931 /// This ID is the unique addressing information of this endpoint and other peers must know -932 /// it to be able to connect to this endpoint. -933 pub fn id(&self) -> EndpointId { -934 self.static_config.tls_config.secret_key.public() -935 } -936 -937 /// Returns the current [`EndpointAddr`]. -938 /// As long as the endpoint was able to bind to a network interface, some -939 /// local addresses will be available. -940 /// -941 /// The state of other fields depends on the state of networking and connectivity. -942 /// Use the [`Endpoint::online`] method to ensure that the endpoint is considered -943 /// "online" (has contacted a relay server) before calling this method, if you want -944 /// to ensure that the `EndpointAddr` will contain enough information to allow this endpoint -945 /// to be dialable by a remote endpoint over the internet. -946 /// -947 /// You can use the [`Endpoint::watch_addr`] method to get updates when the `EndpointAddr` -948 /// changes. -949 pub fn addr(&self) -> EndpointAddr { -950 self.watch_addr().get() -951 } -952 -953 /// Returns a [`Watcher`] for the current [`EndpointAddr`] for this endpoint. -954 /// -955 /// The observed [`EndpointAddr`] will have the current [`RelayUrl`] and direct addresses. +924 // # Getter methods for properties of this Endpoint itself. +925 +926 /// Returns the secret_key of this endpoint. +927 pub fn secret_key(&self) -> &SecretKey { +928 &self.static_config.tls_config.secret_key +929 } +930 +931 /// Returns the endpoint id of this endpoint. +932 /// +933 /// This ID is the unique addressing information of this endpoint and other peers must know +934 /// it to be able to connect to this endpoint. +935 pub fn id(&self) -> EndpointId { +936 self.static_config.tls_config.secret_key.public() +937 } +938 +939 /// Returns the current [`EndpointAddr`]. +940 /// As long as the endpoint was able to bind to a network interface, some +941 /// local addresses will be available. +942 /// +943 /// The state of other fields depends on the state of networking and connectivity. +944 /// Use the [`Endpoint::online`] method to ensure that the endpoint is considered +945 /// "online" (has contacted a relay server) before calling this method, if you want +946 /// to ensure that the `EndpointAddr` will contain enough information to allow this endpoint +947 /// to be dialable by a remote endpoint over the internet. +948 /// +949 /// You can use the [`Endpoint::watch_addr`] method to get updates when the `EndpointAddr` +950 /// changes. +951 pub fn addr(&self) -> EndpointAddr { +952 self.watch_addr().get() +953 } +954 +955 /// Returns a [`Watcher`] for the current [`EndpointAddr`] for this endpoint. 956 /// -957 /// ```no_run -958 /// # async fn wrapper() -> n0_error::Result<()> { -959 /// use iroh::{Endpoint, Watcher}; -960 /// -961 /// let endpoint = Endpoint::builder() -962 /// .alpns(vec![b"my-alpn".to_vec()]) -963 /// .bind() -964 /// .await?; -965 /// let endpoint_addr = endpoint.watch_addr().get(); -966 /// # let _ = endpoint_addr; -967 /// # Ok(()) -968 /// # } -969 /// ``` -970 /// -971 /// The [`Endpoint::online`] method can be used as a convenience method to -972 /// understand if the endpoint has ever been considered "online". But after -973 /// that initial call to [`Endpoint::online`], to understand if your -974 /// endpoint is no longer able to be connected to by endpoints outside -975 /// of the private or local network, watch for changes in it's [`EndpointAddr`]. -976 /// If there are no `addrs`in the [`EndpointAddr`], you may not be dialable by other endpoints -977 /// on the internet. -978 /// -979 /// -980 /// The `EndpointAddr` will change as: -981 /// - network conditions change -982 /// - the endpoint connects to a relay server -983 /// - the endpoint changes its preferred relay server -984 /// - more addresses are discovered for this endpoint -985 /// -986 /// [`RelayUrl`]: crate::RelayUrl -987 #[cfg(not(wasm_browser))] -988 pub fn watch_addr(&self) -> impl n0_watcher::Watcher<Value = EndpointAddr> + use<> { -989 let watch_addrs = self.msock.ip_addrs(); -990 let watch_relay = self.msock.home_relay(); -991 let endpoint_id = self.id(); -992 -993 watch_addrs.or(watch_relay).map(move |(addrs, relays)| { -994 EndpointAddr::from_parts( -995 endpoint_id, -996 relays -997 .into_iter() -998 .map(TransportAddr::Relay) -999 .chain(addrs.into_iter().map(|x| TransportAddr::Ip(x.addr))), -1000 ) -1001 }) -1002 } -1003 -1004 /// Returns a [`Watcher`] for the current [`EndpointAddr`] for this endpoint. -1005 /// -1006 /// When compiled to Wasm, this function returns a watcher that initializes -1007 /// with an [`EndpointAddr`] that only contains a relay URL, but no direct addresses, -1008 /// as there are no APIs for directly using sockets in browsers. -1009 #[cfg(wasm_browser)] -1010 pub fn watch_addr(&self) -> impl n0_watcher::Watcher<Value = EndpointAddr> + use<> { -1011 // In browsers, there will never be any direct addresses, so we wait -1012 // for the home relay instead. This makes the `EndpointAddr` have *some* way -1013 // of connecting to us. -1014 let watch_relay = self.msock.home_relay(); -1015 let endpoint_id = self.id(); -1016 watch_relay.map(move |mut relays| { -1017 EndpointAddr::from_parts(endpoint_id, relays.into_iter().map(TransportAddr::Relay)) -1018 }) -1019 } -1020 -1021 /// A convenience method that waits for the endpoint to be considered "online". -1022 /// -1023 /// This currently means at least one relay server was connected, -1024 /// and at least one local IP address is available. -1025 /// Even if no relays are configured, this will still wait for a relay connection. -1026 /// -1027 /// Once this has been resolved the first time, this will always immediately resolve. +957 /// The observed [`EndpointAddr`] will have the current [`RelayUrl`] and direct addresses. +958 /// +959 /// ```no_run +960 /// # async fn wrapper() -> n0_error::Result<()> { +961 /// use iroh::{Endpoint, Watcher}; +962 /// +963 /// let endpoint = Endpoint::builder() +964 /// .alpns(vec![b"my-alpn".to_vec()]) +965 /// .bind() +966 /// .await?; +967 /// let endpoint_addr = endpoint.watch_addr().get(); +968 /// # let _ = endpoint_addr; +969 /// # Ok(()) +970 /// # } +971 /// ``` +972 /// +973 /// The [`Endpoint::online`] method can be used as a convenience method to +974 /// understand if the endpoint has ever been considered "online". But after +975 /// that initial call to [`Endpoint::online`], to understand if your +976 /// endpoint is no longer able to be connected to by endpoints outside +977 /// of the private or local network, watch for changes in it's [`EndpointAddr`]. +978 /// If there are no `addrs`in the [`EndpointAddr`], you may not be dialable by other endpoints +979 /// on the internet. +980 /// +981 /// +982 /// The `EndpointAddr` will change as: +983 /// - network conditions change +984 /// - the endpoint connects to a relay server +985 /// - the endpoint changes its preferred relay server +986 /// - more addresses are discovered for this endpoint +987 /// +988 /// [`RelayUrl`]: crate::RelayUrl +989 #[cfg(not(wasm_browser))] +990 pub fn watch_addr(&self) -> impl n0_watcher::Watcher<Value = EndpointAddr> + use<> { +991 let watch_addrs = self.msock.ip_addrs(); +992 let watch_relay = self.msock.home_relay(); +993 let endpoint_id = self.id(); +994 +995 watch_addrs.or(watch_relay).map(move |(addrs, relays)| { +996 EndpointAddr::from_parts( +997 endpoint_id, +998 relays +999 .into_iter() +1000 .map(TransportAddr::Relay) +1001 .chain(addrs.into_iter().map(|x| TransportAddr::Ip(x.addr))), +1002 ) +1003 }) +1004 } +1005 +1006 /// Returns a [`Watcher`] for the current [`EndpointAddr`] for this endpoint. +1007 /// +1008 /// When compiled to Wasm, this function returns a watcher that initializes +1009 /// with an [`EndpointAddr`] that only contains a relay URL, but no direct addresses, +1010 /// as there are no APIs for directly using sockets in browsers. +1011 #[cfg(wasm_browser)] +1012 pub fn watch_addr(&self) -> impl n0_watcher::Watcher<Value = EndpointAddr> + use<> { +1013 // In browsers, there will never be any direct addresses, so we wait +1014 // for the home relay instead. This makes the `EndpointAddr` have *some* way +1015 // of connecting to us. +1016 let watch_relay = self.msock.home_relay(); +1017 let endpoint_id = self.id(); +1018 watch_relay.map(move |mut relays| { +1019 EndpointAddr::from_parts(endpoint_id, relays.into_iter().map(TransportAddr::Relay)) +1020 }) +1021 } +1022 +1023 /// A convenience method that waits for the endpoint to be considered "online". +1024 /// +1025 /// This currently means at least one relay server was connected, +1026 /// and at least one local IP address is available. +1027 /// Even if no relays are configured, this will still wait for a relay connection. 1028 /// -1029 /// This has no timeout, so if that is needed, you need to wrap it in a -1030 /// timeout. We recommend using a timeout close to -1031 /// [`crate::NET_REPORT_TIMEOUT`]s, so you can be sure that at least one -1032 /// [`crate::NetReport`] has been attempted. -1033 /// -1034 /// To understand if the endpoint has gone back "offline", -1035 /// you must use the [`Endpoint::watch_addr`] method, to -1036 /// get information on the current relay and direct address information. -1037 /// -1038 /// In the common case where the endpoint's configured relay servers are -1039 /// only accessible via a wide area network (WAN) connection, this method -1040 /// will await indefinitely when the endpoint has no WAN connection. If you're -1041 /// writing an app that's designed to work without a WAN connection, defer -1042 /// any calls to `online` as long as possible, or avoid calling `online` -1043 /// entirely. -1044 /// -1045 /// The online method does not interact with [`crate::discovery::Discovery`] -1046 /// services, which means that any discovery service that relies on a WAN -1047 /// connection is independent of the endpoint's online status. -1048 /// -1049 /// # Examples +1029 /// Once this has been resolved the first time, this will always immediately resolve. +1030 /// +1031 /// This has no timeout, so if that is needed, you need to wrap it in a +1032 /// timeout. We recommend using a timeout close to +1033 /// [`crate::NET_REPORT_TIMEOUT`]s, so you can be sure that at least one +1034 /// [`crate::NetReport`] has been attempted. +1035 /// +1036 /// To understand if the endpoint has gone back "offline", +1037 /// you must use the [`Endpoint::watch_addr`] method, to +1038 /// get information on the current relay and direct address information. +1039 /// +1040 /// In the common case where the endpoint's configured relay servers are +1041 /// only accessible via a wide area network (WAN) connection, this method +1042 /// will await indefinitely when the endpoint has no WAN connection. If you're +1043 /// writing an app that's designed to work without a WAN connection, defer +1044 /// any calls to `online` as long as possible, or avoid calling `online` +1045 /// entirely. +1046 /// +1047 /// The online method does not interact with [`crate::discovery::Discovery`] +1048 /// services, which means that any discovery service that relies on a WAN +1049 /// connection is independent of the endpoint's online status. 1050 /// -1051 /// ```no run -1052 /// use iroh::Endpoint; -1053 /// -1054 /// #[tokio::main] -1055 /// async fn main() { -1056 /// // After this await returns, the endpoint is bound to a local socket. -1057 /// // It can be dialed, but almost certainly hasn't finished picking a -1058 /// // relay. -1059 /// let endpoint = Endpoint::bind().await; -1060 /// -1061 /// // After this await returns we have a connection to at least one relay -1062 /// // and holepunching should work as expected. -1063 /// endpoint.online().await; -1064 /// } -1065 /// ``` -1066 pub async fn online(&self) { -1067 self.msock.home_relay().initialized().await; -1068 } -1069 -1070 /// Returns a [`Watcher`] for any net-reports run from this [`Endpoint`]. -1071 /// -1072 /// A `net-report` checks the network conditions of the [`Endpoint`], such as -1073 /// whether it is connected to the internet via Ipv4 and/or Ipv6, its NAT -1074 /// status, its latency to the relay servers, and its public addresses. -1075 /// -1076 /// The [`Endpoint`] continuously runs `net-reports` to monitor if network -1077 /// conditions have changed. This [`Watcher`] will return the latest result -1078 /// of the `net-report`. -1079 /// -1080 /// When issuing the first call to this method the first report might -1081 /// still be underway, in this case the [`Watcher`] might not be initialized -1082 /// with [`Some`] value yet. Once the net-report has been successfully -1083 /// run, the [`Watcher`] will always return [`Some`] report immediately, which -1084 /// is the most recently run `net-report`. -1085 /// -1086 /// # Examples +1051 /// # Examples +1052 /// +1053 /// ```no run +1054 /// use iroh::Endpoint; +1055 /// +1056 /// #[tokio::main] +1057 /// async fn main() { +1058 /// // After this await returns, the endpoint is bound to a local socket. +1059 /// // It can be dialed, but almost certainly hasn't finished picking a +1060 /// // relay. +1061 /// let endpoint = Endpoint::bind().await; +1062 /// +1063 /// // After this await returns we have a connection to at least one relay +1064 /// // and holepunching should work as expected. +1065 /// endpoint.online().await; +1066 /// } +1067 /// ``` +1068 pub async fn online(&self) { +1069 self.msock.home_relay().initialized().await; +1070 } +1071 +1072 /// Returns a [`Watcher`] for any net-reports run from this [`Endpoint`]. +1073 /// +1074 /// A `net-report` checks the network conditions of the [`Endpoint`], such as +1075 /// whether it is connected to the internet via Ipv4 and/or Ipv6, its NAT +1076 /// status, its latency to the relay servers, and its public addresses. +1077 /// +1078 /// The [`Endpoint`] continuously runs `net-reports` to monitor if network +1079 /// conditions have changed. This [`Watcher`] will return the latest result +1080 /// of the `net-report`. +1081 /// +1082 /// When issuing the first call to this method the first report might +1083 /// still be underway, in this case the [`Watcher`] might not be initialized +1084 /// with [`Some`] value yet. Once the net-report has been successfully +1085 /// run, the [`Watcher`] will always return [`Some`] report immediately, which +1086 /// is the most recently run `net-report`. 1087 /// -1088 /// To get the first report use [`Watcher::initialized`]: -1089 /// ```no_run -1090 /// use iroh::{Endpoint, Watcher as _}; -1091 /// -1092 /// # let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(); -1093 /// # rt.block_on(async move { -1094 /// let ep = Endpoint::bind().await.unwrap(); -1095 /// let _report = ep.net_report().initialized().await; -1096 /// # }); -1097 /// ``` -1098 #[doc(hidden)] -1099 pub fn net_report(&self) -> impl Watcher<Value = Option<NetReport>> + use<> { -1100 self.msock.net_report() -1101 } -1102 -1103 /// Returns the local socket addresses on which the underlying sockets are bound. -1104 /// -1105 /// The [`Endpoint`] always binds on an IPv4 address and also tries to bind on an IPv6 -1106 /// address if available. -1107 #[cfg(not(wasm_browser))] -1108 pub fn bound_sockets(&self) -> Vec<SocketAddr> { -1109 self.msock -1110 .local_addr() -1111 .into_iter() -1112 .filter_map(|addr| addr.into_socket_addr()) -1113 .collect() -1114 } -1115 -1116 // # Methods for less common getters. -1117 // -1118 // Partially they return things passed into the builder. -1119 -1120 /// Returns the DNS resolver used in this [`Endpoint`]. -1121 /// -1122 /// See [`Builder::dns_resolver`]. -1123 #[cfg(not(wasm_browser))] -1124 pub fn dns_resolver(&self) -> &DnsResolver { -1125 self.msock.dns_resolver() -1126 } -1127 -1128 /// Returns the discovery mechanism, if configured. -1129 /// -1130 /// See [`Builder::discovery`]. -1131 pub fn discovery(&self) -> &ConcurrentDiscovery { -1132 self.msock.discovery() -1133 } -1134 -1135 /// Returns metrics collected for this endpoint. -1136 /// -1137 /// The endpoint internally collects various metrics about its operation. -1138 /// The returned [`EndpointMetrics`] struct contains all of these metrics. -1139 /// -1140 /// You can access individual metrics directly by using the public fields: -1141 /// ```rust -1142 /// # use std::collections::BTreeMap; -1143 /// # use iroh::endpoint::Endpoint; -1144 /// # async fn wrapper() -> n0_error::Result<()> { -1145 /// let endpoint = Endpoint::bind().await?; -1146 /// assert_eq!(endpoint.metrics().magicsock.recv_datagrams.get(), 0); -1147 /// # Ok(()) -1148 /// # } -1149 /// ``` -1150 /// -1151 /// [`EndpointMetrics`] implements [`MetricsGroupSet`], and each field -1152 /// implements [`MetricsGroup`]. These traits provide methods to iterate over -1153 /// the groups in the set, and over the individual metrics in each group, without having -1154 /// to access each field manually. With these methods, it is straightforward to collect -1155 /// all metrics into a map or push their values to a metrics collector. -1156 /// -1157 /// For example, the following snippet collects all metrics into a map: -1158 /// ```rust -1159 /// # use std::collections::BTreeMap; -1160 /// # use iroh_metrics::{Metric, MetricsGroup, MetricValue, MetricsGroupSet}; -1161 /// # use iroh::endpoint::Endpoint; -1162 /// # async fn wrapper() -> n0_error::Result<()> { -1163 /// let endpoint = Endpoint::bind().await?; -1164 /// let metrics: BTreeMap<String, MetricValue> = endpoint -1165 /// .metrics() -1166 /// .iter() -1167 /// .map(|(group, metric)| { -1168 /// let name = [group, metric.name()].join(":"); -1169 /// (name, metric.value()) -1170 /// }) -1171 /// .collect(); -1172 /// -1173 /// assert_eq!(metrics["magicsock:recv_datagrams"], MetricValue::Counter(0)); -1174 /// # Ok(()) -1175 /// # } -1176 /// ``` -1177 /// -1178 /// The metrics can also be encoded into the OpenMetrics text format, as used by Prometheus. -1179 /// To do so, use the [`iroh_metrics::Registry`], add the endpoint metrics to the -1180 /// registry with [`Registry::register_all`], and encode the metrics to a string with -1181 /// [`encode_openmetrics_to_string`]: -1182 /// ```rust -1183 /// # use iroh_metrics::{Registry, MetricsSource}; -1184 /// # use iroh::endpoint::Endpoint; -1185 /// # async fn wrapper() -> n0_error::Result<()> { -1186 /// let endpoint = Endpoint::bind().await?; -1187 /// let mut registry = Registry::default(); -1188 /// registry.register_all(endpoint.metrics()); -1189 /// let s = registry.encode_openmetrics_to_string()?; -1190 /// assert!(s.contains(r#"TYPE magicsock_recv_datagrams counter"#)); -1191 /// assert!(s.contains(r#"magicsock_recv_datagrams_total 0"#)); -1192 /// # Ok(()) -1193 /// # } -1194 /// ``` -1195 /// -1196 /// Through a registry, you can also add labels or prefixes to metrics with -1197 /// [`Registry::sub_registry_with_label`] or [`Registry::sub_registry_with_prefix`]. -1198 /// Furthermore, [`iroh_metrics::service`] provides functions to easily start services -1199 /// to serve the metrics with a HTTP server, dump them to a file, or push them -1200 /// to a Prometheus gateway. -1201 /// -1202 /// For example, the following snippet launches an HTTP server that serves the metrics in the -1203 /// OpenMetrics text format: -1204 /// ```no_run -1205 /// # use std::{sync::{Arc, RwLock}, time::Duration}; -1206 /// # use iroh_metrics::{Registry, MetricsSource}; -1207 /// # use iroh::endpoint::Endpoint; -1208 /// # use n0_error::{StackResultExt, StdResultExt}; -1209 /// # async fn wrapper() -> n0_error::Result<()> { -1210 /// // Create a registry, wrapped in a read-write lock so that we can register and serve -1211 /// // the metrics independently. -1212 /// let registry = Arc::new(RwLock::new(Registry::default())); -1213 /// // Spawn a task to serve the metrics on an OpenMetrics HTTP endpoint. -1214 /// let metrics_task = tokio::task::spawn({ -1215 /// let registry = registry.clone(); -1216 /// async move { -1217 /// let addr = "0.0.0.0:9100".parse().unwrap(); -1218 /// iroh_metrics::service::start_metrics_server(addr, registry).await -1219 /// } -1220 /// }); -1221 /// -1222 /// // Spawn an endpoint and add the metrics to the registry. -1223 /// let endpoint = Endpoint::bind().await?; -1224 /// registry.write().unwrap().register_all(endpoint.metrics()); -1225 /// -1226 /// // Wait for the metrics server to bind, then fetch the metrics via HTTP. -1227 /// tokio::time::sleep(Duration::from_millis(500)); -1228 /// let res = reqwest::get("http://localhost:9100/metrics") -1229 /// .await -1230 /// .std_context("get")? -1231 /// .text() -1232 /// .await -1233 /// .std_context("text")?; -1234 /// -1235 /// assert!(res.contains(r#"TYPE magicsock_recv_datagrams counter"#)); -1236 /// assert!(res.contains(r#"magicsock_recv_datagrams_total 0"#)); -1237 /// # metrics_task.abort(); -1238 /// # Ok(()) -1239 /// # } -1240 /// ``` -1241 /// -1242 /// [`Registry`]: iroh_metrics::Registry -1243 /// [`Registry::register_all`]: iroh_metrics::Registry::register_all -1244 /// [`Registry::sub_registry_with_label`]: iroh_metrics::Registry::sub_registry_with_label -1245 /// [`Registry::sub_registry_with_prefix`]: iroh_metrics::Registry::sub_registry_with_prefix -1246 /// [`encode_openmetrics_to_string`]: iroh_metrics::MetricsSource::encode_openmetrics_to_string -1247 /// [`MetricsGroup`]: iroh_metrics::MetricsGroup -1248 /// [`MetricsGroupSet`]: iroh_metrics::MetricsGroupSet -1249 #[cfg(feature = "metrics")] -1250 pub fn metrics(&self) -> &EndpointMetrics { -1251 &self.msock.metrics -1252 } -1253 -1254 /// Returns addressing information about a recently used remote endpoint. -1255 /// -1256 /// The returned [`RemoteInfo`] contains a list of all transport addresses for the remote -1257 /// that we know about. This is a snapshot in time and not a watcher. -1258 /// -1259 /// Returns `None` if the endpoint doesn't have information about the remote. -1260 /// When remote endpoints are no longer used, our endpoint will keep information around -1261 /// for a little while, and then drop it. Afterwards, this will return `None`. -1262 pub async fn remote_info(&self, endpoint_id: EndpointId) -> Option<RemoteInfo> { -1263 self.msock.remote_info(endpoint_id).await -1264 } -1265 -1266 // # Methods for less common state updates. +1088 /// # Examples +1089 /// +1090 /// To get the first report use [`Watcher::initialized`]: +1091 /// ```no_run +1092 /// use iroh::{Endpoint, Watcher as _}; +1093 /// +1094 /// # let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(); +1095 /// # rt.block_on(async move { +1096 /// let ep = Endpoint::bind().await.unwrap(); +1097 /// let _report = ep.net_report().initialized().await; +1098 /// # }); +1099 /// ``` +1100 #[doc(hidden)] +1101 pub fn net_report(&self) -> impl Watcher<Value = Option<NetReport>> + use<> { +1102 self.msock.net_report() +1103 } +1104 +1105 /// Returns the local socket addresses on which the underlying sockets are bound. +1106 /// +1107 /// The [`Endpoint`] always binds on an IPv4 address and also tries to bind on an IPv6 +1108 /// address if available. +1109 #[cfg(not(wasm_browser))] +1110 pub fn bound_sockets(&self) -> Vec<SocketAddr> { +1111 self.msock +1112 .local_addr() +1113 .into_iter() +1114 .filter_map(|addr| addr.into_socket_addr()) +1115 .collect() +1116 } +1117 +1118 // # Methods for less common getters. +1119 // +1120 // Partially they return things passed into the builder. +1121 +1122 /// Returns the DNS resolver used in this [`Endpoint`]. +1123 /// +1124 /// See [`Builder::dns_resolver`]. +1125 #[cfg(not(wasm_browser))] +1126 pub fn dns_resolver(&self) -> &DnsResolver { +1127 self.msock.dns_resolver() +1128 } +1129 +1130 /// Returns the discovery mechanism, if configured. +1131 /// +1132 /// See [`Builder::discovery`]. +1133 pub fn discovery(&self) -> &ConcurrentDiscovery { +1134 self.msock.discovery() +1135 } +1136 +1137 /// Returns metrics collected for this endpoint. +1138 /// +1139 /// The endpoint internally collects various metrics about its operation. +1140 /// The returned [`EndpointMetrics`] struct contains all of these metrics. +1141 /// +1142 /// You can access individual metrics directly by using the public fields: +1143 /// ```rust +1144 /// # use std::collections::BTreeMap; +1145 /// # use iroh::endpoint::Endpoint; +1146 /// # async fn wrapper() -> n0_error::Result<()> { +1147 /// let endpoint = Endpoint::bind().await?; +1148 /// assert_eq!(endpoint.metrics().magicsock.recv_datagrams.get(), 0); +1149 /// # Ok(()) +1150 /// # } +1151 /// ``` +1152 /// +1153 /// [`EndpointMetrics`] implements [`MetricsGroupSet`], and each field +1154 /// implements [`MetricsGroup`]. These traits provide methods to iterate over +1155 /// the groups in the set, and over the individual metrics in each group, without having +1156 /// to access each field manually. With these methods, it is straightforward to collect +1157 /// all metrics into a map or push their values to a metrics collector. +1158 /// +1159 /// For example, the following snippet collects all metrics into a map: +1160 /// ```rust +1161 /// # use std::collections::BTreeMap; +1162 /// # use iroh_metrics::{Metric, MetricsGroup, MetricValue, MetricsGroupSet}; +1163 /// # use iroh::endpoint::Endpoint; +1164 /// # async fn wrapper() -> n0_error::Result<()> { +1165 /// let endpoint = Endpoint::bind().await?; +1166 /// let metrics: BTreeMap<String, MetricValue> = endpoint +1167 /// .metrics() +1168 /// .iter() +1169 /// .map(|(group, metric)| { +1170 /// let name = [group, metric.name()].join(":"); +1171 /// (name, metric.value()) +1172 /// }) +1173 /// .collect(); +1174 /// +1175 /// assert_eq!(metrics["magicsock:recv_datagrams"], MetricValue::Counter(0)); +1176 /// # Ok(()) +1177 /// # } +1178 /// ``` +1179 /// +1180 /// The metrics can also be encoded into the OpenMetrics text format, as used by Prometheus. +1181 /// To do so, use the [`iroh_metrics::Registry`], add the endpoint metrics to the +1182 /// registry with [`Registry::register_all`], and encode the metrics to a string with +1183 /// [`encode_openmetrics_to_string`]: +1184 /// ```rust +1185 /// # use iroh_metrics::{Registry, MetricsSource}; +1186 /// # use iroh::endpoint::Endpoint; +1187 /// # async fn wrapper() -> n0_error::Result<()> { +1188 /// let endpoint = Endpoint::bind().await?; +1189 /// let mut registry = Registry::default(); +1190 /// registry.register_all(endpoint.metrics()); +1191 /// let s = registry.encode_openmetrics_to_string()?; +1192 /// assert!(s.contains(r#"TYPE magicsock_recv_datagrams counter"#)); +1193 /// assert!(s.contains(r#"magicsock_recv_datagrams_total 0"#)); +1194 /// # Ok(()) +1195 /// # } +1196 /// ``` +1197 /// +1198 /// Through a registry, you can also add labels or prefixes to metrics with +1199 /// [`Registry::sub_registry_with_label`] or [`Registry::sub_registry_with_prefix`]. +1200 /// Furthermore, [`iroh_metrics::service`] provides functions to easily start services +1201 /// to serve the metrics with a HTTP server, dump them to a file, or push them +1202 /// to a Prometheus gateway. +1203 /// +1204 /// For example, the following snippet launches an HTTP server that serves the metrics in the +1205 /// OpenMetrics text format: +1206 /// ```no_run +1207 /// # use std::{sync::{Arc, RwLock}, time::Duration}; +1208 /// # use iroh_metrics::{Registry, MetricsSource}; +1209 /// # use iroh::endpoint::Endpoint; +1210 /// # use n0_error::{StackResultExt, StdResultExt}; +1211 /// # async fn wrapper() -> n0_error::Result<()> { +1212 /// // Create a registry, wrapped in a read-write lock so that we can register and serve +1213 /// // the metrics independently. +1214 /// let registry = Arc::new(RwLock::new(Registry::default())); +1215 /// // Spawn a task to serve the metrics on an OpenMetrics HTTP endpoint. +1216 /// let metrics_task = tokio::task::spawn({ +1217 /// let registry = registry.clone(); +1218 /// async move { +1219 /// let addr = "0.0.0.0:9100".parse().unwrap(); +1220 /// iroh_metrics::service::start_metrics_server(addr, registry).await +1221 /// } +1222 /// }); +1223 /// +1224 /// // Spawn an endpoint and add the metrics to the registry. +1225 /// let endpoint = Endpoint::bind().await?; +1226 /// registry.write().unwrap().register_all(endpoint.metrics()); +1227 /// +1228 /// // Wait for the metrics server to bind, then fetch the metrics via HTTP. +1229 /// tokio::time::sleep(Duration::from_millis(500)); +1230 /// let res = reqwest::get("http://localhost:9100/metrics") +1231 /// .await +1232 /// .std_context("get")? +1233 /// .text() +1234 /// .await +1235 /// .std_context("text")?; +1236 /// +1237 /// assert!(res.contains(r#"TYPE magicsock_recv_datagrams counter"#)); +1238 /// assert!(res.contains(r#"magicsock_recv_datagrams_total 0"#)); +1239 /// # metrics_task.abort(); +1240 /// # Ok(()) +1241 /// # } +1242 /// ``` +1243 /// +1244 /// [`Registry`]: iroh_metrics::Registry +1245 /// [`Registry::register_all`]: iroh_metrics::Registry::register_all +1246 /// [`Registry::sub_registry_with_label`]: iroh_metrics::Registry::sub_registry_with_label +1247 /// [`Registry::sub_registry_with_prefix`]: iroh_metrics::Registry::sub_registry_with_prefix +1248 /// [`encode_openmetrics_to_string`]: iroh_metrics::MetricsSource::encode_openmetrics_to_string +1249 /// [`MetricsGroup`]: iroh_metrics::MetricsGroup +1250 /// [`MetricsGroupSet`]: iroh_metrics::MetricsGroupSet +1251 #[cfg(feature = "metrics")] +1252 pub fn metrics(&self) -> &EndpointMetrics { +1253 &self.msock.metrics +1254 } +1255 +1256 /// Returns addressing information about a recently used remote endpoint. +1257 /// +1258 /// The returned [`RemoteInfo`] contains a list of all transport addresses for the remote +1259 /// that we know about. This is a snapshot in time and not a watcher. +1260 /// +1261 /// Returns `None` if the endpoint doesn't have information about the remote. +1262 /// When remote endpoints are no longer used, our endpoint will keep information around +1263 /// for a little while, and then drop it. Afterwards, this will return `None`. +1264 pub async fn remote_info(&self, endpoint_id: EndpointId) -> Option<RemoteInfo> { +1265 self.msock.remote_info(endpoint_id).await +1266 } 1267 -1268 /// Notifies the system of potential network changes. -1269 /// -1270 /// On many systems iroh is able to detect network changes by itself, however -1271 /// some systems like android do not expose this functionality to native code. -1272 /// Android does however provide this functionality to Java code. This -1273 /// function allows for notifying iroh of any potential network changes like -1274 /// this. -1275 /// -1276 /// Even when the network did not change, or iroh was already able to detect -1277 /// the network change itself, there is no harm in calling this function. -1278 pub async fn network_change(&self) { -1279 self.msock.network_change().await; -1280 } -1281 -1282 // # Methods to update internal state. +1268 // # Methods for less common state updates. +1269 +1270 /// Notifies the system of potential network changes. +1271 /// +1272 /// On many systems iroh is able to detect network changes by itself, however +1273 /// some systems like android do not expose this functionality to native code. +1274 /// Android does however provide this functionality to Java code. This +1275 /// function allows for notifying iroh of any potential network changes like +1276 /// this. +1277 /// +1278 /// Even when the network did not change, or iroh was already able to detect +1279 /// the network change itself, there is no harm in calling this function. +1280 pub async fn network_change(&self) { +1281 self.msock.network_change().await; +1282 } 1283 -1284 /// Sets the initial user-defined data to be published in discovery services for this endpoint. -1285 /// -1286 /// If the user-defined data passed to this function is different to the previous one, -1287 /// the endpoint will republish its endpoint info to the configured discovery services. -1288 /// -1289 /// See also [`Builder::user_data_for_discovery`] for setting an initial value when -1290 /// building the endpoint. -1291 pub fn set_user_data_for_discovery(&self, user_data: Option<UserData>) { -1292 self.msock.set_user_data_for_discovery(user_data); -1293 } -1294 -1295 // # Methods for terminating the endpoint. +1284 // # Methods to update internal state. +1285 +1286 /// Sets the initial user-defined data to be published in discovery services for this endpoint. +1287 /// +1288 /// If the user-defined data passed to this function is different to the previous one, +1289 /// the endpoint will republish its endpoint info to the configured discovery services. +1290 /// +1291 /// See also [`Builder::user_data_for_discovery`] for setting an initial value when +1292 /// building the endpoint. +1293 pub fn set_user_data_for_discovery(&self, user_data: Option<UserData>) { +1294 self.msock.set_user_data_for_discovery(user_data); +1295 } 1296 -1297 /// Closes the QUIC endpoint and the magic socket. -1298 /// -1299 /// This will close any remaining open [`Connection`]s with an error code -1300 /// of `0` and an empty reason. Though it is best practice to close those -1301 /// explicitly before with a custom error code and reason. -1302 /// -1303 /// It will then make a best effort to wait for all close notifications to be -1304 /// acknowledged by the peers, re-transmitting them if needed. This ensures the -1305 /// peers are aware of the closed connections instead of having to wait for a timeout -1306 /// on the connection. Once all connections are closed or timed out, the future -1307 /// finishes. -1308 /// -1309 /// The maximum time-out that this future will wait for depends on QUIC transport -1310 /// configurations of non-drained connections at the time of calling, and their current -1311 /// estimates of round trip time. With default parameters and a conservative estimate -1312 /// of round trip time, this call's future should take 3 seconds to resolve in cases of -1313 /// bad connectivity or failed connections. In the usual case, this call's future should -1314 /// return much more quickly. -1315 /// -1316 /// It is highly recommended you *do* wait for this close call to finish, if possible. -1317 /// Not doing so will make connections that were still open while closing the endpoint -1318 /// time out on the remote end. Thus remote ends will assume connections to have failed -1319 /// even if all application data was transmitted successfully. -1320 /// -1321 /// Note: Someone used to closing TCP sockets might wonder why it is necessary to wait -1322 /// for timeouts when closing QUIC endpoints, while they don't have to do this for TCP -1323 /// sockets. This is due to QUIC and its acknowledgments being implemented in user-land, -1324 /// while TCP sockets usually get closed and drained by the operating system in the -1325 /// kernel during the "Time-Wait" period of the TCP socket. -1326 /// -1327 /// Be aware however that the underlying UDP sockets are only closed once all clones of -1328 /// the the respective [`Endpoint`] are dropped. -1329 pub async fn close(&self) { -1330 self.msock.close().await; -1331 } -1332 -1333 /// Check if this endpoint is still alive, or already closed. -1334 pub fn is_closed(&self) -> bool { -1335 self.msock.is_closed() -1336 } -1337 -1338 /// Create a [`ServerConfigBuilder`] for this endpoint that includes the given alpns. -1339 /// -1340 /// Use the [`ServerConfigBuilder`] to customize the [`ServerConfig`] connection configuration -1341 /// for a connection accepted using the [`Incoming::accept_with`] method. -1342 pub fn create_server_config_builder(&self, alpns: Vec<Vec<u8>>) -> ServerConfigBuilder { -1343 let inner = self.static_config.create_server_config(alpns); -1344 ServerConfigBuilder::new(inner, self.static_config.transport_config.clone()) -1345 } -1346 -1347 // # Remaining private methods +1297 // # Methods for terminating the endpoint. +1298 +1299 /// Closes the QUIC endpoint and the magic socket. +1300 /// +1301 /// This will close any remaining open [`Connection`]s with an error code +1302 /// of `0` and an empty reason. Though it is best practice to close those +1303 /// explicitly before with a custom error code and reason. +1304 /// +1305 /// It will then make a best effort to wait for all close notifications to be +1306 /// acknowledged by the peers, re-transmitting them if needed. This ensures the +1307 /// peers are aware of the closed connections instead of having to wait for a timeout +1308 /// on the connection. Once all connections are closed or timed out, the future +1309 /// finishes. +1310 /// +1311 /// The maximum time-out that this future will wait for depends on QUIC transport +1312 /// configurations of non-drained connections at the time of calling, and their current +1313 /// estimates of round trip time. With default parameters and a conservative estimate +1314 /// of round trip time, this call's future should take 3 seconds to resolve in cases of +1315 /// bad connectivity or failed connections. In the usual case, this call's future should +1316 /// return much more quickly. +1317 /// +1318 /// It is highly recommended you *do* wait for this close call to finish, if possible. +1319 /// Not doing so will make connections that were still open while closing the endpoint +1320 /// time out on the remote end. Thus remote ends will assume connections to have failed +1321 /// even if all application data was transmitted successfully. +1322 /// +1323 /// Note: Someone used to closing TCP sockets might wonder why it is necessary to wait +1324 /// for timeouts when closing QUIC endpoints, while they don't have to do this for TCP +1325 /// sockets. This is due to QUIC and its acknowledgments being implemented in user-land, +1326 /// while TCP sockets usually get closed and drained by the operating system in the +1327 /// kernel during the "Time-Wait" period of the TCP socket. +1328 /// +1329 /// Be aware however that the underlying UDP sockets are only closed once all clones of +1330 /// the the respective [`Endpoint`] are dropped. +1331 pub async fn close(&self) { +1332 self.msock.close().await; +1333 } +1334 +1335 /// Check if this endpoint is still alive, or already closed. +1336 pub fn is_closed(&self) -> bool { +1337 self.msock.is_closed() +1338 } +1339 +1340 /// Create a [`ServerConfigBuilder`] for this endpoint that includes the given alpns. +1341 /// +1342 /// Use the [`ServerConfigBuilder`] to customize the [`ServerConfig`] connection configuration +1343 /// for a connection accepted using the [`Incoming::accept_with`] method. +1344 pub fn create_server_config_builder(&self, alpns: Vec<Vec<u8>>) -> ServerConfigBuilder { +1345 let inner = self.static_config.create_server_config(alpns); +1346 ServerConfigBuilder::new(inner, self.static_config.transport_config.clone()) +1347 } 1348 -1349 #[cfg(test)] -1350 pub(crate) fn magic_sock(&self) -> Handle { -1351 self.msock.clone() -1352 } -1353 #[cfg(test)] -1354 pub(crate) fn endpoint(&self) -> &quinn::Endpoint { -1355 self.msock.endpoint() -1356 } -1357} -1358 -1359/// Options for the [`Endpoint::connect_with_opts`] function. -1360#[derive(Default, Debug, Clone)] -1361pub struct ConnectOptions { -1362 transport_config: Option<QuicTransportConfig>, -1363 additional_alpns: Vec<Vec<u8>>, -1364} -1365 -1366impl ConnectOptions { -1367 /// Initializes new connection options. -1368 /// -1369 /// By default, the connection will use the same options -1370 /// as [`Endpoint::connect`], e.g. a default [`QuicTransportConfig`]. -1371 pub fn new() -> Self { -1372 Self::default() -1373 } -1374 -1375 /// Sets the QUIC transport config options for this connection. -1376 pub fn with_transport_config(mut self, transport_config: QuicTransportConfig) -> Self { -1377 self.transport_config = Some(transport_config); -1378 self -1379 } -1380 -1381 /// Sets [ALPN] identifiers that should be signaled as supported on connection, *in -1382 /// addition* to the main [ALPN] identifier used in [`Endpoint::connect_with_opts`]. -1383 /// -1384 /// This allows connecting to servers that may only support older versions of your -1385 /// protocol. In this case, you would add the older [ALPN] identifiers with this -1386 /// function. -1387 /// -1388 /// You'll know the final negotiated [ALPN] identifier once your connection was -1389 /// established using [`Connection::alpn`], or even slightly earlier in the -1390 /// handshake by using [`Connecting::alpn`]. -1391 /// The negotiated [ALPN] identifier may be any of the [ALPN] identifiers in this -1392 /// list or the main [ALPN] used in [`Endpoint::connect_with_opts`]. -1393 /// -1394 /// The [ALPN] identifier order on the connect side doesn't matter, since it's the -1395 /// accept side that determines the protocol. -1396 /// -1397 /// For setting the supported [ALPN] identifiers on the accept side, see the endpoint -1398 /// builder's [`Builder::alpns`] function. -1399 /// -1400 /// [ALPN]: https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation -1401 pub fn with_additional_alpns(mut self, alpns: Vec<Vec<u8>>) -> Self { -1402 self.additional_alpns = alpns; -1403 self -1404 } -1405} -1406 -1407/// Read a proxy url from the environment, in this order -1408/// -1409/// - `HTTP_PROXY` -1410/// - `http_proxy` -1411/// - `HTTPS_PROXY` -1412/// - `https_proxy` -1413fn proxy_url_from_env() -> Option<Url> { -1414 if let Some(url) = std::env::var("HTTP_PROXY") -1415 .ok() -1416 .and_then(|s| s.parse::<Url>().ok()) -1417 { -1418 if is_cgi() { -1419 warn!("HTTP_PROXY environment variable ignored in CGI"); -1420 } else { -1421 return Some(url); -1422 } -1423 } -1424 if let Some(url) = std::env::var("http_proxy") -1425 .ok() -1426 .and_then(|s| s.parse::<Url>().ok()) -1427 { -1428 return Some(url); -1429 } -1430 if let Some(url) = std::env::var("HTTPS_PROXY") -1431 .ok() -1432 .and_then(|s| s.parse::<Url>().ok()) -1433 { -1434 return Some(url); -1435 } -1436 if let Some(url) = std::env::var("https_proxy") -1437 .ok() -1438 .and_then(|s| s.parse::<Url>().ok()) -1439 { -1440 return Some(url); -1441 } -1442 -1443 None -1444} -1445 -1446/// Configuration of the relay servers for an [`Endpoint`]. -1447#[derive(Debug, Clone, PartialEq, Eq)] -1448pub enum RelayMode { -1449 /// Disable relay servers completely. -1450 /// This means that neither listening nor dialing relays will be available. -1451 Disabled, -1452 /// Use the default relay map, with production relay servers from n0. -1453 /// -1454 /// See [`crate::defaults::prod`] for the severs used. -1455 Default, -1456 /// Use the staging relay servers from n0. -1457 Staging, -1458 /// Use a custom relay map. -1459 Custom(RelayMap), -1460} -1461 -1462impl RelayMode { -1463 /// Returns the relay map for this mode. -1464 pub fn relay_map(&self) -> RelayMap { -1465 match self { -1466 RelayMode::Disabled => RelayMap::empty(), -1467 RelayMode::Default => crate::defaults::prod::default_relay_map(), -1468 RelayMode::Staging => crate::defaults::staging::default_relay_map(), -1469 RelayMode::Custom(relay_map) => relay_map.clone(), -1470 } -1471 } -1472 -1473 /// Create a custom relay mode from a list of [`RelayUrl`]s. -1474 /// -1475 /// # Example +1349 // # Remaining private methods +1350 +1351 #[cfg(test)] +1352 pub(crate) fn magic_sock(&self) -> Handle { +1353 self.msock.clone() +1354 } +1355 #[cfg(test)] +1356 pub(crate) fn endpoint(&self) -> &quinn::Endpoint { +1357 self.msock.endpoint() +1358 } +1359} +1360 +1361/// Options for the [`Endpoint::connect_with_opts`] function. +1362#[derive(Default, Debug, Clone)] +1363pub struct ConnectOptions { +1364 transport_config: Option<QuicTransportConfig>, +1365 additional_alpns: Vec<Vec<u8>>, +1366} +1367 +1368impl ConnectOptions { +1369 /// Initializes new connection options. +1370 /// +1371 /// By default, the connection will use the same options +1372 /// as [`Endpoint::connect`], e.g. a default [`QuicTransportConfig`]. +1373 pub fn new() -> Self { +1374 Self::default() +1375 } +1376 +1377 /// Sets the QUIC transport config options for this connection. +1378 pub fn with_transport_config(mut self, transport_config: QuicTransportConfig) -> Self { +1379 self.transport_config = Some(transport_config); +1380 self +1381 } +1382 +1383 /// Sets [ALPN] identifiers that should be signaled as supported on connection, *in +1384 /// addition* to the main [ALPN] identifier used in [`Endpoint::connect_with_opts`]. +1385 /// +1386 /// This allows connecting to servers that may only support older versions of your +1387 /// protocol. In this case, you would add the older [ALPN] identifiers with this +1388 /// function. +1389 /// +1390 /// You'll know the final negotiated [ALPN] identifier once your connection was +1391 /// established using [`Connection::alpn`], or even slightly earlier in the +1392 /// handshake by using [`Connecting::alpn`]. +1393 /// The negotiated [ALPN] identifier may be any of the [ALPN] identifiers in this +1394 /// list or the main [ALPN] used in [`Endpoint::connect_with_opts`]. +1395 /// +1396 /// The [ALPN] identifier order on the connect side doesn't matter, since it's the +1397 /// accept side that determines the protocol. +1398 /// +1399 /// For setting the supported [ALPN] identifiers on the accept side, see the endpoint +1400 /// builder's [`Builder::alpns`] function. +1401 /// +1402 /// [ALPN]: https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation +1403 pub fn with_additional_alpns(mut self, alpns: Vec<Vec<u8>>) -> Self { +1404 self.additional_alpns = alpns; +1405 self +1406 } +1407} +1408 +1409/// Read a proxy url from the environment, in this order +1410/// +1411/// - `HTTP_PROXY` +1412/// - `http_proxy` +1413/// - `HTTPS_PROXY` +1414/// - `https_proxy` +1415fn proxy_url_from_env() -> Option<Url> { +1416 if let Some(url) = std::env::var("HTTP_PROXY") +1417 .ok() +1418 .and_then(|s| s.parse::<Url>().ok()) +1419 { +1420 if is_cgi() { +1421 warn!("HTTP_PROXY environment variable ignored in CGI"); +1422 } else { +1423 return Some(url); +1424 } +1425 } +1426 if let Some(url) = std::env::var("http_proxy") +1427 .ok() +1428 .and_then(|s| s.parse::<Url>().ok()) +1429 { +1430 return Some(url); +1431 } +1432 if let Some(url) = std::env::var("HTTPS_PROXY") +1433 .ok() +1434 .and_then(|s| s.parse::<Url>().ok()) +1435 { +1436 return Some(url); +1437 } +1438 if let Some(url) = std::env::var("https_proxy") +1439 .ok() +1440 .and_then(|s| s.parse::<Url>().ok()) +1441 { +1442 return Some(url); +1443 } +1444 +1445 None +1446} +1447 +1448/// Configuration of the relay servers for an [`Endpoint`]. +1449#[derive(Debug, Clone, PartialEq, Eq)] +1450pub enum RelayMode { +1451 /// Disable relay servers completely. +1452 /// This means that neither listening nor dialing relays will be available. +1453 Disabled, +1454 /// Use the default relay map, with production relay servers from n0. +1455 /// +1456 /// See [`crate::defaults::prod`] for the severs used. +1457 Default, +1458 /// Use the staging relay servers from n0. +1459 Staging, +1460 /// Use a custom relay map. +1461 Custom(RelayMap), +1462} +1463 +1464impl RelayMode { +1465 /// Returns the relay map for this mode. +1466 pub fn relay_map(&self) -> RelayMap { +1467 match self { +1468 RelayMode::Disabled => RelayMap::empty(), +1469 RelayMode::Default => crate::defaults::prod::default_relay_map(), +1470 RelayMode::Staging => crate::defaults::staging::default_relay_map(), +1471 RelayMode::Custom(relay_map) => relay_map.clone(), +1472 } +1473 } +1474 +1475 /// Create a custom relay mode from a list of [`RelayUrl`]s. 1476 /// -1477 /// ``` -1478 /// # fn main() -> n0_error::Result<()> { -1479 /// # use iroh::RelayMode; -1480 /// RelayMode::custom([ -1481 /// "https://use1-1.relay.n0.iroh-canary.iroh.link.".parse()?, -1482 /// "https://euw-1.relay.n0.iroh-canary.iroh.link.".parse()?, -1483 /// ]); -1484 /// # Ok(()) } -1485 /// ``` -1486 pub fn custom(map: impl IntoIterator<Item = RelayUrl>) -> Self { -1487 let m = RelayMap::from_iter(map); -1488 Self::Custom(m) -1489 } -1490} -1491 -1492/// Environment variable to force the use of staging relays. -1493pub const ENV_FORCE_STAGING_RELAYS: &str = "IROH_FORCE_STAGING_RELAYS"; -1494 -1495/// Returns `true` if the use of staging relays is forced. -1496pub fn force_staging_infra() -> bool { -1497 matches!(std::env::var(ENV_FORCE_STAGING_RELAYS), Ok(value) if !value.is_empty()) -1498} -1499 -1500/// Returns the default relay mode. -1501/// -1502/// If the `IROH_FORCE_STAGING_RELAYS` environment variable is non empty, it will return `RelayMode::Staging`. -1503/// Otherwise, it will return `RelayMode::Default`. -1504pub fn default_relay_mode() -> RelayMode { -1505 // Use staging in testing -1506 match force_staging_infra() { -1507 true => RelayMode::Staging, -1508 false => RelayMode::Default, -1509 } -1510} -1511 -1512/// Check if we are being executed in a CGI context. -1513/// -1514/// If so, a malicious client can send the `Proxy:` header, and it will -1515/// be in the `HTTP_PROXY` env var. So we don't use it :) -1516fn is_cgi() -> bool { -1517 std::env::var_os("REQUEST_METHOD").is_some() -1518} -1519 -1520// TODO: These tests could still be flaky, lets fix that: -1521// https://github.com/n0-computer/iroh/issues/1183 -1522#[cfg(test)] -1523mod tests { -1524 use std::{ -1525 io, -1526 net::{IpAddr, Ipv4Addr}, -1527 str::FromStr, -1528 sync::Arc, -1529 time::{Duration, Instant}, -1530 }; -1531 -1532 use iroh_base::{EndpointAddr, EndpointId, RelayUrl, SecretKey, TransportAddr}; -1533 use n0_error::{AnyError as Error, Result, StdResultExt}; -1534 use n0_future::{BufferedStreamExt, StreamExt, stream, time}; -1535 use n0_tracing_test::traced_test; -1536 use n0_watcher::Watcher; -1537 use rand::SeedableRng; -1538 use tokio::sync::oneshot; -1539 use tracing::{Instrument, debug_span, info, info_span, instrument}; -1540 -1541 use super::Endpoint; -1542 use crate::{ -1543 RelayMap, RelayMode, -1544 discovery::static_provider::StaticProvider, -1545 endpoint::{ -1546 ApplicationClose, BindError, BindOpts, ConnectOptions, Connection, ConnectionError, -1547 }, -1548 magicsock::CreateHandleError, -1549 protocol::{AcceptError, ProtocolHandler, Router}, -1550 test_utils::{QlogFileGroup, run_relay_server, run_relay_server_with}, -1551 }; -1552 -1553 const TEST_ALPN: &[u8] = b"n0/iroh/test"; +1477 /// # Example +1478 /// +1479 /// ``` +1480 /// # fn main() -> n0_error::Result<()> { +1481 /// # use iroh::RelayMode; +1482 /// RelayMode::custom([ +1483 /// "https://use1-1.relay.n0.iroh-canary.iroh.link.".parse()?, +1484 /// "https://euw-1.relay.n0.iroh-canary.iroh.link.".parse()?, +1485 /// ]); +1486 /// # Ok(()) } +1487 /// ``` +1488 pub fn custom(map: impl IntoIterator<Item = RelayUrl>) -> Self { +1489 let m = RelayMap::from_iter(map); +1490 Self::Custom(m) +1491 } +1492} +1493 +1494/// Environment variable to force the use of staging relays. +1495pub const ENV_FORCE_STAGING_RELAYS: &str = "IROH_FORCE_STAGING_RELAYS"; +1496 +1497/// Returns `true` if the use of staging relays is forced. +1498pub fn force_staging_infra() -> bool { +1499 matches!(std::env::var(ENV_FORCE_STAGING_RELAYS), Ok(value) if !value.is_empty()) +1500} +1501 +1502/// Returns the default relay mode. +1503/// +1504/// If the `IROH_FORCE_STAGING_RELAYS` environment variable is non empty, it will return `RelayMode::Staging`. +1505/// Otherwise, it will return `RelayMode::Default`. +1506pub fn default_relay_mode() -> RelayMode { +1507 // Use staging in testing +1508 match force_staging_infra() { +1509 true => RelayMode::Staging, +1510 false => RelayMode::Default, +1511 } +1512} +1513 +1514/// Check if we are being executed in a CGI context. +1515/// +1516/// If so, a malicious client can send the `Proxy:` header, and it will +1517/// be in the `HTTP_PROXY` env var. So we don't use it :) +1518fn is_cgi() -> bool { +1519 std::env::var_os("REQUEST_METHOD").is_some() +1520} +1521 +1522// TODO: These tests could still be flaky, lets fix that: +1523// https://github.com/n0-computer/iroh/issues/1183 +1524#[cfg(test)] +1525mod tests { +1526 use std::{ +1527 io, +1528 net::{IpAddr, Ipv4Addr}, +1529 str::FromStr, +1530 sync::Arc, +1531 time::{Duration, Instant}, +1532 }; +1533 +1534 use iroh_base::{EndpointAddr, EndpointId, RelayUrl, SecretKey, TransportAddr}; +1535 use n0_error::{AnyError as Error, Result, StdResultExt}; +1536 use n0_future::{BufferedStreamExt, StreamExt, stream, time}; +1537 use n0_tracing_test::traced_test; +1538 use n0_watcher::Watcher; +1539 use rand::SeedableRng; +1540 use tokio::sync::oneshot; +1541 use tracing::{Instrument, debug_span, info, info_span, instrument}; +1542 +1543 use super::Endpoint; +1544 use crate::{ +1545 RelayMap, RelayMode, +1546 discovery::static_provider::StaticProvider, +1547 endpoint::{ +1548 ApplicationClose, BindError, BindOpts, ConnectOptions, Connection, ConnectionError, +1549 }, +1550 magicsock::CreateHandleError, +1551 protocol::{AcceptError, ProtocolHandler, Router}, +1552 test_utils::{QlogFileGroup, run_relay_server, run_relay_server_with}, +1553 }; 1554 -1555 #[tokio::test] -1556 #[traced_test] -1557 async fn test_connect_self() -> Result { -1558 let ep = Endpoint::empty_builder(RelayMode::Disabled) -1559 .alpns(vec![TEST_ALPN.to_vec()]) -1560 .bind() -1561 .await -1562 .unwrap(); -1563 let my_addr = ep.addr(); -1564 let res = ep.connect(my_addr.clone(), TEST_ALPN).await; -1565 assert!(res.is_err()); -1566 let err = res.err().unwrap(); -1567 assert!(err.to_string().starts_with("Connecting to ourself")); -1568 -1569 Ok(()) -1570 } -1571 -1572 #[tokio::test] -1573 #[traced_test] -1574 async fn endpoint_connect_close() -> Result { -1575 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); -1576 let (relay_map, relay_url, _guard) = run_relay_server().await?; -1577 let server_secret_key = SecretKey::generate(&mut rng); -1578 let server_peer_id = server_secret_key.public(); -1579 -1580 let qlog = QlogFileGroup::from_env("endpoint_connect_close"); +1555 const TEST_ALPN: &[u8] = b"n0/iroh/test"; +1556 +1557 #[tokio::test] +1558 #[traced_test] +1559 async fn test_connect_self() -> Result { +1560 let ep = Endpoint::empty_builder(RelayMode::Disabled) +1561 .alpns(vec![TEST_ALPN.to_vec()]) +1562 .bind() +1563 .await +1564 .unwrap(); +1565 let my_addr = ep.addr(); +1566 let res = ep.connect(my_addr.clone(), TEST_ALPN).await; +1567 assert!(res.is_err()); +1568 let err = res.err().unwrap(); +1569 assert!(err.to_string().starts_with("Connecting to ourself")); +1570 +1571 Ok(()) +1572 } +1573 +1574 #[tokio::test] +1575 #[traced_test] +1576 async fn endpoint_connect_close() -> Result { +1577 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); +1578 let (relay_map, relay_url, _guard) = run_relay_server().await?; +1579 let server_secret_key = SecretKey::generate(&mut rng); +1580 let server_peer_id = server_secret_key.public(); 1581 -1582 // Wait for the endpoint to be started to make sure it's up before clients try to connect -1583 let ep = Endpoint::empty_builder(RelayMode::Custom(relay_map.clone())) -1584 .secret_key(server_secret_key) -1585 .transport_config(qlog.create("server")?) -1586 .alpns(vec![TEST_ALPN.to_vec()]) -1587 .insecure_skip_relay_cert_verify(true) -1588 .bind() -1589 .await?; -1590 // Wait for the endpoint to be reachable via relay -1591 ep.online().await; -1592 -1593 let server = tokio::spawn( -1594 async move { -1595 info!("accepting connection"); -1596 let incoming = ep.accept().await.anyerr()?; -1597 let conn = incoming.await.anyerr()?; -1598 let mut stream = conn.accept_uni().await.anyerr()?; -1599 let mut buf = [0u8; 5]; -1600 stream.read_exact(&mut buf).await.anyerr()?; -1601 info!("Accepted 1 stream, received {buf:?}. Closing now."); -1602 // close the connection -1603 conn.close(7u8.into(), b"bye"); -1604 -1605 let res = conn.accept_uni().await; -1606 assert_eq!(res.unwrap_err(), ConnectionError::LocallyClosed); -1607 -1608 let res = stream.read_to_end(10).await; -1609 assert_eq!( -1610 res.unwrap_err(), -1611 quinn::ReadToEndError::Read(quinn::ReadError::ConnectionLost( -1612 ConnectionError::LocallyClosed -1613 )) -1614 ); -1615 info!("server test completed"); -1616 Ok::<_, Error>(()) -1617 } -1618 .instrument(info_span!("test-server")), -1619 ); -1620 -1621 let client = tokio::spawn( -1622 async move { -1623 let ep = Endpoint::empty_builder(RelayMode::Custom(relay_map)) -1624 .alpns(vec![TEST_ALPN.to_vec()]) -1625 .insecure_skip_relay_cert_verify(true) -1626 .transport_config(qlog.create("client")?) -1627 .bind() -1628 .await?; -1629 info!("client connecting"); -1630 let endpoint_addr = EndpointAddr::new(server_peer_id).with_relay_url(relay_url); -1631 let conn = ep.connect(endpoint_addr, TEST_ALPN).await?; -1632 let mut stream = conn.open_uni().await.anyerr()?; -1633 -1634 // First write is accepted by server. We need this bit of synchronisation -1635 // because if the server closes after simply accepting the connection we can -1636 // not be sure our .open_uni() call would succeed as it may already receive -1637 // the error. -1638 stream.write_all(b"hello").await.anyerr()?; -1639 -1640 info!("waiting for closed"); -1641 // Remote now closes the connection, we should see an error sometime soon. -1642 let err = conn.closed().await; -1643 let expected_err = ConnectionError::ApplicationClosed(ApplicationClose { -1644 error_code: 7u8.into(), -1645 reason: b"bye".to_vec().into(), -1646 }); -1647 assert_eq!(err, expected_err); -1648 -1649 info!("opening new - expect it to fail"); -1650 let res = conn.open_uni().await; -1651 assert_eq!(res.unwrap_err(), expected_err); -1652 info!("client test completed"); -1653 Ok::<_, Error>(()) -1654 } -1655 .instrument(info_span!("test-client")), -1656 ); -1657 -1658 let (server, client) = tokio::time::timeout( -1659 Duration::from_secs(30), -1660 n0_future::future::zip(server, client), -1661 ) -1662 .await -1663 .anyerr()?; -1664 server.anyerr()??; -1665 client.anyerr()??; -1666 Ok(()) -1667 } -1668 -1669 #[tokio::test] -1670 #[traced_test] -1671 async fn endpoint_relay_connect_loop() -> Result { -1672 let test_start = Instant::now(); -1673 let n_clients = 5; -1674 let n_chunks_per_client = 2; -1675 let chunk_size = 100; -1676 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42); -1677 let (relay_map, relay_url, _relay_guard) = run_relay_server().await.unwrap(); -1678 let server_secret_key = SecretKey::generate(&mut rng); -1679 let server_endpoint_id = server_secret_key.public(); -1680 -1681 // Make sure the server is bound before having clients connect to it: -1682 let ep = Endpoint::empty_builder(RelayMode::Custom(relay_map.clone())) -1683 .insecure_skip_relay_cert_verify(true) -1684 .secret_key(server_secret_key) -1685 .alpns(vec![TEST_ALPN.to_vec()]) -1686 .bind() -1687 .await?; -1688 // Also make sure the server has a working relay connection -1689 ep.online().await; -1690 -1691 info!(time = ?test_start.elapsed(), "test setup done"); +1582 let qlog = QlogFileGroup::from_env("endpoint_connect_close"); +1583 +1584 // Wait for the endpoint to be started to make sure it's up before clients try to connect +1585 let ep = Endpoint::empty_builder(RelayMode::Custom(relay_map.clone())) +1586 .secret_key(server_secret_key) +1587 .transport_config(qlog.create("server")?) +1588 .alpns(vec![TEST_ALPN.to_vec()]) +1589 .insecure_skip_relay_cert_verify(true) +1590 .bind() +1591 .await?; +1592 // Wait for the endpoint to be reachable via relay +1593 ep.online().await; +1594 +1595 let server = tokio::spawn( +1596 async move { +1597 info!("accepting connection"); +1598 let incoming = ep.accept().await.anyerr()?; +1599 let conn = incoming.await.anyerr()?; +1600 let mut stream = conn.accept_uni().await.anyerr()?; +1601 let mut buf = [0u8; 5]; +1602 stream.read_exact(&mut buf).await.anyerr()?; +1603 info!("Accepted 1 stream, received {buf:?}. Closing now."); +1604 // close the connection +1605 conn.close(7u8.into(), b"bye"); +1606 +1607 let res = conn.accept_uni().await; +1608 assert_eq!(res.unwrap_err(), ConnectionError::LocallyClosed); +1609 +1610 let res = stream.read_to_end(10).await; +1611 assert_eq!( +1612 res.unwrap_err(), +1613 quinn::ReadToEndError::Read(quinn::ReadError::ConnectionLost( +1614 ConnectionError::LocallyClosed +1615 )) +1616 ); +1617 info!("server test completed"); +1618 Ok::<_, Error>(()) +1619 } +1620 .instrument(info_span!("test-server")), +1621 ); +1622 +1623 let client = tokio::spawn( +1624 async move { +1625 let ep = Endpoint::empty_builder(RelayMode::Custom(relay_map)) +1626 .alpns(vec![TEST_ALPN.to_vec()]) +1627 .insecure_skip_relay_cert_verify(true) +1628 .transport_config(qlog.create("client")?) +1629 .bind() +1630 .await?; +1631 info!("client connecting"); +1632 let endpoint_addr = EndpointAddr::new(server_peer_id).with_relay_url(relay_url); +1633 let conn = ep.connect(endpoint_addr, TEST_ALPN).await?; +1634 let mut stream = conn.open_uni().await.anyerr()?; +1635 +1636 // First write is accepted by server. We need this bit of synchronisation +1637 // because if the server closes after simply accepting the connection we can +1638 // not be sure our .open_uni() call would succeed as it may already receive +1639 // the error. +1640 stream.write_all(b"hello").await.anyerr()?; +1641 +1642 info!("waiting for closed"); +1643 // Remote now closes the connection, we should see an error sometime soon. +1644 let err = conn.closed().await; +1645 let expected_err = ConnectionError::ApplicationClosed(ApplicationClose { +1646 error_code: 7u8.into(), +1647 reason: b"bye".to_vec().into(), +1648 }); +1649 assert_eq!(err, expected_err); +1650 +1651 info!("opening new - expect it to fail"); +1652 let res = conn.open_uni().await; +1653 assert_eq!(res.unwrap_err(), expected_err); +1654 info!("client test completed"); +1655 Ok::<_, Error>(()) +1656 } +1657 .instrument(info_span!("test-client")), +1658 ); +1659 +1660 let (server, client) = tokio::time::timeout( +1661 Duration::from_secs(30), +1662 n0_future::future::zip(server, client), +1663 ) +1664 .await +1665 .anyerr()?; +1666 server.anyerr()??; +1667 client.anyerr()??; +1668 Ok(()) +1669 } +1670 +1671 #[tokio::test] +1672 #[traced_test] +1673 async fn endpoint_relay_connect_loop() -> Result { +1674 let test_start = Instant::now(); +1675 let n_clients = 5; +1676 let n_chunks_per_client = 2; +1677 let chunk_size = 100; +1678 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42); +1679 let (relay_map, relay_url, _relay_guard) = run_relay_server().await.unwrap(); +1680 let server_secret_key = SecretKey::generate(&mut rng); +1681 let server_endpoint_id = server_secret_key.public(); +1682 +1683 // Make sure the server is bound before having clients connect to it: +1684 let ep = Endpoint::empty_builder(RelayMode::Custom(relay_map.clone())) +1685 .insecure_skip_relay_cert_verify(true) +1686 .secret_key(server_secret_key) +1687 .alpns(vec![TEST_ALPN.to_vec()]) +1688 .bind() +1689 .await?; +1690 // Also make sure the server has a working relay connection +1691 ep.online().await; 1692 -1693 // The server accepts the connections of the clients sequentially. -1694 let server = tokio::spawn( -1695 async move { -1696 let eps = ep.bound_sockets(); -1697 -1698 info!(me = %ep.id().fmt_short(), eps = ?eps, "server listening on"); -1699 for i in 0..n_clients { -1700 tokio::time::timeout(Duration::from_secs(4), async { -1701 let round_start = Instant::now(); -1702 info!("[server] round {i}"); -1703 let incoming = ep.accept().await.anyerr()?; -1704 let conn = incoming.await.anyerr()?; -1705 let endpoint_id = conn.remote_id(); -1706 info!(%i, peer = %endpoint_id.fmt_short(), "accepted connection"); -1707 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; -1708 let mut buf = vec![0u8; chunk_size]; -1709 for _i in 0..n_chunks_per_client { -1710 recv.read_exact(&mut buf).await.anyerr()?; -1711 send.write_all(&buf).await.anyerr()?; -1712 } -1713 info!(%i, peer = %endpoint_id.fmt_short(), "finishing"); -1714 send.finish().anyerr()?; -1715 conn.closed().await; // we're the last to send data, so we wait for the other side to close -1716 info!(%i, peer = %endpoint_id.fmt_short(), "finished"); -1717 info!("[server] round {i} done in {:?}", round_start.elapsed()); -1718 Ok::<_, Error>(()) -1719 }) -1720 .await -1721 .std_context("timeout")??; -1722 } -1723 Ok::<_, Error>(()) -1724 } -1725 .instrument(debug_span!("server")), -1726 ); -1727 -1728 let client = tokio::spawn(async move { -1729 for i in 0..n_clients { -1730 let round_start = Instant::now(); -1731 info!("[client] round {i}"); -1732 let client_secret_key = SecretKey::generate(&mut rng); -1733 tokio::time::timeout( -1734 Duration::from_secs(4), -1735 async { -1736 info!("client binding"); -1737 let ep = Endpoint::empty_builder(RelayMode::Custom(relay_map.clone())) -1738 .alpns(vec![TEST_ALPN.to_vec()]) -1739 .insecure_skip_relay_cert_verify(true) -1740 .secret_key(client_secret_key) -1741 .bind() -1742 .await?; -1743 let eps = ep.bound_sockets(); -1744 -1745 info!(me = %ep.id().fmt_short(), eps=?eps, "client bound"); -1746 let endpoint_addr = -1747 EndpointAddr::new(server_endpoint_id).with_relay_url(relay_url.clone()); -1748 info!(to = ?endpoint_addr, "client connecting"); -1749 let conn = ep.connect(endpoint_addr, TEST_ALPN).await.anyerr()?; -1750 info!("client connected"); -1751 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; -1752 -1753 for i in 0..n_chunks_per_client { -1754 let mut buf = vec![i; chunk_size]; -1755 send.write_all(&buf).await.anyerr()?; -1756 recv.read_exact(&mut buf).await.anyerr()?; -1757 assert_eq!(buf, vec![i; chunk_size]); -1758 } -1759 // we're the last to receive data, so we close -1760 conn.close(0u32.into(), b"bye!"); -1761 info!("client finished"); -1762 ep.close().await; -1763 info!("client closed"); -1764 -1765 Ok::<_, Error>(()) -1766 } -1767 .instrument(debug_span!("client", %i)), -1768 ) -1769 .await -1770 .std_context("timeout")??; -1771 info!("[client] round {i} done in {:?}", round_start.elapsed()); -1772 } -1773 Ok::<_, Error>(()) -1774 }); -1775 -1776 server.await.anyerr()??; -1777 client.await.anyerr()??; -1778 Ok(()) -1779 } -1780 -1781 #[tokio::test] -1782 #[traced_test] -1783 async fn endpoint_send_relay() -> Result { -1784 let (relay_map, _relay_url, _guard) = run_relay_server().await?; -1785 let client = Endpoint::empty_builder(RelayMode::Custom(relay_map.clone())) -1786 .insecure_skip_relay_cert_verify(true) -1787 .bind() -1788 .await?; -1789 let server = Endpoint::empty_builder(RelayMode::Custom(relay_map)) -1790 .insecure_skip_relay_cert_verify(true) -1791 .alpns(vec![TEST_ALPN.to_vec()]) -1792 .bind() -1793 .await?; -1794 -1795 let task = tokio::spawn({ -1796 let server = server.clone(); -1797 async move { -1798 let Some(conn) = server.accept().await else { -1799 n0_error::bail_any!("Expected an incoming connection"); -1800 }; -1801 let conn = conn.await.anyerr()?; -1802 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; -1803 let data = recv.read_to_end(1000).await.anyerr()?; -1804 send.write_all(&data).await.anyerr()?; -1805 send.finish().anyerr()?; -1806 conn.closed().await; -1807 -1808 Ok::<_, Error>(()) -1809 } -1810 }); -1811 -1812 let addr = server.addr(); -1813 let conn = client.connect(addr, TEST_ALPN).await?; -1814 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; -1815 send.write_all(b"Hello, world!").await.anyerr()?; -1816 send.finish().anyerr()?; -1817 let data = recv.read_to_end(1000).await.anyerr()?; -1818 conn.close(0u32.into(), b"bye!"); -1819 -1820 task.await.anyerr()??; +1693 info!(time = ?test_start.elapsed(), "test setup done"); +1694 +1695 // The server accepts the connections of the clients sequentially. +1696 let server = tokio::spawn( +1697 async move { +1698 let eps = ep.bound_sockets(); +1699 +1700 info!(me = %ep.id().fmt_short(), eps = ?eps, "server listening on"); +1701 for i in 0..n_clients { +1702 tokio::time::timeout(Duration::from_secs(4), async { +1703 let round_start = Instant::now(); +1704 info!("[server] round {i}"); +1705 let incoming = ep.accept().await.anyerr()?; +1706 let conn = incoming.await.anyerr()?; +1707 let endpoint_id = conn.remote_id(); +1708 info!(%i, peer = %endpoint_id.fmt_short(), "accepted connection"); +1709 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; +1710 let mut buf = vec![0u8; chunk_size]; +1711 for _i in 0..n_chunks_per_client { +1712 recv.read_exact(&mut buf).await.anyerr()?; +1713 send.write_all(&buf).await.anyerr()?; +1714 } +1715 info!(%i, peer = %endpoint_id.fmt_short(), "finishing"); +1716 send.finish().anyerr()?; +1717 conn.closed().await; // we're the last to send data, so we wait for the other side to close +1718 info!(%i, peer = %endpoint_id.fmt_short(), "finished"); +1719 info!("[server] round {i} done in {:?}", round_start.elapsed()); +1720 Ok::<_, Error>(()) +1721 }) +1722 .await +1723 .std_context("timeout")??; +1724 } +1725 Ok::<_, Error>(()) +1726 } +1727 .instrument(debug_span!("server")), +1728 ); +1729 +1730 let client = tokio::spawn(async move { +1731 for i in 0..n_clients { +1732 let round_start = Instant::now(); +1733 info!("[client] round {i}"); +1734 let client_secret_key = SecretKey::generate(&mut rng); +1735 tokio::time::timeout( +1736 Duration::from_secs(4), +1737 async { +1738 info!("client binding"); +1739 let ep = Endpoint::empty_builder(RelayMode::Custom(relay_map.clone())) +1740 .alpns(vec![TEST_ALPN.to_vec()]) +1741 .insecure_skip_relay_cert_verify(true) +1742 .secret_key(client_secret_key) +1743 .bind() +1744 .await?; +1745 let eps = ep.bound_sockets(); +1746 +1747 info!(me = %ep.id().fmt_short(), eps=?eps, "client bound"); +1748 let endpoint_addr = +1749 EndpointAddr::new(server_endpoint_id).with_relay_url(relay_url.clone()); +1750 info!(to = ?endpoint_addr, "client connecting"); +1751 let conn = ep.connect(endpoint_addr, TEST_ALPN).await.anyerr()?; +1752 info!("client connected"); +1753 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; +1754 +1755 for i in 0..n_chunks_per_client { +1756 let mut buf = vec![i; chunk_size]; +1757 send.write_all(&buf).await.anyerr()?; +1758 recv.read_exact(&mut buf).await.anyerr()?; +1759 assert_eq!(buf, vec![i; chunk_size]); +1760 } +1761 // we're the last to receive data, so we close +1762 conn.close(0u32.into(), b"bye!"); +1763 info!("client finished"); +1764 ep.close().await; +1765 info!("client closed"); +1766 +1767 Ok::<_, Error>(()) +1768 } +1769 .instrument(debug_span!("client", %i)), +1770 ) +1771 .await +1772 .std_context("timeout")??; +1773 info!("[client] round {i} done in {:?}", round_start.elapsed()); +1774 } +1775 Ok::<_, Error>(()) +1776 }); +1777 +1778 server.await.anyerr()??; +1779 client.await.anyerr()??; +1780 Ok(()) +1781 } +1782 +1783 #[tokio::test] +1784 #[traced_test] +1785 async fn endpoint_send_relay() -> Result { +1786 let (relay_map, _relay_url, _guard) = run_relay_server().await?; +1787 let client = Endpoint::empty_builder(RelayMode::Custom(relay_map.clone())) +1788 .insecure_skip_relay_cert_verify(true) +1789 .bind() +1790 .await?; +1791 let server = Endpoint::empty_builder(RelayMode::Custom(relay_map)) +1792 .insecure_skip_relay_cert_verify(true) +1793 .alpns(vec![TEST_ALPN.to_vec()]) +1794 .bind() +1795 .await?; +1796 +1797 let task = tokio::spawn({ +1798 let server = server.clone(); +1799 async move { +1800 let Some(conn) = server.accept().await else { +1801 n0_error::bail_any!("Expected an incoming connection"); +1802 }; +1803 let conn = conn.await.anyerr()?; +1804 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; +1805 let data = recv.read_to_end(1000).await.anyerr()?; +1806 send.write_all(&data).await.anyerr()?; +1807 send.finish().anyerr()?; +1808 conn.closed().await; +1809 +1810 Ok::<_, Error>(()) +1811 } +1812 }); +1813 +1814 let addr = server.addr(); +1815 let conn = client.connect(addr, TEST_ALPN).await?; +1816 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; +1817 send.write_all(b"Hello, world!").await.anyerr()?; +1818 send.finish().anyerr()?; +1819 let data = recv.read_to_end(1000).await.anyerr()?; +1820 conn.close(0u32.into(), b"bye!"); 1821 -1822 client.close().await; -1823 server.close().await; -1824 -1825 assert_eq!(&data, b"Hello, world!"); +1822 task.await.anyerr()??; +1823 +1824 client.close().await; +1825 server.close().await; 1826 -1827 Ok(()) -1828 } -1829 -1830 #[tokio::test] -1831 #[traced_test] -1832 async fn endpoint_two_direct_only() -> Result { -1833 // Connect two endpoints on the same network, without a relay server, without -1834 // discovery. -1835 let ep1 = { -1836 let span = info_span!("server"); -1837 let _guard = span.enter(); -1838 Endpoint::builder() -1839 .alpns(vec![TEST_ALPN.to_vec()]) -1840 .relay_mode(RelayMode::Disabled) -1841 .bind() -1842 .await? -1843 }; -1844 let ep2 = { -1845 let span = info_span!("client"); -1846 let _guard = span.enter(); -1847 Endpoint::builder() -1848 .alpns(vec![TEST_ALPN.to_vec()]) -1849 .relay_mode(RelayMode::Disabled) -1850 .bind() -1851 .await? -1852 }; -1853 let ep1_nodeaddr = ep1.addr(); -1854 -1855 #[instrument(name = "client", skip_all)] -1856 async fn connect(ep: Endpoint, dst: EndpointAddr) -> Result<ConnectionError> { -1857 info!(me = %ep.id().fmt_short(), "client starting"); -1858 let conn = ep.connect(dst, TEST_ALPN).await?; -1859 let mut send = conn.open_uni().await.anyerr()?; -1860 send.write_all(b"hello").await.anyerr()?; -1861 send.finish().anyerr()?; -1862 Ok(conn.closed().await) -1863 } -1864 -1865 #[instrument(name = "server", skip_all)] -1866 async fn accept(ep: Endpoint, src: EndpointId) -> Result { -1867 info!(me = %ep.id().fmt_short(), "server starting"); -1868 let conn = ep.accept().await.anyerr()?.await.anyerr()?; -1869 let node_id = conn.remote_id(); -1870 assert_eq!(node_id, src); -1871 let mut recv = conn.accept_uni().await.anyerr()?; -1872 let msg = recv.read_to_end(100).await.anyerr()?; -1873 assert_eq!(msg, b"hello"); -1874 // Dropping the connection closes it just fine. -1875 Ok(()) -1876 } -1877 -1878 let ep1_accept = tokio::spawn(accept(ep1.clone(), ep2.id())); -1879 let ep2_connect = tokio::spawn(connect(ep2.clone(), ep1_nodeaddr)); -1880 -1881 ep1_accept.await.anyerr()??; -1882 let conn_closed = dbg!(ep2_connect.await.anyerr()??); -1883 assert!(matches!( -1884 conn_closed, -1885 ConnectionError::ApplicationClosed(ApplicationClose { .. }) -1886 )); -1887 -1888 Ok(()) -1889 } -1890 -1891 #[tokio::test] -1892 #[traced_test] -1893 async fn endpoint_two_relay_only_becomes_direct() -> Result { -1894 // Connect two endpoints on the same network, via a relay server, without -1895 // discovery. Wait until there is a direct connection. -1896 let (relay_map, _relay_url, _relay_server_guard) = run_relay_server().await?; -1897 let (node_addr_tx, node_addr_rx) = oneshot::channel(); -1898 let qlog = Arc::new(QlogFileGroup::from_env("two_relay_only_becomes_direct")); -1899 -1900 #[instrument(name = "client", skip_all)] -1901 async fn connect( -1902 relay_map: RelayMap, -1903 node_addr_rx: oneshot::Receiver<EndpointAddr>, -1904 qlog: Arc<QlogFileGroup>, -1905 ) -> Result<ConnectionError> { -1906 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); -1907 let secret = SecretKey::generate(&mut rng); -1908 let ep = Endpoint::builder() -1909 .secret_key(secret) -1910 .alpns(vec![TEST_ALPN.to_vec()]) -1911 .insecure_skip_relay_cert_verify(true) -1912 .relay_mode(RelayMode::Custom(relay_map)) -1913 .transport_config(qlog.create("client")?) -1914 .bind() -1915 .await?; -1916 info!(me = %ep.id().fmt_short(), "client starting"); -1917 let dst = node_addr_rx.await.anyerr()?; -1918 -1919 info!(me = %ep.id().fmt_short(), "client connecting"); -1920 let conn = ep.connect(dst, TEST_ALPN).await?; -1921 let mut send = conn.open_uni().await.anyerr()?; -1922 send.write_all(b"hello").await.anyerr()?; -1923 let mut paths = conn.paths().stream(); -1924 info!("Waiting for direct connection"); -1925 while let Some(infos) = paths.next().await { -1926 info!(?infos, "new PathInfos"); -1927 if infos.iter().any(|info| info.is_ip()) { -1928 break; -1929 } -1930 } -1931 info!("Have direct connection"); -1932 // Validate holepunch metrics. -1933 assert_eq!(ep.metrics().magicsock.num_conns_opened.get(), 1); -1934 assert_eq!(ep.metrics().magicsock.num_conns_direct.get(), 1); -1935 -1936 send.write_all(b"close please").await.anyerr()?; -1937 send.finish().anyerr()?; -1938 -1939 Ok(conn.closed().await) -1940 } -1941 -1942 #[instrument(name = "server", skip_all)] -1943 async fn accept( -1944 relay_map: RelayMap, -1945 node_addr_tx: oneshot::Sender<EndpointAddr>, -1946 qlog: Arc<QlogFileGroup>, -1947 ) -> Result { -1948 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1u64); -1949 let secret = SecretKey::generate(&mut rng); -1950 let ep = Endpoint::builder() -1951 .secret_key(secret) -1952 .alpns(vec![TEST_ALPN.to_vec()]) -1953 .insecure_skip_relay_cert_verify(true) -1954 .transport_config(qlog.create("server")?) -1955 .relay_mode(RelayMode::Custom(relay_map)) -1956 .bind() -1957 .await?; -1958 ep.online().await; -1959 let mut node_addr = ep.addr(); -1960 node_addr.addrs.retain(|addr| addr.is_relay()); -1961 node_addr_tx.send(node_addr).unwrap(); -1962 -1963 info!(me = %ep.id().fmt_short(), "server starting"); -1964 let conn = ep.accept().await.anyerr()?.await.anyerr()?; -1965 // let node_id = conn.remote_node_id()?; -1966 // assert_eq!(node_id, src); -1967 let mut recv = conn.accept_uni().await.anyerr()?; -1968 let mut msg = [0u8; 5]; -1969 recv.read_exact(&mut msg).await.anyerr()?; -1970 assert_eq!(&msg, b"hello"); -1971 info!("received hello"); -1972 let msg = recv.read_to_end(100).await.anyerr()?; -1973 assert_eq!(msg, b"close please"); -1974 info!("received 'close please'"); -1975 // Dropping the connection closes it just fine. -1976 Ok(()) -1977 } -1978 -1979 let server_task = tokio::spawn(accept(relay_map.clone(), node_addr_tx, qlog.clone())); -1980 let client_task = tokio::spawn(connect(relay_map, node_addr_rx, qlog)); -1981 -1982 server_task.await.anyerr()??; -1983 let conn_closed = dbg!(client_task.await.anyerr()??); -1984 assert!(matches!( -1985 conn_closed, -1986 ConnectionError::ApplicationClosed(ApplicationClose { .. }) -1987 )); -1988 -1989 Ok(()) -1990 } -1991 -1992 #[tokio::test] -1993 #[traced_test] -1994 async fn endpoint_two_relay_only_no_ip() -> Result { -1995 // Connect two endpoints on the same network, via a relay server, without -1996 // discovery. -1997 let (relay_map, _relay_url, _relay_server_guard) = run_relay_server().await?; -1998 let (node_addr_tx, node_addr_rx) = oneshot::channel(); -1999 -2000 #[instrument(name = "client", skip_all)] -2001 async fn connect( -2002 relay_map: RelayMap, -2003 node_addr_rx: oneshot::Receiver<EndpointAddr>, -2004 ) -> Result<ConnectionError> { -2005 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); -2006 let secret = SecretKey::generate(&mut rng); -2007 let ep = Endpoint::builder() -2008 .secret_key(secret) -2009 .alpns(vec![TEST_ALPN.to_vec()]) -2010 .insecure_skip_relay_cert_verify(true) -2011 .relay_mode(RelayMode::Custom(relay_map)) -2012 .clear_ip_transports() // disable direct -2013 .bind() -2014 .await?; -2015 info!(me = %ep.id().fmt_short(), "client starting"); -2016 let dst = node_addr_rx.await.anyerr()?; -2017 -2018 info!(me = %ep.id().fmt_short(), "client connecting"); -2019 let conn = ep.connect(dst, TEST_ALPN).await?; -2020 let mut send = conn.open_uni().await.anyerr()?; -2021 send.write_all(b"hello").await.anyerr()?; -2022 let mut paths = conn.paths().stream(); -2023 info!("Waiting for connection"); -2024 'outer: while let Some(infos) = paths.next().await { -2025 info!(?infos, "new PathInfos"); -2026 for info in infos { -2027 if info.is_ip() { -2028 panic!("should not happen: {:?}", info); -2029 } -2030 if info.is_relay() { -2031 break 'outer; -2032 } -2033 } -2034 } -2035 info!("Have relay connection"); -2036 send.write_all(b"close please").await.anyerr()?; -2037 send.finish().anyerr()?; -2038 Ok(conn.closed().await) -2039 } -2040 -2041 #[instrument(name = "server", skip_all)] -2042 async fn accept( -2043 relay_map: RelayMap, -2044 node_addr_tx: oneshot::Sender<EndpointAddr>, -2045 ) -> Result { -2046 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1u64); -2047 let secret = SecretKey::generate(&mut rng); -2048 let ep = Endpoint::builder() -2049 .secret_key(secret) -2050 .alpns(vec![TEST_ALPN.to_vec()]) -2051 .insecure_skip_relay_cert_verify(true) -2052 .relay_mode(RelayMode::Custom(relay_map)) -2053 .clear_ip_transports() -2054 .bind() -2055 .await?; -2056 ep.online().await; -2057 let node_addr = ep.addr(); -2058 node_addr_tx.send(node_addr).unwrap(); -2059 -2060 info!(me = %ep.id().fmt_short(), "server starting"); -2061 let conn = ep.accept().await.anyerr()?.await.anyerr()?; -2062 // let node_id = conn.remote_node_id()?; -2063 // assert_eq!(node_id, src); -2064 let mut recv = conn.accept_uni().await.anyerr()?; -2065 let mut msg = [0u8; 5]; -2066 recv.read_exact(&mut msg).await.anyerr()?; -2067 assert_eq!(&msg, b"hello"); -2068 info!("received hello"); -2069 let msg = recv.read_to_end(100).await.anyerr()?; -2070 assert_eq!(msg, b"close please"); -2071 info!("received 'close please'"); -2072 // Dropping the connection closes it just fine. -2073 Ok(()) -2074 } -2075 -2076 let server_task = tokio::spawn(accept(relay_map.clone(), node_addr_tx)); -2077 let client_task = tokio::spawn(connect(relay_map, node_addr_rx)); -2078 -2079 server_task.await.anyerr()??; -2080 let conn_closed = dbg!(client_task.await.anyerr()??); -2081 assert!(matches!( -2082 conn_closed, -2083 ConnectionError::ApplicationClosed(ApplicationClose { .. }) -2084 )); -2085 -2086 Ok(()) -2087 } -2088 -2089 #[tokio::test] -2090 #[traced_test] -2091 async fn endpoint_two_direct_add_relay() -> Result { -2092 // Connect two endpoints on the same network, without relay server and without -2093 // discovery. Add a relay connection later. -2094 let (relay_map, _relay_url, _relay_server_guard) = run_relay_server().await?; -2095 let (node_addr_tx, node_addr_rx) = oneshot::channel(); -2096 -2097 #[instrument(name = "client", skip_all)] -2098 async fn connect( -2099 relay_map: RelayMap, -2100 node_addr_rx: oneshot::Receiver<EndpointAddr>, -2101 ) -> Result<()> { -2102 let secret = SecretKey::from([0u8; 32]); -2103 let ep = Endpoint::builder() -2104 .secret_key(secret) -2105 .alpns(vec![TEST_ALPN.to_vec()]) -2106 .insecure_skip_relay_cert_verify(true) -2107 .relay_mode(RelayMode::Custom(relay_map)) -2108 .bind() -2109 .await?; -2110 info!(me = %ep.id().fmt_short(), "client starting"); -2111 let dst = node_addr_rx.await.anyerr()?; -2112 -2113 info!(me = %ep.id().fmt_short(), "client connecting"); -2114 let conn = ep.connect(dst, TEST_ALPN).await?; -2115 info!(me = %ep.id().fmt_short(), "client connected"); -2116 -2117 // We should be connected via IP, because it is faster than the relay server. -2118 // TODO: Maybe not panic if this is not true? -2119 let path_info = conn.paths().get(); -2120 assert_eq!(path_info.len(), 1); -2121 assert!(path_info.iter().next().unwrap().is_ip()); -2122 -2123 let mut paths = conn.paths().stream(); -2124 time::timeout(Duration::from_secs(5), async move { -2125 while let Some(infos) = paths.next().await { -2126 info!(?infos, "new PathInfos"); -2127 if infos.iter().any(|info| info.is_relay()) { -2128 info!("client has a relay path"); -2129 break; -2130 } -2131 } -2132 }) -2133 .await -2134 .anyerr()?; -2135 -2136 // wait for the server to signal it has the relay connection -2137 let mut stream = conn.accept_uni().await.anyerr()?; -2138 stream.read_to_end(100).await.anyerr()?; -2139 -2140 info!("client closing"); -2141 conn.close(0u8.into(), b""); -2142 ep.close().await; -2143 Ok(()) -2144 } -2145 -2146 #[instrument(name = "server", skip_all)] -2147 async fn accept( -2148 relay_map: RelayMap, -2149 node_addr_tx: oneshot::Sender<EndpointAddr>, -2150 ) -> Result<ConnectionError> { -2151 let secret = SecretKey::from([1u8; 32]); -2152 let ep = Endpoint::builder() -2153 .secret_key(secret) -2154 .alpns(vec![TEST_ALPN.to_vec()]) -2155 .insecure_skip_relay_cert_verify(true) -2156 .relay_mode(RelayMode::Custom(relay_map)) -2157 .bind() -2158 .await?; -2159 ep.online().await; -2160 let node_addr = ep.addr(); -2161 node_addr_tx.send(node_addr).unwrap(); -2162 -2163 info!(me = %ep.id().fmt_short(), "server starting"); -2164 let conn = ep.accept().await.anyerr()?.await.anyerr()?; -2165 info!(me = %ep.id().fmt_short(), "server accepted connection"); -2166 -2167 // Wait for a relay connection to be added. Client does all the asserting here, -2168 // we just want to wait so we get to see all the mechanics of the connection -2169 // being added on this side too. -2170 let mut paths = conn.paths().stream(); -2171 time::timeout(Duration::from_secs(5), async move { -2172 while let Some(infos) = paths.next().await { -2173 info!(?infos, "new PathInfos"); -2174 if infos.iter().any(|path| path.is_relay()) { -2175 info!("server has a relay path"); -2176 break; -2177 } -2178 } -2179 }) -2180 .await -2181 .anyerr()?; -2182 -2183 let mut stream = conn.open_uni().await.anyerr()?; -2184 stream.write_all(b"have relay").await.anyerr()?; -2185 stream.finish().anyerr()?; -2186 info!("waiting conn.closed()"); -2187 -2188 Ok(conn.closed().await) -2189 } -2190 -2191 let server_task = tokio::spawn(accept(relay_map.clone(), node_addr_tx)); -2192 let client_task = tokio::spawn(connect(relay_map, node_addr_rx)); -2193 -2194 client_task.await.anyerr()??; -2195 let conn_closed = dbg!(server_task.await.anyerr()??); -2196 assert!(matches!( -2197 conn_closed, -2198 ConnectionError::ApplicationClosed(ApplicationClose { .. }) -2199 )); -2200 -2201 Ok(()) -2202 } -2203 -2204 #[tokio::test] -2205 #[traced_test] -2206 async fn endpoint_relay_map_change() -> Result { -2207 let (relay_map, relay_url, _guard1) = run_relay_server().await?; -2208 let client = Endpoint::empty_builder(RelayMode::Custom(relay_map.clone())) -2209 .insecure_skip_relay_cert_verify(true) -2210 .bind() -2211 .await?; -2212 let server = Endpoint::empty_builder(RelayMode::Custom(relay_map)) -2213 .insecure_skip_relay_cert_verify(true) -2214 .alpns(vec![TEST_ALPN.to_vec()]) -2215 .bind() -2216 .await?; -2217 -2218 let task = tokio::spawn({ -2219 let server = server.clone(); -2220 async move { -2221 for i in 0..2 { -2222 println!("accept: round {i}"); -2223 let Some(conn) = server.accept().await else { -2224 n0_error::bail_any!("Expected an incoming connection"); -2225 }; -2226 let conn = conn.await.anyerr()?; -2227 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; -2228 let data = recv.read_to_end(1000).await.anyerr()?; -2229 send.write_all(&data).await.anyerr()?; -2230 send.finish().anyerr()?; -2231 conn.closed().await; -2232 } -2233 Ok::<_, Error>(()) -2234 } -2235 }); -2236 -2237 server.online().await; +1827 assert_eq!(&data, b"Hello, world!"); +1828 +1829 Ok(()) +1830 } +1831 +1832 #[tokio::test] +1833 #[traced_test] +1834 async fn endpoint_two_direct_only() -> Result { +1835 // Connect two endpoints on the same network, without a relay server, without +1836 // discovery. +1837 let ep1 = { +1838 let span = info_span!("server"); +1839 let _guard = span.enter(); +1840 Endpoint::builder() +1841 .alpns(vec![TEST_ALPN.to_vec()]) +1842 .relay_mode(RelayMode::Disabled) +1843 .bind() +1844 .await? +1845 }; +1846 let ep2 = { +1847 let span = info_span!("client"); +1848 let _guard = span.enter(); +1849 Endpoint::builder() +1850 .alpns(vec![TEST_ALPN.to_vec()]) +1851 .relay_mode(RelayMode::Disabled) +1852 .bind() +1853 .await? +1854 }; +1855 let ep1_nodeaddr = ep1.addr(); +1856 +1857 #[instrument(name = "client", skip_all)] +1858 async fn connect(ep: Endpoint, dst: EndpointAddr) -> Result<ConnectionError> { +1859 info!(me = %ep.id().fmt_short(), "client starting"); +1860 let conn = ep.connect(dst, TEST_ALPN).await?; +1861 let mut send = conn.open_uni().await.anyerr()?; +1862 send.write_all(b"hello").await.anyerr()?; +1863 send.finish().anyerr()?; +1864 Ok(conn.closed().await) +1865 } +1866 +1867 #[instrument(name = "server", skip_all)] +1868 async fn accept(ep: Endpoint, src: EndpointId) -> Result { +1869 info!(me = %ep.id().fmt_short(), "server starting"); +1870 let conn = ep.accept().await.anyerr()?.await.anyerr()?; +1871 let node_id = conn.remote_id(); +1872 assert_eq!(node_id, src); +1873 let mut recv = conn.accept_uni().await.anyerr()?; +1874 let msg = recv.read_to_end(100).await.anyerr()?; +1875 assert_eq!(msg, b"hello"); +1876 // Dropping the connection closes it just fine. +1877 Ok(()) +1878 } +1879 +1880 let ep1_accept = tokio::spawn(accept(ep1.clone(), ep2.id())); +1881 let ep2_connect = tokio::spawn(connect(ep2.clone(), ep1_nodeaddr)); +1882 +1883 ep1_accept.await.anyerr()??; +1884 let conn_closed = dbg!(ep2_connect.await.anyerr()??); +1885 assert!(matches!( +1886 conn_closed, +1887 ConnectionError::ApplicationClosed(ApplicationClose { .. }) +1888 )); +1889 +1890 Ok(()) +1891 } +1892 +1893 #[tokio::test] +1894 #[traced_test] +1895 async fn endpoint_two_relay_only_becomes_direct() -> Result { +1896 // Connect two endpoints on the same network, via a relay server, without +1897 // discovery. Wait until there is a direct connection. +1898 let (relay_map, _relay_url, _relay_server_guard) = run_relay_server().await?; +1899 let (node_addr_tx, node_addr_rx) = oneshot::channel(); +1900 let qlog = Arc::new(QlogFileGroup::from_env("two_relay_only_becomes_direct")); +1901 +1902 #[instrument(name = "client", skip_all)] +1903 async fn connect( +1904 relay_map: RelayMap, +1905 node_addr_rx: oneshot::Receiver<EndpointAddr>, +1906 qlog: Arc<QlogFileGroup>, +1907 ) -> Result<ConnectionError> { +1908 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); +1909 let secret = SecretKey::generate(&mut rng); +1910 let ep = Endpoint::builder() +1911 .secret_key(secret) +1912 .alpns(vec![TEST_ALPN.to_vec()]) +1913 .insecure_skip_relay_cert_verify(true) +1914 .relay_mode(RelayMode::Custom(relay_map)) +1915 .transport_config(qlog.create("client")?) +1916 .bind() +1917 .await?; +1918 info!(me = %ep.id().fmt_short(), "client starting"); +1919 let dst = node_addr_rx.await.anyerr()?; +1920 +1921 info!(me = %ep.id().fmt_short(), "client connecting"); +1922 let conn = ep.connect(dst, TEST_ALPN).await?; +1923 let mut send = conn.open_uni().await.anyerr()?; +1924 send.write_all(b"hello").await.anyerr()?; +1925 let mut paths = conn.paths().stream(); +1926 info!("Waiting for direct connection"); +1927 while let Some(infos) = paths.next().await { +1928 info!(?infos, "new PathInfos"); +1929 if infos.iter().any(|info| info.is_ip()) { +1930 break; +1931 } +1932 } +1933 info!("Have direct connection"); +1934 // Validate holepunch metrics. +1935 assert_eq!(ep.metrics().magicsock.num_conns_opened.get(), 1); +1936 assert_eq!(ep.metrics().magicsock.num_conns_direct.get(), 1); +1937 +1938 send.write_all(b"close please").await.anyerr()?; +1939 send.finish().anyerr()?; +1940 +1941 Ok(conn.closed().await) +1942 } +1943 +1944 #[instrument(name = "server", skip_all)] +1945 async fn accept( +1946 relay_map: RelayMap, +1947 node_addr_tx: oneshot::Sender<EndpointAddr>, +1948 qlog: Arc<QlogFileGroup>, +1949 ) -> Result { +1950 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1u64); +1951 let secret = SecretKey::generate(&mut rng); +1952 let ep = Endpoint::builder() +1953 .secret_key(secret) +1954 .alpns(vec![TEST_ALPN.to_vec()]) +1955 .insecure_skip_relay_cert_verify(true) +1956 .transport_config(qlog.create("server")?) +1957 .relay_mode(RelayMode::Custom(relay_map)) +1958 .bind() +1959 .await?; +1960 ep.online().await; +1961 let mut node_addr = ep.addr(); +1962 node_addr.addrs.retain(|addr| addr.is_relay()); +1963 node_addr_tx.send(node_addr).unwrap(); +1964 +1965 info!(me = %ep.id().fmt_short(), "server starting"); +1966 let conn = ep.accept().await.anyerr()?.await.anyerr()?; +1967 // let node_id = conn.remote_node_id()?; +1968 // assert_eq!(node_id, src); +1969 let mut recv = conn.accept_uni().await.anyerr()?; +1970 let mut msg = [0u8; 5]; +1971 recv.read_exact(&mut msg).await.anyerr()?; +1972 assert_eq!(&msg, b"hello"); +1973 info!("received hello"); +1974 let msg = recv.read_to_end(100).await.anyerr()?; +1975 assert_eq!(msg, b"close please"); +1976 info!("received 'close please'"); +1977 // Dropping the connection closes it just fine. +1978 Ok(()) +1979 } +1980 +1981 let server_task = tokio::spawn(accept(relay_map.clone(), node_addr_tx, qlog.clone())); +1982 let client_task = tokio::spawn(connect(relay_map, node_addr_rx, qlog)); +1983 +1984 server_task.await.anyerr()??; +1985 let conn_closed = dbg!(client_task.await.anyerr()??); +1986 assert!(matches!( +1987 conn_closed, +1988 ConnectionError::ApplicationClosed(ApplicationClose { .. }) +1989 )); +1990 +1991 Ok(()) +1992 } +1993 +1994 #[tokio::test] +1995 #[traced_test] +1996 async fn endpoint_two_relay_only_no_ip() -> Result { +1997 // Connect two endpoints on the same network, via a relay server, without +1998 // discovery. +1999 let (relay_map, _relay_url, _relay_server_guard) = run_relay_server().await?; +2000 let (node_addr_tx, node_addr_rx) = oneshot::channel(); +2001 +2002 #[instrument(name = "client", skip_all)] +2003 async fn connect( +2004 relay_map: RelayMap, +2005 node_addr_rx: oneshot::Receiver<EndpointAddr>, +2006 ) -> Result<ConnectionError> { +2007 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64); +2008 let secret = SecretKey::generate(&mut rng); +2009 let ep = Endpoint::builder() +2010 .secret_key(secret) +2011 .alpns(vec![TEST_ALPN.to_vec()]) +2012 .insecure_skip_relay_cert_verify(true) +2013 .relay_mode(RelayMode::Custom(relay_map)) +2014 .clear_ip_transports() // disable direct +2015 .bind() +2016 .await?; +2017 info!(me = %ep.id().fmt_short(), "client starting"); +2018 let dst = node_addr_rx.await.anyerr()?; +2019 +2020 info!(me = %ep.id().fmt_short(), "client connecting"); +2021 let conn = ep.connect(dst, TEST_ALPN).await?; +2022 let mut send = conn.open_uni().await.anyerr()?; +2023 send.write_all(b"hello").await.anyerr()?; +2024 let mut paths = conn.paths().stream(); +2025 info!("Waiting for connection"); +2026 'outer: while let Some(infos) = paths.next().await { +2027 info!(?infos, "new PathInfos"); +2028 for info in infos { +2029 if info.is_ip() { +2030 panic!("should not happen: {:?}", info); +2031 } +2032 if info.is_relay() { +2033 break 'outer; +2034 } +2035 } +2036 } +2037 info!("Have relay connection"); +2038 send.write_all(b"close please").await.anyerr()?; +2039 send.finish().anyerr()?; +2040 Ok(conn.closed().await) +2041 } +2042 +2043 #[instrument(name = "server", skip_all)] +2044 async fn accept( +2045 relay_map: RelayMap, +2046 node_addr_tx: oneshot::Sender<EndpointAddr>, +2047 ) -> Result { +2048 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1u64); +2049 let secret = SecretKey::generate(&mut rng); +2050 let ep = Endpoint::builder() +2051 .secret_key(secret) +2052 .alpns(vec![TEST_ALPN.to_vec()]) +2053 .insecure_skip_relay_cert_verify(true) +2054 .relay_mode(RelayMode::Custom(relay_map)) +2055 .clear_ip_transports() +2056 .bind() +2057 .await?; +2058 ep.online().await; +2059 let node_addr = ep.addr(); +2060 node_addr_tx.send(node_addr).unwrap(); +2061 +2062 info!(me = %ep.id().fmt_short(), "server starting"); +2063 let conn = ep.accept().await.anyerr()?.await.anyerr()?; +2064 // let node_id = conn.remote_node_id()?; +2065 // assert_eq!(node_id, src); +2066 let mut recv = conn.accept_uni().await.anyerr()?; +2067 let mut msg = [0u8; 5]; +2068 recv.read_exact(&mut msg).await.anyerr()?; +2069 assert_eq!(&msg, b"hello"); +2070 info!("received hello"); +2071 let msg = recv.read_to_end(100).await.anyerr()?; +2072 assert_eq!(msg, b"close please"); +2073 info!("received 'close please'"); +2074 // Dropping the connection closes it just fine. +2075 Ok(()) +2076 } +2077 +2078 let server_task = tokio::spawn(accept(relay_map.clone(), node_addr_tx)); +2079 let client_task = tokio::spawn(connect(relay_map, node_addr_rx)); +2080 +2081 server_task.await.anyerr()??; +2082 let conn_closed = dbg!(client_task.await.anyerr()??); +2083 assert!(matches!( +2084 conn_closed, +2085 ConnectionError::ApplicationClosed(ApplicationClose { .. }) +2086 )); +2087 +2088 Ok(()) +2089 } +2090 +2091 #[tokio::test] +2092 #[traced_test] +2093 async fn endpoint_two_direct_add_relay() -> Result { +2094 // Connect two endpoints on the same network, without relay server and without +2095 // discovery. Add a relay connection later. +2096 let (relay_map, _relay_url, _relay_server_guard) = run_relay_server().await?; +2097 let (node_addr_tx, node_addr_rx) = oneshot::channel(); +2098 +2099 #[instrument(name = "client", skip_all)] +2100 async fn connect( +2101 relay_map: RelayMap, +2102 node_addr_rx: oneshot::Receiver<EndpointAddr>, +2103 ) -> Result<()> { +2104 let secret = SecretKey::from([0u8; 32]); +2105 let ep = Endpoint::builder() +2106 .secret_key(secret) +2107 .alpns(vec![TEST_ALPN.to_vec()]) +2108 .insecure_skip_relay_cert_verify(true) +2109 .relay_mode(RelayMode::Custom(relay_map)) +2110 .bind() +2111 .await?; +2112 info!(me = %ep.id().fmt_short(), "client starting"); +2113 let dst = node_addr_rx.await.anyerr()?; +2114 +2115 info!(me = %ep.id().fmt_short(), "client connecting"); +2116 let conn = ep.connect(dst, TEST_ALPN).await?; +2117 info!(me = %ep.id().fmt_short(), "client connected"); +2118 +2119 // We should be connected via IP, because it is faster than the relay server. +2120 // TODO: Maybe not panic if this is not true? +2121 let path_info = conn.paths().get(); +2122 assert_eq!(path_info.len(), 1); +2123 assert!(path_info.iter().next().unwrap().is_ip()); +2124 +2125 let mut paths = conn.paths().stream(); +2126 time::timeout(Duration::from_secs(5), async move { +2127 while let Some(infos) = paths.next().await { +2128 info!(?infos, "new PathInfos"); +2129 if infos.iter().any(|info| info.is_relay()) { +2130 info!("client has a relay path"); +2131 break; +2132 } +2133 } +2134 }) +2135 .await +2136 .anyerr()?; +2137 +2138 // wait for the server to signal it has the relay connection +2139 let mut stream = conn.accept_uni().await.anyerr()?; +2140 stream.read_to_end(100).await.anyerr()?; +2141 +2142 info!("client closing"); +2143 conn.close(0u8.into(), b""); +2144 ep.close().await; +2145 Ok(()) +2146 } +2147 +2148 #[instrument(name = "server", skip_all)] +2149 async fn accept( +2150 relay_map: RelayMap, +2151 node_addr_tx: oneshot::Sender<EndpointAddr>, +2152 ) -> Result<ConnectionError> { +2153 let secret = SecretKey::from([1u8; 32]); +2154 let ep = Endpoint::builder() +2155 .secret_key(secret) +2156 .alpns(vec![TEST_ALPN.to_vec()]) +2157 .insecure_skip_relay_cert_verify(true) +2158 .relay_mode(RelayMode::Custom(relay_map)) +2159 .bind() +2160 .await?; +2161 ep.online().await; +2162 let node_addr = ep.addr(); +2163 node_addr_tx.send(node_addr).unwrap(); +2164 +2165 info!(me = %ep.id().fmt_short(), "server starting"); +2166 let conn = ep.accept().await.anyerr()?.await.anyerr()?; +2167 info!(me = %ep.id().fmt_short(), "server accepted connection"); +2168 +2169 // Wait for a relay connection to be added. Client does all the asserting here, +2170 // we just want to wait so we get to see all the mechanics of the connection +2171 // being added on this side too. +2172 let mut paths = conn.paths().stream(); +2173 time::timeout(Duration::from_secs(5), async move { +2174 while let Some(infos) = paths.next().await { +2175 info!(?infos, "new PathInfos"); +2176 if infos.iter().any(|path| path.is_relay()) { +2177 info!("server has a relay path"); +2178 break; +2179 } +2180 } +2181 }) +2182 .await +2183 .anyerr()?; +2184 +2185 let mut stream = conn.open_uni().await.anyerr()?; +2186 stream.write_all(b"have relay").await.anyerr()?; +2187 stream.finish().anyerr()?; +2188 info!("waiting conn.closed()"); +2189 +2190 Ok(conn.closed().await) +2191 } +2192 +2193 let server_task = tokio::spawn(accept(relay_map.clone(), node_addr_tx)); +2194 let client_task = tokio::spawn(connect(relay_map, node_addr_rx)); +2195 +2196 client_task.await.anyerr()??; +2197 let conn_closed = dbg!(server_task.await.anyerr()??); +2198 assert!(matches!( +2199 conn_closed, +2200 ConnectionError::ApplicationClosed(ApplicationClose { .. }) +2201 )); +2202 +2203 Ok(()) +2204 } +2205 +2206 #[tokio::test] +2207 #[traced_test] +2208 async fn endpoint_relay_map_change() -> Result { +2209 let (relay_map, relay_url, _guard1) = run_relay_server().await?; +2210 let client = Endpoint::empty_builder(RelayMode::Custom(relay_map.clone())) +2211 .insecure_skip_relay_cert_verify(true) +2212 .bind() +2213 .await?; +2214 let server = Endpoint::empty_builder(RelayMode::Custom(relay_map)) +2215 .insecure_skip_relay_cert_verify(true) +2216 .alpns(vec![TEST_ALPN.to_vec()]) +2217 .bind() +2218 .await?; +2219 +2220 let task = tokio::spawn({ +2221 let server = server.clone(); +2222 async move { +2223 for i in 0..2 { +2224 println!("accept: round {i}"); +2225 let Some(conn) = server.accept().await else { +2226 n0_error::bail_any!("Expected an incoming connection"); +2227 }; +2228 let conn = conn.await.anyerr()?; +2229 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; +2230 let data = recv.read_to_end(1000).await.anyerr()?; +2231 send.write_all(&data).await.anyerr()?; +2232 send.finish().anyerr()?; +2233 conn.closed().await; +2234 } +2235 Ok::<_, Error>(()) +2236 } +2237 }); 2238 -2239 let mut addr = server.addr(); -2240 println!("round1: {:?}", addr); -2241 -2242 // remove direct addrs to force relay usage -2243 addr.addrs -2244 .retain(|addr| !matches!(addr, TransportAddr::Ip(_))); -2245 -2246 let conn = client.connect(addr, TEST_ALPN).await?; -2247 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; -2248 send.write_all(b"Hello, world!").await.anyerr()?; -2249 send.finish().anyerr()?; -2250 let data = recv.read_to_end(1000).await.anyerr()?; -2251 conn.close(0u32.into(), b"bye!"); -2252 -2253 assert_eq!(&data, b"Hello, world!"); +2239 server.online().await; +2240 +2241 let mut addr = server.addr(); +2242 println!("round1: {:?}", addr); +2243 +2244 // remove direct addrs to force relay usage +2245 addr.addrs +2246 .retain(|addr| !matches!(addr, TransportAddr::Ip(_))); +2247 +2248 let conn = client.connect(addr, TEST_ALPN).await?; +2249 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; +2250 send.write_all(b"Hello, world!").await.anyerr()?; +2251 send.finish().anyerr()?; +2252 let data = recv.read_to_end(1000).await.anyerr()?; +2253 conn.close(0u32.into(), b"bye!"); 2254 -2255 // setup a second relay server -2256 let (new_relay_map, new_relay_url, _guard2) = run_relay_server().await?; -2257 let new_endpoint = new_relay_map -2258 .get(&new_relay_url) -2259 .expect("missing endpoint") -2260 .clone(); -2261 dbg!(&new_relay_map); -2262 -2263 let addr_watcher = server.watch_addr(); +2255 assert_eq!(&data, b"Hello, world!"); +2256 +2257 // setup a second relay server +2258 let (new_relay_map, new_relay_url, _guard2) = run_relay_server().await?; +2259 let new_endpoint = new_relay_map +2260 .get(&new_relay_url) +2261 .expect("missing endpoint") +2262 .clone(); +2263 dbg!(&new_relay_map); 2264 -2265 // add new new relay -2266 assert!( -2267 server -2268 .insert_relay(new_relay_url.clone(), new_endpoint.clone()) -2269 .await -2270 .is_none() -2271 ); -2272 // remove the old relay -2273 assert!(server.remove_relay(&relay_url).await.is_some()); -2274 -2275 println!("------- changed ----- "); +2265 let addr_watcher = server.watch_addr(); +2266 +2267 // add new new relay +2268 assert!( +2269 server +2270 .insert_relay(new_relay_url.clone(), new_endpoint.clone()) +2271 .await +2272 .is_none() +2273 ); +2274 // remove the old relay +2275 assert!(server.remove_relay(&relay_url).await.is_some()); 2276 -2277 let mut addr = tokio::time::timeout(Duration::from_secs(10), async move { -2278 let mut stream = addr_watcher.stream(); -2279 while let Some(addr) = stream.next().await { -2280 if addr.relay_urls().next() != Some(&relay_url) { -2281 return addr; -2282 } -2283 } -2284 panic!("failed to change relay"); -2285 }) -2286 .await -2287 .anyerr()?; -2288 -2289 println!("round2: {:?}", addr); -2290 assert_eq!(addr.relay_urls().next(), Some(&new_relay_url)); -2291 -2292 // remove direct addrs to force relay usage -2293 addr.addrs -2294 .retain(|addr| !matches!(addr, TransportAddr::Ip(_))); -2295 -2296 let conn = client.connect(addr, TEST_ALPN).await?; -2297 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; -2298 send.write_all(b"Hello, world!").await.anyerr()?; -2299 send.finish().anyerr()?; -2300 let data = recv.read_to_end(1000).await.anyerr()?; -2301 conn.close(0u32.into(), b"bye!"); -2302 -2303 task.await.anyerr()??; +2277 println!("------- changed ----- "); +2278 +2279 let mut addr = tokio::time::timeout(Duration::from_secs(10), async move { +2280 let mut stream = addr_watcher.stream(); +2281 while let Some(addr) = stream.next().await { +2282 if addr.relay_urls().next() != Some(&relay_url) { +2283 return addr; +2284 } +2285 } +2286 panic!("failed to change relay"); +2287 }) +2288 .await +2289 .anyerr()?; +2290 +2291 println!("round2: {:?}", addr); +2292 assert_eq!(addr.relay_urls().next(), Some(&new_relay_url)); +2293 +2294 // remove direct addrs to force relay usage +2295 addr.addrs +2296 .retain(|addr| !matches!(addr, TransportAddr::Ip(_))); +2297 +2298 let conn = client.connect(addr, TEST_ALPN).await?; +2299 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; +2300 send.write_all(b"Hello, world!").await.anyerr()?; +2301 send.finish().anyerr()?; +2302 let data = recv.read_to_end(1000).await.anyerr()?; +2303 conn.close(0u32.into(), b"bye!"); 2304 -2305 client.close().await; -2306 server.close().await; -2307 -2308 assert_eq!(&data, b"Hello, world!"); +2305 task.await.anyerr()??; +2306 +2307 client.close().await; +2308 server.close().await; 2309 -2310 Ok(()) -2311 } -2312 -2313 #[tokio::test] -2314 #[traced_test] -2315 async fn endpoint_bidi_send_recv() -> Result { -2316 let disco = StaticProvider::new(); -2317 let ep1 = Endpoint::empty_builder(RelayMode::Disabled) -2318 .discovery(disco.clone()) -2319 .alpns(vec![TEST_ALPN.to_vec()]) -2320 .bind() -2321 .await?; -2322 -2323 let ep2 = Endpoint::empty_builder(RelayMode::Disabled) -2324 .discovery(disco.clone()) -2325 .alpns(vec![TEST_ALPN.to_vec()]) -2326 .bind() -2327 .await?; -2328 -2329 disco.add_endpoint_info(ep1.addr()); -2330 disco.add_endpoint_info(ep2.addr()); -2331 -2332 let ep1_endpointid = ep1.id(); -2333 let ep2_endpointid = ep2.id(); -2334 eprintln!("endpoint id 1 {ep1_endpointid}"); -2335 eprintln!("endpoint id 2 {ep2_endpointid}"); -2336 -2337 async fn connect_hello(ep: Endpoint, dst: EndpointId) -> Result { -2338 let conn = ep.connect(dst, TEST_ALPN).await?; -2339 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; -2340 info!("sending hello"); -2341 send.write_all(b"hello").await.anyerr()?; -2342 send.finish().anyerr()?; -2343 info!("receiving world"); -2344 let m = recv.read_to_end(100).await.anyerr()?; -2345 assert_eq!(m, b"world"); -2346 conn.close(1u8.into(), b"done"); -2347 Ok(()) -2348 } -2349 -2350 async fn accept_world(ep: Endpoint, src: EndpointId) -> Result { -2351 let incoming = ep.accept().await.anyerr()?; -2352 let mut iconn = incoming.accept().anyerr()?; -2353 let alpn = iconn.alpn().await?; -2354 let conn = iconn.await.anyerr()?; -2355 let endpoint_id = conn.remote_id(); -2356 assert_eq!(endpoint_id, src); -2357 assert_eq!(alpn, TEST_ALPN); -2358 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; -2359 info!("receiving hello"); -2360 let m = recv.read_to_end(100).await.anyerr()?; -2361 assert_eq!(m, b"hello"); -2362 info!("sending hello"); -2363 send.write_all(b"world").await.anyerr()?; -2364 send.finish().anyerr()?; -2365 match conn.closed().await { -2366 ConnectionError::ApplicationClosed(closed) => { -2367 assert_eq!(closed.error_code, 1u8.into()); -2368 Ok(()) -2369 } -2370 _ => panic!("wrong close error"), -2371 } -2372 } -2373 -2374 let p1_accept = tokio::spawn(accept_world(ep1.clone(), ep2_endpointid).instrument( -2375 info_span!( -2376 "p1_accept", -2377 ep1 = %ep1.id().fmt_short(), -2378 dst = %ep2_endpointid.fmt_short(), -2379 ), -2380 )); -2381 let p2_accept = tokio::spawn(accept_world(ep2.clone(), ep1_endpointid).instrument( -2382 info_span!( -2383 "p2_accept", -2384 ep2 = %ep2.id().fmt_short(), -2385 dst = %ep1_endpointid.fmt_short(), -2386 ), -2387 )); -2388 let p1_connect = tokio::spawn(connect_hello(ep1.clone(), ep2_endpointid).instrument( -2389 info_span!( -2390 "p1_connect", -2391 ep1 = %ep1.id().fmt_short(), -2392 dst = %ep2_endpointid.fmt_short(), -2393 ), -2394 )); -2395 let p2_connect = tokio::spawn(connect_hello(ep2.clone(), ep1_endpointid).instrument( -2396 info_span!( -2397 "p2_connect", -2398 ep2 = %ep2.id().fmt_short(), -2399 dst = %ep1_endpointid.fmt_short(), -2400 ), -2401 )); -2402 -2403 p1_accept.await.anyerr()??; -2404 p2_accept.await.anyerr()??; -2405 p1_connect.await.anyerr()??; -2406 p2_connect.await.anyerr()??; -2407 -2408 Ok(()) -2409 } -2410 -2411 #[tokio::test] -2412 #[traced_test] -2413 async fn test_direct_addresses_no_qad_relay() -> Result { -2414 let (relay_map, _, _guard) = run_relay_server_with(false).await.unwrap(); -2415 -2416 let ep = Endpoint::empty_builder(RelayMode::Custom(relay_map)) -2417 .alpns(vec![TEST_ALPN.to_vec()]) -2418 .insecure_skip_relay_cert_verify(true) -2419 .bind() -2420 .await?; -2421 -2422 assert!(ep.addr().ip_addrs().count() > 0); +2310 assert_eq!(&data, b"Hello, world!"); +2311 +2312 Ok(()) +2313 } +2314 +2315 #[tokio::test] +2316 #[traced_test] +2317 async fn endpoint_bidi_send_recv() -> Result { +2318 let disco = StaticProvider::new(); +2319 let ep1 = Endpoint::empty_builder(RelayMode::Disabled) +2320 .discovery(disco.clone()) +2321 .alpns(vec![TEST_ALPN.to_vec()]) +2322 .bind() +2323 .await?; +2324 +2325 let ep2 = Endpoint::empty_builder(RelayMode::Disabled) +2326 .discovery(disco.clone()) +2327 .alpns(vec![TEST_ALPN.to_vec()]) +2328 .bind() +2329 .await?; +2330 +2331 disco.add_endpoint_info(ep1.addr()); +2332 disco.add_endpoint_info(ep2.addr()); +2333 +2334 let ep1_endpointid = ep1.id(); +2335 let ep2_endpointid = ep2.id(); +2336 eprintln!("endpoint id 1 {ep1_endpointid}"); +2337 eprintln!("endpoint id 2 {ep2_endpointid}"); +2338 +2339 async fn connect_hello(ep: Endpoint, dst: EndpointId) -> Result { +2340 let conn = ep.connect(dst, TEST_ALPN).await?; +2341 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; +2342 info!("sending hello"); +2343 send.write_all(b"hello").await.anyerr()?; +2344 send.finish().anyerr()?; +2345 info!("receiving world"); +2346 let m = recv.read_to_end(100).await.anyerr()?; +2347 assert_eq!(m, b"world"); +2348 conn.close(1u8.into(), b"done"); +2349 Ok(()) +2350 } +2351 +2352 async fn accept_world(ep: Endpoint, src: EndpointId) -> Result { +2353 let incoming = ep.accept().await.anyerr()?; +2354 let mut iconn = incoming.accept().anyerr()?; +2355 let alpn = iconn.alpn().await?; +2356 let conn = iconn.await.anyerr()?; +2357 let endpoint_id = conn.remote_id(); +2358 assert_eq!(endpoint_id, src); +2359 assert_eq!(alpn, TEST_ALPN); +2360 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; +2361 info!("receiving hello"); +2362 let m = recv.read_to_end(100).await.anyerr()?; +2363 assert_eq!(m, b"hello"); +2364 info!("sending hello"); +2365 send.write_all(b"world").await.anyerr()?; +2366 send.finish().anyerr()?; +2367 match conn.closed().await { +2368 ConnectionError::ApplicationClosed(closed) => { +2369 assert_eq!(closed.error_code, 1u8.into()); +2370 Ok(()) +2371 } +2372 _ => panic!("wrong close error"), +2373 } +2374 } +2375 +2376 let p1_accept = tokio::spawn(accept_world(ep1.clone(), ep2_endpointid).instrument( +2377 info_span!( +2378 "p1_accept", +2379 ep1 = %ep1.id().fmt_short(), +2380 dst = %ep2_endpointid.fmt_short(), +2381 ), +2382 )); +2383 let p2_accept = tokio::spawn(accept_world(ep2.clone(), ep1_endpointid).instrument( +2384 info_span!( +2385 "p2_accept", +2386 ep2 = %ep2.id().fmt_short(), +2387 dst = %ep1_endpointid.fmt_short(), +2388 ), +2389 )); +2390 let p1_connect = tokio::spawn(connect_hello(ep1.clone(), ep2_endpointid).instrument( +2391 info_span!( +2392 "p1_connect", +2393 ep1 = %ep1.id().fmt_short(), +2394 dst = %ep2_endpointid.fmt_short(), +2395 ), +2396 )); +2397 let p2_connect = tokio::spawn(connect_hello(ep2.clone(), ep1_endpointid).instrument( +2398 info_span!( +2399 "p2_connect", +2400 ep2 = %ep2.id().fmt_short(), +2401 dst = %ep1_endpointid.fmt_short(), +2402 ), +2403 )); +2404 +2405 p1_accept.await.anyerr()??; +2406 p2_accept.await.anyerr()??; +2407 p1_connect.await.anyerr()??; +2408 p2_connect.await.anyerr()??; +2409 +2410 Ok(()) +2411 } +2412 +2413 #[tokio::test] +2414 #[traced_test] +2415 async fn test_direct_addresses_no_qad_relay() -> Result { +2416 let (relay_map, _, _guard) = run_relay_server_with(false).await.unwrap(); +2417 +2418 let ep = Endpoint::empty_builder(RelayMode::Custom(relay_map)) +2419 .alpns(vec![TEST_ALPN.to_vec()]) +2420 .insecure_skip_relay_cert_verify(true) +2421 .bind() +2422 .await?; 2423 -2424 Ok(()) -2425 } -2426 -2427 #[cfg_attr(target_os = "windows", ignore = "flaky")] -2428 #[tokio::test] -2429 #[traced_test] -2430 async fn graceful_close() -> Result { -2431 let client = Endpoint::empty_builder(RelayMode::Disabled).bind().await?; -2432 let server = Endpoint::empty_builder(RelayMode::Disabled) -2433 .alpns(vec![TEST_ALPN.to_vec()]) -2434 .bind() -2435 .await?; -2436 let server_addr = server.addr(); -2437 let server_task = tokio::spawn(async move { -2438 let incoming = server.accept().await.anyerr()?; -2439 let conn = incoming.await.anyerr()?; -2440 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; -2441 let msg = recv.read_to_end(1_000).await.anyerr()?; -2442 send.write_all(&msg).await.anyerr()?; -2443 send.finish().anyerr()?; -2444 let close_reason = conn.closed().await; -2445 Ok::<_, Error>(close_reason) -2446 }); -2447 -2448 let conn = client.connect(server_addr, TEST_ALPN).await?; -2449 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; -2450 send.write_all(b"Hello, world!").await.anyerr()?; -2451 send.finish().anyerr()?; -2452 recv.read_to_end(1_000).await.anyerr()?; -2453 conn.close(42u32.into(), b"thanks, bye!"); -2454 client.close().await; -2455 -2456 let close_err = server_task.await.anyerr()??; -2457 let ConnectionError::ApplicationClosed(app_close) = close_err else { -2458 panic!("Unexpected close reason: {close_err:?}"); -2459 }; -2460 -2461 assert_eq!(app_close.error_code, 42u32.into()); -2462 assert_eq!(app_close.reason.as_ref(), b"thanks, bye!"); -2463 -2464 Ok(()) -2465 } -2466 -2467 #[cfg(feature = "metrics")] -2468 #[tokio::test] -2469 #[traced_test] -2470 async fn metrics_smoke() -> Result { -2471 use iroh_metrics::Registry; -2472 -2473 let secret_key = SecretKey::from_bytes(&[0u8; 32]); -2474 let client = Endpoint::empty_builder(RelayMode::Disabled) -2475 .secret_key(secret_key) -2476 .bind() -2477 .await?; -2478 let secret_key = SecretKey::from_bytes(&[1u8; 32]); -2479 let server = Endpoint::empty_builder(RelayMode::Disabled) -2480 .secret_key(secret_key) -2481 .alpns(vec![TEST_ALPN.to_vec()]) -2482 .bind() -2483 .await?; -2484 let server_addr = server.addr(); -2485 let server_task = tokio::task::spawn(async move { -2486 let conn = server.accept().await.anyerr()?.await.anyerr()?; -2487 let mut uni = conn.accept_uni().await.anyerr()?; -2488 uni.read_to_end(10).await.anyerr()?; -2489 drop(conn); -2490 Ok::<_, Error>(server) -2491 }); -2492 let conn = client.connect(server_addr, TEST_ALPN).await?; -2493 let mut uni = conn.open_uni().await.anyerr()?; -2494 uni.write_all(b"helloworld").await.anyerr()?; -2495 uni.finish().anyerr()?; -2496 conn.closed().await; -2497 drop(conn); -2498 let server = server_task.await.anyerr()??; -2499 -2500 let m = client.metrics(); -2501 // assert_eq!(m.magicsock.num_direct_conns_added.get(), 1); -2502 // assert_eq!(m.magicsock.connection_became_direct.get(), 1); -2503 // assert_eq!(m.magicsock.connection_handshake_success.get(), 1); -2504 // assert_eq!(m.magicsock.endpoints_contacted_directly.get(), 1); -2505 assert!(m.magicsock.recv_datagrams.get() > 0); -2506 -2507 let m = server.metrics(); -2508 // assert_eq!(m.magicsock.num_direct_conns_added.get(), 1); -2509 // assert_eq!(m.magicsock.connection_became_direct.get(), 1); -2510 // assert_eq!(m.magicsock.endpoints_contacted_directly.get(), 1); -2511 // assert_eq!(m.magicsock.connection_handshake_success.get(), 1); -2512 assert!(m.magicsock.recv_datagrams.get() > 0); -2513 -2514 // test openmetrics encoding with labeled subregistries per endpoint -2515 fn register_endpoint(registry: &mut Registry, endpoint: &Endpoint) { -2516 let id = endpoint.id().fmt_short(); -2517 let sub_registry = registry.sub_registry_with_label("id", id.to_string()); -2518 sub_registry.register_all(endpoint.metrics()); -2519 } -2520 let mut registry = Registry::default(); -2521 register_endpoint(&mut registry, &client); -2522 register_endpoint(&mut registry, &server); -2523 // let s = registry.encode_openmetrics_to_string().anyerr()?; -2524 // assert!(s.contains(r#"magicsock_endpoints_contacted_directly_total{id="3b6a27bcce"} 1"#)); -2525 // assert!(s.contains(r#"magicsock_endpoints_contacted_directly_total{id="8a88e3dd74"} 1"#)); -2526 Ok(()) -2527 } -2528 -2529 /// Configures the accept side to take `accept_alpns` ALPNs, then connects to it with `primary_connect_alpn` -2530 /// with `secondary_connect_alpns` set, and finally returns the negotiated ALPN. -2531 async fn alpn_connection_test( -2532 accept_alpns: Vec<Vec<u8>>, -2533 primary_connect_alpn: &[u8], -2534 secondary_connect_alpns: Vec<Vec<u8>>, -2535 ) -> Result<Vec<u8>> { -2536 let client = Endpoint::empty_builder(RelayMode::Disabled).bind().await?; -2537 let server = Endpoint::empty_builder(RelayMode::Disabled) -2538 .alpns(accept_alpns) -2539 .bind() -2540 .await?; -2541 let server_addr = server.addr(); -2542 let server_task = tokio::spawn({ -2543 let server = server.clone(); -2544 async move { -2545 let incoming = server.accept().await.anyerr()?; -2546 let conn = incoming.await.anyerr()?; -2547 conn.close(0u32.into(), b"bye!"); -2548 n0_error::Ok(conn.alpn().to_vec()) -2549 } -2550 }); -2551 -2552 let conn = client -2553 .connect_with_opts( -2554 server_addr, -2555 primary_connect_alpn, -2556 ConnectOptions::new().with_additional_alpns(secondary_connect_alpns), -2557 ) -2558 .await?; -2559 let conn = conn.await.anyerr()?; -2560 let client_alpn = conn.alpn(); -2561 conn.closed().await; -2562 client.close().await; -2563 server.close().await; -2564 -2565 let server_alpn = server_task.await.anyerr()??; +2424 assert!(ep.addr().ip_addrs().count() > 0); +2425 +2426 Ok(()) +2427 } +2428 +2429 #[cfg_attr(target_os = "windows", ignore = "flaky")] +2430 #[tokio::test] +2431 #[traced_test] +2432 async fn graceful_close() -> Result { +2433 let client = Endpoint::empty_builder(RelayMode::Disabled).bind().await?; +2434 let server = Endpoint::empty_builder(RelayMode::Disabled) +2435 .alpns(vec![TEST_ALPN.to_vec()]) +2436 .bind() +2437 .await?; +2438 let server_addr = server.addr(); +2439 let server_task = tokio::spawn(async move { +2440 let incoming = server.accept().await.anyerr()?; +2441 let conn = incoming.await.anyerr()?; +2442 let (mut send, mut recv) = conn.accept_bi().await.anyerr()?; +2443 let msg = recv.read_to_end(1_000).await.anyerr()?; +2444 send.write_all(&msg).await.anyerr()?; +2445 send.finish().anyerr()?; +2446 let close_reason = conn.closed().await; +2447 Ok::<_, Error>(close_reason) +2448 }); +2449 +2450 let conn = client.connect(server_addr, TEST_ALPN).await?; +2451 let (mut send, mut recv) = conn.open_bi().await.anyerr()?; +2452 send.write_all(b"Hello, world!").await.anyerr()?; +2453 send.finish().anyerr()?; +2454 recv.read_to_end(1_000).await.anyerr()?; +2455 conn.close(42u32.into(), b"thanks, bye!"); +2456 client.close().await; +2457 +2458 let close_err = server_task.await.anyerr()??; +2459 let ConnectionError::ApplicationClosed(app_close) = close_err else { +2460 panic!("Unexpected close reason: {close_err:?}"); +2461 }; +2462 +2463 assert_eq!(app_close.error_code, 42u32.into()); +2464 assert_eq!(app_close.reason.as_ref(), b"thanks, bye!"); +2465 +2466 Ok(()) +2467 } +2468 +2469 #[cfg(feature = "metrics")] +2470 #[tokio::test] +2471 #[traced_test] +2472 async fn metrics_smoke() -> Result { +2473 use iroh_metrics::Registry; +2474 +2475 let secret_key = SecretKey::from_bytes(&[0u8; 32]); +2476 let client = Endpoint::empty_builder(RelayMode::Disabled) +2477 .secret_key(secret_key) +2478 .bind() +2479 .await?; +2480 let secret_key = SecretKey::from_bytes(&[1u8; 32]); +2481 let server = Endpoint::empty_builder(RelayMode::Disabled) +2482 .secret_key(secret_key) +2483 .alpns(vec![TEST_ALPN.to_vec()]) +2484 .bind() +2485 .await?; +2486 let server_addr = server.addr(); +2487 let server_task = tokio::task::spawn(async move { +2488 let conn = server.accept().await.anyerr()?.await.anyerr()?; +2489 let mut uni = conn.accept_uni().await.anyerr()?; +2490 uni.read_to_end(10).await.anyerr()?; +2491 drop(conn); +2492 Ok::<_, Error>(server) +2493 }); +2494 let conn = client.connect(server_addr, TEST_ALPN).await?; +2495 let mut uni = conn.open_uni().await.anyerr()?; +2496 uni.write_all(b"helloworld").await.anyerr()?; +2497 uni.finish().anyerr()?; +2498 conn.closed().await; +2499 drop(conn); +2500 let server = server_task.await.anyerr()??; +2501 +2502 let m = client.metrics(); +2503 // assert_eq!(m.magicsock.num_direct_conns_added.get(), 1); +2504 // assert_eq!(m.magicsock.connection_became_direct.get(), 1); +2505 // assert_eq!(m.magicsock.connection_handshake_success.get(), 1); +2506 // assert_eq!(m.magicsock.endpoints_contacted_directly.get(), 1); +2507 assert!(m.magicsock.recv_datagrams.get() > 0); +2508 +2509 let m = server.metrics(); +2510 // assert_eq!(m.magicsock.num_direct_conns_added.get(), 1); +2511 // assert_eq!(m.magicsock.connection_became_direct.get(), 1); +2512 // assert_eq!(m.magicsock.endpoints_contacted_directly.get(), 1); +2513 // assert_eq!(m.magicsock.connection_handshake_success.get(), 1); +2514 assert!(m.magicsock.recv_datagrams.get() > 0); +2515 +2516 // test openmetrics encoding with labeled subregistries per endpoint +2517 fn register_endpoint(registry: &mut Registry, endpoint: &Endpoint) { +2518 let id = endpoint.id().fmt_short(); +2519 let sub_registry = registry.sub_registry_with_label("id", id.to_string()); +2520 sub_registry.register_all(endpoint.metrics()); +2521 } +2522 let mut registry = Registry::default(); +2523 register_endpoint(&mut registry, &client); +2524 register_endpoint(&mut registry, &server); +2525 // let s = registry.encode_openmetrics_to_string().anyerr()?; +2526 // assert!(s.contains(r#"magicsock_endpoints_contacted_directly_total{id="3b6a27bcce"} 1"#)); +2527 // assert!(s.contains(r#"magicsock_endpoints_contacted_directly_total{id="8a88e3dd74"} 1"#)); +2528 Ok(()) +2529 } +2530 +2531 /// Configures the accept side to take `accept_alpns` ALPNs, then connects to it with `primary_connect_alpn` +2532 /// with `secondary_connect_alpns` set, and finally returns the negotiated ALPN. +2533 async fn alpn_connection_test( +2534 accept_alpns: Vec<Vec<u8>>, +2535 primary_connect_alpn: &[u8], +2536 secondary_connect_alpns: Vec<Vec<u8>>, +2537 ) -> Result<Vec<u8>> { +2538 let client = Endpoint::empty_builder(RelayMode::Disabled).bind().await?; +2539 let server = Endpoint::empty_builder(RelayMode::Disabled) +2540 .alpns(accept_alpns) +2541 .bind() +2542 .await?; +2543 let server_addr = server.addr(); +2544 let server_task = tokio::spawn({ +2545 let server = server.clone(); +2546 async move { +2547 let incoming = server.accept().await.anyerr()?; +2548 let conn = incoming.await.anyerr()?; +2549 conn.close(0u32.into(), b"bye!"); +2550 n0_error::Ok(conn.alpn().to_vec()) +2551 } +2552 }); +2553 +2554 let conn = client +2555 .connect_with_opts( +2556 server_addr, +2557 primary_connect_alpn, +2558 ConnectOptions::new().with_additional_alpns(secondary_connect_alpns), +2559 ) +2560 .await?; +2561 let conn = conn.await.anyerr()?; +2562 let client_alpn = conn.alpn(); +2563 conn.closed().await; +2564 client.close().await; +2565 server.close().await; 2566 -2567 assert_eq!(client_alpn, server_alpn); +2567 let server_alpn = server_task.await.anyerr()??; 2568 -2569 Ok(server_alpn.to_vec()) -2570 } -2571 -2572 #[tokio::test] -2573 #[traced_test] -2574 async fn connect_multiple_alpn_negotiated() -> Result { -2575 const ALPN_ONE: &[u8] = b"alpn/1"; -2576 const ALPN_TWO: &[u8] = b"alpn/2"; -2577 -2578 assert_eq!( -2579 alpn_connection_test( -2580 // Prefer version 2 over version 1 on the accept side -2581 vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], -2582 ALPN_TWO, -2583 vec![ALPN_ONE.to_vec()], -2584 ) -2585 .await?, -2586 ALPN_TWO.to_vec(), -2587 "accept side prefers version 2 over 1" -2588 ); -2589 -2590 assert_eq!( -2591 alpn_connection_test( -2592 // Only support the old version -2593 vec![ALPN_ONE.to_vec()], -2594 ALPN_TWO, -2595 vec![ALPN_ONE.to_vec()], -2596 ) -2597 .await?, -2598 ALPN_ONE.to_vec(), -2599 "accept side only supports the old version" -2600 ); -2601 -2602 assert_eq!( -2603 alpn_connection_test( -2604 vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], -2605 ALPN_ONE, -2606 vec![ALPN_TWO.to_vec()], -2607 ) -2608 .await?, -2609 ALPN_TWO.to_vec(), -2610 "connect side ALPN order doesn't matter" -2611 ); -2612 -2613 assert_eq!( -2614 alpn_connection_test(vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], ALPN_ONE, vec![],) -2615 .await?, -2616 ALPN_ONE.to_vec(), -2617 "connect side only supports the old version" -2618 ); -2619 -2620 Ok(()) -2621 } -2622 -2623 #[tokio::test] -2624 #[traced_test] -2625 async fn watch_net_report() -> Result { -2626 let endpoint = Endpoint::empty_builder(RelayMode::Staging).bind().await?; -2627 -2628 // can get a first report -2629 endpoint.net_report().updated().await.anyerr()?; -2630 -2631 Ok(()) -2632 } -2633 -2634 /// Tests that initial connection establishment isn't extremely slow compared -2635 /// to subsequent connections. -2636 /// -2637 /// This is a time based test, but uses a very large ratio to reduce flakiness. -2638 /// It also does a number of connections to average out any anomalies. -2639 #[tokio::test] -2640 #[traced_test] -2641 async fn connect_multi_time() -> Result { -2642 let n = 32; -2643 -2644 const NOOP_ALPN: &[u8] = b"noop"; +2569 assert_eq!(client_alpn, server_alpn); +2570 +2571 Ok(server_alpn.to_vec()) +2572 } +2573 +2574 #[tokio::test] +2575 #[traced_test] +2576 async fn connect_multiple_alpn_negotiated() -> Result { +2577 const ALPN_ONE: &[u8] = b"alpn/1"; +2578 const ALPN_TWO: &[u8] = b"alpn/2"; +2579 +2580 assert_eq!( +2581 alpn_connection_test( +2582 // Prefer version 2 over version 1 on the accept side +2583 vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], +2584 ALPN_TWO, +2585 vec![ALPN_ONE.to_vec()], +2586 ) +2587 .await?, +2588 ALPN_TWO.to_vec(), +2589 "accept side prefers version 2 over 1" +2590 ); +2591 +2592 assert_eq!( +2593 alpn_connection_test( +2594 // Only support the old version +2595 vec![ALPN_ONE.to_vec()], +2596 ALPN_TWO, +2597 vec![ALPN_ONE.to_vec()], +2598 ) +2599 .await?, +2600 ALPN_ONE.to_vec(), +2601 "accept side only supports the old version" +2602 ); +2603 +2604 assert_eq!( +2605 alpn_connection_test( +2606 vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], +2607 ALPN_ONE, +2608 vec![ALPN_TWO.to_vec()], +2609 ) +2610 .await?, +2611 ALPN_TWO.to_vec(), +2612 "connect side ALPN order doesn't matter" +2613 ); +2614 +2615 assert_eq!( +2616 alpn_connection_test(vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], ALPN_ONE, vec![],) +2617 .await?, +2618 ALPN_ONE.to_vec(), +2619 "connect side only supports the old version" +2620 ); +2621 +2622 Ok(()) +2623 } +2624 +2625 #[tokio::test] +2626 #[traced_test] +2627 async fn watch_net_report() -> Result { +2628 let endpoint = Endpoint::empty_builder(RelayMode::Staging).bind().await?; +2629 +2630 // can get a first report +2631 endpoint.net_report().updated().await.anyerr()?; +2632 +2633 Ok(()) +2634 } +2635 +2636 /// Tests that initial connection establishment isn't extremely slow compared +2637 /// to subsequent connections. +2638 /// +2639 /// This is a time based test, but uses a very large ratio to reduce flakiness. +2640 /// It also does a number of connections to average out any anomalies. +2641 #[tokio::test] +2642 #[traced_test] +2643 async fn connect_multi_time() -> Result { +2644 let n = 32; 2645 -2646 #[derive(Debug, Clone)] -2647 struct Noop; -2648 -2649 impl ProtocolHandler for Noop { -2650 async fn accept(&self, connection: Connection) -> Result<(), AcceptError> { -2651 connection.closed().await; -2652 Ok(()) -2653 } -2654 } -2655 -2656 async fn noop_server() -> Result<(Router, EndpointAddr)> { -2657 let endpoint = Endpoint::empty_builder(RelayMode::Disabled) -2658 .bind() -2659 .await -2660 .anyerr()?; -2661 let addr = endpoint.addr(); -2662 let router = Router::builder(endpoint).accept(NOOP_ALPN, Noop).spawn(); -2663 Ok((router, addr)) -2664 } -2665 -2666 let routers = stream::iter(0..n) -2667 .map(|_| noop_server()) -2668 .buffered_unordered(32) -2669 .collect::<Vec<_>>() -2670 .await -2671 .into_iter() -2672 .collect::<Result<Vec<_>, _>>() -2673 .anyerr()?; -2674 -2675 let addrs = routers -2676 .iter() -2677 .map(|(_, addr)| addr.clone()) -2678 .collect::<Vec<_>>(); -2679 let ids = addrs.iter().map(|addr| addr.id).collect::<Vec<_>>(); -2680 let discovery = StaticProvider::from_endpoint_info(addrs); -2681 let endpoint = Endpoint::empty_builder(RelayMode::Disabled) -2682 .discovery(discovery) -2683 .bind() -2684 .await -2685 .anyerr()?; -2686 // wait for the endpoint to be initialized. This should not be needed, -2687 // but we don't want to measure endpoint init time but connection time -2688 // from a fully initialized endpoint. -2689 endpoint.addr(); -2690 let t0 = Instant::now(); -2691 for id in &ids { -2692 let conn = endpoint.connect(*id, NOOP_ALPN).await?; -2693 conn.close(0u32.into(), b"done"); -2694 } -2695 let dt0 = t0.elapsed().as_secs_f64(); -2696 let t1 = Instant::now(); -2697 for id in &ids { -2698 let conn = endpoint.connect(*id, NOOP_ALPN).await?; -2699 conn.close(0u32.into(), b"done"); -2700 } -2701 let dt1 = t1.elapsed().as_secs_f64(); -2702 -2703 assert!(dt0 / dt1 < 20.0, "First round: {dt0}s, second round {dt1}s"); -2704 Ok(()) -2705 } -2706 -2707 #[tokio::test] -2708 async fn test_custom_relay() -> Result { -2709 let _ep = Endpoint::empty_builder(RelayMode::custom([RelayUrl::from_str( -2710 "https://use1-1.relay.n0.iroh-canary.iroh.link.", -2711 )?])) -2712 .bind() -2713 .await?; -2714 -2715 let relays = RelayMap::try_from_iter([ -2716 "https://use1-1.relay.n0.iroh.iroh.link/", -2717 "https://euc1-1.relay.n0.iroh.iroh.link/", -2718 ])?; -2719 let _ep = Endpoint::empty_builder(RelayMode::Custom(relays)) -2720 .bind() -2721 .await?; -2722 -2723 Ok(()) -2724 } -2725 -2726 /// Testing bind_addr: Clear IP transports and add single IPv4 bind -2727 #[tokio::test] -2728 #[traced_test] -2729 async fn test_bind_addr_clear() -> Result { -2730 let ep = Endpoint::empty_builder(RelayMode::Disabled) -2731 .clear_ip_transports() -2732 .bind_addr((Ipv4Addr::LOCALHOST, 0))? -2733 .bind() -2734 .await?; -2735 let bound_sockets = ep.bound_sockets(); -2736 assert_eq!(bound_sockets.len(), 1); -2737 assert_eq!(bound_sockets[0].ip(), IpAddr::V4(Ipv4Addr::LOCALHOST)); -2738 ep.close().await; -2739 Ok(()) -2740 } -2741 -2742 /// Testing bind_addr: Do not clear IP transports and add single non-default IPv4 bind -2743 /// -2744 /// This will bind three sockets: wildcard binds for IPv4 and IPv6, and our -2745 /// manually-added IPv4 bind. -2746 #[tokio::test] -2747 #[traced_test] -2748 async fn test_bind_addr_no_clear() -> Result { -2749 // test 2: do not clear ip transports and add single non-default IPv4 bind -2750 let ep = Endpoint::empty_builder(RelayMode::Disabled) -2751 .bind_addr((Ipv4Addr::LOCALHOST, 0))? -2752 .bind() -2753 .await?; -2754 let bound_sockets = ep.bound_sockets(); -2755 assert_eq!(bound_sockets.len(), 3); -2756 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv4()).count(), 2); -2757 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv6()).count(), 1); -2758 // Test that our manually added socket is there -2759 assert!( -2760 bound_sockets -2761 .iter() -2762 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST)) -2763 ); -2764 // Test that the default wildcard socket is there -2765 assert!( -2766 bound_sockets -2767 .iter() -2768 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::UNSPECIFIED)) -2769 ); -2770 ep.close().await; -2771 Ok(()) -2772 } -2773 -2774 // Testing bind_addr: Do not clear IP transports and add single default IPv4 bind. -2775 // -2776 // This replaces the default IPv4 bind added by the builder, -2777 // but keeps the default wildcard IPv6 bind. -2778 #[tokio::test] -2779 #[traced_test] -2780 async fn test_bind_addr_default() -> Result { -2781 let ep = Endpoint::empty_builder(RelayMode::Disabled) -2782 .bind_addr_with_opts( -2783 (Ipv4Addr::LOCALHOST, 0), -2784 BindOpts::default().set_is_default_route(true), -2785 )? -2786 .bind() -2787 .await?; -2788 let bound_sockets = ep.bound_sockets(); -2789 assert_eq!(bound_sockets.len(), 2); -2790 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv4()).count(), 1); -2791 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv6()).count(), 1); -2792 assert!( -2793 bound_sockets -2794 .iter() -2795 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST)) -2796 ); -2797 ep.close().await; -2798 drop(ep); -2799 -2800 Ok(()) -2801 } -2802 -2803 /// Bind on an unusable port with the default opts. -2804 /// -2805 /// Binding the endpoint fails with an AddrInUse error. -2806 #[tokio::test] -2807 #[traced_test] -2808 async fn test_bind_addr_unusuable_port() -> Result { -2809 let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?; -2810 let port = socket.local_addr()?.port(); -2811 -2812 let res = Endpoint::empty_builder(RelayMode::Disabled) -2813 .clear_ip_transports() -2814 .bind_addr((Ipv4Addr::LOCALHOST, port))? -2815 .bind() -2816 .await; -2817 -2818 assert!(matches!( -2819 res, -2820 Err(BindError::MagicSpawn { -2821 source: CreateHandleError::BindSockets { -2822 source: io_error, -2823 .. -2824 }, -2825 .. -2826 }) -2827 if io_error.kind() == io::ErrorKind::AddrInUse -2828 )); -2829 Ok(()) -2830 } -2831 -2832 /// Bind on an unusable port, but set is_required = false. -2833 /// -2834 /// Binding the endpoint succeeds. -2835 #[tokio::test] -2836 #[traced_test] -2837 async fn test_bind_addr_unusuable_port_not_required() -> Result { -2838 let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?; -2839 let port = socket.local_addr()?.port(); -2840 -2841 let ep = Endpoint::empty_builder(RelayMode::Disabled) -2842 .bind_addr_with_opts( -2843 (Ipv4Addr::LOCALHOST, port), -2844 BindOpts::default().set_is_required(false), -2845 )? -2846 .bind() -2847 .await?; -2848 let bound_sockets = ep.bound_sockets(); -2849 // just the default wildcard binds -2850 assert_eq!(bound_sockets.len(), 2); -2851 // our requested bind addr is not included because it failed to bind -2852 assert!( -2853 bound_sockets -2854 .iter() -2855 .find(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST)) -2856 .is_none() -2857 ); -2858 Ok(()) -2859 } -2860 -2861 /// Bind on an unusable port, with is_required = false, and no other transports. -2862 /// -2863 /// Binding the endpoint fails with "no valid address available". -2864 #[tokio::test] -2865 #[traced_test] -2866 async fn test_bind_addr_unusable_port_not_required_no_other_transports() -> Result { -2867 let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?; -2868 let port = socket.local_addr()?.port(); -2869 -2870 let res = Endpoint::empty_builder(RelayMode::Disabled) -2871 .clear_ip_transports() -2872 .bind_addr_with_opts( -2873 (Ipv4Addr::LOCALHOST, port), -2874 BindOpts::default().set_is_required(false), -2875 )? -2876 .bind() -2877 .await; -2878 -2879 assert!(matches!( -2880 res, -2881 Err(BindError::MagicSpawn { -2882 source: CreateHandleError::CreateQuinnEndpoint { -2883 source: io_error, -2884 .. -2885 }, -2886 .. -2887 }) -2888 if io_error.kind() == io::ErrorKind::Other && io_error.to_string() == "no valid address available" -2889 )); -2890 Ok(()) -2891 } -2892}
    \ No newline at end of file +2646 const NOOP_ALPN: &[u8] = b"noop"; +2647 +2648 #[derive(Debug, Clone)] +2649 struct Noop; +2650 +2651 impl ProtocolHandler for Noop { +2652 async fn accept(&self, connection: Connection) -> Result<(), AcceptError> { +2653 connection.closed().await; +2654 Ok(()) +2655 } +2656 } +2657 +2658 async fn noop_server() -> Result<(Router, EndpointAddr)> { +2659 let endpoint = Endpoint::empty_builder(RelayMode::Disabled) +2660 .bind() +2661 .await +2662 .anyerr()?; +2663 let addr = endpoint.addr(); +2664 let router = Router::builder(endpoint).accept(NOOP_ALPN, Noop).spawn(); +2665 Ok((router, addr)) +2666 } +2667 +2668 let routers = stream::iter(0..n) +2669 .map(|_| noop_server()) +2670 .buffered_unordered(32) +2671 .collect::<Vec<_>>() +2672 .await +2673 .into_iter() +2674 .collect::<Result<Vec<_>, _>>() +2675 .anyerr()?; +2676 +2677 let addrs = routers +2678 .iter() +2679 .map(|(_, addr)| addr.clone()) +2680 .collect::<Vec<_>>(); +2681 let ids = addrs.iter().map(|addr| addr.id).collect::<Vec<_>>(); +2682 let discovery = StaticProvider::from_endpoint_info(addrs); +2683 let endpoint = Endpoint::empty_builder(RelayMode::Disabled) +2684 .discovery(discovery) +2685 .bind() +2686 .await +2687 .anyerr()?; +2688 // wait for the endpoint to be initialized. This should not be needed, +2689 // but we don't want to measure endpoint init time but connection time +2690 // from a fully initialized endpoint. +2691 endpoint.addr(); +2692 let t0 = Instant::now(); +2693 for id in &ids { +2694 let conn = endpoint.connect(*id, NOOP_ALPN).await?; +2695 conn.close(0u32.into(), b"done"); +2696 } +2697 let dt0 = t0.elapsed().as_secs_f64(); +2698 let t1 = Instant::now(); +2699 for id in &ids { +2700 let conn = endpoint.connect(*id, NOOP_ALPN).await?; +2701 conn.close(0u32.into(), b"done"); +2702 } +2703 let dt1 = t1.elapsed().as_secs_f64(); +2704 +2705 assert!(dt0 / dt1 < 20.0, "First round: {dt0}s, second round {dt1}s"); +2706 Ok(()) +2707 } +2708 +2709 #[tokio::test] +2710 async fn test_custom_relay() -> Result { +2711 let _ep = Endpoint::empty_builder(RelayMode::custom([RelayUrl::from_str( +2712 "https://use1-1.relay.n0.iroh-canary.iroh.link.", +2713 )?])) +2714 .bind() +2715 .await?; +2716 +2717 let relays = RelayMap::try_from_iter([ +2718 "https://use1-1.relay.n0.iroh.iroh.link/", +2719 "https://euc1-1.relay.n0.iroh.iroh.link/", +2720 ])?; +2721 let _ep = Endpoint::empty_builder(RelayMode::Custom(relays)) +2722 .bind() +2723 .await?; +2724 +2725 Ok(()) +2726 } +2727 +2728 /// Testing bind_addr: Clear IP transports and add single IPv4 bind +2729 #[tokio::test] +2730 #[traced_test] +2731 async fn test_bind_addr_clear() -> Result { +2732 let ep = Endpoint::empty_builder(RelayMode::Disabled) +2733 .clear_ip_transports() +2734 .bind_addr((Ipv4Addr::LOCALHOST, 0))? +2735 .bind() +2736 .await?; +2737 let bound_sockets = ep.bound_sockets(); +2738 assert_eq!(bound_sockets.len(), 1); +2739 assert_eq!(bound_sockets[0].ip(), IpAddr::V4(Ipv4Addr::LOCALHOST)); +2740 ep.close().await; +2741 Ok(()) +2742 } +2743 +2744 /// Testing bind_addr: Do not clear IP transports and add single non-default IPv4 bind +2745 /// +2746 /// This will bind three sockets: wildcard binds for IPv4 and IPv6, and our +2747 /// manually-added IPv4 bind. +2748 #[tokio::test] +2749 #[traced_test] +2750 async fn test_bind_addr_no_clear() -> Result { +2751 // test 2: do not clear ip transports and add single non-default IPv4 bind +2752 let ep = Endpoint::empty_builder(RelayMode::Disabled) +2753 .bind_addr((Ipv4Addr::LOCALHOST, 0))? +2754 .bind() +2755 .await?; +2756 let bound_sockets = ep.bound_sockets(); +2757 assert_eq!(bound_sockets.len(), 3); +2758 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv4()).count(), 2); +2759 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv6()).count(), 1); +2760 // Test that our manually added socket is there +2761 assert!( +2762 bound_sockets +2763 .iter() +2764 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST)) +2765 ); +2766 // Test that the default wildcard socket is there +2767 assert!( +2768 bound_sockets +2769 .iter() +2770 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::UNSPECIFIED)) +2771 ); +2772 ep.close().await; +2773 Ok(()) +2774 } +2775 +2776 // Testing bind_addr: Do not clear IP transports and add single default IPv4 bind. +2777 // +2778 // This replaces the default IPv4 bind added by the builder, +2779 // but keeps the default wildcard IPv6 bind. +2780 #[tokio::test] +2781 #[traced_test] +2782 async fn test_bind_addr_default() -> Result { +2783 let ep = Endpoint::empty_builder(RelayMode::Disabled) +2784 .bind_addr_with_opts( +2785 (Ipv4Addr::LOCALHOST, 0), +2786 BindOpts::default().set_is_default_route(true), +2787 )? +2788 .bind() +2789 .await?; +2790 let bound_sockets = ep.bound_sockets(); +2791 assert_eq!(bound_sockets.len(), 2); +2792 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv4()).count(), 1); +2793 assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv6()).count(), 1); +2794 assert!( +2795 bound_sockets +2796 .iter() +2797 .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST)) +2798 ); +2799 ep.close().await; +2800 drop(ep); +2801 +2802 Ok(()) +2803 } +2804 +2805 /// Bind on an unusable port with the default opts. +2806 /// +2807 /// Binding the endpoint fails with an AddrInUse error. +2808 #[tokio::test] +2809 #[traced_test] +2810 async fn test_bind_addr_unusuable_port() -> Result { +2811 let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?; +2812 let port = socket.local_addr()?.port(); +2813 +2814 let res = Endpoint::empty_builder(RelayMode::Disabled) +2815 .clear_ip_transports() +2816 .bind_addr((Ipv4Addr::LOCALHOST, port))? +2817 .bind() +2818 .await; +2819 +2820 assert!(matches!( +2821 res, +2822 Err(BindError::MagicSpawn { +2823 source: CreateHandleError::BindSockets { +2824 source: io_error, +2825 .. +2826 }, +2827 .. +2828 }) +2829 if io_error.kind() == io::ErrorKind::AddrInUse +2830 )); +2831 Ok(()) +2832 } +2833 +2834 /// Bind on an unusable port, but set is_required = false. +2835 /// +2836 /// Binding the endpoint succeeds. +2837 #[tokio::test] +2838 #[traced_test] +2839 async fn test_bind_addr_unusuable_port_not_required() -> Result { +2840 let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?; +2841 let port = socket.local_addr()?.port(); +2842 +2843 let ep = Endpoint::empty_builder(RelayMode::Disabled) +2844 .bind_addr_with_opts( +2845 (Ipv4Addr::LOCALHOST, port), +2846 BindOpts::default().set_is_required(false), +2847 )? +2848 .bind() +2849 .await?; +2850 let bound_sockets = ep.bound_sockets(); +2851 // just the default wildcard binds +2852 assert_eq!(bound_sockets.len(), 2); +2853 // our requested bind addr is not included because it failed to bind +2854 assert!( +2855 bound_sockets +2856 .iter() +2857 .find(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST)) +2858 .is_none() +2859 ); +2860 Ok(()) +2861 } +2862 +2863 /// Bind on an unusable port, with is_required = false, and no other transports. +2864 /// +2865 /// Binding the endpoint fails with "no valid address available". +2866 #[tokio::test] +2867 #[traced_test] +2868 async fn test_bind_addr_unusable_port_not_required_no_other_transports() -> Result { +2869 let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?; +2870 let port = socket.local_addr()?.port(); +2871 +2872 let res = Endpoint::empty_builder(RelayMode::Disabled) +2873 .clear_ip_transports() +2874 .bind_addr_with_opts( +2875 (Ipv4Addr::LOCALHOST, port), +2876 BindOpts::default().set_is_required(false), +2877 )? +2878 .bind() +2879 .await; +2880 +2881 assert!(matches!( +2882 res, +2883 Err(BindError::MagicSpawn { +2884 source: CreateHandleError::CreateQuinnEndpoint { +2885 source: io_error, +2886 .. +2887 }, +2888 .. +2889 }) +2890 if io_error.kind() == io::ErrorKind::Other && io_error.to_string() == "no valid address available" +2891 )); +2892 Ok(()) +2893 } +2894}
    \ No newline at end of file diff --git a/pr/3836/docs/trait.impl/core/convert/trait.From.js b/pr/3836/docs/trait.impl/core/convert/trait.From.js index be38168d0e..0978fa31a1 100644 --- a/pr/3836/docs/trait.impl/core/convert/trait.From.js +++ b/pr/3836/docs/trait.impl/core/convert/trait.From.js @@ -1,9 +1,9 @@ (function() { - var implementors = Object.fromEntries([["iroh",[["impl From<Infallible> for InvalidSocketAddr"],["impl From<DiscoveryError> for ConnectWithOptsError"],["impl From<DiscoveryError> for AnyError"],["impl From<IntoDiscoveryError> for BindError"],["impl From<IntoDiscoveryError> for AnyError"],["impl From<PkarrError> for DiscoveryError"],["impl From<PkarrError> for AnyError"],["impl From<AlpnError> for AnyError"],["impl From<AuthenticationError> for ConnectingError"],["impl From<AuthenticationError> for AnyError"],["impl From<BindError> for AnyError"],["impl From<ConnectError> for AnyError"],["impl From<ConnectWithOptsError> for ConnectError"],["impl From<ConnectWithOptsError> for AnyError"],["impl From<ConnectingError> for ConnectError"],["impl From<ConnectingError> for AcceptError"],["impl From<ConnectingError> for AnyError"],["impl From<ConnectionError> for AlpnError"],["impl From<ConnectionError> for ConnectError"],["impl From<ConnectionError> for ConnectingError"],["impl From<ConnectionError> for AcceptError"],["impl From<InvalidSocketAddr> for AnyError"],["impl From<ConnectError> for ConnectWithOptsError"],["impl From<RelayMode> for Option<TransportConfig>"],["impl From<AcceptError> for AnyError"],["impl From<AddrParseError> for InvalidSocketAddr"],["impl From<Error> for AcceptError"],["impl From<PrefixLenError> for InvalidSocketAddr"],["impl From<DiscoveryItem> for EndpointInfo"],["impl From<ClosedStream> for AcceptError"],["impl From<RemoteEndpointIdError> for AuthenticationError"],["impl From<RemoteEndpointIdError> for AcceptError"],["impl From<RemoteEndpointIdError> for AnyError"],["impl From<RetryError> for AnyError"],["impl From<TransportAddrInfo> for TransportAddr"],["impl From<AnyError> for AcceptError"],["impl<T> From<T> for ConcurrentDiscovery
    where\n T: IntoIterator<Item = Box<dyn Discovery>>,
    "],["impl<T: ProtocolHandler> From<T> for Box<dyn DynProtocolHandler>"]]],["iroh_base",[["impl From<KeyParsingError> for AnyError"],["impl From<Url> for RelayUrl"],["impl From<PublicKey> for EndpointAddr"],["impl From<RelayUrl> for Url"],["impl From<RelayUrlParseError> for AnyError"],["impl From<SignatureError> for AnyError"],["impl From<DecodeError> for KeyParsingError"],["impl From<Error> for KeyParsingError"],["impl From<[u8; 32]> for SecretKey"]]],["iroh_relay",[["impl From<KeyParsingError> for Error"],["impl From<ConnectError> for AnyError"],["impl From<DialError> for ConnectError"],["impl From<DialError> for AnyError"],["impl From<RecvError> for AnyError"],["impl From<SendError> for AnyError"],["impl From<DnsError> for DialError"],["impl From<DnsError> for LookupError"],["impl From<DnsError> for AnyError"],["impl From<LookupError> for AnyError"],["impl From<DecodingError> for ParseError"],["impl From<DecodingError> for AnyError"],["impl From<EncodingError> for AnyError"],["impl From<ParseError> for LookupError"],["impl From<ParseError> for AnyError"],["impl From<FrameType> for u32"],["impl From<FrameType> for VarInt"],["impl From<FrameTypeError> for Error"],["impl From<FrameTypeError> for Error"],["impl From<FrameTypeError> for AnyError"],["impl From<Error> for ConnectError"],["impl From<Error> for AnyError"],["impl From<Error> for RecvError"],["impl From<Error> for AnyError"],["impl From<Error> for AnyError"],["impl From<SpawnError> for AnyError"],["impl From<SupervisorError> for AnyError"],["impl From<Vec<Box<[u8]>>> for TxtRecordData"],["impl From<Utf8Error> for ParseError"],["impl From<Utf8Error> for Error"],["impl From<Error> for ConnectError"],["impl From<Error> for DialError"],["impl From<EndpointAddr> for EndpointData"],["impl From<EndpointAddr> for EndpointInfo"],["impl From<RelayUrl> for RelayConfig"],["impl From<RelayUrl> for RelayMap"],["impl From<EndpointInfo> for EndpointAddr"],["impl From<MaxLengthExceededError> for AnyError"],["impl From<RelayConfig> for RelayMap"],["impl From<ConnectError> for Error"],["impl From<ConnectionError> for Error"],["impl From<Elapsed> for DialError"],["impl From<Elapsed> for DnsError"],["impl From<Error> for ConnectError"],["impl From<Error> for ConnectError"],["impl From<Error> for DialError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<Error> for Error"],["impl From<Error> for Error"],["impl From<JoinError> for SupervisorError"],["impl From<RecvError> for Error"],["impl From<ResolveError> for DnsError"],["impl<E: StackError + 'static> From<StaggeredError<E>> for AnyError"],["impl<T: AsRef<[u8]>> From<T> for Datagrams"]]]]); + var implementors = Object.fromEntries([["iroh",[["impl From<Infallible> for InvalidSocketAddr"],["impl From<DiscoveryError> for ConnectWithOptsError"],["impl From<DiscoveryError> for AnyError"],["impl From<IntoDiscoveryError> for BindError"],["impl From<IntoDiscoveryError> for AnyError"],["impl From<PkarrError> for DiscoveryError"],["impl From<PkarrError> for AnyError"],["impl From<AlpnError> for AnyError"],["impl From<AuthenticationError> for ConnectingError"],["impl From<AuthenticationError> for AnyError"],["impl From<BindError> for AnyError"],["impl From<ConnectError> for AnyError"],["impl From<ConnectWithOptsError> for ConnectError"],["impl From<ConnectWithOptsError> for AnyError"],["impl From<ConnectingError> for ConnectError"],["impl From<ConnectingError> for AcceptError"],["impl From<ConnectingError> for AnyError"],["impl From<ConnectionError> for AlpnError"],["impl From<ConnectionError> for ConnectError"],["impl From<ConnectionError> for ConnectingError"],["impl From<ConnectionError> for AcceptError"],["impl From<InvalidSocketAddr> for AnyError"],["impl From<ConnectError> for ConnectWithOptsError"],["impl From<RelayMode> for Option<TransportConfig>"],["impl From<AcceptError> for AnyError"],["impl From<AddrParseError> for InvalidSocketAddr"],["impl From<Error> for AcceptError"],["impl From<PrefixLenError> for InvalidSocketAddr"],["impl From<DiscoveryItem> for EndpointInfo"],["impl From<ClosedStream> for AcceptError"],["impl From<RemoteEndpointIdError> for AuthenticationError"],["impl From<RemoteEndpointIdError> for AcceptError"],["impl From<RemoteEndpointIdError> for AnyError"],["impl From<RetryError> for AnyError"],["impl From<TransportAddrInfo> for TransportAddr"],["impl From<AnyError> for AcceptError"],["impl<T> From<T> for ConcurrentDiscovery
    where\n T: IntoIterator<Item = Box<dyn Discovery>>,
    "],["impl<T: ProtocolHandler> From<T> for Box<dyn DynProtocolHandler>"]]],["iroh_base",[["impl From<KeyParsingError> for AnyError"],["impl From<Url> for RelayUrl"],["impl From<PublicKey> for EndpointAddr"],["impl From<RelayUrl> for Url"],["impl From<RelayUrlParseError> for AnyError"],["impl From<SignatureError> for AnyError"],["impl From<DecodeError> for KeyParsingError"],["impl From<Error> for KeyParsingError"],["impl From<[u8; 32]> for SecretKey"]]],["iroh_relay",[["impl From<ConnectError> for AnyError"],["impl From<DialError> for ConnectError"],["impl From<DialError> for AnyError"],["impl From<RecvError> for AnyError"],["impl From<SendError> for AnyError"],["impl From<DnsError> for DialError"],["impl From<DnsError> for LookupError"],["impl From<DnsError> for AnyError"],["impl From<LookupError> for AnyError"],["impl From<DecodingError> for ParseError"],["impl From<DecodingError> for AnyError"],["impl From<EncodingError> for AnyError"],["impl From<ParseError> for LookupError"],["impl From<ParseError> for AnyError"],["impl From<FrameType> for u32"],["impl From<FrameType> for VarInt"],["impl From<FrameTypeError> for Error"],["impl From<FrameTypeError> for Error"],["impl From<FrameTypeError> for AnyError"],["impl From<Error> for ConnectError"],["impl From<Error> for AnyError"],["impl From<Error> for RecvError"],["impl From<Error> for AnyError"],["impl From<Error> for AnyError"],["impl From<SpawnError> for AnyError"],["impl From<SupervisorError> for AnyError"],["impl From<Vec<Box<[u8]>>> for TxtRecordData"],["impl From<Utf8Error> for ParseError"],["impl From<Utf8Error> for Error"],["impl From<Error> for ConnectError"],["impl From<Error> for DialError"],["impl From<EndpointInfo> for EndpointAddr"],["impl From<MaxLengthExceededError> for AnyError"],["impl From<RelayConfig> for RelayMap"],["impl From<ConnectError> for Error"],["impl From<ConnectionError> for Error"],["impl From<Elapsed> for DialError"],["impl From<Elapsed> for DnsError"],["impl From<EndpointAddr> for EndpointData"],["impl From<EndpointAddr> for EndpointInfo"],["impl From<Error> for ConnectError"],["impl From<Error> for ConnectError"],["impl From<Error> for DialError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<Error> for Error"],["impl From<Error> for Error"],["impl From<JoinError> for SupervisorError"],["impl From<KeyParsingError> for Error"],["impl From<RecvError> for Error"],["impl From<RelayUrl> for RelayConfig"],["impl From<RelayUrl> for RelayMap"],["impl From<ResolveError> for DnsError"],["impl<E: StackError + 'static> From<StaggeredError<E>> for AnyError"],["impl<T: AsRef<[u8]>> From<T> for Datagrams"]]]]); if (window.register_implementors) { window.register_implementors(implementors); } else { window.pending_implementors = implementors; } })() -//{"start":57,"fragment_lengths":[15046,3090,19611]} \ No newline at end of file +//{"start":57,"fragment_lengths":[15046,3090,18835]} \ No newline at end of file diff --git a/pr/3836/docs/trait.impl/core/iter/traits/collect/trait.FromIterator.js b/pr/3836/docs/trait.impl/core/iter/traits/collect/trait.FromIterator.js index 6823ee20ab..53eb8f19b7 100644 --- a/pr/3836/docs/trait.impl/core/iter/traits/collect/trait.FromIterator.js +++ b/pr/3836/docs/trait.impl/core/iter/traits/collect/trait.FromIterator.js @@ -1,9 +1,9 @@ (function() { - var implementors = Object.fromEntries([["iroh_relay",[["impl FromIterator<Box<[u8]>> for TxtRecordData"],["impl FromIterator<Arc<RelayConfig>> for RelayMap"],["impl FromIterator<RelayUrl> for RelayMap"],["impl FromIterator<RelayConfig> for RelayMap"]]]]); + var implementors = Object.fromEntries([["iroh_relay",[["impl FromIterator<Box<[u8]>> for TxtRecordData"],["impl FromIterator<Arc<RelayConfig>> for RelayMap"],["impl FromIterator<RelayConfig> for RelayMap"],["impl FromIterator<RelayUrl> for RelayMap"]]]]); if (window.register_implementors) { window.register_implementors(implementors); } else { window.pending_implementors = implementors; } })() -//{"start":57,"fragment_lengths":[2062]} \ No newline at end of file +//{"start":57,"fragment_lengths":[1940]} \ No newline at end of file