Skip to content

Commit 3524db9

Browse files
committed
refactor(client): use a tokio-threadpool for the GaiResolver
1 parent 0bda9ab commit 3524db9

File tree

2 files changed

+64
-115
lines changed

2 files changed

+64
-115
lines changed

src/client/connect/dns.rs

+64-92
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,12 @@ use std::net::{
1616
use std::str::FromStr;
1717
use std::sync::Arc;
1818

19+
use futures_util::{FutureExt, StreamExt};
1920
use tokio_executor::TypedExecutor;
20-
use tokio_sync::oneshot;
21+
use tokio_sync::{mpsc, oneshot};
2122
use tokio_threadpool;
2223

23-
use crate::common::{Future, Pin, Poll, Unpin, task};
24-
use self::sealed::GaiTask;
24+
use crate::common::{Future, Never, Pin, Poll, Unpin, task};
2525

2626
/// Resolve a hostname to a set of IP addresses.
2727
pub trait Resolve: Unpin {
@@ -42,18 +42,24 @@ pub struct Name {
4242
/// A resolver using blocking `getaddrinfo` calls in a threadpool.
4343
#[derive(Clone)]
4444
pub struct GaiResolver {
45-
executor: GaiExecutor,
45+
tx: tokio_threadpool::Sender,
46+
/// A handle to keep the threadpool alive until all `GaiResolver` clones
47+
/// have been dropped.
48+
_threadpool_keep_alive: ThreadPoolKeepAlive,
4649
}
4750

51+
#[derive(Clone)]
52+
struct ThreadPoolKeepAlive(mpsc::Sender<Never>);
53+
4854
/// An iterator of IP addresses returned from `getaddrinfo`.
4955
pub struct GaiAddrs {
5056
inner: IpAddrs,
5157
}
5258

5359
/// A future to resole a name returned by `GaiResolver`.
5460
pub struct GaiFuture {
55-
//rx: oneshot::SpawnHandle<IpAddrs, io::Error>,
56-
blocking: GaiBlocking,
61+
rx: oneshot::Receiver<Result<IpAddrs, io::Error>>,
62+
_threadpool_keep_alive: ThreadPoolKeepAlive,
5763
}
5864

5965
impl Name {
@@ -96,64 +102,66 @@ pub struct InvalidNameError(());
96102

97103
impl fmt::Display for InvalidNameError {
98104
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
99-
self.description().fmt(f)
105+
f.write_str("Not a valid domain name")
100106
}
101107
}
102108

103-
impl Error for InvalidNameError {
104-
fn description(&self) -> &str {
105-
"Not a valid domain name"
106-
}
107-
}
109+
impl Error for InvalidNameError {}
108110

109111

110112
impl GaiResolver {
111113
/// Construct a new `GaiResolver`.
112114
///
113115
/// Takes number of DNS worker threads.
114116
pub fn new(threads: usize) -> Self {
115-
GaiResolver {
116-
executor: GaiExecutor,
117-
}
118-
/*
119-
use tokio_threadpool::Builder;
120-
121-
let pool = Builder::new()
117+
let pool = tokio_threadpool::Builder::new()
122118
.name_prefix("hyper-dns-gai-resolver")
123119
// not for CPU tasks, so only spawn workers
124120
// in blocking mode
125121
.pool_size(1)
126122
.max_blocking(threads)
127123
.build();
128-
GaiResolver::new_with_executor(pool)
129-
*/
130-
}
131124

132-
/*
133-
/// Construct a new `GaiResolver` with a shared thread pool executor.
134-
///
135-
/// Takes an executor to run blocking `getaddrinfo` tasks on.
136-
/*pub */fn new_with_executor<E: 'static>(executor: E) -> Self
137-
where
138-
E: TypedExecutor<GaiTask> + Send + Sync,
139-
{
125+
let tx = pool.sender().clone();
126+
127+
// The pool will start to shutdown once `pool` is dropped,
128+
// so to keep it alive, we spawn a future onto the pool itself
129+
// that will only resolve once all `GaiResolver` requests
130+
// are finished.
131+
let (shutdown_tx, shutdown_rx) = mpsc::channel(1);
132+
133+
let on_shutdown = shutdown_rx
134+
.into_future()
135+
.map(move |(next, _rx)| {
136+
match next {
137+
Some(never) => match never {},
138+
None => (),
139+
}
140+
141+
drop(pool)
142+
});
143+
tx.spawn(on_shutdown);
144+
140145
GaiResolver {
141-
executor: GaiExecutor(Arc::new(executor)),
146+
tx,
147+
_threadpool_keep_alive: ThreadPoolKeepAlive(shutdown_tx),
142148
}
143149
}
144-
*/
145150
}
146151

147152
impl Resolve for GaiResolver {
148153
type Addrs = GaiAddrs;
149154
type Future = GaiFuture;
150155

151156
fn resolve(&self, name: Name) -> Self::Future {
152-
let blocking = GaiBlocking::new(name.host);
153-
//let rx = oneshot::spawn(blocking, &self.executor);
157+
let (tx, rx) = oneshot::channel();
158+
self.tx.spawn(GaiBlocking {
159+
host: name.host,
160+
tx: Some(tx),
161+
});
154162
GaiFuture {
155-
//rx,
156-
blocking,
163+
rx,
164+
_threadpool_keep_alive: self._threadpool_keep_alive.clone(),
157165
}
158166
}
159167
}
@@ -168,13 +176,11 @@ impl Future for GaiFuture {
168176
type Output = Result<GaiAddrs, io::Error>;
169177

170178
fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {
171-
/*
172-
let addrs = try_ready!(self.rx.poll());
173-
Ok(Async::Ready(GaiAddrs {
174-
inner: addrs,
175-
}))
176-
*/
177-
Poll::Ready(self.blocking.block().map(|addrs| GaiAddrs { inner: addrs }))
179+
Pin::new(&mut self.rx).poll(cx).map(|res| match res {
180+
Ok(Ok(addrs)) => Ok(GaiAddrs { inner: addrs }),
181+
Ok(Err(err)) => Err(err),
182+
Err(_canceled) => unreachable!("GaiResolver threadpool shutdown"),
183+
})
178184
}
179185
}
180186

@@ -198,27 +204,13 @@ impl fmt::Debug for GaiAddrs {
198204
}
199205
}
200206

201-
#[derive(Clone)]
202-
struct GaiExecutor/*(Arc<dyn Executor<GaiTask> + Send + Sync>)*/;
203-
204-
/*
205-
impl Executor<oneshot::Execute<GaiBlocking>> for GaiExecutor {
206-
fn execute(&self, future: oneshot::Execute<GaiBlocking>) -> Result<(), ExecuteError<oneshot::Execute<GaiBlocking>>> {
207-
self.0.execute(GaiTask { work: future })
208-
.map_err(|err| ExecuteError::new(err.kind(), err.into_future().work))
209-
}
210-
}
211-
*/
212207

213208
pub(super) struct GaiBlocking {
214209
host: String,
210+
tx: Option<oneshot::Sender<io::Result<IpAddrs>>>,
215211
}
216212

217213
impl GaiBlocking {
218-
pub(super) fn new(host: String) -> GaiBlocking {
219-
GaiBlocking { host }
220-
}
221-
222214
fn block(&self) -> io::Result<IpAddrs> {
223215
debug!("resolving host={:?}", self.host);
224216
(&*self.host, 0).to_socket_addrs()
@@ -227,18 +219,25 @@ impl GaiBlocking {
227219
}
228220
}
229221

230-
/*
231222
impl Future for GaiBlocking {
232-
type Item = IpAddrs;
233-
type Error = io::Error;
223+
type Output = ();
224+
225+
fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {
226+
if self.tx.as_mut().expect("polled after complete").poll_closed(cx).is_ready() {
227+
trace!("resolve future canceled for {:?}", self.host);
228+
return Poll::Ready(());
229+
}
234230

235-
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
236231
debug!("resolving host={:?}", self.host);
237-
(&*self.host, 0).to_socket_addrs()
238-
.map(|i| Async::Ready(IpAddrs { iter: i }))
232+
let res = (&*self.host, 0).to_socket_addrs()
233+
.map(|i| IpAddrs { iter: i });
234+
235+
let tx = self.tx.take().expect("polled after complete");
236+
let _ = tx.send(res);
237+
238+
Poll::Ready(())
239239
}
240240
}
241-
*/
242241

243242
pub(super) struct IpAddrs {
244243
iter: vec::IntoIter<SocketAddr>,
@@ -297,33 +296,6 @@ impl Iterator for IpAddrs {
297296
}
298297
}
299298

300-
// Make this Future unnameable outside of this crate.
301-
pub(super) mod sealed {
302-
use super::*;
303-
// Blocking task to be executed on a thread pool.
304-
pub struct GaiTask {
305-
//pub(super) work: oneshot::Execute<GaiBlocking>
306-
}
307-
308-
impl fmt::Debug for GaiTask {
309-
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
310-
f.pad("GaiTask")
311-
}
312-
}
313-
314-
/*
315-
impl Future for GaiTask {
316-
type Item = ();
317-
type Error = ();
318-
319-
fn poll(&mut self) -> Poll<(), ()> {
320-
self.work.poll()
321-
}
322-
}
323-
*/
324-
}
325-
326-
327299
/// A resolver using `getaddrinfo` calls via the `tokio_threadpool::blocking` API.
328300
///
329301
/// Unlike the `GaiResolver` this will not spawn dedicated threads, but only works when running on the

src/client/connect/http.rs

-23
Original file line numberDiff line numberDiff line change
@@ -81,29 +81,6 @@ impl HttpConnector {
8181
pub fn new(threads: usize) -> HttpConnector {
8282
HttpConnector::new_with_resolver(GaiResolver::new(threads))
8383
}
84-
85-
#[doc(hidden)]
86-
#[deprecated(note = "Use HttpConnector::set_reactor to set a reactor handle")]
87-
pub fn new_with_handle(threads: usize, handle: Handle) -> HttpConnector {
88-
let resolver = GaiResolver::new(threads);
89-
let mut http = HttpConnector::new_with_resolver(resolver);
90-
http.set_reactor(Some(handle));
91-
http
92-
}
93-
94-
/*
95-
/// Construct a new HttpConnector.
96-
///
97-
/// Takes an executor to run blocking `getaddrinfo` tasks on.
98-
pub fn new_with_executor<E: 'static>(executor: E, handle: Option<Handle>) -> HttpConnector
99-
where E: Executor<dns::sealed::GaiTask> + Send + Sync
100-
{
101-
let resolver = GaiResolver::new_with_executor(executor);
102-
let mut http = HttpConnector::new_with_resolver(resolver);
103-
http.set_reactor(handle);
104-
http
105-
}
106-
*/
10784
}
10885

10986
impl HttpConnector<TokioThreadpoolGaiResolver> {

0 commit comments

Comments
 (0)