use std::io::ErrorKind;
use std::net::{Ipv4Addr, SocketAddr};
use std::sync::Mutex as StdMutex;
use std::time::Duration;
use tokio::net::UdpSocket;
use tokio::sync::{Mutex, MutexGuard};
use tokio::time::{Instant, sleep_until, timeout};
use crate::error::{Error, Result};
use crate::protocol::{Request, Response};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RetryPolicy {
pub attempts: u32,
pub attempt_timeout: Duration,
pub min_interval: Duration,
}
impl Default for RetryPolicy {
fn default() -> Self {
Self {
attempts: 3,
attempt_timeout: Duration::from_millis(500),
min_interval: Duration::from_millis(20),
}
}
}
pub(crate) struct Transport {
socket: UdpSocket,
exchange: Mutex<()>,
send: Mutex<()>,
pacer: Pacer,
}
impl Transport {
pub(crate) async fn bind() -> Result<Self> {
Ok(Self {
socket: UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).await?,
exchange: Mutex::new(()),
send: Mutex::new(()),
pacer: Pacer::default(),
})
}
pub(crate) fn local_addr(&self) -> Result<SocketAddr> {
Ok(self.socket.local_addr()?)
}
async fn send_slot(&self, min_interval: Duration) -> SendSlot<'_> {
let send = self.send.lock().await;
self.pacer.pace(min_interval).await;
SendSlot {
socket: &self.socket,
_exchange: None,
_send: send,
}
}
pub(crate) async fn stream_slot(&self, min_interval: Duration) -> SendSlot<'_> {
let exchange = self.exchange.lock().await;
let send = self.send.lock().await;
self.pacer.pace(min_interval).await;
SendSlot {
socket: &self.socket,
_exchange: Some(exchange),
_send: send,
}
}
pub(crate) async fn exchange(
&self,
addr: SocketAddr,
request: &Request,
policy: &RetryPolicy,
) -> Result<Response> {
let payload = serde_json::to_vec(request)?;
let attempts = policy.attempts.max(1);
let started = Instant::now();
let _guard = self.exchange.lock().await;
self.discard_backlog();
for _ in 0..attempts {
let slot = self.send_slot(policy.min_interval).await;
match slot.send(addr, &payload).await {
Ok(()) => {}
Err(e) if e.kind() == ErrorKind::ConnectionReset => continue,
Err(e) => return Err(e.into()),
}
match timeout(policy.attempt_timeout, self.receive(addr, &request.method)).await {
Ok(reply) => return reply,
Err(_elapsed) => continue,
}
}
Err(Error::Timeout {
method: request.method.clone(),
addr,
attempts,
elapsed: started.elapsed(),
})
}
async fn receive(&self, addr: SocketAddr, method: &str) -> Result<Response> {
let mut buf = vec![0u8; 4096];
loop {
let (n, from) = match self.socket.recv_from(&mut buf).await {
Ok(datagram) => datagram,
Err(e) if e.kind() == ErrorKind::ConnectionReset => continue,
Err(e) => return Err(e.into()),
};
if from != addr {
continue;
}
let response: Response = serde_json::from_slice(&buf[..n])?;
if response.method.as_deref().is_some_and(|m| m != method) {
continue;
}
return match response.error {
Some(error) => Err(Error::from_device(method, error)),
None => Ok(response),
};
}
}
fn discard_backlog(&self) {
let mut buf = [0u8; 4096];
while self.socket.try_recv_from(&mut buf).is_ok() {}
}
}
pub(crate) struct SendSlot<'a> {
socket: &'a UdpSocket,
_exchange: Option<MutexGuard<'a, ()>>,
_send: MutexGuard<'a, ()>,
}
impl SendSlot<'_> {
pub(crate) async fn send(self, addr: SocketAddr, payload: &[u8]) -> std::io::Result<()> {
self.socket.send_to(payload, addr).await?;
Ok(())
}
}
#[derive(Default)]
struct Pacer {
next: StdMutex<Option<Instant>>,
}
impl Pacer {
async fn pace(&self, min_interval: Duration) {
let now = Instant::now();
let wait_until = {
let mut next = self.next.lock().expect("pacer mutex poisoned");
let slot = next.filter(|at| *at > now);
*next = Some(slot.unwrap_or(now) + min_interval);
slot
};
if let Some(at) = wait_until {
sleep_until(at).await;
}
}
}