apache_dubbo/triple/transport/resolver/
dns.rs

1/*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements.  See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18use std::future::Future;
19use std::net::SocketAddr;
20use std::net::ToSocketAddrs;
21use std::pin::Pin;
22use std::task::Poll;
23use std::vec;
24
25use tokio::task::JoinHandle;
26use tower_service::Service;
27
28#[derive(Clone, Default)]
29pub struct DnsResolver {}
30
31impl Service<String> for DnsResolver {
32    type Response = vec::IntoIter<SocketAddr>;
33
34    type Error = std::io::Error;
35
36    type Future = DnsFuture;
37
38    fn poll_ready(&mut self, _cx: &mut std::task::Context<'_>) -> Poll<Result<(), Self::Error>> {
39        Poll::Ready(Ok(()))
40    }
41
42    fn call(&mut self, name: String) -> Self::Future {
43        let block = tokio::task::spawn_blocking(move || (name, 0).to_socket_addrs());
44
45        DnsFuture { inner: block }
46    }
47}
48
49pub struct DnsFuture {
50    inner: JoinHandle<Result<vec::IntoIter<SocketAddr>, std::io::Error>>,
51}
52
53impl Future for DnsFuture {
54    type Output = Result<vec::IntoIter<SocketAddr>, std::io::Error>;
55
56    fn poll(
57        mut self: std::pin::Pin<&mut Self>,
58        cx: &mut std::task::Context<'_>,
59    ) -> Poll<Self::Output> {
60        Pin::new(&mut self.inner).poll(cx).map(|res| match res {
61            Ok(Ok(v)) => Ok(v),
62            Ok(Err(err)) => Err(err),
63            Err(join_err) => {
64                if join_err.is_cancelled() {
65                    Err(std::io::Error::new(
66                        std::io::ErrorKind::Interrupted,
67                        join_err,
68                    ))
69                } else {
70                    panic!("dnsfuture poll failed: {:?}", join_err)
71                }
72            }
73        })
74    }
75}