Files
MeshPort/crates/meshport/src/quality.rs
T

60 lines
2.3 KiB
Rust

use crate::{Network, UdpSocket};
use anyhow::Result;
use std::{
net::SocketAddr,
time::{Duration, Instant},
};
impl Network {
/// Samples a reusable UDP echo socket. Ignores late/foreign replies.
pub async fn sample_udp_quality(
&self,
socket: &UdpSocket,
target: SocketAddr,
sequence: u64,
timeout: Duration,
) -> Result<serde_json::Value> {
let before = self.snapshot().await;
let destination = before["routes"]
.as_array()
.and_then(|routes| {
routes.iter().find(|r| {
r["ipv4"].as_str().is_some_and(|ip| {
ip.split('/').next() == Some(target.ip().to_string().as_str())
})
})
})
.cloned();
let payload = format!("MeshPort quality v1 {sequence}").into_bytes();
let started = Instant::now();
let result = tokio::time::timeout(timeout, async {
socket.send_to(&payload, target).await?;
let mut bytes = [0; 2048];
loop {
let (n, source) = socket.recv_from(&mut bytes).await?;
if source == target && bytes[..n] == payload {
return Ok::<_, anyhow::Error>(());
}
}
})
.await;
let success = matches!(result, Ok(Ok(())));
let elapsed_ms = success.then(|| started.elapsed().as_secs_f64() * 1000.0);
let after = self.snapshot().await;
let peer_id = destination.as_ref().and_then(|d| d["peer_id"].as_u64());
let after_hop = after["routes"]
.as_array()
.and_then(|rows| rows.iter().find(|r| r["peer_id"].as_u64() == peer_id))
.and_then(|r| r["next_hop_peer_id"].as_u64());
let before_hop = destination
.as_ref()
.and_then(|d| d["next_hop_peer_id"].as_u64());
Ok(serde_json::json!({"success": success, "sequence": sequence,
"elapsed_ms": elapsed_ms,
"next_hop_peer_id": before_hop,
"next_hop_after": after_hop, "route_changed": before_hop != after_hop,
"target_peer_id": destination.as_ref().and_then(|d| d["peer_id"].as_u64()),
"kind": "udp_echo_roundtrip", "error": if success {None} else {Some("timeout_or_io_error")}
}))
}
}