Skip to main content

hickory_resolver/
name_server.rs

1// Copyright 2015-2019 Benjamin Fry <benjaminfry@me.com>
2//
3// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4// https://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// https://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8#[cfg(not(test))]
9use std::time::{Duration, Instant};
10use std::{
11    cmp,
12    fmt::Debug,
13    marker::PhantomData,
14    net::IpAddr,
15    sync::{
16        Arc,
17        atomic::{AtomicU8, AtomicU32, Ordering},
18    },
19};
20
21use futures_util::lock::Mutex as AsyncMutex;
22use parking_lot::Mutex as SyncMutex;
23#[cfg(test)]
24use tokio::time::{Duration, Instant};
25use tracing::{debug, error, warn};
26
27#[cfg(all(feature = "metrics", any(feature = "__tls", feature = "__quic")))]
28use crate::metrics::opportunistic_encryption::ProbeMetrics;
29#[cfg(feature = "metrics")]
30use crate::metrics::{NameServerAddr, ResolverMetrics};
31use crate::{
32    config::{
33        ConnectionConfig, NameServerConfig, OpportunisticEncryption, ResolverOpts,
34        ServerOrderingStrategy,
35    },
36    connection_provider::ConnectionProvider,
37    name_server_pool::{NameServerTransportState, PoolContext},
38    net::{
39        DnsError, NetError, NoRecords,
40        runtime::{RuntimeProvider, Spawn},
41        xfer::{DnsHandle, FirstAnswer, Protocol},
42    },
43    proto::{
44        op::{DnsRequest, DnsRequestOptions, DnsResponse, Query, ResponseCode},
45        rr::{Name, RecordType},
46    },
47};
48
49/// A remote DNS server, identified by its IP address.
50///
51/// This potentially holds multiple open connections to the server, according to the
52/// configured protocols, and will make new connections as needed.
53pub struct NameServer<P: ConnectionProvider> {
54    config: NameServerConfig,
55    connections: AsyncMutex<Vec<ConnectionState<P>>>,
56    /// Metrics related to opportunistic encryption probes.
57    #[cfg(all(feature = "metrics", any(feature = "__tls", feature = "__quic")))]
58    opportunistic_probe_metrics: ProbeMetrics,
59    /// Metrics related to outgoing queries.
60    #[cfg(feature = "metrics")]
61    resolver_metrics: ResolverMetrics,
62    server_srtt: DecayingSrtt,
63    udp: Arc<ConnectionMeta>,
64    tcp: Arc<ConnectionMeta>,
65    #[cfg(feature = "__tls")]
66    tls: Arc<ConnectionMeta>,
67    #[cfg(feature = "__https")]
68    https: Arc<ConnectionMeta>,
69    #[cfg(feature = "__quic")]
70    quic: Arc<ConnectionMeta>,
71    #[cfg(feature = "__h3")]
72    h3: Arc<ConnectionMeta>,
73    connection_provider: P,
74}
75
76impl<P: ConnectionProvider> NameServer<P> {
77    /// Create a new [`NameServer`] with the given connections and configuration.
78    ///
79    /// The `connections` will usually be empty.
80    pub fn new(
81        connections: impl IntoIterator<Item = (Protocol, P::Conn)>,
82        config: NameServerConfig,
83        options: &ResolverOpts,
84        connection_provider: P,
85    ) -> Self {
86        let udp = Arc::from(ConnectionMeta::default());
87        let tcp = Arc::from(ConnectionMeta::default());
88        #[cfg(feature = "__tls")]
89        let tls = Arc::from(ConnectionMeta::default());
90        #[cfg(feature = "__https")]
91        let https = Arc::from(ConnectionMeta::default());
92        #[cfg(feature = "__quic")]
93        let quic = Arc::from(ConnectionMeta::default());
94        #[cfg(feature = "__tls")]
95        let h3 = Arc::from(ConnectionMeta::default());
96
97        let mut connections = connections
98            .into_iter()
99            .map(|(protocol, handle)| {
100                ConnectionState::new(
101                    handle,
102                    match protocol {
103                        Protocol::Udp => udp.clone(),
104                        Protocol::Tcp => tcp.clone(),
105                        #[cfg(feature = "__tls")]
106                        Protocol::Tls => tls.clone(),
107                        #[cfg(feature = "__https")]
108                        Protocol::Https => https.clone(),
109                        #[cfg(feature = "__quic")]
110                        Protocol::Quic => quic.clone(),
111                        #[cfg(feature = "__h3")]
112                        Protocol::H3 => h3.clone(),
113                        _ => udp.clone(),
114                    },
115                    protocol,
116                )
117            })
118            .collect::<Vec<_>>();
119
120        // Unless the user specified that we should follow the configured order,
121        // re-order the connections to prioritize UDP.
122        if options.server_ordering_strategy != ServerOrderingStrategy::UserProvidedOrder {
123            connections.sort_by_key(|ns| ns.protocol != Protocol::Udp);
124        }
125
126        #[cfg(feature = "metrics")]
127        let resolver_metrics = ResolverMetrics::new(match options.enable_per_name_server_metrics {
128            true => NameServerAddr::Individual(config.ip),
129            false => NameServerAddr::Aggregated,
130        });
131
132        Self {
133            config,
134            connections: AsyncMutex::new(connections),
135            server_srtt: DecayingSrtt::new(Duration::from_micros(rand::random_range(1..32))),
136            #[cfg(all(feature = "metrics", any(feature = "__tls", feature = "__quic")))]
137            opportunistic_probe_metrics: ProbeMetrics::default(),
138            #[cfg(feature = "metrics")]
139            resolver_metrics,
140            udp,
141            tcp,
142            #[cfg(feature = "__tls")]
143            tls,
144            #[cfg(feature = "__https")]
145            https,
146            #[cfg(feature = "__quic")]
147            quic,
148            #[cfg(feature = "__h3")]
149            h3,
150            connection_provider,
151        }
152    }
153
154    // TODO: there needs to be some way of customizing the connection based on EDNS options from the server side...
155    pub(crate) async fn send(
156        self: Arc<Self>,
157        request: DnsRequest,
158        policy: ConnectionPolicy,
159        cx: &Arc<PoolContext>,
160    ) -> Result<DnsResponse, NetError> {
161        let (_protocol, result) = self.send_inner(request, policy, cx).await;
162        #[cfg(feature = "metrics")]
163        if let Some(protocol) = _protocol {
164            self.resolver_metrics
165                .increment_query_result(&protocol, result.as_ref().map(|_| ()));
166        }
167
168        result
169    }
170
171    async fn send_inner(
172        &self,
173        request: DnsRequest,
174        policy: ConnectionPolicy,
175        cx: &Arc<PoolContext>,
176    ) -> (Option<Protocol>, Result<DnsResponse, NetError>) {
177        // Reconnect and retry once if a reused connection was closed mid-flight.
178        // Caps total retries even when the pool holds several reusable connections.
179        let mut reconnect_budget = 1u8;
180        loop {
181            let ConnectedClient {
182                handle,
183                meta,
184                protocol,
185                reuse,
186            } = match self.connected_mut_client(policy, cx).await {
187                Ok(v) => v,
188                Err((err, protocol)) => {
189                    debug!(config = ?self.config, ?protocol, %err, "failed to establish connection to name server");
190                    return (protocol, Err(err));
191                }
192            };
193
194            #[cfg(feature = "metrics")]
195            self.resolver_metrics.increment_outgoing_query(&protocol);
196            let now = Instant::now();
197            let response = handle.send(request.clone()).first_answer().await;
198            let rtt = now.elapsed();
199
200            match response {
201                Ok(response) => {
202                    meta.set_status(Status::Established);
203                    let result = DnsError::from_response(response);
204                    let error = match result {
205                        Ok(response) => {
206                            meta.srtt.record(rtt);
207                            self.server_srtt.record(rtt);
208                            if cx.opportunistic_encryption.is_enabled() && protocol.is_encrypted() {
209                                cx.transport_state()
210                                    .await
211                                    .response_received(self.config.ip, protocol);
212                            }
213                            return (Some(protocol), Ok(response));
214                        }
215                        Err(error) => error,
216                    };
217
218                    let update = match error {
219                        DnsError::NoRecordsFound(NoRecords {
220                            response_code: ResponseCode::ServFail,
221                            ..
222                        }) => Some(true),
223                        DnsError::NoRecordsFound(NoRecords { .. }) => Some(false),
224                        _ => None,
225                    };
226
227                    match update {
228                        Some(true) => {
229                            meta.srtt.record(rtt);
230                            self.server_srtt.record(rtt);
231                        }
232                        Some(false) => {
233                            // record the failure
234                            meta.srtt.record_failure();
235                            self.server_srtt.record_failure();
236                        }
237                        None => {}
238                    }
239
240                    let err = NetError::from(error);
241                    if cx.opportunistic_encryption.is_enabled() && protocol.is_encrypted() {
242                        cx.transport_state()
243                            .await
244                            .error_received(self.config.ip, protocol, &err)
245                    }
246                    return (Some(protocol), Err(err));
247                }
248                Err(error) => {
249                    debug!(config = ?self.config, %error, "failed to connect to name server");
250
251                    // this transitions the state to failure, so the next acquire drops it
252                    meta.set_status(Status::Failed);
253
254                    // A reused connection the peer had already closed isn't a server fault.
255                    // Reconnect and retry once without penalizing server selection. The resend
256                    // is at-least-once; the resolver only sends read-only queries through this pool.
257                    if reuse == ConnectionReuse::Reused
258                        && reconnect_budget > 0
259                        && error.is_connection_closed()
260                    {
261                        #[cfg(feature = "metrics")]
262                        // The increment in send() won't occur since we're retrying.
263                        self.resolver_metrics
264                            .increment_query_result(&protocol, Err(&error));
265                        reconnect_budget -= 1;
266                        continue;
267                    }
268
269                    self.record_connection_failure(protocol, &error);
270
271                    if cx.opportunistic_encryption.is_enabled() && protocol.is_encrypted() {
272                        cx.transport_state()
273                            .await
274                            .error_received(self.config.ip, protocol, &error);
275                    }
276
277                    // These are connection failures, not lookup failures, that is handled in the resolver layer
278                    return (Some(protocol), Err(error));
279                }
280            }
281        }
282    }
283
284    /// This will return a mutable client to allows for sending messages.
285    ///
286    /// If the connection is in a failed state, then this will establish a new connection.
287    ///
288    async fn connected_mut_client(
289        &self,
290        policy: ConnectionPolicy,
291        cx: &Arc<PoolContext>,
292    ) -> Result<ConnectedClient<P>, (NetError, Option<Protocol>)> {
293        // Check for an existing usable connection (short lock)
294        {
295            let mut connections = self.connections.lock().await;
296            connections.retain(|conn| {
297                matches!(
298                    self.meta(conn.protocol).status(),
299                    Status::Init | Status::Established
300                )
301            });
302
303            if let Some(conn) = policy.select_connection(
304                self.config.ip,
305                &*cx.transport_state().await,
306                &cx.opportunistic_encryption,
307                &connections,
308            ) {
309                return Ok(ConnectedClient {
310                    handle: conn.handle.clone(),
311                    meta: self.meta(conn.protocol).clone(),
312                    protocol: conn.protocol,
313                    reuse: ConnectionReuse::Reused,
314                });
315            }
316        }
317
318        // Select connection config and update transport state (no lock)
319        debug!(config = ?self.config, "connecting");
320        let config = policy
321            .select_connection_config(
322                self.config.ip,
323                &*cx.transport_state().await,
324                &cx.opportunistic_encryption,
325                &self.config.connections,
326            )
327            .ok_or((NetError::NoConnections, None))?;
328
329        let protocol = config.protocol.to_protocol();
330        if cx.opportunistic_encryption.is_enabled() && protocol.is_encrypted() {
331            cx.transport_state()
332                .await
333                .initiate_connection(self.config.ip, protocol);
334        } else if cx.opportunistic_encryption.is_enabled() && !protocol.is_encrypted() {
335            self.consider_probe_encrypted_transport(&policy, cx).await;
336        }
337
338        let meta = self.meta(protocol);
339        let handle_failure = |error| {
340            self.record_connection_failure(protocol, &error);
341            (error, Some(protocol))
342        };
343        let handle_fut = self
344            .connection_provider
345            .new_connection(self.config.ip, config, cx)
346            .map_err(handle_failure)?;
347        let handle = Box::pin(handle_fut).await.map_err(handle_failure)?;
348
349        if cx.opportunistic_encryption.is_enabled() && protocol.is_encrypted() {
350            cx.transport_state()
351                .await
352                .complete_connection(self.config.ip, protocol);
353        }
354
355        // Store the new connection (with lock)
356        let state = ConnectionState::new(handle.clone(), meta.clone(), protocol);
357        self.connections.lock().await.push(state);
358        Ok(ConnectedClient {
359            handle,
360            meta: meta.clone(),
361            protocol,
362            reuse: ConnectionReuse::Fresh,
363        })
364    }
365
366    /// Penalizes this server's SRTT for a failure to establish a connection,
367    /// which never reaches the response-handling arm of `send_inner`.
368    fn record_connection_failure(&self, protocol: Protocol, error: &NetError) {
369        if !error.is_transport_error() {
370            return;
371        }
372
373        // This server's per-protocol connection metadata; its SRTT is
374        // compared when selecting among this server's existing connections.
375        self.meta(protocol).srtt.record_failure();
376        // The server-wide SRTT, used as the pool's server ordering key.
377        self.server_srtt.record_failure();
378    }
379
380    pub(super) fn protocols(&self) -> impl Iterator<Item = Protocol> + '_ {
381        self.config
382            .connections
383            .iter()
384            .map(|conn| conn.protocol.to_protocol())
385    }
386
387    pub(super) fn ip(&self) -> IpAddr {
388        self.config.ip
389    }
390
391    /// Returns the TLS server name identifying this server's provider, if any.
392    pub(super) fn provider(&self) -> Option<&Arc<str>> {
393        self.config
394            .connections
395            .iter()
396            .find_map(|conn| conn.protocol.server_name())
397    }
398
399    pub(crate) fn decayed_srtt(&self) -> f64 {
400        self.server_srtt.current()
401    }
402
403    fn meta(&self, protocol: Protocol) -> &Arc<ConnectionMeta> {
404        match protocol {
405            Protocol::Udp => &self.udp,
406            Protocol::Tcp => &self.tcp,
407            #[cfg(feature = "__tls")]
408            Protocol::Tls => &self.tls,
409            #[cfg(feature = "__https")]
410            Protocol::Https => &self.https,
411            #[cfg(feature = "__quic")]
412            Protocol::Quic => &self.quic,
413            #[cfg(feature = "__h3")]
414            Protocol::H3 => &self.h3,
415            _ => &self.udp, // default to UDP for unknown protocols
416        }
417    }
418
419    /// Records an SRTT observation for a server whose in-flight request was
420    /// cancelled because a parallel request to another server succeeded first.
421    ///
422    /// Records the winner's RTT plus a small penalty (`CANCEL_PENALTY`) as the
423    /// observation: the cancelled server was *at least* that slow (it hadn't
424    /// responded yet), and the penalty ensures the winner retains a sorting
425    /// advantage in the next round. This avoids the full `FAILURE_PENALTY`
426    /// which would be too harsh for a server that's merely slightly slower.
427    ///
428    /// A truly unreachable server will be cancelled on every query and its SRTT
429    /// will ratchet up as the EWMA repeatedly incorporates the winner's RTT
430    /// without ever recording a real (successful) measurement to bring it back
431    /// down.
432    pub(super) fn record_cancelled(&self, winner_rtt: Duration) {
433        const CANCEL_PENALTY: Duration = Duration::from_millis(5);
434        self.server_srtt.record(winner_rtt + CANCEL_PENALTY);
435    }
436
437    #[cfg(test)]
438    pub(crate) fn test_record_failure(&self) {
439        self.server_srtt.record_failure();
440    }
441
442    #[cfg(test)]
443    #[allow(dead_code)]
444    pub(crate) fn is_connected(&self) -> bool {
445        let Some(connections) = self.connections.try_lock() else {
446            // assuming that if someone has it locked it will be or is connected
447            return true;
448        };
449
450        connections
451            .iter()
452            .any(|conn| match self.meta(conn.protocol).status() {
453                Status::Established | Status::Init => true,
454                Status::Failed => false,
455            })
456    }
457
458    pub(crate) fn trust_negative_responses(&self) -> bool {
459        self.config.trust_negative_responses
460    }
461
462    async fn consider_probe_encrypted_transport(
463        &self,
464        policy: &ConnectionPolicy,
465        cx: &Arc<PoolContext>,
466    ) {
467        let Some(probe_config) =
468            policy.select_encrypted_connection_config(&self.config.connections)
469        else {
470            warn!("no encrypted connection configs available for probing");
471            return;
472        };
473
474        let probe_protocol = probe_config.protocol.to_protocol();
475        let should_probe = {
476            let state = cx.transport_state().await;
477            state.should_probe_encrypted(
478                self.config.ip,
479                probe_protocol,
480                &cx.opportunistic_encryption,
481            )
482        };
483
484        if !should_probe {
485            return;
486        }
487
488        if let Err(err) = self.probe_encrypted_transport(cx, probe_config) {
489            error!(%err, "opportunistic encrypted probe attempt failed");
490        }
491    }
492
493    fn probe_encrypted_transport(
494        &self,
495        cx: &Arc<PoolContext>,
496        probe_config: &ConnectionConfig,
497    ) -> Result<(), NetError> {
498        let mut budget = cx.opportunistic_probe_budget.load(Ordering::Relaxed);
499        #[cfg(all(feature = "metrics", any(feature = "__tls", feature = "__quic")))]
500        self.opportunistic_probe_metrics.probe_budget.set(budget);
501        loop {
502            if budget == 0 {
503                debug!("no remaining budget for opportunistic probing");
504                return Ok(());
505            }
506            match cx.opportunistic_probe_budget.compare_exchange_weak(
507                budget,
508                budget - 1,
509                Ordering::AcqRel,
510                Ordering::Relaxed,
511            ) {
512                Ok(_) => break,
513                Err(current) => budget = current,
514            }
515        }
516
517        let connect = ProbeRequest::new(
518            probe_config,
519            self,
520            cx,
521            #[cfg(all(feature = "metrics", any(feature = "__tls", feature = "__quic")))]
522            self.opportunistic_probe_metrics.clone(),
523        )?;
524        self.connection_provider
525            .runtime_provider()
526            .create_handle()
527            .spawn_bg(connect.run());
528
529        Ok(())
530    }
531}
532
533struct ProbeRequest<P: ConnectionProvider> {
534    ip: IpAddr,
535    proto: Protocol,
536    connecting: P::FutureConn,
537    context: Arc<PoolContext>,
538    #[cfg(all(feature = "metrics", any(feature = "__tls", feature = "__quic")))]
539    metrics: ProbeMetrics,
540    provider: PhantomData<P>,
541}
542
543impl<P: ConnectionProvider> ProbeRequest<P> {
544    fn new(
545        config: &ConnectionConfig,
546        ns: &NameServer<P>,
547        cx: &Arc<PoolContext>,
548        #[cfg(all(feature = "metrics", any(feature = "__tls", feature = "__quic")))]
549        metrics: ProbeMetrics,
550    ) -> Result<Self, NetError> {
551        Ok(Self {
552            ip: ns.config.ip,
553            proto: config.protocol.to_protocol(),
554            connecting: ns
555                .connection_provider
556                .new_connection(ns.config.ip, config, cx)?,
557            context: cx.clone(),
558            #[cfg(all(feature = "metrics", any(feature = "__tls", feature = "__quic")))]
559            metrics,
560            provider: PhantomData,
561        })
562    }
563
564    async fn run(self) {
565        let Self {
566            ip,
567            proto,
568            connecting,
569            context,
570            #[cfg(all(feature = "metrics", any(feature = "__tls", feature = "__quic")))]
571            metrics,
572            provider: _,
573        } = self;
574
575        #[cfg(all(feature = "metrics", any(feature = "__tls", feature = "__quic")))]
576        let start = Instant::now();
577
578        context
579            .transport_state()
580            .await
581            .initiate_connection(ip, proto);
582        #[cfg(all(feature = "metrics", any(feature = "__tls", feature = "__quic")))]
583        metrics.increment_attempts(proto);
584
585        let conn = match connecting.await {
586            Ok(conn) => conn,
587            Err(err) => {
588                debug!(?proto, "probe connection failed");
589                let _prev = context
590                    .opportunistic_probe_budget
591                    .fetch_add(1, Ordering::Relaxed);
592                #[cfg(all(feature = "metrics", any(feature = "__tls", feature = "__quic")))]
593                {
594                    metrics.increment_errors(proto, &err);
595                    metrics.probe_budget.set(_prev + 1);
596                    metrics.record_probe_duration(proto, start.elapsed());
597                }
598                context
599                    .transport_state()
600                    .await
601                    .error_received(ip, proto, &err);
602                return;
603            }
604        };
605
606        debug!(?proto, "probe connection succeeded");
607        context
608            .transport_state()
609            .await
610            .complete_connection(ip, proto);
611
612        match conn
613            .send(DnsRequest::from_query(
614                Query::query(Name::root(), RecordType::NS),
615                DnsRequestOptions::default(),
616            ))
617            .first_answer()
618            .await
619        {
620            Ok(_) => {
621                debug!(?proto, "probe query succeeded");
622                #[cfg(all(feature = "metrics", any(feature = "__tls", feature = "__quic")))]
623                metrics.increment_successes(proto);
624                context.transport_state().await.response_received(ip, proto);
625            }
626            Err(err) => {
627                debug!(?proto, ?err, "probe query failed");
628                #[cfg(all(feature = "metrics", any(feature = "__tls", feature = "__quic")))]
629                metrics.increment_errors(proto, &err);
630                context
631                    .transport_state()
632                    .await
633                    .error_received(ip, proto, &err);
634            }
635        }
636
637        let _prev = context
638            .opportunistic_probe_budget
639            .fetch_add(1, Ordering::Relaxed);
640        #[cfg(all(feature = "metrics", any(feature = "__tls", feature = "__quic")))]
641        {
642            metrics.probe_budget.set(_prev + 1);
643            metrics.record_probe_duration(proto, start.elapsed());
644        }
645    }
646}
647
648/// Whether `connected_mut_client` returned an existing pooled connection or established a new one.
649#[derive(Clone, Copy, PartialEq, Eq)]
650enum ConnectionReuse {
651    Reused,
652    Fresh,
653}
654
655/// A connection selected by [`NameServer::connected_mut_client`] for sending a request.
656struct ConnectedClient<P: ConnectionProvider> {
657    handle: P::Conn,
658    meta: Arc<ConnectionMeta>,
659    protocol: Protocol,
660    reuse: ConnectionReuse,
661}
662
663struct ConnectionState<P: ConnectionProvider> {
664    protocol: Protocol,
665    handle: P::Conn,
666    meta: Arc<ConnectionMeta>,
667}
668
669impl<P: ConnectionProvider> ConnectionState<P> {
670    fn new(handle: P::Conn, meta: Arc<ConnectionMeta>, protocol: Protocol) -> Self {
671        Self {
672            protocol,
673            handle,
674            meta,
675        }
676    }
677}
678
679struct ConnectionMeta {
680    status: AtomicU8,
681    srtt: DecayingSrtt,
682}
683
684impl ConnectionMeta {
685    fn set_status(&self, status: Status) {
686        self.status.store(status.into(), Ordering::Release);
687    }
688
689    fn status(&self) -> Status {
690        Status::from(self.status.load(Ordering::Acquire))
691    }
692}
693
694impl Default for ConnectionMeta {
695    fn default() -> Self {
696        // Initialize the SRTT to a randomly generated value that represents a
697        // very low RTT. Such a value helps ensure that each server is attempted
698        // early.
699        Self {
700            status: AtomicU8::new(Status::Init.into()),
701            srtt: DecayingSrtt::new(Duration::from_micros(rand::random_range(1..32))),
702        }
703    }
704}
705
706struct DecayingSrtt {
707    /// The smoothed round-trip time (SRTT).
708    ///
709    /// This value represents an exponentially weighted moving average (EWMA) of
710    /// recorded latencies. The algorithm for computing this value is based on
711    /// the following:
712    ///
713    /// <https://en.wikipedia.org/wiki/Moving_average#Application_to_measuring_computer_performance>
714    ///
715    /// It is also partially inspired by the BIND and PowerDNS implementations:
716    ///
717    /// - <https://github.com/isc-projects/bind9/blob/7bf8a7ab1b280c1021bf1e762a239b07aac3c591/lib/dns/adb.c#L3487>
718    /// - <https://github.com/PowerDNS/pdns/blob/7c5f9ae6ae4fb17302d933eaeebc8d6f0249aab2/pdns/syncres.cc#L123>
719    ///
720    /// The algorithm for computing and using this value can be summarized as
721    /// follows:
722    ///
723    /// 1. The value is initialized to a random value that represents a very low
724    ///    latency.
725    /// 2. If the round-trip time (RTT) was successfully measured for a query,
726    ///    then it is incorporated into the EWMA using the formula linked above.
727    /// 3. If the RTT could not be measured (i.e. due to a connection failure),
728    ///    then a constant penalty factor is applied to the EWMA.
729    /// 4. When comparing EWMA values, a time-based decay is applied to each
730    ///    value. Note that this decay is only applied at read time.
731    ///
732    /// For the original discussion regarding this algorithm, see
733    /// <https://github.com/hickory-dns/hickory-dns/issues/1702>.
734    srtt_microseconds: AtomicU32,
735
736    /// The last time the `srtt_microseconds` value was updated.
737    last_update: SyncMutex<Option<Instant>>,
738}
739
740impl DecayingSrtt {
741    fn new(initial_srtt: Duration) -> Self {
742        Self {
743            srtt_microseconds: AtomicU32::new(initial_srtt.as_micros() as u32),
744            last_update: SyncMutex::new(None),
745        }
746    }
747
748    fn record(&self, rtt: Duration) {
749        // If the cast on the result does overflow (it shouldn't), then the
750        // value is saturated to u32::MAX, which is above the `MAX_SRTT_MICROS`
751        // limit (meaning that any potential overflow is inconsequential).
752        // See https://github.com/rust-lang/rust/issues/10184.
753        self.update(
754            rtt.as_micros() as u32,
755            |cur_srtt_microseconds, last_update| {
756                // An arbitrarily low weight is used when computing the factor
757                // to ensure that recent RTT measurements are weighted more
758                // heavily.
759                let factor = compute_srtt_factor(last_update, 3);
760                let new_srtt = (1.0 - factor) * (rtt.as_micros() as f64)
761                    + factor * f64::from(cur_srtt_microseconds);
762                new_srtt.round() as u32
763            },
764        );
765    }
766
767    /// Records a connection failure for a particular query.
768    fn record_failure(&self) {
769        self.update(
770            Self::FAILURE_PENALTY,
771            |cur_srtt_microseconds, _last_update| {
772                cur_srtt_microseconds.saturating_add(Self::FAILURE_PENALTY)
773            },
774        );
775    }
776
777    /// Returns the SRTT value after applying a time based decay.
778    ///
779    /// The decay exponentially decreases the SRTT value. The primary reasons
780    /// for applying a downwards decay are twofold:
781    ///
782    /// 1. It helps distribute query load.
783    /// 2. It helps detect positive network changes. For example, decreases in
784    ///    latency or a server that has recovered from a failure.
785    fn current(&self) -> f64 {
786        let srtt = f64::from(self.srtt_microseconds.load(Ordering::Acquire));
787        self.last_update.lock().map_or(srtt, |last_update| {
788            // In general, if the time between queries is relatively short, then
789            // the server ordering algorithm will approximate a spike
790            // distribution where the servers with the lowest latencies are
791            // chosen much more frequently. Conversely, if the time between
792            // queries is relatively long, then the query distribution will be
793            // more uniform. A larger weight widens the window in which servers
794            // with historically lower latencies will be heavily preferred. On
795            // the other hand, a larger weight may also increase the time it
796            // takes to recover from a failure or to observe positive changes in
797            // latency.
798            srtt * compute_srtt_factor(last_update, 180)
799        })
800    }
801
802    /// Updates the SRTT value.
803    ///
804    /// If the `last_update` value has not been set, then uses the `default`
805    /// value to update the SRTT. Otherwise, invokes the `update_fn` with the
806    /// current SRTT value and the `last_update` timestamp.
807    fn update(&self, default: u32, update_fn: impl Fn(u32, Instant) -> u32) {
808        let last_update = self.last_update.lock().replace(Instant::now());
809        #[expect(deprecated)]
810        let _ = self.srtt_microseconds.fetch_update(
811            Ordering::SeqCst,
812            Ordering::SeqCst,
813            move |cur_srtt_microseconds| {
814                Some(
815                    last_update
816                        .map_or(default, |last_update| {
817                            update_fn(cur_srtt_microseconds, last_update)
818                        })
819                        .min(Self::MAX_SRTT_MICROS),
820                )
821            },
822        );
823    }
824
825    /// Returns the raw SRTT value.
826    ///
827    /// Prefer to use `decayed_srtt` when ordering name servers.
828    #[cfg(all(test, feature = "tokio"))]
829    fn as_duration(&self) -> Duration {
830        Duration::from_micros(u64::from(self.srtt_microseconds.load(Ordering::Acquire)))
831    }
832
833    const FAILURE_PENALTY: u32 = Duration::from_millis(150).as_micros() as u32;
834    const MAX_SRTT_MICROS: u32 = Duration::from_secs(5).as_micros() as u32;
835}
836
837/// Returns an exponentially weighted value in the range of 0.0 < x < 1.0
838///
839/// Computes the value using the following formula:
840///
841/// e<sup>(-t<sub>now</sub> - t<sub>last</sub>) / weight</sup>
842///
843/// As the duration since the `last_update` approaches the provided `weight`,
844/// the returned value decreases.
845fn compute_srtt_factor(last_update: Instant, weight: u32) -> f64 {
846    let exponent = (-last_update.elapsed().as_secs_f64().max(1.0)) / f64::from(weight);
847    exponent.exp()
848}
849
850/// State of a connection with a remote NameServer.
851#[derive(Debug, Eq, PartialEq, Copy, Clone)]
852#[repr(u8)]
853enum Status {
854    /// For some reason the connection failed. For UDP this would generally be a timeout
855    ///  for TCP this could be either Connection could never be established, or it
856    ///  failed at some point after. The Failed state should *not* be entered due to an
857    ///  error contained in a Message received from the server. In All cases to reestablish
858    ///  a new connection will need to be created.
859    Failed = 0,
860    /// Initial state, if Edns is not none, then Edns will be requested
861    Init = 1,
862    /// There has been successful communication with the remote.
863    ///  if no Edns is associated, then the remote does not support Edns
864    Established = 2,
865}
866
867impl From<Status> for u8 {
868    /// used for ordering purposes. The highest priority is placed on open connections
869    fn from(val: Status) -> Self {
870        val as Self
871    }
872}
873
874impl From<u8> for Status {
875    fn from(val: u8) -> Self {
876        match val {
877            2 => Self::Established,
878            1 => Self::Init,
879            _ => Self::Failed,
880        }
881    }
882}
883
884#[derive(Debug, Copy, Clone, Default, Eq, PartialEq)]
885pub(crate) struct ConnectionPolicy {
886    pub(crate) disable_udp: bool,
887}
888
889impl ConnectionPolicy {
890    /// Checks if the given server has any protocols compatible with current policy.
891    pub(crate) fn allows_server<P: ConnectionProvider>(&self, server: &NameServer<P>) -> bool {
892        server.protocols().any(|p| self.allows_protocol(p))
893    }
894
895    /// Select the best pre-existing connection to use.
896    ///
897    /// This choice is made based on opportunistic encryption policy & probe history,
898    /// protocol policy, and the SRTT performance metrics.
899    fn select_connection<'a, P: ConnectionProvider>(
900        &self,
901        ip: IpAddr,
902        encrypted_transport_state: &NameServerTransportState,
903        opportunistic_encryption: &OpportunisticEncryption,
904        connections: &'a [ConnectionState<P>],
905    ) -> Option<&'a ConnectionState<P>> {
906        let selected = connections
907            .iter()
908            .filter(|conn| self.allows_protocol(conn.protocol))
909            .min_by(|a, b| self.compare_connections(opportunistic_encryption.is_enabled(), a, b));
910
911        let selected = selected?;
912
913        // If we're using opportunistic encryption and selected a pre-existing unencrypted connection,
914        // and have successfully probed on any supported encrypted protocol, we should _not_ reuse the
915        // existing connection and instead return `None`. This will result in a new encrypted connection
916        // being made to the successfully probed protocol and added to the connection list for future
917        // re-use.
918        match opportunistic_encryption.is_enabled()
919            && !selected.protocol.is_encrypted()
920            && encrypted_transport_state.any_recent_success(ip, opportunistic_encryption)
921        {
922            true => None,
923            false => Some(selected),
924        }
925    }
926
927    /// Select the best connection configuration to use for a new connection.
928    ///
929    /// This choice is made based on opportunistic encryption policy & probe history,
930    /// and protocol policy.
931    fn select_connection_config<'a>(
932        &self,
933        ip: IpAddr,
934        encrypted_transport_state: &NameServerTransportState,
935        opportunistic_encryption: &OpportunisticEncryption,
936        connection_configs: &'a [ConnectionConfig],
937    ) -> Option<&'a ConnectionConfig> {
938        connection_configs
939            .iter()
940            .filter(|c| self.allows_protocol(c.protocol.to_protocol()))
941            .min_by(|a, b| {
942                self.compare_connection_configs(
943                    ip,
944                    encrypted_transport_state,
945                    opportunistic_encryption,
946                    a,
947                    b,
948                )
949            })
950    }
951
952    /// Select the first protocol allowed by current policy that uses an encrypted transport.
953    fn select_encrypted_connection_config<'a>(
954        &self,
955        connection_config: &'a [ConnectionConfig],
956    ) -> Option<&'a ConnectionConfig> {
957        connection_config
958            .iter()
959            .filter(|c| self.allows_protocol(c.protocol.to_protocol()))
960            .find(|c| c.protocol.to_protocol().is_encrypted())
961    }
962
963    /// Checks if the given protocol is allowed by current policy.
964    fn allows_protocol(&self, protocol: Protocol) -> bool {
965        !(self.disable_udp && protocol == Protocol::Udp)
966    }
967
968    /// Compare two connections according to policy, protocol, and performance.
969    /// If opportunistic encryption is enabled we make an effort to select an encrypted connection.
970    fn compare_connections<P: ConnectionProvider>(
971        &self,
972        opportunistic_encryption: bool,
973        a: &ConnectionState<P>,
974        b: &ConnectionState<P>,
975    ) -> cmp::Ordering {
976        // When opportunistic encryption is in-play, we want to consider encrypted
977        // connections with the greatest priority.
978        if opportunistic_encryption {
979            match (a.protocol.is_encrypted(), b.protocol.is_encrypted()) {
980                (true, false) => return cmp::Ordering::Less,
981                (false, true) => return cmp::Ordering::Greater,
982                // When _both_ are encrypted, then decide on ordering based on other properties (like SRTT).
983                _ => {}
984            }
985        }
986
987        match (a.protocol, b.protocol) {
988            (ap, bp) if ap == bp => a.meta.srtt.current().total_cmp(&b.meta.srtt.current()),
989            (Protocol::Udp, _) => cmp::Ordering::Less,
990            (_, Protocol::Udp) => cmp::Ordering::Greater,
991            _ => a.meta.srtt.current().total_cmp(&b.meta.srtt.current()),
992        }
993    }
994
995    fn compare_connection_configs(
996        &self,
997        ip: IpAddr,
998        encrypted_transport_state: &NameServerTransportState,
999        opportunistic_encryption: &OpportunisticEncryption,
1000        a: &ConnectionConfig,
1001        b: &ConnectionConfig,
1002    ) -> cmp::Ordering {
1003        let a_protocol = a.protocol.to_protocol();
1004        let b_protocol = b.protocol.to_protocol();
1005
1006        // When opportunistic encryption is in-play, prioritize encrypted protocols
1007        // that have recent successful connections
1008        if opportunistic_encryption.is_enabled() {
1009            let a_recent_enc_success = a_protocol.is_encrypted()
1010                && encrypted_transport_state.recent_success(
1011                    ip,
1012                    a_protocol,
1013                    opportunistic_encryption,
1014                );
1015            let b_recent_enc_success = b_protocol.is_encrypted()
1016                && encrypted_transport_state.recent_success(
1017                    ip,
1018                    b_protocol,
1019                    opportunistic_encryption,
1020                );
1021
1022            match (a_recent_enc_success, b_recent_enc_success) {
1023                (true, false) => return cmp::Ordering::Less,
1024                (false, true) => return cmp::Ordering::Greater,
1025                // When both have recent success or neither do, continue with normal ordering
1026                _ => {}
1027            }
1028        }
1029
1030        // Default protocol ordering: UDP first, then others
1031        match (a_protocol, b_protocol) {
1032            (ap, bp) if ap == bp => cmp::Ordering::Equal,
1033            (Protocol::Udp, _) => cmp::Ordering::Less,
1034            (_, Protocol::Udp) => cmp::Ordering::Greater,
1035            _ => cmp::Ordering::Equal,
1036        }
1037    }
1038}
1039
1040#[cfg(all(test, feature = "tokio"))]
1041mod tests {
1042    use std::cmp;
1043    use std::net::{IpAddr, Ipv4Addr};
1044    use std::str::FromStr;
1045    use std::time::Duration;
1046
1047    use test_support::subscribe;
1048    use tokio::net::UdpSocket;
1049    use tokio::spawn;
1050
1051    use super::*;
1052    use crate::config::{ConnectionConfig, ProtocolConfig};
1053    use crate::connection_provider::TlsConfig;
1054    use crate::net::runtime::TokioRuntimeProvider;
1055    use crate::proto::op::{DnsRequest, DnsRequestOptions, Message, Query, ResponseCode};
1056    use crate::proto::rr::rdata::NULL;
1057    use crate::proto::rr::{Name, RData, Record, RecordType};
1058
1059    #[tokio::test]
1060    async fn test_name_server() {
1061        subscribe();
1062
1063        let options = ResolverOpts::default();
1064        let config = NameServerConfig::udp(IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8)));
1065        let name_server = Arc::new(NameServer::new(
1066            [].into_iter(),
1067            config,
1068            &options,
1069            TokioRuntimeProvider::default(),
1070        ));
1071
1072        let cx = Arc::new(PoolContext::new(options, TlsConfig::new().unwrap()));
1073        let name = Name::parse("www.example.com.", None).unwrap();
1074        let response = name_server
1075            .send(
1076                DnsRequest::from_query(
1077                    Query::query(name.clone(), RecordType::A),
1078                    DnsRequestOptions::default(),
1079                ),
1080                ConnectionPolicy::default(),
1081                &cx,
1082            )
1083            .await
1084            .expect("query failed");
1085        assert_eq!(response.response_code, ResponseCode::NoError);
1086    }
1087
1088    #[tokio::test]
1089    async fn test_failed_name_server() {
1090        subscribe();
1091
1092        let options = ResolverOpts {
1093            timeout: Duration::from_millis(1), // this is going to fail, make it fail fast...
1094            ..ResolverOpts::default()
1095        };
1096
1097        let config = NameServerConfig::udp(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 252)));
1098        let name_server = Arc::new(NameServer::new(
1099            [],
1100            config,
1101            &options,
1102            TokioRuntimeProvider::default(),
1103        ));
1104
1105        let cx = Arc::new(PoolContext::new(options, TlsConfig::new().unwrap()));
1106        let name = Name::parse("www.example.com.", None).unwrap();
1107        assert!(
1108            name_server
1109                .send(
1110                    DnsRequest::from_query(
1111                        Query::query(name.clone(), RecordType::A),
1112                        DnsRequestOptions::default(),
1113                    ),
1114                    ConnectionPolicy::default(),
1115                    &cx
1116                )
1117                .await
1118                .is_err()
1119        );
1120    }
1121
1122    #[tokio::test]
1123    async fn case_randomization_query_preserved() {
1124        subscribe();
1125
1126        let provider = TokioRuntimeProvider::default();
1127        let server = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
1128        let server_addr = server.local_addr().unwrap();
1129        let name = Name::from_str("dead.beef.").unwrap();
1130        let data = b"DEADBEEF";
1131
1132        spawn({
1133            let name = name.clone();
1134            async move {
1135                let mut buffer = [0_u8; 512];
1136                let (len, addr) = server.recv_from(&mut buffer).await.unwrap();
1137                let request = Message::from_vec(&buffer[0..len]).unwrap();
1138                let mut response = Message::response(request.id, request.op_code);
1139                response.add_queries(request.queries.to_vec());
1140                response.add_answer(Record::from_rdata(
1141                    name,
1142                    0,
1143                    RData::NULL(NULL::with(data.to_vec())),
1144                ));
1145                let response_buffer = response.to_vec().unwrap();
1146                server.send_to(&response_buffer, addr).await.unwrap();
1147            }
1148        });
1149
1150        let config = NameServerConfig {
1151            ip: server_addr.ip(),
1152            trust_negative_responses: true,
1153            connections: vec![ConnectionConfig {
1154                port: server_addr.port(),
1155                protocol: ProtocolConfig::Udp,
1156                bind_addr: None,
1157            }],
1158        };
1159
1160        let resolver_opts = ResolverOpts {
1161            case_randomization: true,
1162            ..Default::default()
1163        };
1164
1165        let cx = Arc::new(PoolContext::new(resolver_opts, TlsConfig::new().unwrap()));
1166        let mut request_options = DnsRequestOptions::default();
1167        request_options.case_randomization = true;
1168        let ns = Arc::new(NameServer::new([], config, &cx.options, provider));
1169        let response = ns
1170            .send(
1171                DnsRequest::from_query(
1172                    Query::query(name.clone(), RecordType::NULL),
1173                    request_options,
1174                ),
1175                ConnectionPolicy::default(),
1176                &cx,
1177            )
1178            .await
1179            .unwrap();
1180
1181        let response_query_name = response.queries.first().unwrap().name();
1182        assert!(response_query_name.eq_case(&name));
1183    }
1184
1185    #[allow(clippy::extra_unused_type_parameters)]
1186    fn is_send_sync<S: Sync + Send>() -> bool {
1187        true
1188    }
1189
1190    #[test]
1191    fn stats_are_sync() {
1192        assert!(is_send_sync::<ConnectionMeta>());
1193    }
1194
1195    #[tokio::test(start_paused = true)]
1196    async fn test_stats_cmp() {
1197        use std::cmp::Ordering;
1198        let srtt_a = DecayingSrtt::new(Duration::from_micros(10));
1199        let srtt_b = DecayingSrtt::new(Duration::from_micros(20));
1200
1201        // No RTTs or failures have been recorded. The initial SRTTs should be
1202        // compared.
1203        assert_eq!(cmp(&srtt_a, &srtt_b), Ordering::Less);
1204
1205        // Server A was used. Unused server B should now be preferred.
1206        srtt_a.record(Duration::from_millis(30));
1207        tokio::time::advance(Duration::from_secs(5)).await;
1208        assert_eq!(cmp(&srtt_a, &srtt_b), Ordering::Greater);
1209
1210        // Both servers have been used. Server A has a lower SRTT and should be
1211        // preferred.
1212        srtt_b.record(Duration::from_millis(50));
1213        tokio::time::advance(Duration::from_secs(5)).await;
1214        assert_eq!(cmp(&srtt_a, &srtt_b), Ordering::Less);
1215
1216        // Server A experiences a connection failure, which results in Server B
1217        // being preferred.
1218        srtt_a.record_failure();
1219        tokio::time::advance(Duration::from_secs(5)).await;
1220        assert_eq!(cmp(&srtt_a, &srtt_b), Ordering::Greater);
1221
1222        // Server A should eventually recover and once again be preferred.
1223        while cmp(&srtt_a, &srtt_b) != Ordering::Less {
1224            srtt_b.record(Duration::from_millis(50));
1225            tokio::time::advance(Duration::from_secs(5)).await;
1226        }
1227
1228        srtt_a.record(Duration::from_millis(30));
1229        tokio::time::advance(Duration::from_secs(3)).await;
1230        assert_eq!(cmp(&srtt_a, &srtt_b), Ordering::Less);
1231    }
1232
1233    fn cmp(a: &DecayingSrtt, b: &DecayingSrtt) -> cmp::Ordering {
1234        a.current().total_cmp(&b.current())
1235    }
1236
1237    #[tokio::test(start_paused = true)]
1238    async fn test_record_rtt() {
1239        let srtt = DecayingSrtt::new(Duration::from_micros(10));
1240
1241        let first_rtt = Duration::from_millis(50);
1242        srtt.record(first_rtt);
1243
1244        // The first recorded RTT should replace the initial value.
1245        assert_eq!(srtt.as_duration(), first_rtt);
1246
1247        tokio::time::advance(Duration::from_secs(3)).await;
1248
1249        // Subsequent RTTs should factor in previously recorded values.
1250        srtt.record(Duration::from_millis(100));
1251        assert_eq!(srtt.as_duration(), Duration::from_micros(81606));
1252    }
1253
1254    #[test]
1255    fn test_record_rtt_maximum_value() {
1256        let srtt = DecayingSrtt::new(Duration::from_micros(10));
1257
1258        srtt.record(Duration::MAX);
1259        // Updates to the SRTT are capped at a maximum value.
1260        assert_eq!(
1261            srtt.as_duration(),
1262            Duration::from_micros(DecayingSrtt::MAX_SRTT_MICROS.into())
1263        );
1264    }
1265
1266    #[tokio::test(start_paused = true)]
1267    async fn test_record_connection_failure() {
1268        let srtt = DecayingSrtt::new(Duration::from_micros(10));
1269
1270        // Verify that the SRTT value is initially replaced with the penalty and
1271        // subsequent failures result in the penalty being added.
1272        for failure_count in 1..4 {
1273            srtt.record_failure();
1274            assert_eq!(
1275                srtt.as_duration(),
1276                Duration::from_micros(
1277                    DecayingSrtt::FAILURE_PENALTY
1278                        .checked_mul(failure_count)
1279                        .expect("checked_mul overflow")
1280                        .into()
1281                )
1282            );
1283            tokio::time::advance(Duration::from_secs(3)).await;
1284        }
1285
1286        // Verify that the `last_update` timestamp was updated for a connection
1287        // failure and is used in subsequent calculations.
1288        srtt.record(Duration::from_millis(50));
1289        assert_eq!(srtt.as_duration(), Duration::from_micros(197152));
1290    }
1291
1292    #[test]
1293    fn test_record_connection_failure_maximum_value() {
1294        let srtt = DecayingSrtt::new(Duration::from_micros(10));
1295
1296        let num_failures = (DecayingSrtt::MAX_SRTT_MICROS / DecayingSrtt::FAILURE_PENALTY) + 1;
1297        for _ in 0..num_failures {
1298            srtt.record_failure();
1299        }
1300
1301        // Updates to the SRTT are capped at a maximum value.
1302        assert_eq!(
1303            srtt.as_duration(),
1304            Duration::from_micros(DecayingSrtt::MAX_SRTT_MICROS.into())
1305        );
1306    }
1307
1308    #[tokio::test(start_paused = true)]
1309    async fn test_decayed_srtt() {
1310        let initial_srtt = 10;
1311        let srtt = DecayingSrtt::new(Duration::from_micros(initial_srtt));
1312
1313        // No decay should be applied to the initial value.
1314        assert_eq!(srtt.current() as u32, initial_srtt as u32);
1315
1316        tokio::time::advance(Duration::from_secs(5)).await;
1317        srtt.record(Duration::from_millis(100));
1318
1319        // The decay function should assume a minimum of one second has elapsed
1320        // since the last update.
1321        tokio::time::advance(Duration::from_millis(500)).await;
1322        assert_eq!(srtt.current() as u32, 99445);
1323
1324        tokio::time::advance(Duration::from_secs(5)).await;
1325        assert_eq!(srtt.current() as u32, 96990);
1326    }
1327}
1328
1329#[cfg(all(test, feature = "__tls"))]
1330mod opportunistic_enc_tests {
1331    use std::io;
1332    use std::net::{IpAddr, Ipv4Addr};
1333    use std::sync::Arc;
1334    use std::time::{Duration, SystemTime};
1335
1336    #[cfg(feature = "metrics")]
1337    use metrics::{Label, Unit, with_local_recorder};
1338    #[cfg(feature = "metrics")]
1339    use metrics_util::debugging::DebuggingRecorder;
1340    use mock_provider::{MockClientHandle, MockProvider};
1341    use test_support::subscribe;
1342    #[cfg(feature = "metrics")]
1343    use test_support::{assert_counter_eq, assert_gauge_eq, assert_histogram_sample_count_eq};
1344
1345    use crate::config::{
1346        NameServerConfig, OpportunisticEncryption, OpportunisticEncryptionConfig, ProtocolConfig,
1347        ResolverOpts,
1348    };
1349    use crate::connection_provider::TlsConfig;
1350    #[cfg(feature = "metrics")]
1351    use crate::metrics::opportunistic_encryption::{
1352        PROBE_ATTEMPTS_TOTAL, PROBE_BUDGET_TOTAL, PROBE_DURATION_SECONDS, PROBE_ERRORS_TOTAL,
1353        PROBE_SUCCESSES_TOTAL, PROBE_TIMEOUTS_TOTAL,
1354    };
1355    use crate::name_server::{
1356        ConnectionMeta, ConnectionPolicy, ConnectionState, NameServer, mock_provider,
1357    };
1358    use crate::name_server_pool::{NameServerTransportState, PoolContext};
1359    use crate::net::NetError;
1360    use crate::net::xfer::Protocol;
1361
1362    #[tokio::test]
1363    async fn test_select_connection_opportunistic_enc_disabled() {
1364        let mut policy = ConnectionPolicy::default();
1365        let connections = vec![
1366            mock_connection(Protocol::Udp),
1367            mock_connection(Protocol::Tcp),
1368        ];
1369
1370        let ns_ip = IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1));
1371        let state = NameServerTransportState::default();
1372        let opp_enc = OpportunisticEncryption::Disabled;
1373
1374        // When opportunistic encryption is disabled, and disable_udp isn't active,
1375        // we should select the UDP conn.
1376        let selected = policy.select_connection(ns_ip, &state, &opp_enc, &connections);
1377        assert!(selected.is_some());
1378        assert_eq!(selected.unwrap().protocol, Protocol::Udp);
1379
1380        // When opportunistic encryption is disabled, and disable_udp is active,
1381        // we should select the TCP conn.
1382        policy.disable_udp = true;
1383        let selected = policy.select_connection(ns_ip, &state, &opp_enc, &connections);
1384        assert!(selected.is_some());
1385        assert_eq!(selected.unwrap().protocol, Protocol::Tcp);
1386    }
1387
1388    #[tokio::test]
1389    async fn test_select_connection_opportunistic_enc_enabled() {
1390        let policy = ConnectionPolicy::default();
1391        let connections = [
1392            mock_connection(Protocol::Udp),
1393            mock_connection(Protocol::Tcp),
1394            // Include a pre-existing encrypted protocol connection.
1395            mock_connection(Protocol::Tls),
1396        ];
1397
1398        let ns_ip = IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1));
1399        let state = NameServerTransportState::default();
1400        let opp_enc = &OpportunisticEncryption::Enabled {
1401            config: OpportunisticEncryptionConfig::default(),
1402        };
1403
1404        // When opportunistic encryption is enabled, and there is an encrypted connection available,
1405        // we should always choose it as the most preferred.
1406        let selected = policy.select_connection(ns_ip, &state, opp_enc, &connections);
1407        assert!(selected.is_some());
1408        assert_eq!(selected.unwrap().protocol, Protocol::Tls);
1409    }
1410
1411    #[tokio::test]
1412    async fn test_select_connection_opportunistic_enc_enabled_no_state() {
1413        let mut policy = ConnectionPolicy::default();
1414        let connections = [
1415            mock_connection(Protocol::Udp),
1416            mock_connection(Protocol::Tcp),
1417            // No pre-existing encrypted protocol connection is available.
1418        ];
1419
1420        let ns_ip = IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1));
1421        let state = NameServerTransportState::default();
1422        let opp_enc = &OpportunisticEncryption::Enabled {
1423            config: OpportunisticEncryptionConfig::default(),
1424        };
1425
1426        // When opportunistic encryption is enabled, but there are no encrypted connections available,
1427        // and we have no probe state, we should select the UDP conn.
1428        let selected = policy.select_connection(ns_ip, &state, opp_enc, &connections);
1429        assert!(selected.is_some());
1430        assert_eq!(selected.unwrap().protocol, Protocol::Udp);
1431
1432        // When opportunistic encryption is enabled, but there are no encrypted connections available,
1433        // and we have no probe state, we should select the TCP conn.
1434        policy.disable_udp = true;
1435        let selected = policy.select_connection(ns_ip, &state, opp_enc, &connections);
1436        assert!(selected.is_some());
1437        assert_eq!(selected.unwrap().protocol, Protocol::Tcp);
1438    }
1439
1440    #[tokio::test]
1441    async fn test_select_connection_opportunistic_enc_enabled_failed_probe() {
1442        let policy = ConnectionPolicy::default();
1443        let connections = [
1444            mock_connection(Protocol::Udp),
1445            mock_connection(Protocol::Tcp),
1446            // No pre-existing encrypted protocol connection is available.
1447        ];
1448
1449        let ns_ip = IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1));
1450        let mut state = NameServerTransportState::default();
1451        let opp_enc = &OpportunisticEncryption::Enabled {
1452            config: OpportunisticEncryptionConfig::default(),
1453        };
1454
1455        // Update the state to reflect that we failed a previous probe attempt.
1456        state.error_received(
1457            ns_ip,
1458            Protocol::Tls,
1459            &NetError::from(io::Error::new(
1460                io::ErrorKind::ConnectionRefused,
1461                "nameserver refused TLS connection",
1462            )),
1463        );
1464
1465        // When opportunistic encryption is enabled, but there are no encrypted connections available,
1466        // and our probe state indicates a failure, we should select the UDP conn.
1467        let selected = policy.select_connection(ns_ip, &state, opp_enc, &connections);
1468        assert!(selected.is_some());
1469        assert_eq!(selected.unwrap().protocol, Protocol::Udp);
1470    }
1471
1472    #[tokio::test]
1473    async fn test_select_connection_opportunistic_enc_enabled_in_progress_probe() {
1474        let policy = ConnectionPolicy::default();
1475        let connections = [
1476            mock_connection(Protocol::Udp),
1477            mock_connection(Protocol::Tcp),
1478            // No pre-existing encrypted protocol connection is available.
1479        ];
1480
1481        let ns_ip = IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1));
1482        let mut state = NameServerTransportState::default();
1483        let opp_enc = &OpportunisticEncryption::Enabled {
1484            config: OpportunisticEncryptionConfig::default(),
1485        };
1486
1487        // Update the state to reflect that we have an in-progress probe in-flight.
1488        state.initiate_connection(ns_ip, Protocol::Tls);
1489
1490        // When opportunistic encryption is enabled, but there are no encrypted connections available,
1491        // and our probe state indicates an in-flight probe, we should select the UDP conn.
1492        let selected = policy.select_connection(ns_ip, &state, opp_enc, &connections);
1493        assert!(selected.is_some());
1494        assert_eq!(selected.unwrap().protocol, Protocol::Udp);
1495
1496        // Update the state to reflect that we completed the connection, but haven't
1497        // received a response.
1498        state.complete_connection(ns_ip, Protocol::Tls);
1499
1500        // In this case we should still select the UDP conn.
1501        let selected = policy.select_connection(ns_ip, &state, opp_enc, &connections);
1502        assert!(selected.is_some());
1503        assert_eq!(selected.unwrap().protocol, Protocol::Udp);
1504    }
1505
1506    #[tokio::test]
1507    async fn test_select_connection_opportunistic_enc_enabled_stale_probe() {
1508        let policy = ConnectionPolicy::default();
1509        let connections = [
1510            mock_connection(Protocol::Udp),
1511            mock_connection(Protocol::Tcp),
1512            // No pre-existing encrypted protocol connection is available.
1513        ];
1514
1515        let ns_ip = IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1));
1516        let mut state = NameServerTransportState::default();
1517        let opp_enc_config = OpportunisticEncryptionConfig {
1518            persistence_period: Duration::from_secs(10),
1519            ..OpportunisticEncryptionConfig::default()
1520        };
1521        let opp_enc = &OpportunisticEncryption::Enabled {
1522            config: opp_enc_config.clone(),
1523        };
1524
1525        // Update the state to reflect that we have successfully probed this NS.
1526        state.complete_connection(ns_ip, Protocol::Tls);
1527        state.response_received(ns_ip, Protocol::Tls);
1528        // And then update the last response time to be too stale for consideration.
1529        let stale_time =
1530            SystemTime::now() - opp_enc_config.persistence_period - Duration::from_secs(1);
1531        state.set_last_response(ns_ip, Protocol::Tls, stale_time);
1532
1533        // When opportunistic encryption is enabled, but there are no encrypted connections available,
1534        // and our probe state indicates success that is too stale, we should select an unencrypted
1535        // connection since the probe is no longer considered recent.
1536        let selected = policy.select_connection(ns_ip, &state, opp_enc, &connections);
1537        assert!(selected.is_some());
1538        assert_eq!(selected.unwrap().protocol, Protocol::Udp);
1539    }
1540
1541    #[tokio::test]
1542    async fn test_select_connection_opportunistic_enc_enabled_good_probe() {
1543        let policy = ConnectionPolicy::default();
1544        let connections = [
1545            mock_connection(Protocol::Udp),
1546            mock_connection(Protocol::Tcp),
1547            // No pre-existing encrypted protocol connection is available.
1548        ];
1549
1550        let ns_ip = IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1));
1551        let mut state = NameServerTransportState::default();
1552        let opp_enc = &OpportunisticEncryption::Enabled {
1553            config: OpportunisticEncryptionConfig::default(),
1554        };
1555
1556        // Update the state to reflect that we have successfully probed this NS within
1557        // the persistence period and received a response.
1558        state.complete_connection(ns_ip, Protocol::Tls);
1559        state.response_received(ns_ip, Protocol::Tls);
1560
1561        // When opportunistic encryption is enabled, but there are no encrypted connections available,
1562        // and our probe state indicates a recent enough success, we should return `None` so that
1563        // we make a new encrypted connection.
1564        let selected = policy.select_connection(ns_ip, &state, opp_enc, &connections);
1565        assert!(selected.is_none());
1566    }
1567
1568    #[tokio::test]
1569    async fn test_select_connection_config_opportunistic_enc_disabled() {
1570        let mut policy = ConnectionPolicy::default();
1571
1572        let ns_ip = IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1));
1573        let configs = NameServerConfig::opportunistic_encryption(ns_ip).connections;
1574
1575        let state = NameServerTransportState::default();
1576        let opp_enc = OpportunisticEncryption::Disabled;
1577
1578        // When opportunistic encryption is disabled, and disable_udp isn't active,
1579        // we should select the UDP config.
1580        let selected = policy.select_connection_config(ns_ip, &state, &opp_enc, &configs);
1581        assert!(selected.is_some());
1582        assert_eq!(selected.unwrap().protocol, ProtocolConfig::Udp);
1583
1584        // When opportunistic encryption is disabled, and disable_udp is active,
1585        // we should select the TCP config.
1586        policy.disable_udp = true;
1587        let selected = policy.select_connection_config(ns_ip, &state, &opp_enc, &configs);
1588        assert!(selected.is_some());
1589        assert_eq!(selected.unwrap().protocol, ProtocolConfig::Tcp);
1590    }
1591
1592    #[tokio::test]
1593    async fn test_select_connection_config_opportunistic_enc_enabled_no_state() {
1594        let mut policy = ConnectionPolicy::default();
1595        let ns_ip = IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1));
1596        let configs = NameServerConfig::opportunistic_encryption(ns_ip).connections;
1597
1598        let state = NameServerTransportState::default();
1599        let opp_enc = &OpportunisticEncryption::Enabled {
1600            config: OpportunisticEncryptionConfig::default(),
1601        };
1602
1603        // When opportunistic encryption is enabled, but we have no probe state,
1604        // we should select the UDP config (default protocol ordering).
1605        let selected = policy.select_connection_config(ns_ip, &state, opp_enc, &configs);
1606        assert!(selected.is_some());
1607        assert_eq!(selected.unwrap().protocol, ProtocolConfig::Udp);
1608
1609        // When opportunistic encryption is enabled, but we have no probe state,
1610        // and disable_udp is active, we should select the TCP config.
1611        policy.disable_udp = true;
1612        let selected = policy.select_connection_config(ns_ip, &state, opp_enc, &configs);
1613        assert!(selected.is_some());
1614        assert_eq!(selected.unwrap().protocol, ProtocolConfig::Tcp);
1615    }
1616
1617    #[tokio::test]
1618    async fn test_select_connection_config_opportunistic_enc_enabled_failed_probe() {
1619        let policy = ConnectionPolicy::default();
1620        let ns_ip = IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1));
1621        let configs = NameServerConfig::opportunistic_encryption(ns_ip).connections;
1622
1623        let mut state = NameServerTransportState::default();
1624        let opp_enc = &OpportunisticEncryption::Enabled {
1625            config: OpportunisticEncryptionConfig::default(),
1626        };
1627
1628        // Update the state to reflect that we failed a previous probe attempt.
1629        state.error_received(
1630            ns_ip,
1631            Protocol::Tls,
1632            &NetError::from(io::Error::new(
1633                io::ErrorKind::ConnectionRefused,
1634                "nameserver refused TLS connection",
1635            )),
1636        );
1637
1638        // When opportunistic encryption is enabled, but our probe state indicates a failure,
1639        // we should select the UDP config.
1640        let selected = policy.select_connection_config(ns_ip, &state, opp_enc, &configs);
1641        assert!(selected.is_some());
1642        assert_eq!(selected.unwrap().protocol, ProtocolConfig::Udp);
1643    }
1644
1645    #[tokio::test]
1646    async fn test_select_connection_config_opportunistic_enc_enabled_stale_probe() {
1647        let policy = ConnectionPolicy::default();
1648        let ns_ip = IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1));
1649        let configs = NameServerConfig::opportunistic_encryption(ns_ip).connections;
1650
1651        let mut state = NameServerTransportState::default();
1652        let opp_enc_config = OpportunisticEncryptionConfig {
1653            persistence_period: Duration::from_secs(10),
1654            ..OpportunisticEncryptionConfig::default()
1655        };
1656        let opp_enc = &OpportunisticEncryption::Enabled {
1657            config: opp_enc_config.clone(),
1658        };
1659
1660        // Update the state to reflect that we have successfully probed this NS.
1661        state.complete_connection(ns_ip, Protocol::Tls);
1662        state.response_received(ns_ip, Protocol::Tls);
1663        // And then update the last response time to be too stale for consideration.
1664        let stale_time =
1665            SystemTime::now() - opp_enc_config.persistence_period - Duration::from_secs(1);
1666        state.set_last_response(ns_ip, Protocol::Tls, stale_time);
1667
1668        // When opportunistic encryption is enabled, but our probe state indicates success that is too stale,
1669        // we should select an unencrypted config since the probe is no longer considered recent.
1670        let selected = policy.select_connection_config(ns_ip, &state, opp_enc, &configs);
1671        assert!(selected.is_some());
1672        assert_eq!(selected.unwrap().protocol, ProtocolConfig::Udp);
1673    }
1674
1675    #[tokio::test]
1676    async fn test_select_connection_config_opportunistic_enc_enabled_good_probe() {
1677        let policy = ConnectionPolicy::default();
1678        let ns_ip = IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1));
1679        let configs = NameServerConfig::opportunistic_encryption(ns_ip).connections;
1680
1681        let mut state = NameServerTransportState::default();
1682        let opp_enc = &OpportunisticEncryption::Enabled {
1683            config: OpportunisticEncryptionConfig::default(),
1684        };
1685
1686        // Update the state to reflect that we have successfully probed this NS within
1687        // the persistence period and received a response.
1688        state.complete_connection(ns_ip, Protocol::Tls);
1689        state.response_received(ns_ip, Protocol::Tls);
1690
1691        // When opportunistic encryption is enabled, and our probe state indicates a recent enough success,
1692        // we should select the encrypted config with highest priority.
1693        let selected = policy.select_connection_config(ns_ip, &state, opp_enc, &configs);
1694        assert!(selected.is_some());
1695        assert!(matches!(
1696            selected.unwrap().protocol,
1697            ProtocolConfig::Tls { .. }
1698        ));
1699    }
1700
1701    #[tokio::test]
1702    async fn test_opportunistic_probe() {
1703        subscribe();
1704
1705        // Enable opportunistic encryption
1706        let cx = PoolContext::new(ResolverOpts::default(), TlsConfig::new().unwrap())
1707            .with_opportunistic_encryption()
1708            .with_probe_budget(10);
1709
1710        let ns_ip = IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1));
1711        let mock_provider = MockProvider::default();
1712        assert!(
1713            test_connected_mut_client(ns_ip, Arc::new(cx), &mock_provider)
1714                .await
1715                .is_ok()
1716        );
1717
1718        let recorded_calls = mock_provider.new_connection_calls();
1719        // We should have made two new connection calls.
1720        assert_eq!(recorded_calls.len(), 2);
1721        let (ips, protocols): (Vec<IpAddr>, Vec<ProtocolConfig>) =
1722            recorded_calls.into_iter().unzip();
1723        // All connections should be to the expected NS IP.
1724        assert!(ips.iter().all(|ip| *ip == ns_ip));
1725        // We should have made connections for both the UDP protocol, and the encrypted probe protocol.
1726        let protocols = protocols
1727            .iter()
1728            .map(ProtocolConfig::to_protocol)
1729            .collect::<Vec<_>>();
1730        assert!(protocols.contains(&Protocol::Udp));
1731        assert!(protocols.contains(&Protocol::Tls));
1732    }
1733
1734    #[tokio::test]
1735    async fn test_opportunistic_probe_skip_in_progress() {
1736        subscribe();
1737
1738        let ns_ip = IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1));
1739        let cx = PoolContext::new(ResolverOpts::default(), TlsConfig::new().unwrap())
1740            .with_opportunistic_encryption()
1741            .with_probe_budget(10);
1742
1743        // Set up state to show an in-flight connection already initiated
1744        cx.transport_state()
1745            .await
1746            .initiate_connection(ns_ip, Protocol::Tls);
1747
1748        let mock_provider = MockProvider::default();
1749        assert!(
1750            test_connected_mut_client(ns_ip, Arc::new(cx), &mock_provider)
1751                .await
1752                .is_ok()
1753        );
1754
1755        let recorded_calls = mock_provider.new_connection_calls();
1756        // We should have made only one connection call (UDP), no probe because one is already in-flight
1757        assert_eq!(recorded_calls.len(), 1);
1758        let (ip, protocol) = &recorded_calls[0];
1759        assert_eq!(*ip, ns_ip);
1760        assert_eq!(protocol.to_protocol(), Protocol::Udp);
1761    }
1762
1763    #[tokio::test]
1764    async fn test_opportunistic_probe_skip_recent_failure() {
1765        subscribe();
1766
1767        let ns_ip = IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1));
1768        let cx = PoolContext::new(ResolverOpts::default(), TlsConfig::new().unwrap())
1769            .with_opportunistic_encryption()
1770            .with_probe_budget(10);
1771
1772        // Set up state to show a recent failure within the damping period
1773        cx.transport_state().await.error_received(
1774            ns_ip,
1775            Protocol::Tls,
1776            &NetError::from(io::Error::new(
1777                io::ErrorKind::ConnectionRefused,
1778                "connection refused",
1779            )),
1780        );
1781
1782        let mock_provider = MockProvider::default();
1783        assert!(
1784            test_connected_mut_client(ns_ip, Arc::new(cx), &mock_provider)
1785                .await
1786                .is_ok()
1787        );
1788
1789        let recorded_calls = mock_provider.new_connection_calls();
1790        // We should have made only one connection call (UDP), no probe due to recent failure
1791        assert_eq!(recorded_calls.len(), 1);
1792        let (ip, protocol) = &recorded_calls[0];
1793        assert_eq!(*ip, ns_ip);
1794        assert_eq!(protocol.to_protocol(), Protocol::Udp);
1795    }
1796
1797    #[tokio::test]
1798    async fn test_opportunistic_probe_stale_failure() {
1799        subscribe();
1800
1801        let ns_ip = IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1));
1802        let mut cx = PoolContext::new(ResolverOpts::default(), TlsConfig::new().unwrap())
1803            .with_probe_budget(10);
1804        let opp_enc_config = OpportunisticEncryptionConfig {
1805            damping_period: Duration::from_secs(5),
1806            ..OpportunisticEncryptionConfig::default()
1807        };
1808        cx.opportunistic_encryption = OpportunisticEncryption::Enabled {
1809            config: opp_enc_config.clone(),
1810        };
1811
1812        // Set up state to show an old failure outside the damping period.
1813        {
1814            let mut state = cx.transport_state().await;
1815            let old_failure_time =
1816                SystemTime::now() - opp_enc_config.damping_period - Duration::from_secs(1);
1817            state.set_failure_time(ns_ip, Protocol::Tls, old_failure_time);
1818        }
1819
1820        let mock_provider = MockProvider::default();
1821        assert!(
1822            test_connected_mut_client(ns_ip, Arc::new(cx), &mock_provider)
1823                .await
1824                .is_ok()
1825        );
1826
1827        let recorded_calls = mock_provider.new_connection_calls();
1828        // We should have made two connection calls (UDP + TLS probe) because the failure is old
1829        assert_eq!(recorded_calls.len(), 2);
1830        let protocols = recorded_calls
1831            .iter()
1832            .map(|(_, protocol)| protocol.to_protocol())
1833            .collect::<Vec<_>>();
1834        assert!(protocols.contains(&Protocol::Udp));
1835        assert!(protocols.contains(&Protocol::Tls));
1836    }
1837
1838    #[tokio::test]
1839    async fn test_opportunistic_probe_skip_no_budget() {
1840        subscribe();
1841
1842        let ns_ip = IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1));
1843        let cx = PoolContext::new(ResolverOpts::default(), TlsConfig::new().unwrap())
1844            .with_opportunistic_encryption();
1845        let mock_provider = MockProvider::default();
1846        // Set budget to 0 to simulate exhausted probe budget
1847        assert!(
1848            test_connected_mut_client(ns_ip, Arc::new(cx), &mock_provider)
1849                .await
1850                .is_ok()
1851        );
1852
1853        let recorded_calls = mock_provider.new_connection_calls();
1854        // We should have made only one connection call (UDP), no probe due to exhausted budget
1855        assert_eq!(recorded_calls.len(), 1);
1856        let (ip, protocol) = &recorded_calls[0];
1857        assert_eq!(*ip, ns_ip);
1858        assert_eq!(protocol.to_protocol(), Protocol::Udp);
1859    }
1860
1861    fn mock_connection(protocol: Protocol) -> ConnectionState<MockProvider> {
1862        ConnectionState::new(
1863            MockClientHandle::default(),
1864            Arc::new(ConnectionMeta::default()),
1865            protocol,
1866        )
1867    }
1868
1869    #[cfg(feature = "metrics")]
1870    #[test]
1871    fn test_opportunistic_probe_metrics_success() {
1872        subscribe();
1873        let recorder = DebuggingRecorder::new();
1874        let snapshotter = recorder.snapshotter();
1875        let initial_budget = 10;
1876
1877        with_local_recorder(&recorder, || {
1878            let runtime = tokio::runtime::Builder::new_current_thread()
1879                .enable_all()
1880                .build()
1881                .unwrap();
1882
1883            runtime.block_on(async {
1884                assert!(
1885                    test_connected_mut_client(
1886                        IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1)),
1887                        Arc::new(
1888                            PoolContext::new(ResolverOpts::default(), TlsConfig::new().unwrap())
1889                                .with_opportunistic_encryption()
1890                                .with_probe_budget(initial_budget),
1891                        ),
1892                        &MockProvider::default(),
1893                    )
1894                    .await
1895                    .is_ok()
1896                );
1897            });
1898        });
1899
1900        #[allow(clippy::mutable_key_type)]
1901        let map = snapshotter.snapshot().into_hashmap();
1902
1903        // We should have registered 1 TLS protocol probe attempt.
1904        let protocol = vec![Label::new("protocol", "tls")];
1905        assert_counter_eq(&map, PROBE_ATTEMPTS_TOTAL, protocol.clone(), 1);
1906        // And seen 1 probe duration observation.
1907        assert_histogram_sample_count_eq(
1908            &map,
1909            PROBE_DURATION_SECONDS,
1910            protocol.clone(),
1911            1,
1912            Unit::Seconds,
1913        );
1914
1915        // We should have registered 1 TLS protocol probe success.
1916        assert_counter_eq(&map, PROBE_SUCCESSES_TOTAL, protocol.clone(), 1);
1917
1918        // We should have registered 0 TLS protocol probe errors.
1919        assert_counter_eq(&map, PROBE_ERRORS_TOTAL, protocol, 0);
1920
1921        // The budget should be back to the initial value now that the probe completed.
1922        assert_gauge_eq(&map, PROBE_BUDGET_TOTAL, vec![], initial_budget);
1923    }
1924
1925    #[cfg(feature = "metrics")]
1926    #[test]
1927    fn test_opportunistic_probe_metrics_budget_exhausted() {
1928        subscribe();
1929        let recorder = DebuggingRecorder::new();
1930        let snapshotter = recorder.snapshotter();
1931
1932        with_local_recorder(&recorder, || {
1933            let runtime = tokio::runtime::Builder::new_current_thread()
1934                .enable_all()
1935                .build()
1936                .unwrap();
1937
1938            runtime.block_on(async {
1939                assert!(
1940                    test_connected_mut_client(
1941                        IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1)),
1942                        Arc::new(
1943                            PoolContext::new(ResolverOpts::default(), TlsConfig::new().unwrap())
1944                                .with_opportunistic_encryption(),
1945                        ),
1946                        &MockProvider::default(),
1947                    )
1948                    .await
1949                    .is_ok()
1950                );
1951            });
1952        });
1953
1954        #[allow(clippy::mutable_key_type)]
1955        let map = snapshotter.snapshot().into_hashmap();
1956
1957        // The budget metric should confirm that there's no budget.
1958        assert_gauge_eq(&map, PROBE_BUDGET_TOTAL, vec![], 0);
1959
1960        // We should not have registered a probe attempt.
1961        let protocol = vec![Label::new("protocol", "tls")];
1962        assert_counter_eq(&map, PROBE_ATTEMPTS_TOTAL, protocol.clone(), 0);
1963        // Or seen a probe duration observation.
1964        assert_histogram_sample_count_eq(&map, PROBE_DURATION_SECONDS, protocol, 0, Unit::Seconds);
1965    }
1966
1967    #[cfg(feature = "metrics")]
1968    #[test]
1969    fn test_opportunistic_probe_metrics_connection_error() {
1970        subscribe();
1971        let recorder = DebuggingRecorder::new();
1972        let snapshotter = recorder.snapshotter();
1973        let initial_budget = 10;
1974
1975        with_local_recorder(&recorder, || {
1976            let runtime = tokio::runtime::Builder::new_current_thread()
1977                .enable_all()
1978                .build()
1979                .unwrap();
1980
1981            runtime.block_on(async {
1982                let _ = test_connected_mut_client(
1983                    IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1)),
1984                    Arc::new(
1985                        PoolContext::new(ResolverOpts::default(), TlsConfig::new().unwrap())
1986                            .with_opportunistic_encryption()
1987                            .with_probe_budget(initial_budget),
1988                    ),
1989                    // Configure a mock provider that always produces an error when new connections are requested.
1990                    &MockProvider {
1991                        new_connection_error: Some(NetError::from(io::Error::new(
1992                            io::ErrorKind::ConnectionRefused,
1993                            "connection refused",
1994                        ))),
1995                        ..MockProvider::default()
1996                    },
1997                )
1998                .await;
1999            });
2000        });
2001
2002        #[allow(clippy::mutable_key_type)]
2003        let map = snapshotter.snapshot().into_hashmap();
2004
2005        // We should have registered 1 TLS protocol probe attempt.
2006        let protocol = vec![Label::new("protocol", "tls")];
2007        assert_counter_eq(&map, PROBE_ATTEMPTS_TOTAL, protocol.clone(), 1);
2008        // And seen 1 probe duration observation.
2009        assert_histogram_sample_count_eq(
2010            &map,
2011            PROBE_DURATION_SECONDS,
2012            protocol.clone(),
2013            1,
2014            Unit::Seconds,
2015        );
2016
2017        // We should have registered 1 TLS protocol probe error.
2018        assert_counter_eq(&map, PROBE_ERRORS_TOTAL, protocol.clone(), 1);
2019
2020        // We shouldn't have registered any TLS protocol probe successes due to the
2021        // mock new connection error.
2022        assert_counter_eq(&map, PROBE_SUCCESSES_TOTAL, protocol, 0);
2023
2024        // The budget should be back to the initial value now that the probe completed.
2025        assert_gauge_eq(&map, PROBE_BUDGET_TOTAL, vec![], initial_budget);
2026    }
2027
2028    #[cfg(feature = "metrics")]
2029    #[test]
2030    fn test_opportunistic_probe_metrics_connection_timeout_error() {
2031        subscribe();
2032        let recorder = DebuggingRecorder::new();
2033        let snapshotter = recorder.snapshotter();
2034        let initial_budget = 10;
2035
2036        with_local_recorder(&recorder, || {
2037            let runtime = tokio::runtime::Builder::new_current_thread()
2038                .enable_all()
2039                .build()
2040                .unwrap();
2041
2042            runtime.block_on(async {
2043                let _ = test_connected_mut_client(
2044                    IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1)),
2045                    Arc::new(
2046                        PoolContext::new(ResolverOpts::default(), TlsConfig::new().unwrap())
2047                            .with_opportunistic_encryption()
2048                            .with_probe_budget(initial_budget),
2049                    ),
2050                    // Configure a mock provider that always produces a Timeout error when new connections are requested.
2051                    &MockProvider {
2052                        new_connection_error: Some(NetError::Timeout),
2053                        ..MockProvider::default()
2054                    },
2055                )
2056                .await;
2057            });
2058        });
2059
2060        #[allow(clippy::mutable_key_type)]
2061        let map = snapshotter.snapshot().into_hashmap();
2062
2063        // We should have registered 1 TLS protocol probe attempt.
2064        let protocol = vec![Label::new("protocol", "tls")];
2065        assert_counter_eq(&map, PROBE_ATTEMPTS_TOTAL, protocol.clone(), 1);
2066        // And seen 1 probe duration observation.
2067        assert_histogram_sample_count_eq(
2068            &map,
2069            PROBE_DURATION_SECONDS,
2070            protocol.clone(),
2071            1,
2072            Unit::Seconds,
2073        );
2074
2075        // We should have registered 1 TLS protocol probe timeout.
2076        assert_counter_eq(&map, PROBE_TIMEOUTS_TOTAL, protocol.clone(), 1);
2077
2078        // We shouldn't have registered a more general probe error.
2079        assert_counter_eq(&map, PROBE_ERRORS_TOTAL, protocol.clone(), 0);
2080
2081        // We shouldn't have registered any TLS protocol probe successes due to the
2082        // mock new connection error.
2083        assert_counter_eq(&map, PROBE_SUCCESSES_TOTAL, protocol, 0);
2084
2085        // The budget should be back to the initial value now that the probe completed.
2086        assert_gauge_eq(&map, PROBE_BUDGET_TOTAL, vec![], initial_budget);
2087    }
2088
2089    /// Construct a nameserver appropriate for opportunistic encryption and assert connected_mut_client
2090    /// returns Ok.
2091    ///
2092    /// Behind the scenes this may provoke probing behaviour that the calling test can observe via
2093    /// the `MockProvider`'s recorded calls.
2094    async fn test_connected_mut_client(
2095        ns_ip: IpAddr,
2096        cx: Arc<PoolContext>,
2097        provider: &MockProvider,
2098    ) -> Result<(), NetError> {
2099        let name_server = NameServer::new(
2100            [],
2101            NameServerConfig::opportunistic_encryption(ns_ip),
2102            &ResolverOpts::default(),
2103            provider.clone(),
2104        );
2105
2106        match name_server
2107            .connected_mut_client(ConnectionPolicy::default(), &cx)
2108            .await
2109        {
2110            Ok(_) => Ok(()),
2111            Err((e, _)) => Err(e),
2112        }
2113    }
2114}
2115
2116#[cfg(all(test, feature = "metrics"))]
2117mod resolver_metrics_tests {
2118    use std::net::{IpAddr, Ipv4Addr};
2119
2120    use metrics::{Label, with_local_recorder};
2121    use metrics_util::debugging::DebuggingRecorder;
2122    use mock_provider::MockProvider;
2123    use test_support::assert_counter_eq;
2124    use test_support::subscribe;
2125
2126    use super::*;
2127    use crate::connection_provider::TlsConfig;
2128    use crate::metrics::OUTGOING_QUERIES_TOTAL;
2129
2130    #[test]
2131    fn test_outgoing_query_protocol_metrics_udp() {
2132        subscribe();
2133        let recorder = DebuggingRecorder::new();
2134        let snapshotter = recorder.snapshotter();
2135
2136        with_local_recorder(&recorder, || {
2137            let runtime = tokio::runtime::Builder::new_current_thread()
2138                .enable_all()
2139                .build()
2140                .unwrap();
2141
2142            runtime.block_on(async {
2143                let options = ResolverOpts {
2144                    enable_per_name_server_metrics: true,
2145                    ..ResolverOpts::default()
2146                };
2147                let config = NameServerConfig::udp(IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8)));
2148                let name_server = Arc::new(NameServer::new(
2149                    [],
2150                    config,
2151                    &options,
2152                    MockProvider::default(),
2153                ));
2154
2155                let cx = Arc::new(PoolContext::new(options, TlsConfig::new().unwrap()));
2156                let name = Name::parse("www.example.com.", None).unwrap();
2157                let _ = name_server
2158                    .send(
2159                        DnsRequest::from_query(
2160                            Query::query(name.clone(), RecordType::A),
2161                            DnsRequestOptions::default(),
2162                        ),
2163                        ConnectionPolicy::default(),
2164                        &cx,
2165                    )
2166                    .await;
2167            });
2168        });
2169
2170        #[allow(clippy::mutable_key_type)]
2171        let map = snapshotter.snapshot().into_hashmap();
2172
2173        // We should have registered 1 UDP protocol query.
2174        let protocol = vec![Label::new("protocol", "udp")];
2175        assert_counter_eq(&map, OUTGOING_QUERIES_TOTAL, protocol, 1);
2176    }
2177
2178    #[test]
2179    fn test_outgoing_query_protocol_metrics_tcp() {
2180        subscribe();
2181        let recorder = DebuggingRecorder::new();
2182        let snapshotter = recorder.snapshotter();
2183
2184        with_local_recorder(&recorder, || {
2185            let runtime = tokio::runtime::Builder::new_current_thread()
2186                .enable_all()
2187                .build()
2188                .unwrap();
2189
2190            runtime.block_on(async {
2191                let options = ResolverOpts::default();
2192                let config = NameServerConfig::tcp(IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8)));
2193                let name_server = Arc::new(NameServer::new(
2194                    [],
2195                    config,
2196                    &options,
2197                    MockProvider::default(),
2198                ));
2199
2200                let cx = Arc::new(PoolContext::new(options, TlsConfig::new().unwrap()));
2201                let name = Name::parse("www.example.com.", None).unwrap();
2202                let _ = name_server
2203                    .send(
2204                        DnsRequest::from_query(
2205                            Query::query(name.clone(), RecordType::A),
2206                            DnsRequestOptions::default(),
2207                        ),
2208                        ConnectionPolicy::default(),
2209                        &cx,
2210                    )
2211                    .await;
2212            });
2213        });
2214
2215        #[allow(clippy::mutable_key_type)]
2216        let map = snapshotter.snapshot().into_hashmap();
2217
2218        // We should have registered 1 TCP protocol query.
2219        let protocol = vec![Label::new("protocol", "tcp")];
2220        assert_counter_eq(&map, OUTGOING_QUERIES_TOTAL, protocol, 1);
2221    }
2222
2223    #[cfg(feature = "__tls")]
2224    #[test]
2225    fn test_outgoing_query_protocol_metrics_tls() {
2226        subscribe();
2227        let recorder = DebuggingRecorder::new();
2228        let snapshotter = recorder.snapshotter();
2229
2230        with_local_recorder(&recorder, || {
2231            let runtime = tokio::runtime::Builder::new_current_thread()
2232                .enable_all()
2233                .build()
2234                .unwrap();
2235
2236            runtime.block_on(async {
2237                let options = ResolverOpts::default();
2238                let config = NameServerConfig::tls(
2239                    IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8)),
2240                    "dns.google".into(),
2241                );
2242                let name_server = Arc::new(NameServer::new(
2243                    [],
2244                    config,
2245                    &options,
2246                    MockProvider::default(),
2247                ));
2248
2249                let cx = Arc::new(PoolContext::new(options, TlsConfig::new().unwrap()));
2250                let name = Name::parse("www.example.com.", None).unwrap();
2251                let _ = name_server
2252                    .send(
2253                        DnsRequest::from_query(
2254                            Query::query(name.clone(), RecordType::A),
2255                            DnsRequestOptions::default(),
2256                        ),
2257                        ConnectionPolicy::default(),
2258                        &cx,
2259                    )
2260                    .await;
2261            });
2262        });
2263
2264        #[allow(clippy::mutable_key_type)]
2265        let map = snapshotter.snapshot().into_hashmap();
2266
2267        // We should have registered 1 TLS protocol query.
2268        let protocol = vec![Label::new("protocol", "tls")];
2269        assert_counter_eq(&map, OUTGOING_QUERIES_TOTAL, protocol, 1);
2270    }
2271
2272    #[test]
2273    fn test_name_server_query_success_metrics() {
2274        subscribe();
2275        let recorder = DebuggingRecorder::new();
2276        let snapshotter = recorder.snapshotter();
2277
2278        with_local_recorder(&recorder, || {
2279            let runtime = tokio::runtime::Builder::new_current_thread()
2280                .enable_all()
2281                .build()
2282                .unwrap();
2283
2284            runtime.block_on(async {
2285                let options = ResolverOpts {
2286                    enable_per_name_server_metrics: true,
2287                    ..ResolverOpts::default()
2288                };
2289                let config = NameServerConfig::udp(IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8)));
2290                let mock_provider = MockProvider::default();
2291                let name_server = Arc::new(NameServer::new([], config, &options, mock_provider));
2292
2293                let cx = Arc::new(PoolContext::new(options, TlsConfig::new().unwrap()));
2294                let name = Name::parse("www.example.com.", None).unwrap();
2295                let _ = name_server
2296                    .send(
2297                        DnsRequest::from_query(
2298                            Query::query(name.clone(), RecordType::A),
2299                            DnsRequestOptions::default(),
2300                        ),
2301                        ConnectionPolicy::default(),
2302                        &cx,
2303                    )
2304                    .await;
2305            });
2306        });
2307
2308        #[allow(clippy::mutable_key_type)]
2309        let map = snapshotter.snapshot().into_hashmap();
2310
2311        use crate::metrics::NAME_SERVER_QUERY_RESPONSES;
2312        let labels = vec![
2313            Label::new("addr", "8.8.8.8"),
2314            Label::new("protocol", "udp"),
2315            Label::new("status", "success"),
2316        ];
2317        assert_counter_eq(&map, NAME_SERVER_QUERY_RESPONSES, labels, 1);
2318    }
2319
2320    #[test]
2321    fn test_name_server_query_connection_failure_metrics() {
2322        subscribe();
2323        let recorder = DebuggingRecorder::new();
2324        let snapshotter = recorder.snapshotter();
2325
2326        with_local_recorder(&recorder, || {
2327            let runtime = tokio::runtime::Builder::new_current_thread()
2328                .enable_all()
2329                .build()
2330                .unwrap();
2331
2332            runtime.block_on(async {
2333                let options = ResolverOpts {
2334                    enable_per_name_server_metrics: true,
2335                    ..ResolverOpts::default()
2336                };
2337                let config = NameServerConfig::udp(IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8)));
2338                let mock_provider = MockProvider {
2339                    new_connection_error: Some(NetError::Io(Arc::new(std::io::Error::new(
2340                        std::io::ErrorKind::ConnectionRefused,
2341                        "connection refused",
2342                    )))),
2343                    ..MockProvider::default()
2344                };
2345                let name_server = Arc::new(NameServer::new([], config, &options, mock_provider));
2346
2347                let cx = Arc::new(PoolContext::new(options, TlsConfig::new().unwrap()));
2348                let name = Name::parse("www.example.com.", None).unwrap();
2349                let _ = name_server
2350                    .send(
2351                        DnsRequest::from_query(
2352                            Query::query(name.clone(), RecordType::A),
2353                            DnsRequestOptions::default(),
2354                        ),
2355                        ConnectionPolicy::default(),
2356                        &cx,
2357                    )
2358                    .await;
2359            });
2360        });
2361
2362        #[allow(clippy::mutable_key_type)]
2363        let map = snapshotter.snapshot().into_hashmap();
2364
2365        use crate::metrics::NAME_SERVER_QUERY_RESPONSES;
2366        let labels = vec![
2367            Label::new("addr", "8.8.8.8"),
2368            Label::new("protocol", "udp"),
2369            Label::new("status", "io_connection_refused"),
2370        ];
2371        assert_counter_eq(&map, NAME_SERVER_QUERY_RESPONSES, labels, 1);
2372    }
2373
2374    #[test]
2375    fn test_name_server_query_response_code_failure_metrics() {
2376        subscribe();
2377        let recorder = DebuggingRecorder::new();
2378        let snapshotter = recorder.snapshotter();
2379
2380        with_local_recorder(&recorder, || {
2381            let runtime = tokio::runtime::Builder::new_current_thread()
2382                .enable_all()
2383                .build()
2384                .unwrap();
2385
2386            runtime.block_on(async {
2387                let options = ResolverOpts {
2388                    enable_per_name_server_metrics: true,
2389                    ..ResolverOpts::default()
2390                };
2391                let config = NameServerConfig::udp(IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8)));
2392                let mock_provider = MockProvider::default();
2393                mock_provider
2394                    .send_outcomes
2395                    .lock()
2396                    .push_back(Some(NetError::Dns(DnsError::ResponseCode(
2397                        ResponseCode::ServFail,
2398                    ))));
2399                let name_server = Arc::new(NameServer::new([], config, &options, mock_provider));
2400
2401                let cx = Arc::new(PoolContext::new(options, TlsConfig::new().unwrap()));
2402                let name = Name::parse("www.example.com.", None).unwrap();
2403                let _ = name_server
2404                    .send(
2405                        DnsRequest::from_query(
2406                            Query::query(name.clone(), RecordType::A),
2407                            DnsRequestOptions::default(),
2408                        ),
2409                        ConnectionPolicy::default(),
2410                        &cx,
2411                    )
2412                    .await;
2413            });
2414        });
2415
2416        #[allow(clippy::mutable_key_type)]
2417        let map = snapshotter.snapshot().into_hashmap();
2418
2419        use crate::metrics::NAME_SERVER_QUERY_RESPONSES;
2420        let labels = vec![
2421            Label::new("addr", "8.8.8.8"),
2422            Label::new("protocol", "udp"),
2423            Label::new("status", "dns_response_code_servfail"),
2424        ];
2425        assert_counter_eq(&map, NAME_SERVER_QUERY_RESPONSES, labels, 1);
2426    }
2427
2428    #[test]
2429    fn test_name_server_query_no_records_success_metrics() {
2430        subscribe();
2431        let recorder = DebuggingRecorder::new();
2432        let snapshotter = recorder.snapshotter();
2433
2434        with_local_recorder(&recorder, || {
2435            let runtime = tokio::runtime::Builder::new_current_thread()
2436                .enable_all()
2437                .build()
2438                .unwrap();
2439
2440            runtime.block_on(async {
2441                let options = ResolverOpts {
2442                    enable_per_name_server_metrics: true,
2443                    ..ResolverOpts::default()
2444                };
2445                let config = NameServerConfig::udp(IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8)));
2446                let name = Name::parse("www.example.com.", None).unwrap();
2447                let query = Query::query(name.clone(), RecordType::A);
2448                let mock_provider = MockProvider::default();
2449                mock_provider
2450                    .send_outcomes
2451                    .lock()
2452                    .push_back(Some(NetError::Dns(DnsError::NoRecordsFound(
2453                        NoRecords::new(query, ResponseCode::NXDomain),
2454                    ))));
2455                let name_server = Arc::new(NameServer::new([], config, &options, mock_provider));
2456
2457                let cx = Arc::new(PoolContext::new(options, TlsConfig::new().unwrap()));
2458                let _ = name_server
2459                    .send(
2460                        DnsRequest::from_query(
2461                            Query::query(name.clone(), RecordType::A),
2462                            DnsRequestOptions::default(),
2463                        ),
2464                        ConnectionPolicy::default(),
2465                        &cx,
2466                    )
2467                    .await;
2468            });
2469        });
2470
2471        #[allow(clippy::mutable_key_type)]
2472        let map = snapshotter.snapshot().into_hashmap();
2473
2474        use crate::metrics::NAME_SERVER_QUERY_RESPONSES;
2475        let labels = vec![
2476            Label::new("addr", "8.8.8.8"),
2477            Label::new("protocol", "udp"),
2478            Label::new("status", "dns_no_records"),
2479        ];
2480        assert_counter_eq(&map, NAME_SERVER_QUERY_RESPONSES, labels, 1);
2481    }
2482
2483    #[test]
2484    fn test_name_server_query_metrics_aggregation() {
2485        subscribe();
2486        let recorder = DebuggingRecorder::new();
2487        let snapshotter = recorder.snapshotter();
2488
2489        with_local_recorder(&recorder, || {
2490            let runtime = tokio::runtime::Builder::new_current_thread()
2491                .enable_all()
2492                .build()
2493                .unwrap();
2494
2495            runtime.block_on(async {
2496                let name = Name::parse("www.example.com.", None).unwrap();
2497                let options = ResolverOpts {
2498                    enable_per_name_server_metrics: false,
2499                    ..Default::default()
2500                };
2501                let config = NameServerConfig::udp(IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8)));
2502                let mock_provider = MockProvider::default();
2503                let name_server = Arc::new(NameServer::new([], config, &options, mock_provider));
2504
2505                let cx = Arc::new(PoolContext::new(options, TlsConfig::new().unwrap()));
2506                let _ = name_server
2507                    .send(
2508                        DnsRequest::from_query(
2509                            Query::query(name.clone(), RecordType::A),
2510                            DnsRequestOptions::default(),
2511                        ),
2512                        ConnectionPolicy::default(),
2513                        &cx,
2514                    )
2515                    .await;
2516            });
2517        });
2518
2519        #[allow(clippy::mutable_key_type)]
2520        let map = snapshotter.snapshot().into_hashmap();
2521
2522        use crate::metrics::NAME_SERVER_QUERY_RESPONSES;
2523        let labels = vec![
2524            // No address label.
2525            Label::new("protocol", "udp"),
2526            Label::new("status", "success"),
2527        ];
2528        assert_counter_eq(&map, NAME_SERVER_QUERY_RESPONSES, labels, 1);
2529    }
2530}
2531
2532#[cfg(all(test, any(feature = "metrics", feature = "__tls")))]
2533mod reconnect_tests {
2534    use std::collections::VecDeque;
2535    use std::io;
2536    use std::net::{IpAddr, Ipv4Addr};
2537    use std::sync::Arc;
2538
2539    use parking_lot::Mutex as SyncMutex;
2540    use test_support::subscribe;
2541
2542    use super::mock_provider::MockProvider;
2543    use super::{ConnectionPolicy, NameServer};
2544    use crate::config::{NameServerConfig, ResolverOpts};
2545    use crate::connection_provider::TlsConfig;
2546    use crate::name_server_pool::PoolContext;
2547    use crate::net::NetError;
2548    use crate::proto::op::{DnsRequest, DnsRequestOptions, Query};
2549    use crate::proto::rr::{Name, RecordType};
2550
2551    fn connection_closed() -> NetError {
2552        NetError::from(io::Error::from(io::ErrorKind::ConnectionReset))
2553    }
2554
2555    fn query() -> DnsRequest {
2556        DnsRequest::from_query(
2557            Query::query(
2558                Name::parse("www.example.com.", None).unwrap(),
2559                RecordType::A,
2560            ),
2561            DnsRequestOptions::default(),
2562        )
2563    }
2564
2565    /// Build a name server whose connections replay `outcomes` across the sends they receive.
2566    fn name_server_with(
2567        outcomes: VecDeque<Option<NetError>>,
2568    ) -> (
2569        Arc<NameServer<MockProvider>>,
2570        MockProvider,
2571        Arc<PoolContext>,
2572    ) {
2573        let provider = MockProvider {
2574            send_outcomes: Arc::new(SyncMutex::new(outcomes)),
2575            ..MockProvider::default()
2576        };
2577        let options = ResolverOpts::default();
2578        let config = NameServerConfig::udp(IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8)));
2579        let ns = Arc::new(NameServer::new([], config, &options, provider.clone()));
2580        let cx = Arc::new(PoolContext::new(options, TlsConfig::new().unwrap()));
2581        (ns, provider, cx)
2582    }
2583
2584    /// A reused pooled connection that the peer closed while idle should be
2585    /// transparently reconnected rather than surfacing the error to the caller.
2586    #[tokio::test]
2587    async fn reconnects_once_when_reused_connection_was_closed() {
2588        subscribe();
2589
2590        // Establish (ok), the reused send fails connection-closed, and the
2591        // post-reconnect send succeeds (empty queue falls through to success).
2592        let (ns, provider, cx) =
2593            name_server_with(VecDeque::from([None, Some(connection_closed())]));
2594
2595        ns.clone()
2596            .send(query(), ConnectionPolicy::default(), &cx)
2597            .await
2598            .expect("initial query establishes the connection");
2599        ns.clone()
2600            .send(query(), ConnectionPolicy::default(), &cx)
2601            .await
2602            .expect("stale reused connection is transparently reconnected");
2603
2604        // The initial connection plus the post-failure reconnect.
2605        assert_eq!(provider.new_connection_calls().len(), 2);
2606    }
2607
2608    /// A connection-closed error on a brand-new (non-reused) connection is a real
2609    /// failure, not a stale-pool artifact: it must propagate without a retry.
2610    #[tokio::test]
2611    async fn does_not_retry_when_a_fresh_connection_fails_closed() {
2612        subscribe();
2613
2614        let (ns, provider, cx) = name_server_with(VecDeque::from([Some(connection_closed())]));
2615
2616        ns.send(query(), ConnectionPolicy::default(), &cx)
2617            .await
2618            .expect_err("a fresh connection failure must not be retried");
2619
2620        assert_eq!(provider.new_connection_calls().len(), 1);
2621    }
2622}
2623
2624#[cfg(all(test, any(feature = "metrics", feature = "__tls")))]
2625mod mock_provider {
2626    use std::collections::VecDeque;
2627    use std::future::Future;
2628    use std::io;
2629    use std::pin::Pin;
2630    use std::task::{Context, Poll};
2631
2632    use futures_util::stream::once;
2633    use futures_util::{Stream, future};
2634    use tokio::net::UdpSocket;
2635
2636    use super::*;
2637    use crate::config::ProtocolConfig;
2638    use crate::net::runtime::TokioTime;
2639    use crate::net::runtime::iocompat::AsyncIoTokioAsStd;
2640    use crate::proto::op::Message;
2641    use crate::proto::rr::rdata::NULL;
2642    use crate::proto::rr::{RData, Record};
2643
2644    /// `MockProvider` is a `ConnectionProvider` that uses a synchronous runtime provider.
2645    ///
2646    /// It also tracks calls to `new_connection`, exposing the arguments provided as
2647    /// `new_connection_calls` for test to interrogate. The optional `new_connection_error`
2648    /// `ProtoError` can be set to have `new_connection()` return a future that will error
2649    /// when polled, mocking a connection failure.
2650    #[derive(Clone)]
2651    pub(super) struct MockProvider {
2652        pub(super) runtime: MockSyncRuntimeProvider,
2653        pub(super) new_connection_calls: Arc<SyncMutex<Vec<(IpAddr, ProtocolConfig)>>>,
2654        pub(super) new_connection_error: Option<NetError>,
2655        /// Per-send outcomes, consumed front-to-back across all connections this
2656        /// provider hands out: `Some(err)` fails that send, `None` (or an empty
2657        /// queue) succeeds.
2658        pub(super) send_outcomes: Arc<SyncMutex<VecDeque<Option<NetError>>>>,
2659    }
2660
2661    impl MockProvider {
2662        pub(super) fn new_connection_calls(&self) -> Vec<(IpAddr, ProtocolConfig)> {
2663            self.new_connection_calls.lock().clone()
2664        }
2665    }
2666
2667    impl ConnectionProvider for MockProvider {
2668        type Conn = MockClientHandle;
2669        type FutureConn = Pin<Box<dyn Send + Future<Output = Result<Self::Conn, NetError>>>>;
2670        type RuntimeProvider = MockSyncRuntimeProvider;
2671
2672        fn new_connection(
2673            &self,
2674            ip: IpAddr,
2675            config: &ConnectionConfig,
2676            _cx: &PoolContext,
2677        ) -> Result<Self::FutureConn, NetError> {
2678            self.new_connection_calls
2679                .lock()
2680                .push((ip, config.protocol.clone()));
2681
2682            Ok(Box::pin(future::ready(match &self.new_connection_error {
2683                Some(err) => Err(err.clone()),
2684                None => Ok(MockClientHandle {
2685                    send_outcomes: self.send_outcomes.clone(),
2686                }),
2687            })))
2688        }
2689
2690        fn runtime_provider(&self) -> &Self::RuntimeProvider {
2691            &self.runtime
2692        }
2693    }
2694
2695    impl Default for MockProvider {
2696        fn default() -> Self {
2697            Self {
2698                runtime: MockSyncRuntimeProvider,
2699                new_connection_calls: Arc::new(SyncMutex::new(Vec::new())),
2700                new_connection_error: None,
2701                send_outcomes: Arc::new(SyncMutex::new(VecDeque::new())),
2702            }
2703        }
2704    }
2705
2706    /// `MockClientHandle` is a `DnsHandle` that uses a synchronous runtime provider.
2707    ///
2708    /// Its `send` method replays the provider's scripted `send_outcomes`: a `Some(err)`
2709    /// entry fails that send, while `None` or an exhausted queue yields a `NoError` response.
2710    #[derive(Clone, Default)]
2711    pub(super) struct MockClientHandle {
2712        send_outcomes: Arc<SyncMutex<VecDeque<Option<NetError>>>>,
2713    }
2714
2715    impl DnsHandle for MockClientHandle {
2716        type Response = Pin<Box<dyn Stream<Item = Result<DnsResponse, NetError>> + Send>>;
2717        type Runtime = MockSyncRuntimeProvider;
2718
2719        fn send(&self, request: DnsRequest) -> Self::Response {
2720            if let Some(Some(err)) = self.send_outcomes.lock().pop_front() {
2721                return Box::pin(once(future::ready(Err(err))));
2722            }
2723            let mut response = Message::response(request.id, request.op_code);
2724            response.metadata.response_code = ResponseCode::NoError;
2725            response.add_queries(request.queries.clone());
2726            if let Some(query) = request.queries.first() {
2727                response.add_answer(Record::from_rdata(
2728                    query.name.clone(),
2729                    0,
2730                    RData::NULL(NULL::with(vec![0])),
2731                ));
2732            }
2733            Box::pin(once(future::ready(Ok(
2734                DnsResponse::from_message(response).unwrap()
2735            ))))
2736        }
2737    }
2738
2739    /// `MockSyncRuntimeProvider` is a `RuntimeProvider` that creates `MockSyncHandle` instances.
2740    ///
2741    /// Trait methods other than `create_handle` are not implemented.
2742    #[derive(Clone)]
2743    pub(super) struct MockSyncRuntimeProvider;
2744
2745    impl RuntimeProvider for MockSyncRuntimeProvider {
2746        type Handle = MockSyncHandle;
2747        type Timer = TokioTime;
2748        type Udp = UdpSocket;
2749        type Tcp = AsyncIoTokioAsStd<tokio::net::TcpStream>;
2750
2751        fn create_handle(&self) -> Self::Handle {
2752            MockSyncHandle
2753        }
2754
2755        #[allow(clippy::unimplemented)]
2756        fn connect_tcp(
2757            &self,
2758            _server_addr: std::net::SocketAddr,
2759            _bind_addr: Option<std::net::SocketAddr>,
2760            _timeout: Option<Duration>,
2761        ) -> Pin<Box<dyn Future<Output = Result<Self::Tcp, io::Error>> + Send>> {
2762            unimplemented!();
2763        }
2764
2765        #[allow(clippy::unimplemented)]
2766        fn bind_udp(
2767            &self,
2768            _local_addr: std::net::SocketAddr,
2769            _server_addr: std::net::SocketAddr,
2770        ) -> Pin<Box<dyn Future<Output = Result<Self::Udp, io::Error>> + Send>> {
2771            unimplemented!();
2772        }
2773    }
2774
2775    /// `MockSyncHandle` is a `Spawn` implementation that polls task futures synchronously.
2776    ///
2777    /// Provided futures will be polled until completion, allowing tests to avoid needing to
2778    /// coordinate with background tasks to determine their completion state.
2779    #[derive(Clone)]
2780    pub(super) struct MockSyncHandle;
2781
2782    impl Spawn for MockSyncHandle {
2783        fn spawn_bg(&mut self, future: impl Future<Output = ()> + Send + 'static) {
2784            // Instead of spawning the future as a background task, poll it synchronously
2785            // until completion.
2786            let waker = futures_util::task::noop_waker();
2787            let mut context = Context::from_waker(&waker);
2788            let mut future = Box::pin(future);
2789
2790            loop {
2791                match future.as_mut().poll(&mut context) {
2792                    Poll::Ready(_) => break,
2793                    Poll::Pending => continue,
2794                }
2795            }
2796        }
2797    }
2798}