refactor(dns): unify symbol naming

Renamed the following
- `dns::GenDnsConfig`  ->  `dns::Config`
- `dns::DnsConfig` -> `dns::async_std::Config`
- `dns::TokioDnsConfig` -> `dns::tokio::Config`

If async-std feature is enable, use `dns::async_std::Config`. When using tokio, import `dns::tokio::Config` . There is no need to use `dns::Config` directly.

Resolves #4486.
Related: #2217.

Pull-Request: #4505.
This commit is contained in:
whtsht
2023-09-24 14:31:42 +09:00
committed by GitHub
parent b4d9e5294b
commit 95890b550b
11 changed files with 154 additions and 127 deletions

2
Cargo.lock generated
View File

@ -2535,7 +2535,7 @@ dependencies = [
[[package]] [[package]]
name = "libp2p-dns" name = "libp2p-dns"
version = "0.40.0" version = "0.40.1"
dependencies = [ dependencies = [
"async-std", "async-std",
"async-std-resolver", "async-std-resolver",

View File

@ -78,7 +78,7 @@ libp2p-connection-limits = { version = "0.2.1", path = "misc/connection-limits"
libp2p-core = { version = "0.40.1", path = "core" } libp2p-core = { version = "0.40.1", path = "core" }
libp2p-dcutr = { version = "0.10.0", path = "protocols/dcutr" } libp2p-dcutr = { version = "0.10.0", path = "protocols/dcutr" }
libp2p-deflate = { version = "0.40.0", path = "transports/deflate" } libp2p-deflate = { version = "0.40.0", path = "transports/deflate" }
libp2p-dns = { version = "0.40.0", path = "transports/dns" } libp2p-dns = { version = "0.40.1", path = "transports/dns" }
libp2p-floodsub = { version = "0.43.0", path = "protocols/floodsub" } libp2p-floodsub = { version = "0.43.0", path = "protocols/floodsub" }
libp2p-gossipsub = { version = "0.45.1", path = "protocols/gossipsub" } libp2p-gossipsub = { version = "0.45.1", path = "protocols/gossipsub" }
libp2p-identify = { version = "0.43.0", path = "protocols/identify" } libp2p-identify = { version = "0.43.0", path = "protocols/identify" }

View File

@ -33,9 +33,7 @@ use libp2p::{
transport::Transport, transport::Transport,
upgrade, upgrade,
}, },
dcutr, dcutr, dns, identify, identity, noise, ping, quic, relay,
dns::DnsConfig,
identify, identity, noise, ping, quic, relay,
swarm::{NetworkBehaviour, SwarmBuilder, SwarmEvent}, swarm::{NetworkBehaviour, SwarmBuilder, SwarmEvent},
tcp, yamux, PeerId, tcp, yamux, PeerId,
}; };
@ -102,7 +100,7 @@ fn main() -> Result<(), Box<dyn Error>> {
&local_key, &local_key,
))); )));
block_on(DnsConfig::system(relay_tcp_quic_transport)) block_on(dns::async_std::Transport::system(relay_tcp_quic_transport))
.unwrap() .unwrap()
.map(|either_output, _| match either_output { .map(|either_output, _| match either_output {
Either::Left((peer_id, muxer)) => (peer_id, StreamMuxerBox::new(muxer)), Either::Left((peer_id, muxer)) => (peer_id, StreamMuxerBox::new(muxer)),

View File

@ -189,12 +189,12 @@ pub async fn development_transport(
keypair: identity::Keypair, keypair: identity::Keypair,
) -> std::io::Result<core::transport::Boxed<(PeerId, core::muxing::StreamMuxerBox)>> { ) -> std::io::Result<core::transport::Boxed<(PeerId, core::muxing::StreamMuxerBox)>> {
let transport = { let transport = {
let dns_tcp = dns::DnsConfig::system(tcp::async_io::Transport::new( let dns_tcp = dns::async_std::Transport::system(tcp::async_io::Transport::new(
tcp::Config::new().nodelay(true), tcp::Config::new().nodelay(true),
)) ))
.await?; .await?;
let ws_dns_tcp = websocket::WsConfig::new( let ws_dns_tcp = websocket::WsConfig::new(
dns::DnsConfig::system(tcp::async_io::Transport::new( dns::async_std::Transport::system(tcp::async_io::Transport::new(
tcp::Config::new().nodelay(true), tcp::Config::new().nodelay(true),
)) ))
.await?, .await?,
@ -234,10 +234,10 @@ pub fn tokio_development_transport(
keypair: identity::Keypair, keypair: identity::Keypair,
) -> std::io::Result<core::transport::Boxed<(PeerId, core::muxing::StreamMuxerBox)>> { ) -> std::io::Result<core::transport::Boxed<(PeerId, core::muxing::StreamMuxerBox)>> {
let transport = { let transport = {
let dns_tcp = dns::TokioDnsConfig::system(tcp::tokio::Transport::new( let dns_tcp = dns::tokio::Transport::system(tcp::tokio::Transport::new(
tcp::Config::new().nodelay(true), tcp::Config::new().nodelay(true),
))?; ))?;
let ws_dns_tcp = websocket::WsConfig::new(dns::TokioDnsConfig::system( let ws_dns_tcp = websocket::WsConfig::new(dns::tokio::Transport::system(
tcp::tokio::Transport::new(tcp::Config::new().nodelay(true)), tcp::tokio::Transport::new(tcp::Config::new().nodelay(true)),
)?); )?);
dns_tcp.or_transport(ws_dns_tcp) dns_tcp.or_transport(ws_dns_tcp)

View File

@ -88,7 +88,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
let quic_transport = quic::tokio::Transport::new(quic::Config::new(&local_keypair)); let quic_transport = quic::tokio::Transport::new(quic::Config::new(&local_keypair));
dns::TokioDnsConfig::system(libp2p::core::transport::OrTransport::new( dns::tokio::Transport::system(libp2p::core::transport::OrTransport::new(
quic_transport, quic_transport,
tcp_transport, tcp_transport,
))? ))?

View File

@ -405,7 +405,7 @@ async fn swarm<B: NetworkBehaviour + Default>() -> Result<Swarm<B>> {
libp2p_quic::tokio::Transport::new(config) libp2p_quic::tokio::Transport::new(config)
}; };
let dns = libp2p_dns::TokioDnsConfig::system(OrTransport::new(quic, tcp))?; let dns = libp2p_dns::tokio::Transport::system(OrTransport::new(quic, tcp))?;
dns.map(|either_output, _| match either_output { dns.map(|either_output, _| match either_output {
Either::Left((peer_id, muxer)) => (peer_id, StreamMuxerBox::new(muxer)), Either::Left((peer_id, muxer)) => (peer_id, StreamMuxerBox::new(muxer)),

View File

@ -1,3 +1,11 @@
## 0.40.1 - unreleased
- Remove `Dns` prefix from types like `TokioDnsConfig` and `DnsConfig` in favor of modules that describe the different variants.
Users are encouraged to import the `libp2p::dns` module and refer to types as `dns::tokio::Transport` and `dns::async_std::Transport`.
See [PR 4505].
[PR 4505]: https://github.com/libp2p/rust-libp2p/pull/4505
## 0.40.0 ## 0.40.0
- Raise MSRV to 1.65. - Raise MSRV to 1.65.

View File

@ -3,7 +3,7 @@ name = "libp2p-dns"
edition = "2021" edition = "2021"
rust-version = { workspace = true } rust-version = { workspace = true }
description = "DNS transport implementation for libp2p" description = "DNS transport implementation for libp2p"
version = "0.40.0" version = "0.40.1"
authors = ["Parity Technologies <admin@parity.io>"] authors = ["Parity Technologies <admin@parity.io>"]
license = "MIT" license = "MIT"
repository = "https://github.com/libp2p/rust-libp2p" repository = "https://github.com/libp2p/rust-libp2p"
@ -35,7 +35,7 @@ tokio = ["trust-dns-resolver/tokio-runtime"]
tokio-dns-over-rustls = ["tokio", "trust-dns-resolver/dns-over-rustls"] tokio-dns-over-rustls = ["tokio", "trust-dns-resolver/dns-over-rustls"]
tokio-dns-over-https-rustls = ["tokio", "trust-dns-resolver/dns-over-https-rustls"] tokio-dns-over-https-rustls = ["tokio", "trust-dns-resolver/dns-over-https-rustls"]
# Passing arguments to the docsrs builder in order to properly document cfg's. # Passing arguments to the docsrs builder in order to properly document cfg's.
# More information: https://docs.rs/about/builds#cross-compiling # More information: https://docs.rs/about/builds#cross-compiling
[package.metadata.docs.rs] [package.metadata.docs.rs]
all-features = true all-features = true

View File

@ -21,17 +21,17 @@
//! # [DNS name resolution](https://github.com/libp2p/specs/blob/master/addressing/README.md#ip-and-name-resolution) //! # [DNS name resolution](https://github.com/libp2p/specs/blob/master/addressing/README.md#ip-and-name-resolution)
//! [`Transport`] for libp2p. //! [`Transport`] for libp2p.
//! //!
//! This crate provides the type [`GenDnsConfig`] with its instantiations //! This crate provides the type [`async_std::Transport`] and [`tokio::Transport`]
//! [`DnsConfig`] and `TokioDnsConfig` for use with `async-std` and `tokio`, //! for use with `async-std` and `tokio`,
//! respectively. //! respectively.
//! //!
//! A [`GenDnsConfig`] is an address-rewriting [`Transport`] wrapper around //! A [`Transport`] is an address-rewriting [`libp2p_core::Transport`] wrapper around
//! an inner `Transport`. The composed transport behaves like the inner //! an inner `Transport`. The composed transport behaves like the inner
//! transport, except that [`Transport::dial`] resolves `/dns/...`, `/dns4/...`, //! transport, except that [`libp2p_core::Transport::dial`] resolves `/dns/...`, `/dns4/...`,
//! `/dns6/...` and `/dnsaddr/...` components of the given `Multiaddr` through //! `/dns6/...` and `/dnsaddr/...` components of the given `Multiaddr` through
//! a DNS, replacing them with the resolved protocols (typically TCP/IP). //! a DNS, replacing them with the resolved protocols (typically TCP/IP).
//! //!
//! The `async-std` feature and hence the `DnsConfig` are //! The `async-std` feature and hence the [`async_std::Transport`] are
//! enabled by default. Tokio users can furthermore opt-in //! enabled by default. Tokio users can furthermore opt-in
//! to the `tokio-dns-over-rustls` and `tokio-dns-over-https-rustls` //! to the `tokio-dns-over-rustls` and `tokio-dns-over-https-rustls`
//! features. For more information about these features, please //! features. For more information about these features, please
@ -49,7 +49,7 @@
//! problematic on platforms like Android, where there's a lot of //! problematic on platforms like Android, where there's a lot of
//! complexity hidden behind the system APIs. //! complexity hidden behind the system APIs.
//! If the implementation requires different characteristics, one should //! If the implementation requires different characteristics, one should
//! consider providing their own implementation of [`GenDnsConfig`] or use //! consider providing their own implementation of [`Transport`] or use
//! platform specific APIs to extract the host's DNS configuration (if possible) //! platform specific APIs to extract the host's DNS configuration (if possible)
//! and provide a custom [`ResolverConfig`]. //! and provide a custom [`ResolverConfig`].
//! //!
@ -58,14 +58,87 @@
#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
#[cfg(feature = "async-std")] #[cfg(feature = "async-std")]
use async_std_resolver::AsyncStdResolver; pub mod async_std {
use async_std_resolver::AsyncStdResolver;
use parking_lot::Mutex;
use std::{io, sync::Arc};
use trust_dns_resolver::{
config::{ResolverConfig, ResolverOpts},
system_conf,
};
/// A `Transport` wrapper for performing DNS lookups when dialing `Multiaddr`esses
/// using `async-std` for all async I/O.
pub type Transport<T> = crate::Transport<T, AsyncStdResolver>;
impl<T> Transport<T> {
/// Creates a new [`Transport`] from the OS's DNS configuration and defaults.
pub async fn system(inner: T) -> Result<Transport<T>, io::Error> {
let (cfg, opts) = system_conf::read_system_conf()?;
Self::custom(inner, cfg, opts).await
}
/// Creates a [`Transport`] with a custom resolver configuration and options.
pub async fn custom(
inner: T,
cfg: ResolverConfig,
opts: ResolverOpts,
) -> Result<Transport<T>, io::Error> {
Ok(Transport {
inner: Arc::new(Mutex::new(inner)),
resolver: async_std_resolver::resolver(cfg, opts).await,
})
}
}
}
#[cfg(feature = "async-std")]
#[deprecated(note = "Use `async_std::Transport` instead.")]
pub type DnsConfig<T> = async_std::Transport<T>;
#[cfg(feature = "tokio")]
pub mod tokio {
use parking_lot::Mutex;
use std::sync::Arc;
use trust_dns_resolver::{system_conf, TokioAsyncResolver};
/// A `Transport` wrapper for performing DNS lookups when dialing `Multiaddr`esses
/// using `tokio` for all async I/O.
pub type Transport<T> = crate::Transport<T, TokioAsyncResolver>;
impl<T> Transport<T> {
/// Creates a new [`Transport`] from the OS's DNS configuration and defaults.
pub fn system(inner: T) -> Result<crate::Transport<T, TokioAsyncResolver>, std::io::Error> {
let (cfg, opts) = system_conf::read_system_conf()?;
Self::custom(inner, cfg, opts)
}
/// Creates a [`Transport`] with a custom resolver configuration
/// and options.
pub fn custom(
inner: T,
cfg: trust_dns_resolver::config::ResolverConfig,
opts: trust_dns_resolver::config::ResolverOpts,
) -> Result<crate::Transport<T, TokioAsyncResolver>, std::io::Error> {
// TODO: Make infallible in next breaking release. Or deprecation?
Ok(Transport {
inner: Arc::new(Mutex::new(inner)),
resolver: TokioAsyncResolver::tokio(cfg, opts),
})
}
}
}
#[cfg(feature = "tokio")]
#[deprecated(note = "Use `tokio::Transport` instead.")]
pub type TokioDnsConfig<T> = tokio::Transport<T>;
use async_trait::async_trait; use async_trait::async_trait;
use futures::{future::BoxFuture, prelude::*}; use futures::{future::BoxFuture, prelude::*};
use libp2p_core::{ use libp2p_core::{
connection::Endpoint, connection::Endpoint,
multiaddr::{Multiaddr, Protocol}, multiaddr::{Multiaddr, Protocol},
transport::{ListenerId, TransportError, TransportEvent}, transport::{ListenerId, TransportError, TransportEvent},
Transport,
}; };
use parking_lot::Mutex; use parking_lot::Mutex;
use smallvec::SmallVec; use smallvec::SmallVec;
@ -80,10 +153,6 @@ use std::{
sync::Arc, sync::Arc,
task::{Context, Poll}, task::{Context, Poll},
}; };
#[cfg(any(feature = "async-std", feature = "tokio"))]
use trust_dns_resolver::system_conf;
#[cfg(feature = "tokio")]
use trust_dns_resolver::TokioAsyncResolver;
pub use trust_dns_resolver::config::{ResolverConfig, ResolverOpts}; pub use trust_dns_resolver::config::{ResolverConfig, ResolverOpts};
pub use trust_dns_resolver::error::{ResolveError, ResolveErrorKind}; pub use trust_dns_resolver::error::{ResolveError, ResolveErrorKind};
@ -110,85 +179,28 @@ const MAX_DNS_LOOKUPS: usize = 32;
/// result of a single `/dnsaddr` lookup. /// result of a single `/dnsaddr` lookup.
const MAX_TXT_RECORDS: usize = 16; const MAX_TXT_RECORDS: usize = 16;
/// A `Transport` wrapper for performing DNS lookups when dialing `Multiaddr`esses /// A [`Transport`] for performing DNS lookups when dialing `Multiaddr`esses.
/// using `async-std` for all async I/O. /// You shouldn't need to use this type directly. Use [`tokio::Transport`] or [`async_std::Transport`] instead.
#[cfg(feature = "async-std")]
pub type DnsConfig<T> = GenDnsConfig<T, AsyncStdResolver>;
/// A `Transport` wrapper for performing DNS lookups when dialing `Multiaddr`esses
/// using `tokio` for all async I/O.
#[cfg(feature = "tokio")]
pub type TokioDnsConfig<T> = GenDnsConfig<T, TokioAsyncResolver>;
/// A `Transport` wrapper for performing DNS lookups when dialing `Multiaddr`esses.
#[derive(Debug)] #[derive(Debug)]
pub struct GenDnsConfig<T, R> { pub struct Transport<T, R> {
/// The underlying transport. /// The underlying transport.
inner: Arc<Mutex<T>>, inner: Arc<Mutex<T>>,
/// The DNS resolver used when dialing addresses with DNS components. /// The DNS resolver used when dialing addresses with DNS components.
resolver: R, resolver: R,
} }
#[cfg(feature = "async-std")] #[deprecated(note = "Use `async_std::Transport` or `tokio::Transport` instead.")]
impl<T> DnsConfig<T> pub type GenDnsConfig<T, R> = Transport<T, R>;
impl<T, R> libp2p_core::Transport for Transport<T, R>
where where
T: Send, T: libp2p_core::Transport + Send + Unpin + 'static,
{
/// Creates a new [`DnsConfig`] from the OS's DNS configuration and defaults.
pub async fn system(inner: T) -> Result<DnsConfig<T>, io::Error> {
let (cfg, opts) = system_conf::read_system_conf()?;
Self::custom(inner, cfg, opts).await
}
/// Creates a [`DnsConfig`] with a custom resolver configuration and options.
pub async fn custom(
inner: T,
cfg: ResolverConfig,
opts: ResolverOpts,
) -> Result<DnsConfig<T>, io::Error> {
// TODO: Make infallible in next breaking release. Or deprecation?
Ok(DnsConfig {
inner: Arc::new(Mutex::new(inner)),
resolver: async_std_resolver::resolver(cfg, opts).await,
})
}
}
#[cfg(feature = "tokio")]
impl<T> TokioDnsConfig<T>
where
T: Send,
{
/// Creates a new [`TokioDnsConfig`] from the OS's DNS configuration and defaults.
pub fn system(inner: T) -> Result<TokioDnsConfig<T>, io::Error> {
let (cfg, opts) = system_conf::read_system_conf()?;
Self::custom(inner, cfg, opts)
}
/// Creates a [`TokioDnsConfig`] with a custom resolver configuration
/// and options.
pub fn custom(
inner: T,
cfg: ResolverConfig,
opts: ResolverOpts,
) -> Result<TokioDnsConfig<T>, io::Error> {
// TODO: Make infallible in next breaking release. Or deprecation?
Ok(TokioDnsConfig {
inner: Arc::new(Mutex::new(inner)),
resolver: TokioAsyncResolver::tokio(cfg, opts),
})
}
}
impl<T, R> Transport for GenDnsConfig<T, R>
where
T: Transport + Send + Unpin + 'static,
T::Error: Send, T::Error: Send,
T::Dial: Send, T::Dial: Send,
R: Clone + Send + Sync + Resolver + 'static, R: Clone + Send + Sync + Resolver + 'static,
{ {
type Output = T::Output; type Output = T::Output;
type Error = DnsErr<T::Error>; type Error = Error<T::Error>;
type ListenerUpgrade = future::MapErr<T::ListenerUpgrade, fn(T::Error) -> Self::Error>; type ListenerUpgrade = future::MapErr<T::ListenerUpgrade, fn(T::Error) -> Self::Error>;
type Dial = future::Either< type Dial = future::Either<
future::MapErr<T::Dial, fn(T::Error) -> Self::Error>, future::MapErr<T::Dial, fn(T::Error) -> Self::Error>,
@ -203,7 +215,7 @@ where
self.inner self.inner
.lock() .lock()
.listen_on(id, addr) .listen_on(id, addr)
.map_err(|e| e.map(DnsErr::Transport)) .map_err(|e| e.map(Error::Transport))
} }
fn remove_listener(&mut self, id: ListenerId) -> bool { fn remove_listener(&mut self, id: ListenerId) -> bool {
@ -230,17 +242,17 @@ where
cx: &mut Context<'_>, cx: &mut Context<'_>,
) -> Poll<TransportEvent<Self::ListenerUpgrade, Self::Error>> { ) -> Poll<TransportEvent<Self::ListenerUpgrade, Self::Error>> {
let mut inner = self.inner.lock(); let mut inner = self.inner.lock();
Transport::poll(Pin::new(inner.deref_mut()), cx).map(|event| { libp2p_core::Transport::poll(Pin::new(inner.deref_mut()), cx).map(|event| {
event event
.map_upgrade(|upgr| upgr.map_err::<_, fn(_) -> _>(DnsErr::Transport)) .map_upgrade(|upgr| upgr.map_err::<_, fn(_) -> _>(Error::Transport))
.map_err(DnsErr::Transport) .map_err(Error::Transport)
}) })
} }
} }
impl<T, R> GenDnsConfig<T, R> impl<T, R> Transport<T, R>
where where
T: Transport + Send + Unpin + 'static, T: libp2p_core::Transport + Send + Unpin + 'static,
T::Error: Send, T::Error: Send,
T::Dial: Send, T::Dial: Send,
R: Clone + Send + Sync + Resolver + 'static, R: Clone + Send + Sync + Resolver + 'static,
@ -249,7 +261,10 @@ where
&mut self, &mut self,
addr: Multiaddr, addr: Multiaddr,
role_override: Endpoint, role_override: Endpoint,
) -> Result<<Self as Transport>::Dial, TransportError<<Self as Transport>::Error>> { ) -> Result<
<Self as libp2p_core::Transport>::Dial,
TransportError<<Self as libp2p_core::Transport>::Error>,
> {
let resolver = self.resolver.clone(); let resolver = self.resolver.clone();
let inner = self.inner.clone(); let inner = self.inner.clone();
@ -279,7 +294,7 @@ where
}) { }) {
if dns_lookups == MAX_DNS_LOOKUPS { if dns_lookups == MAX_DNS_LOOKUPS {
log::debug!("Too many DNS lookups. Dropping unresolved {}.", addr); log::debug!("Too many DNS lookups. Dropping unresolved {}.", addr);
last_err = Some(DnsErr::TooManyLookups); last_err = Some(Error::TooManyLookups);
// There may still be fully resolved addresses in `unresolved`, // There may still be fully resolved addresses in `unresolved`,
// so keep going until `unresolved` is empty. // so keep going until `unresolved` is empty.
continue; continue;
@ -344,12 +359,12 @@ where
// actually accepted, i.e. for which it produced // actually accepted, i.e. for which it produced
// a dialing future. // a dialing future.
dial_attempts += 1; dial_attempts += 1;
out.await.map_err(DnsErr::Transport) out.await.map_err(Error::Transport)
} }
Err(TransportError::MultiaddrNotSupported(a)) => { Err(TransportError::MultiaddrNotSupported(a)) => {
Err(DnsErr::MultiaddrNotSupported(a)) Err(Error::MultiaddrNotSupported(a))
} }
Err(TransportError::Other(err)) => Err(DnsErr::Transport(err)), Err(TransportError::Other(err)) => Err(Error::Transport(err)),
}; };
match result { match result {
@ -377,7 +392,7 @@ where
// for the given address to begin with (i.e. DNS lookups succeeded but // for the given address to begin with (i.e. DNS lookups succeeded but
// produced no records relevant for the given `addr`). // produced no records relevant for the given `addr`).
Err(last_err.unwrap_or_else(|| { Err(last_err.unwrap_or_else(|| {
DnsErr::ResolveError(ResolveErrorKind::Message("No matching records found.").into()) Error::ResolveError(ResolveErrorKind::Message("No matching records found.").into())
})) }))
} }
.boxed() .boxed()
@ -385,10 +400,10 @@ where
} }
} }
/// The possible errors of a [`GenDnsConfig`] wrapped transport. /// The possible errors of a [`Transport`] wrapped transport.
#[derive(Debug)] #[derive(Debug)]
#[allow(clippy::large_enum_variant)] #[allow(clippy::large_enum_variant)]
pub enum DnsErr<TErr> { pub enum Error<TErr> {
/// The underlying transport encountered an error. /// The underlying transport encountered an error.
Transport(TErr), Transport(TErr),
/// DNS resolution failed. /// DNS resolution failed.
@ -404,30 +419,33 @@ pub enum DnsErr<TErr> {
TooManyLookups, TooManyLookups,
} }
impl<TErr> fmt::Display for DnsErr<TErr> #[deprecated(note = "Use `Error` instead.")]
pub type DnsErr<TErr> = Error<TErr>;
impl<TErr> fmt::Display for Error<TErr>
where where
TErr: fmt::Display, TErr: fmt::Display,
{ {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
DnsErr::Transport(err) => write!(f, "{err}"), Error::Transport(err) => write!(f, "{err}"),
DnsErr::ResolveError(err) => write!(f, "{err}"), Error::ResolveError(err) => write!(f, "{err}"),
DnsErr::MultiaddrNotSupported(a) => write!(f, "Unsupported resolved address: {a}"), Error::MultiaddrNotSupported(a) => write!(f, "Unsupported resolved address: {a}"),
DnsErr::TooManyLookups => write!(f, "Too many DNS lookups"), Error::TooManyLookups => write!(f, "Too many DNS lookups"),
} }
} }
} }
impl<TErr> error::Error for DnsErr<TErr> impl<TErr> error::Error for Error<TErr>
where where
TErr: error::Error + 'static, TErr: error::Error + 'static,
{ {
fn source(&self) -> Option<&(dyn error::Error + 'static)> { fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self { match self {
DnsErr::Transport(err) => Some(err), Error::Transport(err) => Some(err),
DnsErr::ResolveError(err) => Some(err), Error::ResolveError(err) => Some(err),
DnsErr::MultiaddrNotSupported(_) => None, Error::MultiaddrNotSupported(_) => None,
DnsErr::TooManyLookups => None, Error::TooManyLookups => None,
} }
} }
} }
@ -453,7 +471,7 @@ enum Resolved<'a> {
fn resolve<'a, E: 'a + Send, R: Resolver>( fn resolve<'a, E: 'a + Send, R: Resolver>(
proto: &Protocol<'a>, proto: &Protocol<'a>,
resolver: &'a R, resolver: &'a R,
) -> BoxFuture<'a, Result<Resolved<'a>, DnsErr<E>>> { ) -> BoxFuture<'a, Result<Resolved<'a>, Error<E>>> {
match proto { match proto {
Protocol::Dns(ref name) => resolver Protocol::Dns(ref name) => resolver
.lookup_ip(name.clone().into_owned()) .lookup_ip(name.clone().into_owned())
@ -475,7 +493,7 @@ fn resolve<'a, E: 'a + Send, R: Resolver>(
Ok(Resolved::One(Protocol::from(one))) Ok(Resolved::One(Protocol::from(one)))
} }
} }
Err(e) => Err(DnsErr::ResolveError(e)), Err(e) => Err(Error::ResolveError(e)),
}) })
.boxed(), .boxed(),
Protocol::Dns4(ref name) => resolver Protocol::Dns4(ref name) => resolver
@ -499,7 +517,7 @@ fn resolve<'a, E: 'a + Send, R: Resolver>(
Ok(Resolved::One(Protocol::from(Ipv4Addr::from(one)))) Ok(Resolved::One(Protocol::from(Ipv4Addr::from(one))))
} }
} }
Err(e) => Err(DnsErr::ResolveError(e)), Err(e) => Err(Error::ResolveError(e)),
}) })
.boxed(), .boxed(),
Protocol::Dns6(ref name) => resolver Protocol::Dns6(ref name) => resolver
@ -523,7 +541,7 @@ fn resolve<'a, E: 'a + Send, R: Resolver>(
Ok(Resolved::One(Protocol::from(Ipv6Addr::from(one)))) Ok(Resolved::One(Protocol::from(Ipv6Addr::from(one))))
} }
} }
Err(e) => Err(DnsErr::ResolveError(e)), Err(e) => Err(Error::ResolveError(e)),
}) })
.boxed(), .boxed(),
Protocol::Dnsaddr(ref name) => { Protocol::Dnsaddr(ref name) => {
@ -548,7 +566,7 @@ fn resolve<'a, E: 'a + Send, R: Resolver>(
} }
Ok(Resolved::Addrs(addrs)) Ok(Resolved::Addrs(addrs))
} }
Err(e) => Err(DnsErr::ResolveError(e)), Err(e) => Err(Error::ResolveError(e)),
}) })
.boxed() .boxed()
} }
@ -664,7 +682,7 @@ mod tests {
} }
} }
async fn run<T, R>(mut transport: GenDnsConfig<T, R>) async fn run<T, R>(mut transport: super::Transport<T, R>)
where where
T: Transport + Clone + Send + Unpin + 'static, T: Transport + Clone + Send + Unpin + 'static,
T::Error: Send, T::Error: Send,
@ -719,7 +737,7 @@ mod tests {
.unwrap() .unwrap()
.await .await
{ {
Err(DnsErr::ResolveError(_)) => {} Err(Error::ResolveError(_)) => {}
Err(e) => panic!("Unexpected error: {e:?}"), Err(e) => panic!("Unexpected error: {e:?}"),
Ok(_) => panic!("Unexpected success."), Ok(_) => panic!("Unexpected success."),
} }
@ -730,7 +748,7 @@ mod tests {
.unwrap() .unwrap()
.await .await
{ {
Err(DnsErr::ResolveError(e)) => match e.kind() { Err(Error::ResolveError(e)) => match e.kind() {
ResolveErrorKind::NoRecordsFound { .. } => {} ResolveErrorKind::NoRecordsFound { .. } => {}
_ => panic!("Unexpected DNS error: {e:?}"), _ => panic!("Unexpected DNS error: {e:?}"),
}, },
@ -746,7 +764,8 @@ mod tests {
let config = ResolverConfig::quad9(); let config = ResolverConfig::quad9();
let opts = ResolverOpts::default(); let opts = ResolverOpts::default();
async_std_crate::task::block_on( async_std_crate::task::block_on(
DnsConfig::custom(CustomTransport, config, opts).then(|dns| run(dns.unwrap())), async_std::Transport::custom(CustomTransport, config, opts)
.then(|dns| run(dns.unwrap())),
); );
} }
@ -761,8 +780,9 @@ mod tests {
.enable_time() .enable_time()
.build() .build()
.unwrap(); .unwrap();
rt.block_on(run( rt.block_on(run(
TokioDnsConfig::custom(CustomTransport, config, opts).unwrap() tokio::Transport::custom(CustomTransport, config, opts).unwrap()
)); ));
} }
} }

View File

@ -35,5 +35,6 @@ env_logger = "0.10.0"
# More information: https://docs.rs/about/builds#cross-compiling # More information: https://docs.rs/about/builds#cross-compiling
[package.metadata.docs.rs] [package.metadata.docs.rs]
all-features = true all-features = true
rustdoc-args = ["--cfg", "docsrs"] rustdoc-args = ["--cfg", "docsrs"]
rustc-args = ["--cfg", "docsrs"] rustc-args = ["--cfg", "docsrs"]

View File

@ -74,7 +74,7 @@ use std::{
/// # #[async_std::main] /// # #[async_std::main]
/// # async fn main() { /// # async fn main() {
/// ///
/// let mut transport = websocket::WsConfig::new(dns::DnsConfig::system( /// let mut transport = websocket::WsConfig::new(dns::async_std::Transport::system(
/// tcp::async_io::Transport::new(tcp::Config::default()), /// tcp::async_io::Transport::new(tcp::Config::default()),
/// ).await.unwrap()); /// ).await.unwrap());
/// ///