Skip to content

Commit

Permalink
perf(ext/fetch): use trust_dns_resolver instead of default `GaiReso…
Browse files Browse the repository at this point in the history
…lver`
  • Loading branch information
sahandevs committed Nov 5, 2024
1 parent 770ef14 commit f5e7f20
Show file tree
Hide file tree
Showing 6 changed files with 94 additions and 3 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,7 @@ tower = { version = "0.4.13", default-features = false, features = ["util"] }
tower-http = { version = "0.6.1", features = ["decompression-br", "decompression-gzip"] }
tower-lsp = { package = "deno_tower_lsp", version = "0.1.0", features = ["proposed"] }
tower-service = "0.3.2"
trust-dns-resolver = { version = "0.23", features = ["tokio-runtime", "serde-config"] }
twox-hash = "=1.6.3"
# Upgrading past 2.4.1 may cause WPT failures
url = { version = "< 2.5.0", features = ["serde", "expose_internals"] }
Expand Down
1 change: 1 addition & 0 deletions ext/fetch/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ tokio-util = { workspace = true, features = ["io"] }
tower.workspace = true
tower-http.workspace = true
tower-service.workspace = true
trust-dns-resolver.workspace = true

[dev-dependencies]
fast-socks5.workspace = true
82 changes: 82 additions & 0 deletions ext/fetch/dns.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
use std::future::Future;
use std::io;
use std::net::SocketAddr;
use std::pin::Pin;
use std::task::Poll;
use std::task::{self};
use std::vec;

use hyper_util::client::legacy::connect::dns::Name;
use tokio::task::JoinHandle;
use tower::Service;
use trust_dns_resolver::error::ResolveError;
use trust_dns_resolver::name_server::GenericConnector;
use trust_dns_resolver::name_server::TokioRuntimeProvider;
use trust_dns_resolver::AsyncResolver;

#[derive(Clone)]
pub struct TrustResolver {
resolver: AsyncResolver<GenericConnector<TokioRuntimeProvider>>,
}

impl TrustResolver {
pub fn new() -> Result<TrustResolver, ResolveError> {
Ok(Self {
resolver: trust_dns_resolver::AsyncResolver::tokio_from_system_conf()?,
})
}
}

type SocketAddrs = vec::IntoIter<SocketAddr>;

pub struct AltResolverFut {
inner: JoinHandle<Result<SocketAddrs, ResolveError>>,
}

impl Future for AltResolverFut {
type Output = Result<SocketAddrs, io::Error>;

fn poll(
mut self: Pin<&mut Self>,
cx: &mut task::Context<'_>,
) -> Poll<Self::Output> {
Pin::new(&mut self.inner).poll(cx).map(|res| match res {
Ok(Ok(addrs)) => Ok(addrs),
Ok(Err(e)) => Err(e.into()),
Err(join_err) => {
if join_err.is_cancelled() {
Err(io::Error::new(io::ErrorKind::Interrupted, join_err))
} else {
panic!("gai background task failed: {:?}", join_err)
}
}
})
}
}

impl Service<Name> for TrustResolver {
type Response = SocketAddrs;
type Error = io::Error;
type Future = AltResolverFut;

fn poll_ready(
&mut self,
_cx: &mut task::Context<'_>,
) -> Poll<Result<(), io::Error>> {
Poll::Ready(Ok(()))
}

fn call(&mut self, name: Name) -> Self::Future {
let resolver = self.resolver.clone();
let task = tokio::spawn(async move {
let result = resolver.lookup_ip(name.as_str()).await?;

let x: Vec<_> =
result.into_iter().map(|x| SocketAddr::new(x, 0)).collect();
let iter: SocketAddrs = x.into_iter();
Ok(iter)
});

AltResolverFut { inner: task }
}
}
10 changes: 8 additions & 2 deletions ext/fetch/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.

mod dns;
mod fs_fetch_handler;
mod proxy;
#[cfg(test)]
Expand Down Expand Up @@ -78,6 +79,7 @@ pub use data_url;
pub use proxy::basic_auth;

pub use fs_fetch_handler::FsFetchHandler;
use trust_dns_resolver::error::ResolveError;

#[derive(Clone)]
pub struct Options {
Expand Down Expand Up @@ -943,6 +945,8 @@ pub enum HttpClientCreateError {
InvalidProxyUrl,
#[error("Cannot create Http Client: either `http1` or `http2` needs to be set to true")]
HttpVersionSelectionInvalid,
#[error("Cannot initialize trust dns resolver")]
Resolver(ResolveError),
#[error(transparent)]
RootCertStore(deno_core::error::AnyError),
}
Expand Down Expand Up @@ -976,7 +980,9 @@ pub fn create_http_client(
tls_config.alpn_protocols = alpn_protocols;
let tls_config = Arc::from(tls_config);

let mut http_connector = HttpConnector::new();
let mut http_connector = HttpConnector::new_with_resolver(
dns::TrustResolver::new().map_err(HttpClientCreateError::Resolver)?,
);
http_connector.enforce_http(false);

let user_agent = user_agent.parse::<HeaderValue>().map_err(|_| {
Expand Down Expand Up @@ -1051,7 +1057,7 @@ pub struct Client {
user_agent: HeaderValue,
}

type Connector = proxy::ProxyConnector<HttpConnector>;
type Connector = proxy::ProxyConnector<HttpConnector<dns::TrustResolver>>;

// clippy is wrong here
#[allow(clippy::declare_interior_mutable_const)]
Expand Down
2 changes: 1 addition & 1 deletion ext/net/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,4 @@ socket2.workspace = true
thiserror.workspace = true
tokio.workspace = true
trust-dns-proto = "0.23"
trust-dns-resolver = { version = "0.23", features = ["tokio-runtime", "serde-config"] }
trust-dns-resolver.workspace = true

0 comments on commit f5e7f20

Please sign in to comment.