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:
1 parent
fb7a959d23
commit
200e716c28
34 files changed
+3658
-88
No files matched your search
@@ -0,0 +1,490 @@
|
||||
use crate::measurement::{Pacer, Receiver, Search};
|
||||
use crate::packet::{MAX_MTU, MIN_MTU, PacketBuilder};
|
||||
use crate::{
|
||||
Control, Datagram, Direction, Feedback, NORMAL_BYTES, Progress, Quality, Reading, Start, State,
|
||||
};
|
||||
use bytes::Bytes;
|
||||
use std::future::Future;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use tokio::time::{Instant, MissedTickBehavior, interval_at, sleep_until, timeout_at};
|
||||
|
||||
const TOTAL_TIME: Duration = Duration::from_secs(5);
|
||||
const DIRECTION_TIME: Duration = Duration::from_millis(1900);
|
||||
const FEEDBACK_TICK: Duration = Duration::from_millis(25);
|
||||
const PACE_TICK: Duration = Duration::from_millis(2);
|
||||
|
||||
/// Parameters for one locally admitted, authenticated peer.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Config {
|
||||
/// Fresh random identifier for the exchange. A responder uses the identifier from the request.
|
||||
pub id: u64,
|
||||
/// Local overlay IPv4 address on this network.
|
||||
pub local: Ipv4Addr,
|
||||
/// Authenticated peer's overlay address on this network.
|
||||
pub remote: Ipv4Addr,
|
||||
/// Maximum complete diagnostic datagram size supported by this route.
|
||||
pub mtu: u16,
|
||||
/// Local policy's maximum diagnostic IPv4 bytes in each direction.
|
||||
pub byte_limit: u32,
|
||||
/// Recent peer RTT, used to select the feedback interval and bound the final drain.
|
||||
pub rtt: Duration,
|
||||
}
|
||||
|
||||
/// Delivery for exactly one network and peer. The host uses its usual network
|
||||
/// authentication for control and its ordinary encrypted packet path for probes.
|
||||
pub trait Io: Send + Sync {
|
||||
/// Enqueue or send one reliable authenticated control record.
|
||||
fn control(&self, message: Control) -> impl Future<Output = bool> + Send;
|
||||
/// Attempt to send one packet without blocking the tunnel or buffering unbounded data.
|
||||
fn packet(&self, packet: Bytes) -> bool;
|
||||
/// Publish a live observation or terminal state.
|
||||
fn progress(&self, update: Progress);
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Ingress(Mutex<Option<Receiver>>);
|
||||
|
||||
impl Ingress {
|
||||
fn with<T>(&self, f: impl FnOnce(&mut Option<Receiver>) -> T) -> T {
|
||||
let mut guard = self.0.lock().unwrap_or_else(|poison| poison.into_inner());
|
||||
f(&mut guard)
|
||||
}
|
||||
}
|
||||
|
||||
/// Cloneable, nonblocking ingress for a single test. Data is counted in place;
|
||||
/// it is never put on the reliable message queue.
|
||||
#[derive(Clone)]
|
||||
pub struct Handle {
|
||||
id: u64,
|
||||
local: Ipv4Addr,
|
||||
remote: Ipv4Addr,
|
||||
events: mpsc::Sender<Control>,
|
||||
cancel: watch::Sender<bool>,
|
||||
ingress: Arc<Ingress>,
|
||||
}
|
||||
|
||||
impl Handle {
|
||||
/// Deliver an authenticated control record for an existing test.
|
||||
pub fn control(&self, message: Control) {
|
||||
if message.id() == self.id && message.valid() {
|
||||
if matches!(message, Control::Cancel { .. }) {
|
||||
self.cancel();
|
||||
} else {
|
||||
let _ = self.events.try_send(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Count a validated probe from the bound peer in the current receiving direction.
|
||||
pub fn data(&self, packet: Datagram) {
|
||||
if packet.id == self.id && packet.source == self.remote && packet.destination == self.local
|
||||
{
|
||||
self.ingress.with(|rx| {
|
||||
if let Some(rx) = rx {
|
||||
rx.put(packet, Instant::now());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Interrupt local work, including outstanding control sends.
|
||||
pub fn cancel(&self) {
|
||||
self.cancel.send_replace(true);
|
||||
}
|
||||
}
|
||||
|
||||
/// A single, bounded two-direction exchange. Nothing runs until the host calls `run`.
|
||||
pub struct Session {
|
||||
cfg: Config,
|
||||
request: Option<Start>,
|
||||
events: mpsc::Receiver<Control>,
|
||||
cancel: watch::Receiver<bool>,
|
||||
ingress: Arc<Ingress>,
|
||||
progress: Progress,
|
||||
}
|
||||
|
||||
/// Prepare an outgoing session. The test begins when its runner sends its Start record.
|
||||
pub fn initiate(config: Config) -> (Handle, Session) {
|
||||
new_session(config, None)
|
||||
}
|
||||
|
||||
/// Prepare the response to a verified Start. Local and requested traffic limits are intersected.
|
||||
pub fn respond(mut config: Config, request: Start) -> (Handle, Session) {
|
||||
config.id = request.id;
|
||||
new_session(config, Some(request))
|
||||
}
|
||||
|
||||
fn new_session(config: Config, request: Option<Start>) -> (Handle, Session) {
|
||||
let (tx, events) = mpsc::channel(32);
|
||||
let (cancel_tx, cancel) = watch::channel(false);
|
||||
let ingress = Arc::new(Ingress::default());
|
||||
let handle = Handle {
|
||||
id: config.id,
|
||||
local: config.local,
|
||||
remote: config.remote,
|
||||
events: tx,
|
||||
cancel: cancel_tx,
|
||||
ingress: ingress.clone(),
|
||||
};
|
||||
let session = Session {
|
||||
cfg: config,
|
||||
request,
|
||||
events,
|
||||
cancel,
|
||||
ingress,
|
||||
progress: Progress::default(),
|
||||
};
|
||||
(handle, session)
|
||||
}
|
||||
|
||||
fn open_control(control: Option<Control>) -> Result<Control, State> {
|
||||
match control {
|
||||
Some(Control::Busy { .. }) => Err(State::Busy),
|
||||
Some(Control::Cancel { .. }) => Err(State::Cancelled),
|
||||
Some(control) => Ok(control),
|
||||
None => Err(State::Cancelled),
|
||||
}
|
||||
}
|
||||
|
||||
async fn send(io: &impl Io, message: Control) -> Result<(), State> {
|
||||
if io.control(message).await {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(State::Failed)
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Run both directions under one five-second deadline and return the same final
|
||||
/// snapshot that is published to the host. Dropping the future stops packet generation.
|
||||
pub async fn run(mut self, io: impl Io) -> Progress {
|
||||
let deadline = Instant::now() + TOTAL_TIME;
|
||||
let mut cancellation = self.cancel.clone();
|
||||
io.progress(self.progress);
|
||||
let state = tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.wait_for(|v| *v) => State::Cancelled,
|
||||
result = timeout_at(deadline, self.exchange(&io, deadline)) => {
|
||||
match result { Ok(Ok(())) => State::Complete, Ok(Err(state)) => state, Err(_) => State::TimedOut }
|
||||
}
|
||||
};
|
||||
self.ingress.with(|rx| *rx = None);
|
||||
self.progress.state = state;
|
||||
io.progress(self.progress);
|
||||
if matches!(state, State::Cancelled | State::Failed | State::TimedOut) {
|
||||
// A blocked control stream must never delay local release or shutdown.
|
||||
let _ = timeout_at(
|
||||
deadline.min(Instant::now() + Duration::from_millis(20)),
|
||||
io.control(Control::Cancel { id: self.cfg.id }),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
self.progress
|
||||
}
|
||||
|
||||
async fn exchange(&mut self, io: &impl Io, deadline: Instant) -> Result<(), State> {
|
||||
let id = self.cfg.id;
|
||||
self.cfg.byte_limit = self.cfg.byte_limit.min(NORMAL_BYTES);
|
||||
self.cfg.mtu = self.cfg.mtu.min(MAX_MTU);
|
||||
if self.cfg.mtu < MIN_MTU || self.cfg.byte_limit == 0 || self.cfg.local == self.cfg.remote {
|
||||
return Err(State::Failed);
|
||||
}
|
||||
if let Some(start) = self.request {
|
||||
if !Control::Start(start).valid() {
|
||||
return Err(State::Failed);
|
||||
}
|
||||
self.cfg.mtu = self.cfg.mtu.min(start.mtu);
|
||||
self.cfg.byte_limit = self.cfg.byte_limit.min(start.byte_limit);
|
||||
send(
|
||||
io,
|
||||
Control::Accepted {
|
||||
id,
|
||||
mtu: self.cfg.mtu,
|
||||
byte_limit: self.cfg.byte_limit,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
} else {
|
||||
send(
|
||||
io,
|
||||
Control::Start(Start {
|
||||
id,
|
||||
mtu: self.cfg.mtu,
|
||||
byte_limit: self.cfg.byte_limit,
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
loop {
|
||||
if let Control::Accepted {
|
||||
mtu, byte_limit, ..
|
||||
} = open_control(self.events.recv().await)?
|
||||
{
|
||||
if mtu > self.cfg.mtu || byte_limit > self.cfg.byte_limit {
|
||||
return Err(State::Failed);
|
||||
}
|
||||
self.cfg.mtu = mtu;
|
||||
self.cfg.byte_limit = byte_limit;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for direction in [Direction::Download, Direction::Upload] {
|
||||
self.progress.state = match direction {
|
||||
Direction::Download => State::Download,
|
||||
Direction::Upload => State::Upload,
|
||||
};
|
||||
io.progress(self.progress);
|
||||
let sender = (direction == Direction::Download) == self.request.is_some();
|
||||
let result = if sender {
|
||||
self.send_probes(io, direction, deadline).await?
|
||||
} else {
|
||||
self.receive_probes(io, direction).await?
|
||||
};
|
||||
*self.progress.at(direction) = result;
|
||||
io.progress(self.progress);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn send_probes(
|
||||
&mut self,
|
||||
io: &impl Io,
|
||||
direction: Direction,
|
||||
deadline: Instant,
|
||||
) -> Result<Reading, State> {
|
||||
loop {
|
||||
if matches!(open_control(self.events.recv().await)?, Control::Ready { direction: d, .. } if d == direction)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
let start = Instant::now();
|
||||
// Leave room for the opposite direction and the final reliable report.
|
||||
let remaining = deadline
|
||||
.saturating_duration_since(start)
|
||||
.saturating_sub(Duration::from_millis(200));
|
||||
let phase = if direction == Direction::Download {
|
||||
remaining / 2
|
||||
} else {
|
||||
remaining
|
||||
};
|
||||
let end = start + phase.min(DIRECTION_TIME);
|
||||
let mut tick = interval_at(start + PACE_TICK, PACE_TICK);
|
||||
tick.set_missed_tick_behavior(MissedTickBehavior::Skip);
|
||||
let mut search = Search::default();
|
||||
let mut pacer = Pacer::new(start, self.cfg.mtu);
|
||||
let builder = PacketBuilder::new(
|
||||
self.cfg.local,
|
||||
self.cfg.remote,
|
||||
self.cfg.id,
|
||||
direction,
|
||||
self.cfg.mtu,
|
||||
);
|
||||
let limit = self.cfg.byte_limit / u32::from(self.cfg.mtu);
|
||||
let mut packets = 0;
|
||||
let mut last_bytes = 0;
|
||||
let mut last_feedback = start;
|
||||
let max_silence = (self
|
||||
.cfg
|
||||
.rtt
|
||||
.saturating_mul(3)
|
||||
.saturating_add(Duration::from_millis(200)))
|
||||
.clamp(Duration::from_millis(700), Duration::from_millis(950));
|
||||
while packets < limit && !search.done() && Instant::now() < end {
|
||||
tokio::select! {
|
||||
control = self.events.recv() => {
|
||||
if let Control::Feedback { direction: d, sample, .. } = open_control(control)?
|
||||
&& d == direction && sample.bytes >= last_bytes && sample.bytes <= self.cfg.byte_limit
|
||||
{
|
||||
if sample.bytes > last_bytes {
|
||||
last_feedback = Instant::now();
|
||||
last_bytes = sample.bytes;
|
||||
}
|
||||
if sample.bps > 0 {
|
||||
*self.progress.at(direction) = Reading { bps: Some(sample.bps), bytes: last_bytes, quality: Quality::Measuring };
|
||||
io.progress(self.progress);
|
||||
}
|
||||
search.observe(sample, start.elapsed().as_micros() as u32);
|
||||
}
|
||||
}
|
||||
_ = tick.tick() => {
|
||||
let now = Instant::now();
|
||||
let silence = if last_bytes == 0 { max_silence.max(Duration::from_millis(1100)) } else { max_silence };
|
||||
if now.duration_since(last_feedback) > silence {
|
||||
break;
|
||||
}
|
||||
let emit = pacer.packets(now, search.target).min(limit - packets);
|
||||
let elapsed_us = now.duration_since(start).as_micros() as u32;
|
||||
for index in 0..emit {
|
||||
// A full tunnel queue is part of the observed data path. Charging
|
||||
// attempted probes bounds work during overload and preserves sequence gaps.
|
||||
if !io.packet(builder.packet(search.stage, packets + index, elapsed_us)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
packets += emit;
|
||||
}
|
||||
}
|
||||
}
|
||||
send(
|
||||
io,
|
||||
Control::End {
|
||||
id: self.cfg.id,
|
||||
direction,
|
||||
packets,
|
||||
reading: search.result(last_bytes),
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
loop {
|
||||
if let Control::Report {
|
||||
direction: d,
|
||||
reading,
|
||||
..
|
||||
} = open_control(self.events.recv().await)?
|
||||
&& d == direction
|
||||
{
|
||||
if reading.bytes > packets * u32::from(self.cfg.mtu - crate::packet::HEADER) {
|
||||
return Err(State::Failed);
|
||||
}
|
||||
return Ok(reading);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn receive_probes(
|
||||
&mut self,
|
||||
io: &impl Io,
|
||||
direction: Direction,
|
||||
) -> Result<Reading, State> {
|
||||
let id = self.cfg.id;
|
||||
self.ingress
|
||||
.with(|rx| *rx = Some(Receiver::new(direction, self.cfg.mtu, self.cfg.byte_limit)));
|
||||
send(io, Control::Ready { id, direction }).await?;
|
||||
let mut tick = interval_at(Instant::now() + FEEDBACK_TICK, FEEDBACK_TICK);
|
||||
tick.set_missed_tick_behavior(MissedTickBehavior::Skip);
|
||||
let window = self
|
||||
.cfg
|
||||
.rtt
|
||||
.clamp(Duration::from_millis(100), Duration::from_millis(220));
|
||||
let (packets, estimate) = loop {
|
||||
tokio::select! {
|
||||
control = self.events.recv() => {
|
||||
if let Control::End { direction: d, packets, reading, .. } = open_control(control)?
|
||||
&& d == direction
|
||||
{
|
||||
if packets > self.cfg.byte_limit / u32::from(self.cfg.mtu) { return Err(State::Failed); }
|
||||
break (packets, reading);
|
||||
}
|
||||
}
|
||||
_ = tick.tick() => {
|
||||
let sample = self.ingress.with(|rx| rx.as_mut().and_then(|r| r.sample(Instant::now(), window)));
|
||||
if let Some(sample) = sample {
|
||||
self.update_receiver(io, direction, sample);
|
||||
send(io, Control::Feedback { id, direction, sample }).await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
let received = self.ingress.with(|rx| rx.as_ref().map_or(0, |r| r.count));
|
||||
if received < packets {
|
||||
// Reliable End and encrypted probes may take different paths.
|
||||
let drain = self
|
||||
.cfg
|
||||
.rtt
|
||||
.clamp(Duration::from_millis(25), Duration::from_millis(120));
|
||||
sleep_until(Instant::now() + drain).await;
|
||||
}
|
||||
let rx = self.ingress.with(Option::take).ok_or(State::Failed)?;
|
||||
if rx.count > packets {
|
||||
return Err(State::Failed);
|
||||
}
|
||||
// A short final burst can never establish a rate on its own. Only complete
|
||||
// receiver windows are eligible, even if the sender reports a higher value.
|
||||
let bps = estimate
|
||||
.bps
|
||||
.filter(|_| rx.best > 0)
|
||||
.map(|v| v.min(rx.best))
|
||||
.or_else(|| (rx.best > 0).then_some(rx.best));
|
||||
let quality = if bps.is_none() {
|
||||
Quality::Insufficient
|
||||
} else if estimate.quality == Quality::Measured {
|
||||
Quality::Measured
|
||||
} else {
|
||||
Quality::AtLeast
|
||||
};
|
||||
let reading = Reading {
|
||||
bps,
|
||||
bytes: rx.bytes(),
|
||||
quality,
|
||||
};
|
||||
send(
|
||||
io,
|
||||
Control::Report {
|
||||
id,
|
||||
direction,
|
||||
reading,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
Ok(reading)
|
||||
}
|
||||
|
||||
fn update_receiver(&mut self, io: &impl Io, direction: Direction, sample: Feedback) {
|
||||
let reading = self.progress.at(direction);
|
||||
reading.bytes = sample.bytes;
|
||||
if sample.bps > 0 {
|
||||
reading.bps = Some(sample.bps);
|
||||
}
|
||||
io.progress(self.progress);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn data_ingress_is_bound_to_the_session_id_and_both_assigned_addresses() {
|
||||
let local = Ipv4Addr::new(10, 1, 2, 3);
|
||||
let remote = Ipv4Addr::new(10, 1, 2, 4);
|
||||
let conf = Config {
|
||||
id: 42,
|
||||
local,
|
||||
remote,
|
||||
mtu: 1280,
|
||||
byte_limit: 32_000,
|
||||
rtt: Duration::ZERO,
|
||||
};
|
||||
let (handle, _) = initiate(conf);
|
||||
handle.ingress.with(|rx| {
|
||||
*rx = Some(Receiver::new(
|
||||
Direction::Download,
|
||||
conf.mtu,
|
||||
conf.byte_limit,
|
||||
))
|
||||
});
|
||||
let make = |src, dst, id, seq| {
|
||||
let raw = PacketBuilder::new(src, dst, id, Direction::Download, 1280).packet(0, seq, 7);
|
||||
crate::decode_packet(&raw).unwrap()
|
||||
};
|
||||
for (ipfrom, ipto, id, seq) in [
|
||||
(remote, local, 41, 0),
|
||||
(local, remote, 42, 1),
|
||||
(Ipv4Addr::LOCALHOST, local, 42, 2),
|
||||
(remote, Ipv4Addr::LOCALHOST, 42, 3),
|
||||
(remote, local, 42, 4),
|
||||
] {
|
||||
handle.data(make(ipfrom, ipto, id, seq));
|
||||
}
|
||||
assert_eq!(
|
||||
handle.ingress.with(|rx| rx.as_ref().map(|r| r.count)),
|
||||
Some(1)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
//! Directional goodput measurements for an authenticated peer on its existing IPv4 tunnel.
|
||||
//!
|
||||
//! The host advertises and negotiates this crate's wire version, admits at most one
|
||||
//! test at a time, and delivers control messages over its reliable authenticated
|
||||
//! channel. Probe packets take the same encrypted IPv4 path as application traffic.
|
||||
|
||||
mod engine;
|
||||
mod measurement;
|
||||
mod packet;
|
||||
mod wire;
|
||||
|
||||
pub use engine::{Config, Handle, Io, Session, initiate, respond};
|
||||
pub use packet::{Datagram, decode_packet, is_test_packet};
|
||||
pub use wire::{Control, Direction, Feedback, Progress, Quality, Reading, Start, State};
|
||||
|
||||
/// Capability negotiated by peers for this protocol.
|
||||
pub const PROTOCOL: &str = "speedtest";
|
||||
/// Wire version of the control records and IPv4 payload, independent of software versions.
|
||||
pub const VERSION: u16 = 1;
|
||||
/// Absolute per-direction diagnostic IPv4 traffic budget.
|
||||
pub const NORMAL_BYTES: u32 = 96 * 1024 * 1024;
|
||||
/// Suggested per-direction budget on metered paths.
|
||||
pub const METERED_BYTES: u32 = 8 * 1024 * 1024;
|
||||
@@ -0,0 +1,372 @@
|
||||
use crate::packet::HEADER;
|
||||
use crate::wire::MAX_BPS;
|
||||
use crate::{Datagram, Direction, Feedback, Quality, Reading};
|
||||
use std::time::Duration;
|
||||
use tokio::time::Instant;
|
||||
|
||||
const INITIAL_BPS: u64 = 4_000_000;
|
||||
const MIN_BPS: u64 = 32_000;
|
||||
|
||||
pub(crate) struct Receiver {
|
||||
pub(crate) direction: Direction,
|
||||
mtu: u16,
|
||||
packets: u32,
|
||||
seen: Vec<u64>,
|
||||
window: Option<Window>,
|
||||
pub(crate) count: u32,
|
||||
pub(crate) best: u64,
|
||||
}
|
||||
|
||||
struct Window {
|
||||
start: Instant,
|
||||
stage: u8,
|
||||
received: u32,
|
||||
starts_on_packet: bool,
|
||||
arrival_groups: u8,
|
||||
last_group: Instant,
|
||||
first_arrival: Instant,
|
||||
last_arrival: Instant,
|
||||
first: u32,
|
||||
highest: u32,
|
||||
last_send_us: u32,
|
||||
}
|
||||
|
||||
impl Receiver {
|
||||
pub(crate) fn new(direction: Direction, mtu: u16, budget: u32) -> Self {
|
||||
let packets = budget / u32::from(mtu);
|
||||
Self {
|
||||
direction,
|
||||
mtu,
|
||||
packets,
|
||||
seen: vec![0; packets.div_ceil(64) as usize],
|
||||
window: None,
|
||||
count: 0,
|
||||
best: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn put(&mut self, probe: Datagram, now: Instant) {
|
||||
if probe.direction != self.direction
|
||||
|| probe.size != self.mtu
|
||||
|| probe.sequence >= self.packets
|
||||
{
|
||||
return;
|
||||
}
|
||||
let word = &mut self.seen[(probe.sequence / 64) as usize];
|
||||
let bit = 1u64 << (probe.sequence % 64);
|
||||
if *word & bit != 0 {
|
||||
return;
|
||||
}
|
||||
*word |= bit;
|
||||
self.count += 1;
|
||||
if self.window.as_ref().is_none_or(|w| w.stage < probe.stage) {
|
||||
self.window = Some(Window {
|
||||
start: now,
|
||||
stage: probe.stage,
|
||||
received: 0,
|
||||
starts_on_packet: true,
|
||||
arrival_groups: 0,
|
||||
last_group: now,
|
||||
first_arrival: now,
|
||||
last_arrival: now,
|
||||
first: probe.sequence,
|
||||
highest: probe.sequence,
|
||||
last_send_us: probe.sent_us,
|
||||
});
|
||||
}
|
||||
if let Some(w) = &mut self.window
|
||||
&& w.stage == probe.stage
|
||||
{
|
||||
if w.received == 0 {
|
||||
w.first_arrival = now;
|
||||
w.last_group = now;
|
||||
w.arrival_groups = 1;
|
||||
w.first = probe.sequence;
|
||||
w.highest = probe.sequence;
|
||||
} else {
|
||||
if w.arrival_groups < 3
|
||||
&& now.duration_since(w.last_group) >= Duration::from_millis(20)
|
||||
{
|
||||
w.arrival_groups += 1;
|
||||
w.last_group = now;
|
||||
}
|
||||
w.first = w.first.min(probe.sequence);
|
||||
w.highest = w.highest.max(probe.sequence);
|
||||
}
|
||||
w.received += 1;
|
||||
w.last_arrival = now;
|
||||
w.last_send_us = w.last_send_us.max(probe.sent_us);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn bytes(&self) -> u32 {
|
||||
self.count * u32::from(self.mtu - HEADER)
|
||||
}
|
||||
|
||||
// A rate needs observations spread over a real interval. A queued burst
|
||||
// followed by silence must never turn into a capacity estimate.
|
||||
pub(crate) fn sample(&mut self, now: Instant, minimum: Duration) -> Option<Feedback> {
|
||||
let bytes = self.bytes();
|
||||
let w = self.window.as_mut()?;
|
||||
let elapsed = now.duration_since(w.start);
|
||||
if elapsed < minimum {
|
||||
return None;
|
||||
}
|
||||
let span = w.highest - w.first + 1;
|
||||
let loss = (u64::from(span.saturating_sub(w.received)) * 1000 / u64::from(span)) as u16;
|
||||
let spread = w.last_arrival.duration_since(w.first_arrival);
|
||||
// The first packet of a stage starts its clock. Its bytes arrived before
|
||||
// the measured interval. Later windows start exactly when the last one closed.
|
||||
let sampled = w.received.saturating_sub(u32::from(w.starts_on_packet));
|
||||
let enough = sampled >= 3 && w.arrival_groups >= 3 && spread >= elapsed * 2 / 3;
|
||||
if !enough && elapsed < Duration::from_millis(600) {
|
||||
return None;
|
||||
}
|
||||
let bps = if enough {
|
||||
(u64::from(sampled) * u64::from(self.mtu - HEADER) * 8_000_000
|
||||
/ elapsed.as_micros().max(1) as u64)
|
||||
.min(MAX_BPS)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let feedback = Feedback {
|
||||
stage: w.stage,
|
||||
bps,
|
||||
lost_per_mille: loss,
|
||||
bytes,
|
||||
echo_us: w.last_send_us,
|
||||
};
|
||||
w.start = now;
|
||||
w.received = 0;
|
||||
w.starts_on_packet = false;
|
||||
if bps > 0 {
|
||||
self.best = self.best.max(bps);
|
||||
}
|
||||
Some(feedback)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Search {
|
||||
pub(crate) stage: u8,
|
||||
pub(crate) target: u64,
|
||||
best: u64,
|
||||
baseline_delay: Option<u32>,
|
||||
initial_loss: Option<u16>,
|
||||
last_echo: Option<u32>,
|
||||
confirm: bool,
|
||||
previous: Option<u64>,
|
||||
measured: Option<u64>,
|
||||
}
|
||||
|
||||
impl Default for Search {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
stage: 0,
|
||||
target: INITIAL_BPS,
|
||||
best: 0,
|
||||
baseline_delay: None,
|
||||
initial_loss: None,
|
||||
last_echo: None,
|
||||
confirm: false,
|
||||
previous: None,
|
||||
measured: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Search {
|
||||
pub(crate) fn observe(&mut self, sample: Feedback, elapsed_us: u32) {
|
||||
if sample.stage != self.stage
|
||||
|| self.measured.is_some()
|
||||
|| sample.echo_us > elapsed_us
|
||||
|| self.last_echo.is_some_and(|echo| echo >= sample.echo_us)
|
||||
{
|
||||
return;
|
||||
}
|
||||
self.last_echo = Some(sample.echo_us);
|
||||
let bps = sample.bps;
|
||||
self.best = self.best.max(bps);
|
||||
let delay = elapsed_us - sample.echo_us;
|
||||
let base = *self.baseline_delay.get_or_insert(delay);
|
||||
self.baseline_delay = Some(base.min(delay));
|
||||
let queuing = delay > base.saturating_add(45_000).max(base.saturating_mul(2));
|
||||
// A small, constant random loss is common on Wi-Fi and cellular links.
|
||||
// Reduce on growing loss, queue delay or a receiver rate below the offer.
|
||||
let baseline_loss = *self
|
||||
.initial_loss
|
||||
.get_or_insert(sample.lost_per_mille.min(100));
|
||||
let congested =
|
||||
sample.lost_per_mille > baseline_loss + 30 || bps < self.target * 4 / 5 || queuing;
|
||||
if congested {
|
||||
self.confirm = true;
|
||||
self.previous = None;
|
||||
self.offer(if bps == 0 {
|
||||
self.target / 2
|
||||
} else {
|
||||
bps * 97 / 100
|
||||
});
|
||||
} else if self.confirm {
|
||||
if sample.lost_per_mille > 100 {
|
||||
self.previous = None;
|
||||
return;
|
||||
}
|
||||
if let Some(prev) = self.previous
|
||||
&& prev.abs_diff(bps) <= bps / 6
|
||||
{
|
||||
self.measured = Some((prev + bps) / 2);
|
||||
} else {
|
||||
self.previous = Some(bps);
|
||||
}
|
||||
} else if self.target < MAX_BPS {
|
||||
self.offer(self.target.saturating_mul(4));
|
||||
}
|
||||
}
|
||||
|
||||
fn offer(&mut self, bps: u64) {
|
||||
self.target = bps.clamp(MIN_BPS, MAX_BPS);
|
||||
self.stage = self.stage.saturating_add(1);
|
||||
}
|
||||
|
||||
pub(crate) fn done(&self) -> bool {
|
||||
self.measured.is_some()
|
||||
}
|
||||
|
||||
pub(crate) fn result(&self, bytes: u32) -> Reading {
|
||||
if let Some(bps) = self.measured {
|
||||
Reading {
|
||||
bps: Some(bps),
|
||||
bytes,
|
||||
quality: Quality::Measured,
|
||||
}
|
||||
} else if self.best > 0 {
|
||||
Reading {
|
||||
bps: Some(self.best),
|
||||
bytes,
|
||||
quality: Quality::AtLeast,
|
||||
}
|
||||
} else {
|
||||
Reading {
|
||||
bps: None,
|
||||
bytes,
|
||||
quality: Quality::Insufficient,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Pacer {
|
||||
last_tick: Instant,
|
||||
// Fractional packet credit in payload bit-nanoseconds.
|
||||
credit: u64,
|
||||
cost: u64,
|
||||
}
|
||||
|
||||
impl Pacer {
|
||||
pub(crate) fn new(start: Instant, mtu: u16) -> Self {
|
||||
Self {
|
||||
last_tick: start,
|
||||
credit: 0,
|
||||
cost: u64::from(mtu - HEADER) * 8_000_000_000,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn packets(&mut self, now: Instant, bps: u64) -> u32 {
|
||||
// The event loop may have been descheduled. Never catch up with a long burst.
|
||||
let elapsed = now.duration_since(self.last_tick).as_nanos().min(3_000_000) as u64;
|
||||
self.last_tick = now;
|
||||
self.credit += elapsed * bps;
|
||||
let packets = self.credit / self.cost;
|
||||
self.credit %= self.cost;
|
||||
packets.min(512) as u32
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
fn packet(sequence: u32, stage: u8, sent_us: u32) -> Datagram {
|
||||
Datagram {
|
||||
id: 7,
|
||||
source: Ipv4Addr::LOCALHOST,
|
||||
destination: Ipv4Addr::BROADCAST,
|
||||
direction: Direction::Download,
|
||||
stage,
|
||||
sequence,
|
||||
sent_us,
|
||||
size: 1280,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounded_reordered_packets_are_counted_once_and_do_not_reopen_earlier_stages() {
|
||||
let t = Instant::now();
|
||||
let mut rx = Receiver::new(Direction::Download, 1280, 1280 * 8);
|
||||
for (i, s) in [(7, 1), (1, 0), (3, 1), (3, 1), (8, 1), (u32::MAX, 1)] {
|
||||
rx.put(packet(i, s, 0), t);
|
||||
}
|
||||
rx.put(
|
||||
Datagram {
|
||||
direction: Direction::Upload,
|
||||
..packet(4, 1, 0)
|
||||
},
|
||||
t,
|
||||
);
|
||||
rx.put(
|
||||
Datagram {
|
||||
size: 1500,
|
||||
..packet(5, 1, 0)
|
||||
},
|
||||
t,
|
||||
);
|
||||
assert_eq!(rx.count, 3);
|
||||
assert_eq!(rx.bytes(), 3 * u32::from(1280 - HEADER));
|
||||
assert!(
|
||||
rx.window
|
||||
.as_ref()
|
||||
.is_some_and(|w| w.stage == 1 && w.received == 2)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_short_burst_or_compressed_catchup_cannot_establish_throughput() {
|
||||
let start = Instant::now();
|
||||
let mut receiver = Receiver::new(Direction::Download, 1280, NORMAL_BYTES_FOR_TEST);
|
||||
for i in 0..500 {
|
||||
receiver.put(packet(i, 0, i), start);
|
||||
}
|
||||
let window = Duration::from_millis(120);
|
||||
for i in 500..520 {
|
||||
receiver.put(packet(i, 0, i), start + window);
|
||||
}
|
||||
assert!(receiver.sample(start + window, window).is_none());
|
||||
let feedback = receiver
|
||||
.sample(start + Duration::from_millis(650), window)
|
||||
.unwrap();
|
||||
assert_eq!(feedback.bps, 0);
|
||||
assert_eq!(receiver.best, 0);
|
||||
}
|
||||
|
||||
const NORMAL_BYTES_FOR_TEST: u32 = 1024 * 1024;
|
||||
|
||||
#[test]
|
||||
fn retransmitted_feedback_does_not_supply_two_confirmation_windows() {
|
||||
let mut search = Search::default();
|
||||
let f = |stage, bps, lost_per_mille, bytes, echo_us| Feedback {
|
||||
stage,
|
||||
bps,
|
||||
lost_per_mille,
|
||||
bytes,
|
||||
echo_us,
|
||||
};
|
||||
search.observe(f(0, 1_000_000, 700, 15000, 120_000), 121_000);
|
||||
let observed = f(1, 970_000, 0, 30000, 241_000);
|
||||
search.observe(observed, 242_000);
|
||||
search.observe(observed, 243_000);
|
||||
assert!(!search.done());
|
||||
search.observe(f(1, 970_000, 0, 45000, 360_000), 361_000);
|
||||
assert!(search.done());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
use crate::Direction;
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
pub(crate) const MIN_MTU: u16 = 576;
|
||||
pub(crate) const MAX_MTU: u16 = 1500;
|
||||
pub(crate) const HEADER: u16 = 46;
|
||||
const MAGIC: &[u8; 8] = b"TSNGSP01";
|
||||
const IP_PROTOCOL: u8 = 253; // RFC 3692 local experiment, disambiguated by MAGIC.
|
||||
|
||||
/// Fields from a validated version-one diagnostic IPv4 packet. Probes carry no arbitrary stream data.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Datagram {
|
||||
/// Measurement identifier from the authenticated control exchange.
|
||||
pub id: u64,
|
||||
/// Source address of the inner IPv4 datagram.
|
||||
pub source: Ipv4Addr,
|
||||
/// Destination address of the inner IPv4 datagram.
|
||||
pub destination: Ipv4Addr,
|
||||
pub(crate) direction: Direction,
|
||||
pub(crate) stage: u8,
|
||||
pub(crate) sequence: u32,
|
||||
pub(crate) sent_us: u32,
|
||||
pub(crate) size: u16,
|
||||
}
|
||||
|
||||
impl Datagram {
|
||||
/// Number of delivered diagnostic payload bytes, excluding both headers.
|
||||
pub fn payload_len(self) -> u16 {
|
||||
self.size - HEADER
|
||||
}
|
||||
}
|
||||
|
||||
/// Identify this crate's reserved IPv4 payload, including malformed records that should be dropped.
|
||||
pub fn is_test_packet(bytes: &[u8]) -> bool {
|
||||
if bytes.len() < 20 || bytes[0] >> 4 != 4 || bytes[9] != IP_PROTOCOL {
|
||||
return false;
|
||||
}
|
||||
let offset = usize::from(bytes[0] & 0x0f) * 4;
|
||||
offset >= 20 && bytes.get(offset..offset + MAGIC.len()) == Some(MAGIC)
|
||||
}
|
||||
|
||||
/// Validate an entire diagnostic datagram before handing its fixed-size metadata to the receiver.
|
||||
pub fn decode_packet(bytes: &[u8]) -> Option<Datagram> {
|
||||
let size = u16::try_from(bytes.len()).ok()?;
|
||||
if !(MIN_MTU..=MAX_MTU).contains(&size)
|
||||
|| bytes[0] != 0x45
|
||||
|| bytes[9] != IP_PROTOCOL
|
||||
|| bytes[20..28] != *MAGIC
|
||||
|| u16::from_be_bytes([bytes[2], bytes[3]]) != size
|
||||
|| u16::from_be_bytes([bytes[6], bytes[7]]) & !0x4000 != 0
|
||||
|| checksum(&bytes[..20]) != 0
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let direction = match bytes[36] {
|
||||
0 => Direction::Download,
|
||||
1 => Direction::Upload,
|
||||
_ => return None,
|
||||
};
|
||||
let sent_us = u32::from_be_bytes(bytes[42..46].try_into().ok()?);
|
||||
if sent_us > 5_000_000 {
|
||||
return None;
|
||||
}
|
||||
Some(Datagram {
|
||||
source: Ipv4Addr::from(<[u8; 4]>::try_from(&bytes[12..16]).ok()?),
|
||||
destination: Ipv4Addr::from(<[u8; 4]>::try_from(&bytes[16..20]).ok()?),
|
||||
id: u64::from_be_bytes(bytes[28..36].try_into().ok()?),
|
||||
direction,
|
||||
stage: bytes[37],
|
||||
sequence: u32::from_be_bytes(bytes[38..42].try_into().ok()?),
|
||||
sent_us,
|
||||
size,
|
||||
})
|
||||
}
|
||||
|
||||
// Build the immutable header and deterministic padding once per direction. The
|
||||
// underlying data tunnel encrypts the packet before it goes on the wire.
|
||||
pub(crate) struct PacketBuilder(Bytes);
|
||||
|
||||
impl PacketBuilder {
|
||||
pub(crate) fn new(
|
||||
source: Ipv4Addr,
|
||||
destination: Ipv4Addr,
|
||||
id: u64,
|
||||
direction: Direction,
|
||||
mtu: u16,
|
||||
) -> Self {
|
||||
let mut bytes = BytesMut::zeroed(usize::from(mtu));
|
||||
bytes[0] = 0x45;
|
||||
bytes[2..4].copy_from_slice(&mtu.to_be_bytes());
|
||||
bytes[6] = 0x40;
|
||||
bytes[8] = 64;
|
||||
bytes[9] = IP_PROTOCOL;
|
||||
bytes[12..16].copy_from_slice(&source.octets());
|
||||
bytes[16..20].copy_from_slice(&destination.octets());
|
||||
let check = checksum(&bytes[..20]);
|
||||
bytes[10..12].copy_from_slice(&check.to_be_bytes());
|
||||
bytes[20..28].copy_from_slice(MAGIC);
|
||||
bytes[28..36].copy_from_slice(&id.to_be_bytes());
|
||||
bytes[36] = match direction {
|
||||
Direction::Download => 0,
|
||||
Direction::Upload => 1,
|
||||
};
|
||||
Self(bytes.freeze())
|
||||
}
|
||||
|
||||
pub(crate) fn packet(&self, stage: u8, sequence: u32, sent_us: u32) -> Bytes {
|
||||
let mut bytes = BytesMut::from(self.0.as_ref());
|
||||
bytes[37] = stage;
|
||||
bytes[38..42].copy_from_slice(&sequence.to_be_bytes());
|
||||
bytes[42..46].copy_from_slice(&sent_us.to_be_bytes());
|
||||
bytes.freeze()
|
||||
}
|
||||
}
|
||||
|
||||
fn checksum(bytes: &[u8]) -> u16 {
|
||||
let mut sum: u32 = bytes
|
||||
.as_chunks::<2>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|&word| u32::from(u16::from_be_bytes(word)))
|
||||
.sum();
|
||||
while sum > u32::from(u16::MAX) {
|
||||
sum = (sum & 0xffff) + (sum >> 16);
|
||||
}
|
||||
!(sum as u16)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
|
||||
fn probe() -> Bytes {
|
||||
PacketBuilder::new(
|
||||
Ipv4Addr::new(10, 1, 10, 1),
|
||||
Ipv4Addr::new(10, 1, 10, 2),
|
||||
42,
|
||||
Direction::Upload,
|
||||
1280,
|
||||
)
|
||||
.packet(3, 908, 12_000)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn routeable_ip_header_and_test_metadata_round_trip() {
|
||||
let bytes = probe();
|
||||
assert!(is_test_packet(&bytes));
|
||||
let data = decode_packet(&bytes).unwrap();
|
||||
assert_eq!(data.source, Ipv4Addr::new(10, 1, 10, 1));
|
||||
assert_eq!(data.destination, Ipv4Addr::new(10, 1, 10, 2));
|
||||
assert_eq!(
|
||||
(
|
||||
data.id,
|
||||
data.direction,
|
||||
data.stage,
|
||||
data.sequence,
|
||||
data.sent_us
|
||||
),
|
||||
(42, Direction::Upload, 3, 908, 12_000)
|
||||
);
|
||||
assert_eq!(data.payload_len(), 1280 - HEADER);
|
||||
for n in [0, 1, 19, 27, 45, 100, 1279] {
|
||||
assert!(decode_packet(&bytes[..n]).is_none());
|
||||
}
|
||||
for (byte, value) in [
|
||||
(0, 0x65),
|
||||
(2, 0x04),
|
||||
(6, 0x20),
|
||||
(9, 17),
|
||||
(10, 0),
|
||||
(20, b'z'),
|
||||
(36, 3),
|
||||
(42, 255),
|
||||
] {
|
||||
let mut bad = bytes.to_vec();
|
||||
bad[byte] = value;
|
||||
assert!(decode_packet(&bad).is_none(), "corrupted {byte}");
|
||||
}
|
||||
let mut broken = bytes.to_vec();
|
||||
broken[36] = 123;
|
||||
assert!(is_test_packet(&broken));
|
||||
broken[20] = 0;
|
||||
assert!(!is_test_packet(&broken));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
use crate::NORMAL_BYTES;
|
||||
use crate::packet::{MAX_MTU, MIN_MTU};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Both endpoints name directions from the initiating user's point of view.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum Direction {
|
||||
/// From the responding peer to the initiator.
|
||||
Download,
|
||||
/// From the initiator to the responding peer.
|
||||
Upload,
|
||||
}
|
||||
|
||||
/// What the received samples establish about the path.
|
||||
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum Quality {
|
||||
/// Measurement in progress.
|
||||
#[default]
|
||||
Measuring,
|
||||
/// The receiver confirmed a stable rate after the probe reached the path's limit.
|
||||
Measured,
|
||||
/// Sustained delivery at this rate was established before the time or byte budget ended.
|
||||
AtLeast,
|
||||
/// No full observation window was available.
|
||||
Insufficient,
|
||||
}
|
||||
|
||||
/// Useful probe payload received in one direction.
|
||||
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Reading {
|
||||
/// Delivered bits per second, if there was enough evidence to calculate a rate.
|
||||
pub bps: Option<u64>,
|
||||
/// Unique, received probe payload bytes, excluding IPv4 and diagnostic headers.
|
||||
pub bytes: u32,
|
||||
/// Meaning of the reported rate.
|
||||
pub quality: Quality,
|
||||
}
|
||||
|
||||
/// Lifecycle of a single bidirectional test.
|
||||
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum State {
|
||||
/// Negotiating a test.
|
||||
#[default]
|
||||
Starting,
|
||||
/// Receiving from the peer.
|
||||
Download,
|
||||
/// Sending to the peer.
|
||||
Upload,
|
||||
/// Both direction reports were exchanged.
|
||||
Complete,
|
||||
/// A participant cancelled this test.
|
||||
Cancelled,
|
||||
/// The other endpoint is already testing.
|
||||
Busy,
|
||||
/// A participant failed to finish before the deadline.
|
||||
TimedOut,
|
||||
/// The transport failed, configuration was invalid, or a peer sent inconsistent results.
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// A snapshot suitable for status or a live display.
|
||||
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Progress {
|
||||
/// Current phase or final outcome.
|
||||
pub state: State,
|
||||
/// Peer to initiator.
|
||||
pub down: Reading,
|
||||
/// Initiator to peer.
|
||||
pub up: Reading,
|
||||
}
|
||||
|
||||
impl Progress {
|
||||
pub(crate) fn at(&mut self, direction: Direction) -> &mut Reading {
|
||||
match direction {
|
||||
Direction::Download => &mut self.down,
|
||||
Direction::Upload => &mut self.up,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Request to start one measurement under both peers' local limits.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Start {
|
||||
/// Fresh random identifier selected by the initiator.
|
||||
pub id: u64,
|
||||
/// Maximum diagnostic IPv4 bytes to send per direction.
|
||||
pub byte_limit: u32,
|
||||
/// Maximum complete IPv4 datagram size supported by the initiating endpoint.
|
||||
pub mtu: u16,
|
||||
}
|
||||
|
||||
/// Receiver-clock observation at one offered rate.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Feedback {
|
||||
pub(crate) stage: u8,
|
||||
pub(crate) bps: u64,
|
||||
pub(crate) lost_per_mille: u16,
|
||||
pub(crate) bytes: u32,
|
||||
pub(crate) echo_us: u32,
|
||||
}
|
||||
|
||||
/// Bounded records carried by the authenticated, reliable control connection.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum Control {
|
||||
/// Request a test between these two peers.
|
||||
Start(Start),
|
||||
/// Negotiated maximum datagram size and per-direction budget.
|
||||
Accepted {
|
||||
/// Test identifier.
|
||||
id: u64,
|
||||
/// Per-direction budget in IPv4 bytes.
|
||||
byte_limit: u32,
|
||||
/// Size of every probe datagram.
|
||||
mtu: u16,
|
||||
},
|
||||
/// The responder already has an active test.
|
||||
Busy {
|
||||
/// Test identifier.
|
||||
id: u64,
|
||||
},
|
||||
/// Receiver has installed its data sink before the sender begins.
|
||||
Ready {
|
||||
/// Test identifier.
|
||||
id: u64,
|
||||
/// Direction about to start.
|
||||
direction: Direction,
|
||||
},
|
||||
/// Observed goodput and loss over a full interval of the receiver's clock.
|
||||
Feedback {
|
||||
/// Test identifier.
|
||||
id: u64,
|
||||
/// Direction being measured.
|
||||
direction: Direction,
|
||||
/// Receiver's observation.
|
||||
sample: Feedback,
|
||||
},
|
||||
/// The sender has stopped issuing probes and shares the result of its rate search.
|
||||
End {
|
||||
/// Test identifier.
|
||||
id: u64,
|
||||
/// Direction ending.
|
||||
direction: Direction,
|
||||
/// Number of IPv4 datagrams issued by the sender.
|
||||
packets: u32,
|
||||
/// Rate search result based on receiver feedback.
|
||||
reading: Reading,
|
||||
},
|
||||
/// Final delivery numbers after draining late probes.
|
||||
Report {
|
||||
/// Test identifier.
|
||||
id: u64,
|
||||
/// Direction completed.
|
||||
direction: Direction,
|
||||
/// Agreed result for this direction.
|
||||
reading: Reading,
|
||||
},
|
||||
/// End the exchange early in either direction.
|
||||
Cancel {
|
||||
/// Test identifier.
|
||||
id: u64,
|
||||
},
|
||||
}
|
||||
|
||||
pub(crate) const MAX_BPS: u64 = 8_000_000_000;
|
||||
const MAX_RECORD: usize = 64;
|
||||
|
||||
impl Control {
|
||||
/// Identifier used to bind the record to an already authenticated peer and session.
|
||||
pub fn id(&self) -> u64 {
|
||||
match *self {
|
||||
Self::Start(start) => start.id,
|
||||
Self::Accepted { id, .. }
|
||||
| Self::Busy { id }
|
||||
| Self::Ready { id, .. }
|
||||
| Self::Feedback { id, .. }
|
||||
| Self::End { id, .. }
|
||||
| Self::Report { id, .. }
|
||||
| Self::Cancel { id } => id,
|
||||
}
|
||||
}
|
||||
|
||||
/// Encode a control record into its compact version-one representation.
|
||||
pub fn encode(&self) -> Result<Vec<u8>, postcard::Error> {
|
||||
postcard::to_stdvec(self)
|
||||
}
|
||||
|
||||
/// Parse exactly one version-one record. Trailing bytes and values outside the protocol limits are rejected.
|
||||
pub fn decode(bytes: &[u8]) -> Option<Self> {
|
||||
if bytes.len() > MAX_RECORD {
|
||||
return None;
|
||||
}
|
||||
let (control, rest) = postcard::take_from_bytes::<Self>(bytes).ok()?;
|
||||
(rest.is_empty() && control.valid()).then_some(control)
|
||||
}
|
||||
|
||||
pub(crate) fn valid(self) -> bool {
|
||||
match self {
|
||||
Self::Start(Start {
|
||||
byte_limit, mtu, ..
|
||||
})
|
||||
| Self::Accepted {
|
||||
byte_limit, mtu, ..
|
||||
} => (1..=NORMAL_BYTES).contains(&byte_limit) && (MIN_MTU..=MAX_MTU).contains(&mtu),
|
||||
Self::Feedback { sample, .. } => {
|
||||
sample.bps <= MAX_BPS
|
||||
&& sample.lost_per_mille <= 1000
|
||||
&& sample.bytes <= NORMAL_BYTES
|
||||
&& sample.echo_us <= 5_000_000
|
||||
}
|
||||
Self::End {
|
||||
packets, reading, ..
|
||||
} => packets <= NORMAL_BYTES / u32::from(MIN_MTU) && valid_result(reading),
|
||||
Self::Report { reading, .. } => valid_result(reading),
|
||||
Self::Busy { .. } | Self::Ready { .. } | Self::Cancel { .. } => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn valid_result(reading: Reading) -> bool {
|
||||
reading.bytes <= NORMAL_BYTES
|
||||
&& match reading.quality {
|
||||
Quality::Insufficient => reading.bps.is_none(),
|
||||
Quality::Measured | Quality::AtLeast => {
|
||||
reading.bytes > 0 && reading.bps.is_some_and(|v| (1..=MAX_BPS).contains(&v))
|
||||
}
|
||||
Quality::Measuring => false,
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user