1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

//! Interfaces for resolving DNS

use crate::box_error::BoxError;
use crate::impl_shared_conversions;
use std::error::Error as StdError;
use std::fmt;
use std::net::IpAddr;
use std::sync::Arc;

/// Error that occurs when failing to perform a DNS lookup.
#[derive(Debug)]
pub struct ResolveDnsError {
    source: BoxError,
}

impl ResolveDnsError {
    /// Creates a new `DnsLookupFailed` error.
    pub fn new(source: impl Into<BoxError>) -> Self {
        ResolveDnsError {
            source: source.into(),
        }
    }
}

impl fmt::Display for ResolveDnsError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "failed to perform DNS lookup")
    }
}

impl StdError for ResolveDnsError {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        Some(&*self.source as _)
    }
}

new_type_future! {
    #[doc = "New-type for the future returned by the [`ResolveDns`] trait."]
    pub struct DnsFuture<'a, Vec<IpAddr>, ResolveDnsError>;
}

/// Trait for resolving domain names
pub trait ResolveDns: fmt::Debug + Send + Sync {
    /// Asynchronously resolve the given domain name
    fn resolve_dns<'a>(&'a self, name: &'a str) -> DnsFuture<'a>;
}

/// Shared instance of [`ResolveDns`].
#[derive(Clone, Debug)]
pub struct SharedDnsResolver(Arc<dyn ResolveDns>);

impl SharedDnsResolver {
    /// Create a new `SharedDnsResolver`.
    pub fn new(resolver: impl ResolveDns + 'static) -> Self {
        Self(Arc::new(resolver))
    }
}

impl ResolveDns for SharedDnsResolver {
    fn resolve_dns<'a>(&'a self, name: &'a str) -> DnsFuture<'a> {
        self.0.resolve_dns(name)
    }
}

impl_shared_conversions!(convert SharedDnsResolver from ResolveDns using SharedDnsResolver::new);

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn check_send() {
        fn is_send<T: Send>() {}
        is_send::<DnsFuture<'_>>();
    }
}