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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
use crate::name::Name;
use async_trait::async_trait;
use std::{
error::Error,
fmt::{self, Display, Formatter},
net::{IpAddr, Ipv4Addr, Ipv6Addr},
};
pub type LookupResult<T> = Result<T, LookupError>;
#[derive(Debug)]
pub enum LookupError {
Timeout,
NoRecords,
Dns(Option<Box<dyn Error + Send + Sync>>),
}
impl Error for LookupError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Timeout | Self::NoRecords => None,
Self::Dns(e) => e.as_ref().map(|e| e.as_ref() as _),
}
}
}
impl Display for LookupError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::Timeout => write!(f, "lookup timed out"),
Self::NoRecords => write!(f, "no records found"),
Self::Dns(source) => match source {
None => write!(f, "lookup returned error"),
Some(error) => write!(f, "lookup returned error with cause: {}", error),
},
}
}
}
#[async_trait]
pub trait Lookup {
async fn lookup_a(&self, name: &Name) -> LookupResult<Vec<Ipv4Addr>>;
async fn lookup_aaaa(&self, name: &Name) -> LookupResult<Vec<Ipv6Addr>>;
async fn lookup_mx(&self, name: &Name) -> LookupResult<Vec<Name>>;
async fn lookup_txt(&self, name: &Name) -> LookupResult<Vec<String>>;
async fn lookup_ptr(&self, ip: IpAddr) -> LookupResult<Vec<Name>>;
}
#[cfg(test)]
mod tests {
use super::*;
struct MockLookup;
#[async_trait]
impl Lookup for MockLookup {
async fn lookup_a(&self, _name: &Name) -> LookupResult<Vec<Ipv4Addr>> {
unimplemented!();
}
async fn lookup_aaaa(&self, _name: &Name) -> LookupResult<Vec<Ipv6Addr>> {
unimplemented!();
}
async fn lookup_mx(&self, _name: &Name) -> LookupResult<Vec<Name>> {
unimplemented!();
}
async fn lookup_txt(&self, name: &Name) -> LookupResult<Vec<String>> {
Ok(vec![name.to_string()])
}
async fn lookup_ptr(&self, _ip: IpAddr) -> LookupResult<Vec<Name>> {
unimplemented!();
}
}
#[tokio::test]
async fn lookup_call_ok() {
let resolver = MockLookup;
let v = resolver
.lookup_txt(&Name::new("gluet.ch").unwrap())
.await
.unwrap();
assert_eq!(v, vec![String::from("gluet.ch")]);
}
}