hickory_net/xfer/
dns_exchange.rs1use core::future::Future;
11use core::marker::PhantomData;
12use core::pin::Pin;
13use core::task::{Context, Poll};
14
15use futures_channel::mpsc;
16use futures_util::stream::{Peekable, Stream, StreamExt};
17use tracing::debug;
18
19use crate::error::NetError;
20use crate::proto::op::{DnsRequest, DnsResponse};
21use crate::runtime::RuntimeProvider;
22use crate::runtime::Time;
23use crate::xfer::dns_handle::DnsHandle;
24use crate::xfer::{
25 BufDnsRequestStreamHandle, DEFAULT_STREAM_BUFFER_SIZE, DnsRequestSender, DnsResponseReceiver,
26 OneshotDnsRequest,
27};
28
29#[must_use = "futures do nothing unless polled"]
34pub struct DnsExchange<P> {
35 sender: BufDnsRequestStreamHandle<P>,
36}
37
38impl<P: RuntimeProvider> DnsExchange<P> {
39 pub fn from_stream<S: DnsRequestSender>(
52 stream: S,
53 ) -> (Self, DnsExchangeBackground<S, P::Timer>) {
54 let (sender, outbound_messages) = mpsc::channel(DEFAULT_STREAM_BUFFER_SIZE);
55 (
56 Self {
57 sender: BufDnsRequestStreamHandle {
58 sender,
59 _phantom: PhantomData,
60 },
61 },
62 DnsExchangeBackground {
63 io_stream: stream,
64 outbound_messages: outbound_messages.peekable(),
65 marker: PhantomData,
66 },
67 )
68 }
69}
70
71impl<P: Clone> Clone for DnsExchange<P> {
72 fn clone(&self) -> Self {
73 Self {
74 sender: self.sender.clone(),
75 }
76 }
77}
78
79impl<P: RuntimeProvider> DnsHandle for DnsExchange<P> {
80 type Response = DnsExchangeSend<P>;
81 type Runtime = P;
82
83 fn send(&self, request: DnsRequest) -> Self::Response {
84 DnsExchangeSend {
85 result: self.sender.send(request),
86 _sender: self.sender.clone(), }
88 }
89}
90
91#[must_use = "futures do nothing unless polled"]
93pub struct DnsExchangeSend<P> {
94 result: DnsResponseReceiver,
95 _sender: BufDnsRequestStreamHandle<P>,
96}
97
98impl<P: Unpin> Stream for DnsExchangeSend<P> {
99 type Item = Result<DnsResponse, NetError>;
100
101 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
102 self.result.poll_next_unpin(cx)
104 }
105}
106
107#[must_use = "futures do nothing unless polled"]
111pub struct DnsExchangeBackground<S, TE> {
112 io_stream: S,
113 outbound_messages: Peekable<mpsc::Receiver<OneshotDnsRequest>>,
114 marker: PhantomData<TE>,
115}
116
117impl<S, TE> DnsExchangeBackground<S, TE> {
118 fn pollable_split(&mut self) -> (&mut S, &mut Peekable<mpsc::Receiver<OneshotDnsRequest>>) {
119 (&mut self.io_stream, &mut self.outbound_messages)
120 }
121}
122
123impl<S: DnsRequestSender, TE: Time> Future for DnsExchangeBackground<S, TE> {
124 type Output = ();
125
126 #[allow(clippy::unused_unit)]
127 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
128 let (io_stream, outbound_messages) = self.pollable_split();
129 let mut io_stream = Pin::new(io_stream);
130 let mut outbound_messages = Pin::new(outbound_messages);
131
132 loop {
135 match io_stream.as_mut().poll_next(cx) {
137 Poll::Ready(Some(Ok(()))) => (),
139 Poll::Pending => {
140 if io_stream.is_shutdown() {
141 return Poll::Pending;
143 }
144
145 ()
147 } Poll::Ready(None) => {
149 debug!("io_stream is done, shutting down");
150 return Poll::Ready(());
151 }
152 Poll::Ready(Some(Err(error))) => {
153 debug!(
154 %error,
155 "io_stream hit an error, shutting down"
156 );
157
158 return Poll::Ready(());
159 }
160 }
161
162 match outbound_messages.as_mut().poll_next(cx) {
164 Poll::Ready(Some(dns_request)) => {
166 if dns_request.is_canceled() {
168 debug!("dropping a request whose requester stopped waiting");
169 continue;
170 }
171 let (dns_request, serial_response): (DnsRequest, _) = dns_request.into_parts();
173
174 match serial_response.send_response(io_stream.send_message(dns_request)) {
179 Ok(()) => (),
180 Err(_) => {
181 debug!("failed to associate send_message response to the sender");
182 }
183 }
184 }
185 Poll::Pending => return Poll::Pending,
187 Poll::Ready(None) => {
188 io_stream.shutdown();
190
191 }
193 }
194
195 }
197 }
198}
199
200#[cfg(all(test, feature = "tokio"))]
201mod tests {
202 use std::sync::{Arc, Mutex};
203
204 use futures_util::task::noop_waker;
205
206 use super::*;
207 use crate::proto::op::{DnsRequestOptions, Message, Query};
208 use crate::proto::rr::{Name, RecordType};
209 use crate::runtime::TokioRuntimeProvider;
210 use crate::xfer::DnsResponseStream;
211
212 struct Recording(Arc<Mutex<Vec<u16>>>);
215
216 impl Stream for Recording {
217 type Item = Result<(), NetError>;
218
219 fn poll_next(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> {
220 Poll::Pending
221 }
222 }
223
224 impl DnsRequestSender for Recording {
225 fn send_message(&mut self, request: DnsRequest) -> DnsResponseStream {
226 self.0.lock().unwrap().push(request.id);
227 NetError::from("recorded").into()
228 }
229
230 fn shutdown(&mut self) {}
231
232 fn is_shutdown(&self) -> bool {
233 false
234 }
235 }
236
237 fn request(id: u16) -> DnsRequest {
238 let mut message = Message::query();
239 message.metadata.id = id;
240 message.add_query(Query::query(
241 Name::from_ascii("www.example.com.").unwrap(),
242 RecordType::A,
243 ));
244 DnsRequest::new(message, DnsRequestOptions::default())
245 }
246
247 #[test]
248 fn a_request_whose_requester_stopped_waiting_is_not_sent() {
249 let sent = Arc::new(Mutex::new(Vec::new()));
250 let (exchange, mut background) =
251 DnsExchange::<TokioRuntimeProvider>::from_stream(Recording(sent.clone()));
252
253 drop(exchange.send(request(1)));
255 let mut kept = exchange.send(request(2));
257
258 let waker = noop_waker();
259 let mut cx = Context::from_waker(&waker);
260 assert!(Pin::new(&mut background).poll(&mut cx).is_pending());
261
262 assert_eq!(*sent.lock().unwrap(), vec![2]);
263 match Pin::new(&mut kept).poll_next(&mut cx) {
265 Poll::Ready(Some(Err(NetError::Message("recorded")))) => {}
266 other => panic!("the kept request did not get its response stream: {other:?}"),
267 }
268 }
269}