pata 0.0.1

A fast, lightweight, and evidence-driven email validation library for Rust
Documentation
use std::{sync::Arc, time::Duration};

use moka::{Expiry, future::Cache};

use crate::dns::{Resolution, Resolve, ResolveError, Resolver};

pub(super) struct CachedResolver {
    inner: Arc<dyn Resolver>,
    entries: Cache<String, Resolution>,
    #[cfg(feature = "posture")]
    text_entries: Cache<String, crate::dns::TextRecords>,
}

impl CachedResolver {
    pub(super) fn new(resolver: impl Resolver + 'static) -> Self {
        Self {
            inner: Arc::new(resolver),
            entries: Cache::builder()
                .max_capacity(4_096)
                .expire_after(RouteExpiry)
                .build(),
            #[cfg(feature = "posture")]
            text_entries: Cache::builder()
                .max_capacity(4_096)
                .expire_after(TextExpiry)
                .build(),
        }
    }
}

impl Resolver for CachedResolver {
    fn resolve(&self, domain: &str) -> Resolve<'_> {
        let key = domain.to_owned();
        let lookup_key = key.clone();
        let inner = Arc::clone(&self.inner);
        Box::pin(async move {
            self.entries
                .try_get_with(key, async move { inner.resolve(&lookup_key).await })
                .await
                .map_err(|error: Arc<ResolveError>| (*error).clone())
        })
    }

    #[cfg(feature = "posture")]
    fn resolve_text(&self, domain: &str) -> crate::dns::ResolveText<'_> {
        let key = domain.to_owned();
        let lookup_key = key.clone();
        let inner = Arc::clone(&self.inner);
        Box::pin(async move {
            self.text_entries
                .try_get_with(key, async move { inner.resolve_text(&lookup_key).await })
                .await
                .map_err(|error: Arc<ResolveError>| (*error).clone())
        })
    }
}

struct RouteExpiry;

impl Expiry<String, Resolution> for RouteExpiry {
    fn expire_after_create(
        &self,
        _key: &String,
        value: &Resolution,
        _created_at: std::time::Instant,
    ) -> Option<Duration> {
        let fallback = match value.kind() {
            crate::dns::ResolutionKind::Mx | crate::dns::ResolutionKind::ImplicitMx => {
                Duration::from_secs(300)
            }
            crate::dns::ResolutionKind::NullMx
            | crate::dns::ResolutionKind::NxDomain
            | crate::dns::ResolutionKind::NoMailRoute => Duration::from_secs(60),
        };
        Some(
            value
                .valid_for()
                .unwrap_or(fallback)
                .min(Duration::from_secs(3_600)),
        )
    }
}

#[cfg(feature = "posture")]
struct TextExpiry;

#[cfg(feature = "posture")]
impl Expiry<String, crate::dns::TextRecords> for TextExpiry {
    fn expire_after_create(
        &self,
        _key: &String,
        value: &crate::dns::TextRecords,
        _created_at: std::time::Instant,
    ) -> Option<Duration> {
        Some(
            value
                .valid_for()
                .unwrap_or(Duration::from_secs(300))
                .min(Duration::from_secs(3_600)),
        )
    }
}

#[cfg(test)]
mod tests {
    use std::sync::atomic::{AtomicUsize, Ordering};

    use futures_executor::block_on;

    use super::*;
    use crate::dns::ResolutionKind;

    struct CountingResolver(Arc<AtomicUsize>);

    impl Resolver for CountingResolver {
        fn resolve(&self, _domain: &str) -> Resolve<'_> {
            let calls = Arc::clone(&self.0);
            Box::pin(async move {
                calls.fetch_add(1, Ordering::Relaxed);
                Ok(Resolution::new(
                    ResolutionKind::NullMx,
                    Vec::new(),
                    Some(Duration::from_secs(60)),
                ))
            })
        }
    }

    #[test]
    fn successful_domain_results_are_reused_without_address_keys() {
        let calls = Arc::new(AtomicUsize::new(0));
        let resolver = CachedResolver::new(CountingResolver(Arc::clone(&calls)));

        block_on(resolver.resolve("example.com")).unwrap();
        block_on(resolver.resolve("example.com")).unwrap();

        assert_eq!(calls.load(Ordering::Relaxed), 1);
    }

    #[test]
    fn authoritative_short_ttl_is_not_extended() {
        let resolution = Resolution::new(
            ResolutionKind::NullMx,
            Vec::new(),
            Some(Duration::from_secs(2)),
        );

        assert_eq!(
            RouteExpiry.expire_after_create(
                &"example.com".to_owned(),
                &resolution,
                std::time::Instant::now(),
            ),
            Some(Duration::from_secs(2))
        );
    }

    #[test]
    fn negative_results_without_a_ttl_use_a_short_fallback() {
        let resolution = Resolution::new(ResolutionKind::NxDomain, Vec::new(), None);

        assert_eq!(
            RouteExpiry.expire_after_create(
                &"example.com".to_owned(),
                &resolution,
                std::time::Instant::now(),
            ),
            Some(Duration::from_secs(60))
        );
    }
}