Measure live peer throughput on the encrypted mesh path

Advertise an optional versioned diagnostic to authenticated peers. A small
control exchange negotiates limits and carries receiver feedback. Paced
IPv4 probes enter the ordinary WireGuard tunnel and follow its current
carrier or relay. Accept them only for an active session and the peer's
actual signed address pair. Agents without the capability still exchange
normal mesh traffic.

Raise the offered rate using receiver-clock windows and unique payload
bytes. Require sustained delivery before reporting a rate, distinguish a
lower bound from a measured ceiling, and discard interrupted live values.
An agent runs one exchange at a time, with a five-second deadline and a
cap at both ends. Queued exit tests share a separate batch budget. Keep
bounded per-network results in memory and cancel on session replacement,
network removal or a change to a metered underlay.

Add a fixed speed cell to desktop and Android device views. Show direction
and live rate, let a click on the result rerun the test, and offer a
stoppable sequential test of compatible exit nodes. Expose local actions
and progress over IPC v27. Mesh identity and stored state are unchanged.

On macOS arm64 the real WireGuard test covered both directions, a
control-only peer, the responder's metered limit and stopping a repeat.
The three-peer exit batch test passed. The diagnostic crate passed 17
tests including shaped throughput, loss, delay, duplication and bursts.
All 33 shared UI tests passed. Strict Clippy passed for the diagnostic
and core libraries and an ARM64 Android debug APK was built.
This commit is contained in:
Aleksandr Bogomiakov committed 2026-11-25 19:25:58 +02:00
1 parent fb7a959d23
commit 200e716c28
34 files changed
+3658 -88

No files matched your search

+1
View File
@@ -35,6 +35,7 @@ dns-publish = ["dep:zbus"]
testing = ["dep:tempfile", "dep:tracing-subscriber"]
[dependencies]
tsunagi-speedtest = { path = "../tsunagi-speedtest", version = "0.1.0" }
arc-swap = "1.9"
iroh.workspace = true
# `net` for the local control interface: a Unix socket on Unix, a named pipe
+10
View File
@@ -22,6 +22,7 @@ mod events;
mod network;
mod session;
mod shutdown;
mod speed;
mod status;
pub use events::Event;
@@ -95,6 +96,7 @@ pub struct Agent {
#[derive(Debug)]
struct Inner {
config: AgentConfig,
speed: speed::SpeedTests,
limits: Arc<Limits>,
storage: Storage,
identity: DeviceIdentity,
@@ -220,6 +222,9 @@ impl PacketSink for Sink {
let Some(inner) = self.0.upgrade() else {
return;
};
if speed::receive_packet(&inner, network, peer, &packet) {
return;
}
let Some(interface) = inner.interface.get() else {
return;
};
@@ -444,6 +449,7 @@ impl Agent {
let (range_changed, range_updates) = watch::channel(());
let inner = Arc::new(Inner {
speed: speed::SpeedTests::default(),
limits,
storage,
identity,
@@ -1007,6 +1013,7 @@ impl Agent {
self.inner.ensure_interface().await;
}
let handle = network::spawn(RuntimeParams {
agent: Arc::downgrade(&self.inner),
vips,
retirements,
broadcast,
@@ -1080,6 +1087,7 @@ impl Agent {
}
async fn stop_network_locked(&self, network_id: NetworkId) -> Result<()> {
self.inner.speed.remove_network(network_id);
let handle = {
let mut networks = self.inner.networks.write().await;
networks
@@ -1316,6 +1324,7 @@ impl Agent {
})
.collect();
networks.push(NetworkStatus {
speed: Default::default(),
vips,
protocols: self.effective_protocols(stored.protocols.as_ref()),
auto_start: stored.auto_start,
@@ -1395,6 +1404,7 @@ impl Agent {
/// After this returns, the state directory can be opened by another agent.
pub async fn shutdown(&self) {
self.inner.shutdown.trigger();
self.inner.speed.shutdown();
let lifecycle_guard = self.inner.lifecycle.lock().await;
let handles: Vec<NetworkHandle> = {
+46 -2
View File
@@ -177,6 +177,7 @@ impl NetworkHandle {
/// Everything a network runtime needs to run.
pub(crate) struct RuntimeParams {
pub(super) agent: std::sync::Weak<super::Inner>,
pub(crate) vips: crate::vip::VipSet,
pub(crate) retirements: Vec<SignedRetirement>,
pub(crate) broadcast: bool,
@@ -656,7 +657,7 @@ impl Runtime {
message,
reply,
} => {
if matches!(&message, ControlMessage::Transport { .. })
if matches!(&message, ControlMessage::Transport { protocol, .. } if protocol != tsunagi_speedtest::PROTOCOL)
&& let Some(interface) = self.params.interface.clone()
{
// Locally bound pair sockets must be protected before their
@@ -2691,6 +2692,9 @@ impl Runtime {
return;
}
if let Some(old) = self.sessions.remove(&peer) {
if let Some(inner) = self.params.agent.upgrade() {
inner.speed.disconnected(self.network_id, peer);
}
old.abort();
old.conn
.close(0u32.into(), b"replaced by preferred session");
@@ -2779,6 +2783,12 @@ impl Runtime {
if self.params.carriers.len() > 1 {
capabilities.push(selection::capability());
}
if self.params.interface.is_some()
&& self.params.tunnel.is_some()
&& !self.params.carriers.is_empty()
{
capabilities.push(super::speed::capability());
}
capabilities.truncate(self.params.limits.max_capabilities);
self.local_capabilities = capabilities
.iter()
@@ -2861,6 +2871,9 @@ impl Runtime {
if current != Some(session_id) {
return;
}
if let Some(inner) = self.params.agent.upgrade() {
inner.speed.disconnected(self.network_id, peer);
}
if let Some(session) = self.sessions.remove(&peer) {
// Read the cause before local cleanup closes a still-open connection.
if let Some(cause) = session.conn.close_reason() {
@@ -2934,6 +2947,25 @@ impl Runtime {
fn dispatch_message(&mut self, peer: EndpointId, message: ControlMessage) {
match &message {
ControlMessage::Transport { protocol, payload } => {
if protocol == tsunagi_speedtest::PROTOCOL {
if super::speed::supported(&self.local_capabilities)
&& let Some(session) = self.sessions.get(&peer)
&& super::speed::supported(&session.capabilities)
&& let Some(message) =
tsunagi_speedtest::Control::decode(payload.as_bytes())
&& let Some(inner) = self.params.agent.upgrade()
&& let Some(reply) = super::speed::receive_control(
&inner,
self.network_id,
peer,
message,
|| snapshot_connection(&session.conn).rtt,
)
{
let _ = self.send_to(peer, reply);
}
return;
}
if protocol == selection::PROTOCOL {
self.receive_choice(peer, payload.as_bytes());
return;
@@ -2986,7 +3018,7 @@ impl Runtime {
let changed = self.sessions.get(&peer).is_some_and(|session| {
let selection = |caps: &[PluginCapability]| {
caps.iter()
.filter(|c| c.enabled)
.filter(|c| c.enabled && c.protocol != tsunagi_speedtest::PROTOCOL)
.map(|c| (c.protocol.clone(), c.version))
.collect::<Vec<_>>()
};
@@ -3347,6 +3379,18 @@ impl Runtime {
let exit = self.exit_policy();
NetworkStatus {
speed: self
.params
.agent
.upgrade()
.map(|inner| {
inner.speed.report(
self.network_id,
&peers,
super::speed::supported(&self.local_capabilities),
)
})
.unwrap_or_default(),
vips: self.params.routes.vips.statuses(self.network_id),
protocols: self
.params
+582
View File
@@ -0,0 +1,582 @@
//! Local ownership of one bounded throughput diagnostic. Control carries
//! negotiation and receiver feedback. Every data packet uses the current cipher and carrier.
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, Weak};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use arc_swap::ArcSwapOption;
use bytes::Bytes;
use iroh::EndpointId;
use tsunagi_speedtest as wire;
use super::{Agent, DataPath, Inner, PeerStatus};
use crate::dataplane::PluginCapability;
use crate::error::{Error, Result};
use crate::identity::NetworkId;
use crate::ipc::{SpeedBatchReport, SpeedPeerReport, SpeedPhase, SpeedRate, SpeedReport};
use crate::proto::message::{ControlMessage, TransportPayload};
type Key = (NetworkId, EndpointId);
/// A batch can spend at most this many IPv4 bytes in *each* direction.
/// Every remaining peer gets an equal reservation even when earlier probes are lost.
const BATCH_BYTES: u32 = 128 * 1024 * 1024;
const METERED_BATCH_BYTES: u32 = 16 * 1024 * 1024;
pub(super) fn capability() -> PluginCapability {
PluginCapability {
protocol: wire::PROTOCOL.into(),
version: wire::VERSION,
enabled: true,
data: Vec::new(),
}
}
pub(super) fn supported(caps: &[PluginCapability]) -> bool {
caps.iter()
.any(|c| c.enabled && c.protocol == wire::PROTOCOL && c.version == wire::VERSION)
}
fn envelope(message: &wire::Control) -> Option<ControlMessage> {
Some(ControlMessage::Transport {
protocol: wire::PROTOCOL.into(),
payload: TransportPayload::new(message.encode().ok()?),
})
}
fn now() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
}
struct Channel {
key: Key,
id: u64,
limit: u32,
handle: wire::Handle,
}
struct Job {
generation: u64,
network: NetworkId,
batch: Option<SpeedBatchReport>,
}
#[derive(Default)]
struct Jobs {
job: Option<Job>,
history: BTreeMap<Key, SpeedPeerReport>,
}
#[derive(Default)]
pub(super) struct SpeedTests {
// Admission, completion and cancellation serialize here. Decrypted packets
// only read the active channel and its receiver counter.
jobs: Mutex<Jobs>,
active: ArcSwapOption<Channel>,
metered: AtomicBool,
}
impl std::fmt::Debug for SpeedTests {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SpeedTests").finish_non_exhaustive()
}
}
impl SpeedTests {
fn lock(&self) -> MutexGuard<'_, Jobs> {
self.jobs.lock().unwrap_or_else(|e| e.into_inner())
}
fn clear_channel(&self, key: Key, id: u64) {
// Called with the jobs lock held so an old task cannot clear its successor.
if self
.active
.load()
.as_ref()
.is_some_and(|c| c.key == key && c.id == id)
{
self.active.store(None);
}
}
pub(super) fn report(
&self,
network: NetworkId,
peers: &[PeerStatus],
enabled: bool,
) -> SpeedReport {
let jobs = self.lock();
SpeedReport {
batch: jobs
.job
.as_ref()
.filter(|j| j.network == network)
.and_then(|j| j.batch),
peers: jobs
.history
.iter()
.filter(|((net, _), _)| *net == network)
.map(|((_, peer), report)| (peer.to_string(), report.clone()))
.collect(),
capable: peers
.iter()
.filter(|p| enabled && supported(&p.capabilities))
.map(|p| p.endpoint_id.to_string())
.collect(),
}
}
pub(super) fn disconnected(&self, network: NetworkId, peer: EndpointId) {
if let Some(c) = self
.active
.load()
.as_ref()
.filter(|c| c.key == (network, peer))
{
c.handle.cancel();
}
}
fn cancel_locked(&self, jobs: &mut Jobs, network: NetworkId) {
if let Some(c) = self.active.load().as_ref().filter(|c| c.key.0 == network) {
c.handle.cancel();
}
if jobs.job.as_ref().is_some_and(|job| job.network == network) {
jobs.job = None;
for ((net, _), report) in &mut jobs.history {
if *net == network
&& matches!(
report.phase,
SpeedPhase::Queued
| SpeedPhase::Preparing
| SpeedPhase::Download
| SpeedPhase::Upload
)
{
match report.phase {
SpeedPhase::Download => report.down = None,
SpeedPhase::Upload => report.up = None,
_ => {}
}
report.phase = SpeedPhase::Cancelled;
report.measured_at_unix_secs = now();
}
}
}
}
pub(super) fn remove_network(&self, network: NetworkId) {
let mut jobs = self.lock();
self.cancel_locked(&mut jobs, network);
jobs.history.retain(|(net, _), _| *net != network);
}
pub(super) fn shutdown(&self) {
let mut jobs = self.lock();
jobs.job = None;
if let Some(channel) = self.active.swap(None) {
channel.handle.cancel();
}
}
}
/// Recognized probe frames never go to a host socket. Admission is stricter
/// than exit traffic: both addresses must be the current signed overlay pair.
pub(super) fn receive_packet(
inner: &Inner,
network: NetworkId,
peer: EndpointId,
packet: &[u8],
) -> bool {
if !wire::is_test_packet(packet) {
return false;
}
if let Some(channel) = inner.speed.active.load().as_ref()
&& channel.key == (network, peer)
&& let Some(data) = wire::decode_packet(packet)
&& data.id == channel.id
&& inner.routes.peer_addresses(network, peer) == Some((data.destination, data.source))
{
channel.handle.data(data);
}
true
}
fn config(
inner: &Inner,
key: Key,
id: u64,
bytes: u32,
rtt: Option<Duration>,
) -> Option<wire::Config> {
let (local, remote) = inner.routes.peer_addresses(key.0, key.1)?;
let ceiling = if inner.speed.metered.load(Ordering::Relaxed) {
wire::METERED_BYTES
} else {
wire::NORMAL_BYTES
};
Some(wire::Config {
id,
local,
remote,
mtu: u16::try_from(inner.config.interface_mtu).unwrap_or(u16::MAX),
byte_limit: bytes.min(ceiling),
rtt: rtt.unwrap_or(Duration::from_millis(100)),
})
}
pub(super) fn receive_control(
inner: &Arc<Inner>,
network: NetworkId,
peer: EndpointId,
message: wire::Control,
rtt: impl FnOnce() -> Option<Duration>,
) -> Option<ControlMessage> {
let key = (network, peer);
let id = message.id();
if let wire::Control::Start(request) = message {
let jobs = inner.speed.lock();
if inner.shutdown.is_triggered()
|| jobs.job.is_some()
|| inner.speed.active.load().is_some()
{
return envelope(&wire::Control::Busy { id });
}
let cfg = config(inner, key, id, request.byte_limit, rtt())?;
let limit = cfg.byte_limit;
let (handle, session) = wire::respond(cfg, request);
inner.speed.active.store(Some(Arc::new(Channel {
key,
id,
limit,
handle,
})));
drop(jobs);
let io = TestIo::new(inner, key, None);
tokio::spawn(async move {
let owner = io.inner.clone();
session.run(io).await;
if let Some(inner) = owner.upgrade() {
let _guard = inner.speed.lock();
inner.speed.clear_channel(key, id);
}
});
} else if let Some(c) = inner
.speed
.active
.load()
.as_ref()
.filter(|c| c.key == key && c.id == id)
{
c.handle.control(message);
}
None
}
struct TestIo {
inner: Weak<Inner>,
key: Key,
generation: Option<u64>,
started: Instant,
}
impl TestIo {
fn new(inner: &Arc<Inner>, key: Key, generation: Option<u64>) -> Self {
Self {
inner: Arc::downgrade(inner),
key,
generation,
started: Instant::now(),
}
}
}
impl wire::Io for TestIo {
async fn control(&self, message: wire::Control) -> bool {
let (Some(inner), Some(message)) = (self.inner.upgrade(), envelope(&message)) else {
return false;
};
Agent { inner }
.send(self.key.0, self.key.1, message)
.await
.is_ok()
}
fn packet(&self, packet: Bytes) -> bool {
self.inner.upgrade().is_some_and(|inner| {
inner
.config
.tunnel
.as_ref()
.is_some_and(|t| t.carry(self.key.0, self.key.1, packet))
})
}
fn progress(&self, update: wire::Progress) {
if !matches!(
update.state,
wire::State::Starting | wire::State::Download | wire::State::Upload
) {
return; // Publish terminal results together with releasing the slot.
}
if let Some(generation) = self.generation
&& let Some(inner) = self.inner.upgrade()
{
let mut jobs = inner.speed.lock();
if jobs
.job
.as_ref()
.is_some_and(|j| j.generation == generation)
&& let Some(report) = jobs.history.get_mut(&self.key)
{
update_report(report, update, self.started);
}
}
}
}
fn update_report(report: &mut SpeedPeerReport, progress: wire::Progress, started: Instant) {
let live = matches!(progress.state, wire::State::Download | wire::State::Upload);
let rate = |reading: wire::Reading| {
reading
.bps
.filter(|_| match reading.quality {
wire::Quality::Measured | wire::Quality::AtLeast => true,
wire::Quality::Measuring => live,
wire::Quality::Insufficient => false,
})
.map(|bps| SpeedRate {
bps,
lower_bound: reading.quality == wire::Quality::AtLeast,
})
};
report.down = rate(progress.down);
report.up = rate(progress.up);
report.bytes = u64::from(progress.down.bytes) + u64::from(progress.up.bytes);
report.elapsed_ms = u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX);
report.measured_at_unix_secs = now();
report.phase = match progress.state {
wire::State::Starting => SpeedPhase::Preparing,
wire::State::Download => SpeedPhase::Download,
wire::State::Upload => SpeedPhase::Upload,
wire::State::Complete if report.down.is_some() || report.up.is_some() => SpeedPhase::Done,
wire::State::Complete => SpeedPhase::Failed("Insufficient data for a reliable rate".into()),
wire::State::Busy => SpeedPhase::Failed("Peer is already running a speed test".into()),
wire::State::TimedOut => {
SpeedPhase::Failed("Peer did not finish the speed test in time".into())
}
wire::State::Cancelled => SpeedPhase::Cancelled,
wire::State::Failed => {
SpeedPhase::Failed("The data path could not complete the speed test".into())
}
};
}
fn describe_path(peer: &PeerStatus) -> Option<String> {
match &peer.data_path {
DataPath::None => None,
DataPath::Direct { transport } => Some(match &peer.data_transport_detail {
Some(detail) => format!("{transport} · {detail}"),
None => transport.clone(),
}),
DataPath::Relayed { hops, via } => Some(format!("{hops} hops via {}", via.fmt_short())),
}
}
impl Agent {
/// Runs one peer diagnostic, or sequentially tests the capable exit nodes in the network.
pub async fn start_speed_test(
&self,
network: NetworkId,
peer: Option<EndpointId>,
metered: bool,
) -> Result<()> {
let status = self.network_status(network).await?;
let targets: Vec<_> = status
.peers
.iter()
.filter(|p| {
peer.map_or(p.exit_node, |selected| p.endpoint_id == selected)
&& status.speed.capable.contains(&p.endpoint_id.to_string())
})
.map(|p| p.endpoint_id)
.collect();
if targets.is_empty() {
return Err(Error::SpeedTest(
if peer.is_some() {
"Peer is offline or does not support this speed-test version"
} else {
"No online exit nodes support speed tests in this network"
}
.into(),
));
}
let cap = self.inner.limits.max_speed_results;
if targets.len() > cap {
return Err(Error::SpeedTest("Too many peers for one test batch".into()));
}
let generation = rand::random();
let mut jobs = self.inner.speed.lock();
if self.inner.shutdown.is_triggered() {
return Err(Error::Stopped);
}
if jobs.job.is_some() || self.inner.speed.active.load().is_some() {
return Err(Error::SpeedTest(
"Another speed test is already running".into(),
));
}
// Make room before inserting the queue, preserving results of other networks when possible.
for target in &targets {
jobs.history.remove(&(network, *target));
}
while jobs.history.len() + targets.len() > cap {
let Some(oldest) = jobs
.history
.iter()
.min_by_key(|(_, r)| r.measured_at_unix_secs)
.map(|(k, _)| *k)
else {
break;
};
jobs.history.remove(&oldest);
}
let count = targets.len() as u32;
jobs.job = Some(Job {
generation,
network,
batch: peer.is_none().then_some(SpeedBatchReport {
done: 0,
total: count,
}),
});
for target in &targets {
jobs.history.insert(
(network, *target),
SpeedPeerReport {
measured_at_unix_secs: now(),
..Default::default()
},
);
}
let owner = Arc::downgrade(&self.inner);
let metered = metered || self.inner.speed.metered.load(Ordering::Relaxed);
let per_peer = if metered {
wire::METERED_BYTES
} else {
wire::NORMAL_BYTES
};
let limit = if peer.is_none() {
per_peer.min(
if metered {
METERED_BATCH_BYTES
} else {
BATCH_BYTES
} / count,
)
} else {
per_peer
};
tokio::spawn(async move {
for (index, target) in targets.into_iter().enumerate() {
let key = (network, target);
let Some(inner) = owner.upgrade() else {
return;
};
let result = run_outgoing(&inner, key, generation, limit, peer.is_none()).await;
let mut jobs = inner.speed.lock();
if let Some((id, _, _)) = &result {
inner.speed.clear_channel(key, *id);
}
if jobs.job.as_ref().is_none_or(|j| j.generation != generation) {
return;
}
if let Some(report) = jobs.history.get_mut(&key) {
match result {
Some((_, update, started)) => update_report(report, update, started),
None => {
report.phase = SpeedPhase::Failed(
"Peer is no longer eligible or its overlay address is unavailable"
.into(),
)
}
}
}
if index + 1 == count as usize {
jobs.job = None;
} else if let Some(batch) = jobs.job.as_mut().and_then(|j| j.batch.as_mut()) {
batch.done += 1;
}
}
});
Ok(())
}
/// Cancels the current test and any queued peers in this network.
pub fn stop_speed_test(&self, network: NetworkId) {
let mut jobs = self.inner.speed.lock();
self.inner.speed.cancel_locked(&mut jobs, network);
}
/// Applies the host's actual metered-link policy to incoming and outgoing measurements.
pub fn set_speed_test_metered(&self, metered: bool) {
if self.inner.speed.metered.swap(metered, Ordering::Relaxed) || !metered {
return;
}
let mut jobs = self.inner.speed.lock();
if let Some(network) = jobs.job.as_ref().map(|j| j.network) {
self.inner.speed.cancel_locked(&mut jobs, network);
} else if let Some(c) = self
.inner
.speed
.active
.load()
.as_ref()
.filter(|c| c.limit > wire::METERED_BYTES)
{
c.handle.cancel();
}
}
}
async fn run_outgoing(
inner: &Arc<Inner>,
key: Key,
generation: u64,
limit: u32,
exits_only: bool,
) -> Option<(u64, wire::Progress, Instant)> {
let agent = Agent {
inner: Arc::clone(inner),
};
let status = agent.network_status(key.0).await.ok()?;
let peer = status.peers.iter().find(|p| {
p.endpoint_id == key.1 && (!exits_only || p.exit_node) && supported(&p.capabilities)
})?;
let id = rand::random();
let cfg = config(inner, key, id, limit, peer.data_rtt.or(peer.rtt))?;
let limit = cfg.byte_limit;
let (handle, session) = wire::initiate(cfg);
let io = TestIo::new(inner, key, Some(generation));
{
let mut jobs = inner.speed.lock();
if jobs.job.as_ref().is_none_or(|j| j.generation != generation) {
return None;
}
let report = jobs.history.get_mut(&key)?;
report.phase = SpeedPhase::Preparing;
report.path = describe_path(peer);
inner.speed.active.store(Some(Arc::new(Channel {
key,
id,
limit,
handle,
})));
}
let started = io.started;
let update = session.run(io).await;
Some((id, update, started))
}
+2
View File
@@ -240,6 +240,8 @@ pub struct RangeConflict {
/// Status of one network.
#[derive(Debug, Clone)]
pub struct NetworkStatus {
/// Available mesh throughput tests, with local progress and results.
pub speed: crate::ipc::SpeedReport,
/// Shared service configuration with this client's routing observations.
pub vips: Vec<crate::vip::VipStatus>,
/// Enabled local data-plane protocols, in preference order.
+3
View File
@@ -211,6 +211,8 @@ pub struct Limits {
pub max_discovery_candidates: usize,
/// Maximum simultaneous authenticated sessions per network.
pub max_sessions_per_network: usize,
/// Maximum per-peer speed results or queued tests retained by the agent.
pub max_speed_results: usize,
/// Maximum simultaneous inbound connections being handshaken.
pub max_inbound_handshakes: usize,
/// Capacity of a session's outbound queue, providing backpressure.
@@ -247,6 +249,7 @@ impl Default for Limits {
max_concurrent_dials: 8,
max_discovery_candidates: 16,
max_sessions_per_network: 64,
max_speed_results: 256,
max_inbound_handshakes: 32,
session_send_queue: 64,
event_buffer: 512,
+3
View File
@@ -15,6 +15,9 @@ pub type Result<T, E = Error> = std::result::Result<T, E>;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
/// A requested mesh throughput test cannot run.
#[error("{0}")]
SpeedTest(String),
/// A node-history cleanup is unsafe, stale or cannot be performed.
#[error("cannot forget node: {0}")]
ForgetNode(String),
+99 -1
View File
@@ -25,6 +25,9 @@
//! rather than the crate's internal structures, so internal refactors do not
//! silently change what a client sees.
mod speed;
pub use speed::{SpeedBatchReport, SpeedPeerReport, SpeedPhase, SpeedRate, SpeedReport};
#[cfg(unix)]
pub mod unix;
#[cfg(windows)]
@@ -277,6 +280,20 @@ pub enum Request {
/// The member's endpoint id, or `None` to stop using an exit node.
peer: Option<String>,
},
/// Begin a peer test or a sequential batch of advertised exits.
StartSpeedTest {
/// Active network identifier.
network_id: String,
/// One peer, or all online exits when absent.
peer: Option<String>,
/// Apply the smaller metered-link byte budget.
metered: bool,
},
/// Cancel the active local test or batch in this network.
StopSpeedTest {
/// Active network identifier.
network_id: String,
},
}
impl std::fmt::Debug for Request {
@@ -300,6 +317,15 @@ impl std::fmt::Debug for Request {
f,
"SetProtocols {{ {network_id}, protocols: {protocols:?} }}"
),
Request::StartSpeedTest {
network_id,
peer,
metered,
} => write!(
f,
"StartSpeedTest {{ {network_id}, peer: {peer:?}, metered: {metered} }}"
),
Request::StopSpeedTest { network_id } => write!(f, "StopSpeedTest({network_id})"),
Request::Status => f.write_str("Status"),
Request::SetBroadcast {
network_id,
@@ -331,6 +357,8 @@ impl std::fmt::Debug for Request {
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum Response {
/// A speed-test action was accepted.
SpeedTestAccepted,
/// Accepted configuration with fresh local routing observations.
Vips(Vec<crate::vip::VipStatus>),
/// An observed offline claim was durably retired.
@@ -711,6 +739,9 @@ pub struct ProtocolReport {
/// One network.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct NetworkReport {
/// Current capabilities and results of peer speed tests.
#[serde(default)]
pub speed: SpeedReport,
/// Shared VIPs and this client's routing observations.
#[serde(default)]
pub vips: Vec<crate::vip::VipStatus>,
@@ -1063,6 +1094,24 @@ pub trait ReportSource: Send + Sync + 'static {
Box::pin(async move { Err("this agent cannot change broadcast participation".into()) })
}
/// Queues a diagnostic against one peer, or all current exit peers.
fn start_speed_test(
&self,
_network_id: String,
_peer: Option<String>,
_metered: bool,
) -> BoxFuture<'_, std::result::Result<(), String>> {
Box::pin(async { Err("this agent cannot test peer speeds".into()) })
}
/// Cancels an individual test and any remaining batch members.
fn stop_speed_test(
&self,
_network_id: String,
) -> BoxFuture<'_, std::result::Result<(), String>> {
Box::pin(async { Err("this agent cannot stop speed tests".into()) })
}
/// Stops serving a network, or starts serving it again.
///
/// Defaulted to a refusal, like the others.
@@ -1147,7 +1196,7 @@ pub const EXCHANGE_TIMEOUT: Duration = Duration::from_secs(5);
///
/// Bump it whenever [`Request`], [`Response`] or anything they contain
/// changes shape.
pub const CONTROL_PROTOCOL: u32 = u32::from_be_bytes([b'T', b'S', b'N', 26]);
pub const CONTROL_PROTOCOL: u32 = u32::from_be_bytes([b'T', b'S', b'N', 27]);
/// Reads one request off an accepted stream, answers it, writes the response.
///
@@ -1233,6 +1282,18 @@ where
Ok(secret) => Response::Secret(RedactedText::new(secret)),
Err(reason) => Response::Error(reason),
},
Request::StartSpeedTest {
network_id,
peer,
metered,
} => match source.start_speed_test(network_id, peer, metered).await {
Ok(()) => Response::SpeedTestAccepted,
Err(reason) => Response::Error(reason),
},
Request::StopSpeedTest { network_id } => match source.stop_speed_test(network_id).await {
Ok(()) => Response::SpeedTestAccepted,
Err(reason) => Response::Error(reason),
},
Request::SetExitOffer {
network_id,
enabled,
@@ -1452,6 +1513,43 @@ pub async fn set_exit_node(
}
}
/// Measures the mesh data path to one peer, or queues the network's online exit nodes.
pub async fn start_speed_test(
path: impl AsRef<Path>,
network_id: &str,
peer: Option<&str>,
metered: bool,
) -> Result<()> {
speed_request(
path.as_ref(),
Request::StartSpeedTest {
network_id: network_id.to_owned(),
peer: peer.map(str::to_owned),
metered,
},
)
.await
}
/// Stops the current local speed test and clears its remaining queue.
pub async fn stop_speed_test(path: impl AsRef<Path>, network_id: &str) -> Result<()> {
speed_request(
path.as_ref(),
Request::StopSpeedTest {
network_id: network_id.to_owned(),
},
)
.await
}
async fn speed_request(path: &Path, request: Request) -> Result<()> {
match exchange(path, &request, EXCHANGE_TIMEOUT).await? {
Response::SpeedTestAccepted => Ok(()),
Response::Error(reason) => Err(Error::SpeedTest(reason)),
other => Err(Error::Storage(format!("unexpected answer: {other:?}"))),
}
}
/// Asks a running agent for a configured network's shared secret, in its
/// `tsn1…` text form, so a local client can copy it. The secret is never
/// logged by this path.
+72
View File
@@ -0,0 +1,72 @@
//! Local presentation of receiver-measured peer throughput.
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
/// Tests last requested on this device, scoped to one network.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SpeedReport {
/// Progress of the current sequential exit-node test.
pub batch: Option<SpeedBatchReport>,
/// Per-peer progress or the last local result, keyed by endpoint ID.
pub peers: BTreeMap<String, SpeedPeerReport>,
/// Currently connected peers advertising the same diagnostic wire version.
pub capable: Vec<String>,
}
/// Progress of an exit-node batch.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct SpeedBatchReport {
/// Number of peers that have finished, including failures.
pub done: u32,
/// Number selected when the batch started.
pub total: u32,
}
/// A receiver-confirmed rate in decimal bits per second.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct SpeedRate {
/// Measured bits per second.
pub bps: u64,
/// The test reached its budget before establishing a throughput ceiling.
pub lower_bound: bool,
}
/// Locally observed phase of one diagnostic.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum SpeedPhase {
/// Waiting behind another exit in the same batch.
#[default]
Queued,
/// Negotiating over the authenticated control session.
Preparing,
/// Receiving test data.
Download,
/// Sending test data.
Upload,
/// Measurement is complete.
Done,
/// The test could not produce a result, with an explanation for the user.
Failed(String),
/// The test was stopped.
Cancelled,
}
/// A single live or completed diagnostic on this device.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SpeedPeerReport {
/// Current or terminal phase.
pub phase: SpeedPhase,
/// Download rate from the remote peer.
pub down: Option<SpeedRate>,
/// Upload rate to the remote peer.
pub up: Option<SpeedRate>,
/// Time since the individual test began.
pub elapsed_ms: u32,
/// Unique payload bytes received across both directions.
pub bytes: u64,
/// Wall-clock time of the most recent update, for display only.
pub measured_at_unix_secs: u64,
/// Data path at the start of the measurement, when known.
pub path: Option<String>,
}
+12
View File
@@ -121,6 +121,18 @@ impl RoutingTable {
Self::default()
}
/// Exact local and signed remote addresses for a mesh diagnostic. Exit routes do not qualify.
pub(crate) fn peer_addresses(
&self,
network: NetworkId,
peer: EndpointId,
) -> Option<(Ipv4Addr, Ipv4Addr)> {
let networks = self.read();
let routes = networks.get(&network)?;
let (address, _) = routes.peers.iter().find(|(_, owner)| *owner == peer)?;
Some((routes.local?, *address))
}
fn read(&self) -> std::sync::RwLockReadGuard<'_, HashMap<NetworkId, NetworkRoutes>> {
match self.networks.read() {
Ok(guard) => guard,