torrentdht 0.1.1

DHT discovery with mTLS handshake handoff; optional BitTorrent when the host opts in
Documentation
//! Address-bound request/response correlation for UDP protocols.
//!
//! Pending replies are keyed by `(expected_peer, transaction_id)`. A datagram
//! from any other source — or with a guessed id — cannot complete a query.
//! Transaction ids must come from [`crate::net::random`], never a PRNG.
//!
//! The map is capacity- and TTL-bounded so forgotten cancel paths cannot grow
//! without limit. Expired waiters are notified with `Err` on the oneshot.

use std::collections::HashMap;
use std::hash::Hash;
use std::net::SocketAddr;
use std::time::{Duration, Instant};

use tokio::sync::oneshot;

use crate::error::{Error, Result};

/// Opaque transaction id bytes (DHT uses variable length; UDP tracker uses 4).
pub type TxId = Vec<u8>;

/// Default in-flight UDP query budget per socket owner.
pub const DEFAULT_PENDING_MAX: usize = 1024;

/// Default TTL for pending entries (must exceed typical query timeouts).
pub const DEFAULT_PENDING_TTL: Duration = Duration::from_secs(30);

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CorrelationKey {
    pub peer: SocketAddr,
    pub tx: TxId,
}

impl CorrelationKey {
    pub fn new(peer: SocketAddr, tx: impl Into<TxId>) -> Self {
        Self {
            peer,
            tx: tx.into(),
        }
    }
}

struct PendingEntry<T> {
    sender: oneshot::Sender<Result<T>>,
    inserted_at: Instant,
}

/// Map of in-flight UDP queries awaiting a reply from a specific peer.
pub struct PendingMap<T> {
    inner: HashMap<CorrelationKey, PendingEntry<T>>,
    max: usize,
    ttl: Duration,
}

impl<T> Default for PendingMap<T> {
    fn default() -> Self {
        Self::with_limits(DEFAULT_PENDING_MAX, DEFAULT_PENDING_TTL)
    }
}

impl<T> PendingMap<T> {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_limits(max: usize, ttl: Duration) -> Self {
        Self {
            inner: HashMap::new(),
            max: max.max(1),
            ttl,
        }
    }

    /// Insert a waiter. Returns an error when the map is at capacity after expiry.
    ///
    /// The oneshot delivers `Ok(T)` on complete or `Err` on TTL expiry.
    pub fn try_insert(
        &mut self,
        peer: SocketAddr,
        tx: TxId,
        sender: oneshot::Sender<Result<T>>,
    ) -> Result<()> {
        self.expire();
        if self.inner.len() >= self.max {
            return Err(Error::Dht(format!(
                "pending UDP queries at capacity ({})",
                self.max
            )));
        }
        let peer = crate::net::normalize_socket_addr(peer);
        self.inner.insert(
            CorrelationKey::new(peer, tx),
            PendingEntry {
                sender,
                inserted_at: Instant::now(),
            },
        );
        Ok(())
    }

    /// Complete a pending query only when both peer and tx match.
    pub fn complete(&mut self, peer: SocketAddr, tx: &[u8], value: T) -> bool {
        self.expire();
        let peer = crate::net::normalize_socket_addr(peer);
        let key = CorrelationKey::new(peer, tx.to_vec());
        if let Some(entry) = self.inner.remove(&key) {
            let _ = entry.sender.send(Ok(value));
            true
        } else {
            false
        }
    }

    pub fn cancel(&mut self, peer: SocketAddr, tx: &[u8]) {
        let peer = crate::net::normalize_socket_addr(peer);
        self.inner
            .remove(&CorrelationKey::new(peer, tx.to_vec()));
    }

    pub fn len(&self) -> usize {
        self.inner.len()
    }

    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    pub fn max(&self) -> usize {
        self.max
    }

    fn expire(&mut self) {
        let now = Instant::now();
        let before = std::mem::take(&mut self.inner);
        for (key, entry) in before {
            if now.duration_since(entry.inserted_at) < self.ttl {
                self.inner.insert(key, entry);
            } else {
                let _ = entry.sender.send(Err(Error::Dht(
                    "pending UDP query expired (TTL)".into(),
                )));
            }
        }
    }
}

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

    #[test]
    fn rejects_wrong_peer_or_tx() {
        let mut map = PendingMap::<u32>::new();
        let a: SocketAddr = SocketAddrV4::new(std::net::Ipv4Addr::LOCALHOST, 1).into();
        let b: SocketAddr = SocketAddrV4::new(std::net::Ipv4Addr::LOCALHOST, 2).into();
        let (tx, mut rx) = oneshot::channel();
        map.try_insert(a, b"ab".to_vec(), tx).expect("insert");
        assert!(!map.complete(b, b"ab", 1));
        assert!(!map.complete(a, b"xx", 1));
        assert!(map.complete(a, b"ab", 7));
        assert_eq!(rx.try_recv().expect("recv").expect("ok"), 7);
    }

    #[test]
    fn refuses_insert_at_capacity() {
        let mut map = PendingMap::<u32>::with_limits(1, Duration::from_secs(30));
        let a: SocketAddr = SocketAddrV4::new(std::net::Ipv4Addr::LOCALHOST, 1).into();
        let b: SocketAddr = SocketAddrV4::new(std::net::Ipv4Addr::LOCALHOST, 2).into();
        let (tx1, _rx1) = oneshot::channel();
        let (tx2, _rx2) = oneshot::channel();
        map.try_insert(a, b"a".to_vec(), tx1).expect("first");
        assert!(map.try_insert(b, b"b".to_vec(), tx2).is_err());
    }

    #[test]
    fn expire_notifies_waiter() {
        let mut map = PendingMap::<u32>::with_limits(4, Duration::from_millis(1));
        let a: SocketAddr = SocketAddrV4::new(std::net::Ipv4Addr::LOCALHOST, 1).into();
        let (tx, mut rx) = oneshot::channel();
        map.try_insert(a, b"ab".to_vec(), tx).expect("insert");
        std::thread::sleep(Duration::from_millis(5));
        // Next insert triggers expire and notifies the stale waiter.
        let (tx2, _rx2) = oneshot::channel();
        let _ = map.try_insert(a, b"cd".to_vec(), tx2);
        let err = rx.try_recv().expect("recv").expect_err("ttl");
        assert!(err.to_string().contains("expired"));
    }
}