Fix peer speed measurements and fit compact traffic counters

A slow first download could make the rate search settle around 60 Mbit/s
on a much faster link. A final faster train could also exhaust the byte
budget before its feedback reached the sender. Reprobe above the first
apparent limit and use unique payload actually delivered over sustained
sender and receiver intervals. Count each submitted packet even when the
tunnel is backpressured, and keep the unused part of the pacing batch
available. The five-second deadline, metered limits and v1 wire format
remain compatible with existing peers.

Show achieved Mbit/s in the devices list and describe a lower bound in
the tooltip. Reserve a font-measured TX/RX width independent of changing
byte counts on narrow desktop windows and landscape Android. Support
counters through exabytes and retain exact packet counts. Align the
application, Android and Nix versions for 1.0.7.

On a shaped 300/250 Mbit/s path with a cold download, the regression
measured 295/247 Mbit/s after the fix and 59/244 on 1.0.6. The suite
also covers trailing feedback, local tunnel pressure and compact layouts
at multiple font sizes and display densities. Mixed 1.0.6/1.0.7 speed
sessions completed in both roles. Two unmetered runs over real WireGuard
on loopback measured 251 and 250 Mbit/s down and completed both directions
in 3.0 and 3.1 seconds.

On macOS arm64, workspace formatting and strict Clippy passed, and the
locked all-targets suite passed 646 tests with six opt-in tests ignored.
Cargo also reported the existing directories manifest warning. The GNU
Windows workspace cross-check and Android arm64 debug APK build passed.
This commit is contained in:
Aleksandr Bogomiakov committed 2026-11-25 20:46:43 +02:00
1 parent e3b74babba
commit b47acb8321
23 files changed
+616 -207

No files matched your search

Generated
+10 -10
View File
@@ -6296,7 +6296,7 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
[[package]] [[package]]
name = "tsunagi" name = "tsunagi"
version = "1.0.6" version = "1.0.7"
dependencies = [ dependencies = [
"anstream", "anstream",
"anstyle", "anstyle",
@@ -6320,7 +6320,7 @@ dependencies = [
[[package]] [[package]]
name = "tsunagi-android" name = "tsunagi-android"
version = "1.0.6" version = "1.0.7"
dependencies = [ dependencies = [
"bytes", "bytes",
"egui", "egui",
@@ -6344,7 +6344,7 @@ dependencies = [
[[package]] [[package]]
name = "tsunagi-awg" name = "tsunagi-awg"
version = "1.0.6" version = "1.0.7"
dependencies = [ dependencies = [
"bytes", "bytes",
"iroh", "iroh",
@@ -6359,7 +6359,7 @@ dependencies = [
[[package]] [[package]]
name = "tsunagi-core" name = "tsunagi-core"
version = "1.0.6" version = "1.0.7"
dependencies = [ dependencies = [
"arc-swap", "arc-swap",
"bytes", "bytes",
@@ -6404,7 +6404,7 @@ dependencies = [
[[package]] [[package]]
name = "tsunagi-runtime" name = "tsunagi-runtime"
version = "1.0.6" version = "1.0.7"
dependencies = [ dependencies = [
"tokio", "tokio",
"tracing", "tracing",
@@ -6427,7 +6427,7 @@ dependencies = [
[[package]] [[package]]
name = "tsunagi-tcp-tls" name = "tsunagi-tcp-tls"
version = "1.0.6" version = "1.0.7"
dependencies = [ dependencies = [
"bytes", "bytes",
"caps", "caps",
@@ -6447,7 +6447,7 @@ dependencies = [
[[package]] [[package]]
name = "tsunagi-tray" name = "tsunagi-tray"
version = "1.0.6" version = "1.0.7"
dependencies = [ dependencies = [
"eframe", "eframe",
"egui-phosphor", "egui-phosphor",
@@ -6463,7 +6463,7 @@ dependencies = [
[[package]] [[package]]
name = "tsunagi-ui" name = "tsunagi-ui"
version = "1.0.6" version = "1.0.7"
dependencies = [ dependencies = [
"egui", "egui",
"egui-phosphor", "egui-phosphor",
@@ -6476,7 +6476,7 @@ dependencies = [
[[package]] [[package]]
name = "tsunagi-wg-quic" name = "tsunagi-wg-quic"
version = "1.0.6" version = "1.0.7"
dependencies = [ dependencies = [
"boringtun", "boringtun",
"bytes", "bytes",
@@ -6503,7 +6503,7 @@ dependencies = [
[[package]] [[package]]
name = "tsunagi-wireguard" name = "tsunagi-wireguard"
version = "1.0.6" version = "1.0.7"
dependencies = [ dependencies = [
"boringtun", "boringtun",
"bytes", "bytes",
+8 -5
View File
@@ -150,13 +150,16 @@ Select a peer’s speedometer in **Devices** to measure download and upload
through its current encrypted mesh path. The cell shows live rates in Mbit/s. through its current encrypted mesh path. The cell shows live rates in Mbit/s.
Select the result to test again, or use **Test exits** to check the network’s Select the result to test again, or use **Test exits** to check the network’s
online, compatible exit nodes one at a time. The test ends at the peer, so its online, compatible exit nodes one at a time. The test ends at the peer, so its
Internet uplink beyond that peer is outside the measurement. A **≥** result is a Internet uplink beyond that peer is outside the measurement. Hover or long-press
sustained lower bound when the time or traffic budget runs out. A missing the result for details. “At least” means the receiver sustained that rate and
direction means the sample was too short. Both peers need speed-test support. the test ended before it could confirm the limit. A missing direction means
the sample was too short. Both peers need speed-test support.
A test runs for up to five seconds. It raises the offered rate in steps and A test runs for up to five seconds. It raises the offered rate in steps and
counts unique payload bytes at the receiver. The traffic ceiling is 96 MiB per tries a higher rate again after a slow start. The receiver counts unique payload
direction for one peer, or 8 MiB when either endpoint reports a metered link. bytes across sustained trains of packets, including the last train before the
traffic budget runs out. The traffic ceiling is 96 MiB per direction for one
peer, or 8 MiB when either endpoint reports a metered link.
A batch shares 128 MiB per direction among its exits, or 16 MiB on a metered A batch shares 128 MiB per direction among its exits, or 16 MiB on a metered
initiator. These ceilings count probe IP packets before tunnel overhead. initiator. These ceilings count probe IP packets before tunnel overhead.
+1 -1
View File
@@ -24,7 +24,7 @@ android {
targetSdk 35 targetSdk 35
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner' testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
versionCode providers.gradleProperty('tsunagiVersionCode').getOrElse('1').toInteger() versionCode providers.gradleProperty('tsunagiVersionCode').getOrElse('1').toInteger()
versionName providers.gradleProperty('tsunagiVersionName').getOrElse('1.0.6') versionName providers.gradleProperty('tsunagiVersionName').getOrElse('1.0.7')
ndk { abiFilters abi } ndk { abiFilters abi }
} }
} }
+2 -2
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "tsunagi-android" name = "tsunagi-android"
version = "1.0.6" version = "1.0.7"
description = "Android VPN client and egui views for tsunagi." description = "Android VPN client and egui views for tsunagi."
edition.workspace = true edition.workspace = true
rust-version.workspace = true rust-version.workspace = true
@@ -16,7 +16,7 @@ name = "vpn_source_probe"
crate-type = ["cdylib"] crate-type = ["cdylib"]
[dependencies] [dependencies]
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.6" } tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.7" }
tsunagi-ui = { path = "../tsunagi-ui" } tsunagi-ui = { path = "../tsunagi-ui" }
tsunagi-core = { path = "../tsunagi-core" } tsunagi-core = { path = "../tsunagi-core" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic" } tsunagi-wg-quic = { path = "../tsunagi-wg-quic" }
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "tsunagi-awg" name = "tsunagi-awg"
version = "1.0.6" version = "1.0.7"
description = "Ephemeral pairwise Amnezia transport for Tsunagi." description = "Ephemeral pairwise Amnezia transport for Tsunagi."
edition.workspace = true edition.workspace = true
rust-version.workspace = true rust-version.workspace = true
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "tsunagi-core" name = "tsunagi-core"
version = "1.0.6" version = "1.0.7"
description = "Small private mesh networks: persistent agent identity, deterministic network spaces, an iroh control plane, signed state and a local DNS view." description = "Small private mesh networks: persistent agent identity, deterministic network spaces, an iroh control plane, signed state and a local DNS view."
readme = "../../README.md" readme = "../../README.md"
keywords = ["mesh", "p2p", "iroh", "networking"] keywords = ["mesh", "p2p", "iroh", "networking"]
+6 -6
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "tsunagi-runtime" name = "tsunagi-runtime"
version = "1.0.6" version = "1.0.7"
description = "Built-in mesh transports and status reporting for native tsunagi agents." description = "Built-in mesh transports and status reporting for native tsunagi agents."
edition.workspace = true edition.workspace = true
rust-version.workspace = true rust-version.workspace = true
@@ -8,11 +8,11 @@ license.workspace = true
repository.workspace = true repository.workspace = true
[dependencies] [dependencies]
tsunagi-core = { path = "../tsunagi-core", version = "1.0.6" } tsunagi-core = { path = "../tsunagi-core", version = "1.0.7" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.6" } tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.7" }
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.6" } tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.7" }
tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.6" } tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.7" }
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.6" } tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.7" }
tokio.workspace = true tokio.workspace = true
tracing.workspace = true tracing.workspace = true
+12 -25
View File
@@ -14,7 +14,7 @@ use tokio::time::{Instant, MissedTickBehavior, interval_at, sleep_until, timeout
const TOTAL_TIME: Duration = Duration::from_secs(5); const TOTAL_TIME: Duration = Duration::from_secs(5);
const DIRECTION_TIME: Duration = Duration::from_millis(1900); const DIRECTION_TIME: Duration = Duration::from_millis(1900);
const FEEDBACK_TICK: Duration = Duration::from_millis(25); const FEEDBACK_TICK: Duration = Duration::from_millis(25);
const PACE_TICK: Duration = Duration::from_millis(2); const PACE_TICK: Duration = Duration::from_millis(1);
/// Parameters for one locally admitted, authenticated peer. /// Parameters for one locally admitted, authenticated peer.
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
@@ -318,15 +318,20 @@ impl Session {
break; break;
} }
let emit = pacer.packets(now, search.target).min(limit - packets); 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 { for index in 0..emit {
// A full tunnel queue is part of the observed data path. Charging if index > 0 && index.is_multiple_of(64) {
// attempted probes bounds work during overload and preserves sequence gaps. tokio::task::yield_now().await;
if !io.packet(builder.packet(search.stage, packets + index, elapsed_us)) { }
let elapsed_us = start.elapsed().as_micros() as u32;
let packet = builder.packet(search.stage, packets, elapsed_us);
// A tunnel waiting for a handshake can retain a submitted
// packet. Charge that attempt, then release the unissued
// part of this batch for a later tick if the tunnel is full.
packets += 1;
if !io.packet(packet) {
break; break;
} }
} }
packets += emit;
} }
} }
} }
@@ -403,25 +408,7 @@ impl Session {
if rx.count > packets { if rx.count > packets {
return Err(State::Failed); return Err(State::Failed);
} }
// A short final burst can never establish a rate on its own. Only complete let reading = rx.finish(estimate);
// 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( send(
io, io,
Control::Report { Control::Report {
+191 -80
View File
@@ -4,7 +4,10 @@ use crate::{Datagram, Direction, Feedback, Quality, Reading};
use std::time::Duration; use std::time::Duration;
use tokio::time::Instant; use tokio::time::Instant;
const INITIAL_BPS: u64 = 4_000_000; const INITIAL_BPS: u64 = 8_000_000;
// A tail shorter than a regular feedback period may still contain a sustained
// train. Require both clocks to span this interval and multiple arrival groups.
const MIN_TRAIN: Duration = Duration::from_millis(60);
const MIN_BPS: u64 = 32_000; const MIN_BPS: u64 = 32_000;
pub(crate) struct Receiver { pub(crate) struct Receiver {
@@ -12,25 +15,74 @@ pub(crate) struct Receiver {
mtu: u16, mtu: u16,
packets: u32, packets: u32,
seen: Vec<u64>, seen: Vec<u64>,
stage: u8,
window: Option<Window>, window: Option<Window>,
pub(crate) count: u32, pub(crate) count: u32,
pub(crate) best: u64, best: u64,
} }
struct Window { struct Window {
start: Instant,
stage: u8,
received: u32, received: u32,
starts_on_packet: bool, opening_group: u32,
arrival_groups: u8, arrival_groups: u8,
last_group: Instant, last_group: Instant,
first_arrival: Instant, first_arrival: Instant,
last_arrival: Instant, last_arrival: Instant,
first: u32, first: u32,
highest: u32, highest: u32,
first_send_us: u32,
last_send_us: u32, last_send_us: u32,
} }
impl Window {
fn new(probe: Datagram, now: Instant) -> Self {
Self {
received: 1,
opening_group: 1,
arrival_groups: 1,
last_group: now,
first_arrival: now,
last_arrival: now,
first: probe.sequence,
highest: probe.sequence,
first_send_us: probe.sent_us,
last_send_us: probe.sent_us,
}
}
fn push(&mut self, probe: Datagram, now: Instant) {
if self.arrival_groups < 3
&& now.duration_since(self.last_group) >= Duration::from_millis(20)
{
self.arrival_groups += 1;
self.last_group = now;
}
self.first = self.first.min(probe.sequence);
self.highest = self.highest.max(probe.sequence);
self.first_send_us = self.first_send_us.min(probe.sent_us);
self.last_send_us = self.last_send_us.max(probe.sent_us);
// Packets already in the first arrival batch did not traverse the measured interval.
if now.duration_since(self.first_arrival) < Duration::from_millis(1) {
self.opening_group += 1;
}
self.received += 1;
self.last_arrival = now;
}
fn rate(&self, mtu: u16) -> Option<u64> {
let arrivals = self.last_arrival.duration_since(self.first_arrival);
let sends = Duration::from_micros(u64::from(self.last_send_us - self.first_send_us));
let packets = self.received.saturating_sub(self.opening_group);
if packets < 3 || self.arrival_groups < 3 || arrivals < MIN_TRAIN || sends < MIN_TRAIN {
return None;
}
// Feedback and End may arrive late, or queued packets may arrive together.
// Use the slower of the sender's and receiver's independent train clocks.
let elapsed = arrivals.max(sends).as_micros() as u64;
Some((u64::from(packets) * u64::from(mtu - HEADER) * 8_000_000 / elapsed).min(MAX_BPS))
}
}
impl Receiver { impl Receiver {
pub(crate) fn new(direction: Direction, mtu: u16, budget: u32) -> Self { pub(crate) fn new(direction: Direction, mtu: u16, budget: u32) -> Self {
let packets = budget / u32::from(mtu); let packets = budget / u32::from(mtu);
@@ -39,6 +91,7 @@ impl Receiver {
mtu, mtu,
packets, packets,
seen: vec![0; packets.div_ceil(64) as usize], seen: vec![0; packets.div_ceil(64) as usize],
stage: 0,
window: None, window: None,
count: 0, count: 0,
best: 0, best: 0,
@@ -59,43 +112,50 @@ impl Receiver {
} }
*word |= bit; *word |= bit;
self.count += 1; self.count += 1;
if self.window.as_ref().is_none_or(|w| w.stage < probe.stage) { if probe.stage < self.stage {
self.window = Some(Window { return;
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 if probe.stage > self.stage {
&& w.stage == probe.stage self.finish_window();
self.stage = probe.stage;
}
match &mut self.window {
Some(window) => window.push(probe, now),
None => self.window = Some(Window::new(probe, now)),
}
}
fn finish_window(&mut self) {
if let Some(rate) = self.window.take().and_then(|w| w.rate(self.mtu)) {
self.best = self.best.max(rate);
}
}
pub(crate) fn finish(mut self, estimate: Reading) -> Reading {
self.finish_window();
// Final delivery belongs to the receiver. A sender may have stopped on its
// byte limit before receiving feedback for a faster, fully observed train.
if self.best == 0 {
return Reading {
bps: None,
bytes: self.bytes(),
quality: Quality::Insufficient,
};
}
if estimate.quality == Quality::Measured
&& let Some(rate) = estimate.bps
&& self.best.abs_diff(rate) <= rate / 5
{ {
if w.received == 0 { return Reading {
w.first_arrival = now; bps: Some(rate.min(self.best)),
w.last_group = now; bytes: self.bytes(),
w.arrival_groups = 1; quality: Quality::Measured,
w.first = probe.sequence; };
w.highest = probe.sequence; }
} else { Reading {
if w.arrival_groups < 3 bps: Some(self.best),
&& now.duration_since(w.last_group) >= Duration::from_millis(20) bytes: self.bytes(),
{ quality: Quality::AtLeast,
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);
} }
} }
@@ -107,45 +167,39 @@ impl Receiver {
// followed by silence must never turn into a capacity estimate. // followed by silence must never turn into a capacity estimate.
pub(crate) fn sample(&mut self, now: Instant, minimum: Duration) -> Option<Feedback> { pub(crate) fn sample(&mut self, now: Instant, minimum: Duration) -> Option<Feedback> {
let bytes = self.bytes(); let bytes = self.bytes();
let w = self.window.as_mut()?; let w = self.window.as_ref()?;
let elapsed = now.duration_since(w.start); let elapsed = now.duration_since(w.first_arrival);
if elapsed < minimum { if elapsed < minimum {
return None; return None;
} }
let span = w.highest - w.first + 1; let span = w.highest - w.first + 1;
let loss = (u64::from(span.saturating_sub(w.received)) * 1000 / u64::from(span)) as u16; 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); let rate = w.rate(self.mtu);
// The first packet of a stage starts its clock. Its bytes arrived before if rate.is_none() && elapsed < Duration::from_millis(600) {
// 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; return None;
} }
let bps = if enough { let bps = rate.unwrap_or(0);
(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 { let feedback = Feedback {
stage: w.stage, stage: self.stage,
bps, bps,
lost_per_mille: loss, lost_per_mille: loss,
bytes, bytes,
echo_us: w.last_send_us, echo_us: w.last_send_us,
}; };
w.start = now; self.window = None;
w.received = 0; self.best = self.best.max(bps);
w.starts_on_packet = false;
if bps > 0 {
self.best = self.best.max(bps);
}
Some(feedback) Some(feedback)
} }
} }
#[derive(Clone, Copy)]
enum Phase {
Ramp,
// A rate backed off from congestion needs another, higher offer to test it.
Settle { verified: bool },
Challenge { previous_rate: u64 },
}
pub(crate) struct Search { pub(crate) struct Search {
pub(crate) stage: u8, pub(crate) stage: u8,
pub(crate) target: u64, pub(crate) target: u64,
@@ -153,7 +207,7 @@ pub(crate) struct Search {
baseline_delay: Option<u32>, baseline_delay: Option<u32>,
initial_loss: Option<u16>, initial_loss: Option<u16>,
last_echo: Option<u32>, last_echo: Option<u32>,
confirm: bool, phase: Phase,
previous: Option<u64>, previous: Option<u64>,
measured: Option<u64>, measured: Option<u64>,
} }
@@ -167,7 +221,7 @@ impl Default for Search {
baseline_delay: None, baseline_delay: None,
initial_loss: None, initial_loss: None,
last_echo: None, last_echo: None,
confirm: false, phase: Phase::Ramp,
previous: None, previous: None,
measured: None, measured: None,
} }
@@ -190,34 +244,53 @@ impl Search {
let base = *self.baseline_delay.get_or_insert(delay); let base = *self.baseline_delay.get_or_insert(delay);
self.baseline_delay = Some(base.min(delay)); self.baseline_delay = Some(base.min(delay));
let queuing = delay > base.saturating_add(45_000).max(base.saturating_mul(2)); 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. // Loss present at the first offer also reduces the payload rate that
// Reduce on growing loss, queue delay or a receiver rate below the offer. // can arrive at higher offers. Look for additional loss or queuing.
// A very lossy first sample may already be an overloaded slow path.
let baseline_loss = *self let baseline_loss = *self
.initial_loss .initial_loss
.get_or_insert(sample.lost_per_mille.min(100)); .get_or_insert(sample.lost_per_mille.min(400));
let expected = self.target * u64::from(1000 - baseline_loss) / 1000;
let congested = let congested =
sample.lost_per_mille > baseline_loss + 30 || bps < self.target * 4 / 5 || queuing; sample.lost_per_mille > baseline_loss + 30 || bps < expected * 4 / 5 || queuing;
if congested { if congested {
self.confirm = true; let verified = match self.phase {
Phase::Challenge { previous_rate } => {
bps.abs_diff(previous_rate) <= previous_rate / 5
}
Phase::Settle { verified } => verified && bps >= self.target * 4 / 5,
Phase::Ramp => false,
};
self.phase = Phase::Settle { verified };
self.previous = None; self.previous = None;
self.offer(if bps == 0 { self.offer(if bps == 0 {
self.target / 2 self.target / 2
} else { } else {
bps * 97 / 100 bps * 97 / 100
}); });
} else if self.confirm { } else if let Phase::Settle { verified } = self.phase {
if sample.lost_per_mille > 100 { if sample.lost_per_mille > 100 {
self.previous = None; self.previous = None;
return; return;
} }
if let Some(prev) = self.previous if let Some(prev) = self.previous.replace(bps)
&& prev.abs_diff(bps) <= bps / 6 && prev.abs_diff(bps) <= bps / 6
{ {
self.measured = Some((prev + bps) / 2); let steady = (prev + bps) / 2;
} else { if verified {
self.previous = Some(bps); self.measured = Some(steady);
} else if elapsed_us >= 850_000 {
// A cold tunnel or one busy scheduler slice can look like a bottleneck.
// Two samples at our own reduced rate prove only that we can sustain it.
self.phase = Phase::Challenge {
previous_rate: steady,
};
self.offer(steady * 2);
self.previous = None;
}
} }
} else if self.target < MAX_BPS { } else if self.target < MAX_BPS {
self.phase = Phase::Ramp;
self.offer(self.target.saturating_mul(4)); self.offer(self.target.saturating_mul(4));
} }
} }
@@ -272,7 +345,10 @@ impl Pacer {
pub(crate) fn packets(&mut self, now: Instant, bps: u64) -> u32 { 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. // 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; let elapsed = now
.duration_since(self.last_tick)
.as_nanos()
.min(12_000_000) as u64;
self.last_tick = now; self.last_tick = now;
self.credit += elapsed * bps; self.credit += elapsed * bps;
let packets = self.credit / self.cost; let packets = self.credit / self.cost;
@@ -323,11 +399,8 @@ mod tests {
); );
assert_eq!(rx.count, 3); assert_eq!(rx.count, 3);
assert_eq!(rx.bytes(), 3 * u32::from(1280 - HEADER)); assert_eq!(rx.bytes(), 3 * u32::from(1280 - HEADER));
assert!( assert_eq!(rx.stage, 1);
rx.window assert!(rx.window.as_ref().is_some_and(|w| w.received == 2));
.as_ref()
.is_some_and(|w| w.stage == 1 && w.received == 2)
);
} }
#[test] #[test]
@@ -351,6 +424,38 @@ mod tests {
const NORMAL_BYTES_FOR_TEST: u32 = 1024 * 1024; const NORMAL_BYTES_FOR_TEST: u32 = 1024 * 1024;
#[test]
fn final_rate_uses_delivered_payload_even_when_end_overtakes_feedback() {
let start = Instant::now();
let mut rx = Receiver::new(Direction::Download, 1280, NORMAL_BYTES_FOR_TEST);
// The first train takes twice as long to arrive as to send. The faster
// second train ends before the next feedback tick.
for i in 0..=100 {
rx.put(
packet(i, 0, i * 1_000),
start + Duration::from_millis(u64::from(i) * 2),
);
}
let tick = Duration::from_millis(220);
let initial = rx.sample(start + tick, tick).unwrap();
let payload_bits = u64::from(1280 - HEADER) * 8;
assert_eq!(initial.bps, payload_bits * 500);
for i in 0..=100 {
rx.put(
packet(101 + i, 1, 250_000 + i * 1_000),
start + Duration::from_millis(250 + u64::from(i)),
);
}
let result = rx.finish(Reading {
bytes: initial.bytes,
bps: Some(initial.bps),
quality: Quality::AtLeast,
});
assert_eq!(result.bps, Some(payload_bits * 1000));
assert_eq!(result.quality, Quality::AtLeast);
assert_eq!(result.bytes, 202 * u32::from(1280 - HEADER));
}
#[test] #[test]
fn retransmitted_feedback_does_not_supply_two_confirmation_windows() { fn retransmitted_feedback_does_not_supply_two_confirmation_windows() {
let mut search = Search::default(); let mut search = Search::default();
@@ -367,6 +472,12 @@ mod tests {
search.observe(observed, 243_000); search.observe(observed, 243_000);
assert!(!search.done()); assert!(!search.done());
search.observe(f(1, 970_000, 0, 45000, 360_000), 361_000); search.observe(f(1, 970_000, 0, 45000, 360_000), 361_000);
assert!(!search.done());
search.observe(f(1, 970_000, 0, 100_000, 900_000), 901_000);
assert_eq!(search.stage, 2);
search.observe(f(2, 1_000_000, 450, 120_000, 1_060_000), 1_061_000);
search.observe(f(3, 970_000, 0, 150_000, 1_220_000), 1_221_000);
search.observe(f(3, 970_000, 0, 180_000, 1_380_000), 1_381_000);
assert!(search.done()); assert!(search.done());
} }
} }
+138 -8
View File
@@ -14,6 +14,7 @@ struct Link {
remote: Handle, remote: Handle,
start: Instant, start: Instant,
rate: u64, rate: u64,
warmup: Option<(Duration, u64)>,
control_delay: Duration, control_delay: Duration,
drop_every: u32, drop_every: u32,
state: Arc<Mutex<Delivery>>, state: Arc<Mutex<Delivery>>,
@@ -45,11 +46,14 @@ impl Io for Link {
fn packet(&self, packet: Bytes) -> bool { fn packet(&self, packet: Bytes) -> bool {
let probe = decode_packet(&packet).unwrap(); let probe = decode_packet(&packet).unwrap();
let tick = self.start.elapsed().as_millis() as u64; let tick = self.start.elapsed().as_millis() as u64;
let rate = self
.warmup
.filter(|(until, _)| self.start.elapsed() < *until)
.map_or(self.rate, |(_, rate)| rate);
let mut state = self.state.lock().unwrap(); let mut state = self.state.lock().unwrap();
if state.tick != tick { if state.tick != tick {
let elapsed = tick - state.tick; let elapsed = tick - state.tick;
state.credit = state.credit = (state.credit + rate * elapsed / 8000).min(rate * 4 / 8000 + 1300);
(state.credit + self.rate * elapsed / 8000).min(self.rate * 4 / 8000 + 1300);
state.tick = tick; state.tick = tick;
} }
state.bytes += packet.len() as u64; state.bytes += packet.len() as u64;
@@ -83,7 +87,7 @@ fn config(local: u8, remote: u8, bytes: u32) -> Config {
} }
async fn measure(down: u64, up: u64, budget: u32) -> (Progress, Progress, Link, Link) { async fn measure(down: u64, up: u64, budget: u32) -> (Progress, Progress, Link, Link) {
shaped(down, up, budget, Duration::ZERO, 0).await shaped(down, up, budget, Duration::ZERO, 0, None).await
} }
async fn shaped( async fn shaped(
@@ -92,6 +96,7 @@ async fn shaped(
budget: u32, budget: u32,
control_delay: Duration, control_delay: Duration,
drop_every: u32, drop_every: u32,
warmup: Option<(Duration, u64)>,
) -> (Progress, Progress, Link, Link) { ) -> (Progress, Progress, Link, Link) {
let cfg = |a, b| Config { let cfg = |a, b| Config {
rtt: control_delay.max(Duration::from_millis(20)), rtt: control_delay.max(Duration::from_millis(20)),
@@ -105,7 +110,8 @@ async fn shaped(
}; };
let (b, responder) = respond(cfg(2, 1), start); let (b, responder) = respond(cfg(2, 1), start);
let now = Instant::now(); let now = Instant::now();
let link = |remote, rate| Link { let link = |remote, rate, warmup| Link {
warmup,
remote, remote,
start: now, start: now,
rate, rate,
@@ -114,9 +120,13 @@ async fn shaped(
state: Default::default(), state: Default::default(),
samples: Default::default(), samples: Default::default(),
}; };
let ab = link(b, up); let ab = link(b, up, None);
let ba = link(a, down); let ba = link(a, down, warmup);
let (a, b) = tokio::join!(initiator.run(ab.clone()), responder.run(ba.clone())); let (a, b) = tokio::join!(initiator.run(ab.clone()), responder.run(ba.clone()));
println!(
"Shaped path {down}/{up} bit/s, receiver readings {:?}/{:?}",
a.down.bps, a.up.bps
);
assert!(now.elapsed() <= Duration::from_secs(5)); assert!(now.elapsed() <= Duration::from_secs(5));
assert!(ab.state.lock().unwrap().bytes <= u64::from(budget)); assert!(ab.state.lock().unwrap().bytes <= u64::from(budget));
assert!(ba.state.lock().unwrap().bytes <= u64::from(budget)); assert!(ba.state.lock().unwrap().bytes <= u64::from(budget));
@@ -173,6 +183,7 @@ async fn persistent_random_loss_does_not_masquerade_as_a_slow_link() {
NORMAL_BYTES, NORMAL_BYTES,
Duration::from_millis(45), Duration::from_millis(45),
20, 20,
None,
) )
.await; .await;
assert_eq!(a.state, State::Complete); assert_eq!(a.state, State::Complete);
@@ -299,6 +310,7 @@ async fn slower_control_feedback_leaves_time_for_both_directions() {
NORMAL_BYTES, NORMAL_BYTES,
Duration::from_millis(130), Duration::from_millis(130),
0, 0,
None,
) )
.await; .await;
assert_eq!(a, b); assert_eq!(a, b);
@@ -329,10 +341,22 @@ async fn slow_links_accumulate_enough_arrivals_for_a_rate() {
#[tokio::test(start_paused = true)] #[tokio::test(start_paused = true)]
async fn persistent_heavy_loss_reports_only_sustained_lower_bounds() { async fn persistent_heavy_loss_reports_only_sustained_lower_bounds() {
let (a, _, _, _) = shaped(50_000_000, 50_000_000, NORMAL_BYTES, Duration::ZERO, 3).await; let (a, _, _, _) = shaped(
50_000_000,
50_000_000,
NORMAL_BYTES,
Duration::ZERO,
3,
None,
)
.await;
for r in [a.down, a.up] { for r in [a.down, a.up] {
assert_eq!(r.quality, Quality::AtLeast, "{r:?}"); assert_eq!(r.quality, Quality::AtLeast, "{r:?}");
assert!(r.bps.is_some_and(|v| (100_000..=33_500_000).contains(&v))); assert!(
r.bps
.is_some_and(|v| (28_000_000..=36_000_000).contains(&v)),
"{r:?}"
);
} }
} }
@@ -351,3 +375,109 @@ fn a_finished_rate_requires_evidence_of_delivered_payload() {
assert!(Control::decode(&message.encode().unwrap()).is_none()); assert!(Control::decode(&message.encode().unwrap()).is_none());
} }
} }
#[tokio::test(start_paused = true)]
async fn a_cold_download_reprobes_after_the_path_warms_up() {
let (result, _, _, _) = shaped(
300_000_000,
250_000_000,
NORMAL_BYTES,
Duration::ZERO,
0,
Some((Duration::from_millis(850), 60_000_000)),
)
.await;
for (reading, expected) in [(result.down, 300_000_000), (result.up, 250_000_000)] {
assert!(
reading
.bps
.is_some_and(|rate| (expected * 8 / 10..=expected * 11 / 10).contains(&rate)),
"{result:?}"
);
}
}
#[tokio::test(start_paused = true)]
async fn delayed_feedback_does_not_hide_the_metered_receivers_last_sustained_rate() {
let (result, _, _, _) = shaped(
350_000_000,
200_000_000,
METERED_BYTES,
Duration::from_millis(95),
0,
None,
)
.await;
for (reading, expected) in [(result.down, 350_000_000), (result.up, 200_000_000)] {
assert!(
reading
.bps
.is_some_and(|rate| (expected * 75 / 100..=expected * 11 / 10).contains(&rate)),
"{result:?}"
);
}
}
#[tokio::test(start_paused = true)]
async fn a_full_tunnel_charges_only_packets_actually_submitted_to_it() {
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
struct BusyQueue {
other: Handle,
start: Instant,
stalled: AtomicBool,
submitted: AtomicU32,
}
impl Io for BusyQueue {
async fn control(&self, message: Control) -> bool {
if let Control::End { packets, .. } = message {
assert!(self.stalled.load(Ordering::Relaxed));
assert_eq!(packets, self.submitted.load(Ordering::Relaxed));
}
if !matches!(message, Control::Start(_)) {
self.other.control(message);
}
true
}
fn packet(&self, packet: Bytes) -> bool {
let count = self.submitted.fetch_add(1, Ordering::Relaxed);
let full = self.start.elapsed() > Duration::from_millis(180) && count.is_multiple_of(3);
if full {
self.stalled.store(true, Ordering::Relaxed);
}
// A backpressured tunnel may drop the packet or retain it for a
// pending handshake. Either outcome must respect the byte budget.
if !full || count.is_multiple_of(2) {
self.other.data(decode_packet(&packet).unwrap());
}
!full
}
fn progress(&self, _: Progress) {}
}
let budget = 2 * 1024 * 1024;
let (a, outgoing) = initiate(config(1, 2, budget));
let (b, incoming) = respond(
config(2, 1, budget),
Start {
id: 7,
byte_limit: budget,
mtu: 1280,
},
);
let queue = |other| BusyQueue {
other,
start: Instant::now(),
stalled: AtomicBool::new(false),
submitted: AtomicU32::new(0),
};
let (initiator, responder) = tokio::join!(
outgoing.run(queue(b.clone())),
incoming.run(queue(a.clone()))
);
assert_eq!(initiator.state, State::Complete);
assert_eq!(initiator, responder);
}
+2 -2
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "tsunagi-tcp-tls" name = "tsunagi-tcp-tls"
version = "1.0.6" version = "1.0.7"
description = "TCP TLS carrier for independently encrypted tsunagi mesh traffic." description = "TCP TLS carrier for independently encrypted tsunagi mesh traffic."
edition.workspace = true edition.workspace = true
rust-version.workspace = true rust-version.workspace = true
@@ -8,7 +8,7 @@ license.workspace = true
repository.workspace = true repository.workspace = true
[dependencies] [dependencies]
tsunagi-core = { path = "../tsunagi-core", version = "1.0.6" } tsunagi-core = { path = "../tsunagi-core", version = "1.0.7" }
iroh.workspace = true iroh.workspace = true
tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] } tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] }
rustls = "0.23" rustls = "0.23"
+2 -2
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "tsunagi-tray" name = "tsunagi-tray"
version = "1.0.6" version = "1.0.7"
description = "Tray application to manage a running tsunagi agent." description = "Tray application to manage a running tsunagi agent."
edition.workspace = true edition.workspace = true
rust-version.workspace = true rust-version.workspace = true
@@ -16,7 +16,7 @@ tsunagi-ui = { path = "../tsunagi-ui" }
# The agent control client and the report types: the GUI is a thin client over # The agent control client and the report types: the GUI is a thin client over
# the same local control interface the CLI uses, so it reuses these directly # the same local control interface the CLI uses, so it reuses these directly
# and never re-implements the protocol. # and never re-implements the protocol.
tsunagi-core = { path = "../tsunagi-core", version = "1.0.6" } tsunagi-core = { path = "../tsunagi-core", version = "1.0.7" }
# Native, lightweight GUI — no web engine. eframe re-exports egui. # Native, lightweight GUI — no web engine. eframe re-exports egui.
eframe = { version = "0.31", default-features = false, features = ["default_fonts", "glow", "wayland", "x11"] } eframe = { version = "0.31", default-features = false, features = ["default_fonts", "glow", "wayland", "x11"] }
# Cross-platform tray icon + menu (Windows tray, macOS menu bar, Linux SNI). # Cross-platform tray icon + menu (Windows tray, macOS menu bar, Linux SNI).
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "tsunagi-ui" name = "tsunagi-ui"
version = "1.0.6" version = "1.0.7"
description = "Shared egui widgets for the tray and Android clients." description = "Shared egui widgets for the tray and Android clients."
edition.workspace = true edition.workspace = true
rust-version.workspace = true rust-version.workspace = true
+71 -34
View File
@@ -37,45 +37,82 @@ impl Column {
} }
} }
fn columns(ui: &Ui, width: f32, landscape: bool, unit: Unit) -> Vec<(Column, f32)> { fn columns(
ui: &Ui,
width: f32,
landscape: bool,
unit: Unit,
members: &[Device<'_>],
) -> Vec<(Column, f32)> {
let font = egui::TextStyle::Body.resolve(ui.style()); let font = egui::TextStyle::Body.resolve(ui.style());
let measure = |s: &str| { let text_width = |s: &str| {
ui.painter() ui.painter()
.layout_no_wrap(s.into(), font.clone(), Color32::WHITE) .layout_no_wrap(s.into(), font.clone(), Color32::WHITE)
.size() .size()
.x .x
+ 10.
}; };
let mut cols = vec![ let measure = |s: &str| text_width(s) + 10.;
(Column::Device, 0.), let disclosure = text_width(icon::CARET_RIGHT) + 3.;
( let name = 20. + text_width("device") + 3.;
Column::Speed, let available = width - name - disclosure;
if landscape { let small_speed = speed::PORTRAIT_WIDTH.min(width * 0.18);
speed::WIDTH.min(width * 0.28) let address = measure("255.255.255.255").min(width * if landscape { 0.27 } else { 0.35 });
} else { let rtt = measure("Data RTT")
speed::PORTRAIT_WIDTH.min(width * 0.18) .max(measure("9999 ms"))
}, .min(width * if landscape { 0.15 } else { 0.22 });
), let traffic = (landscape && width >= 420.)
]; .then(|| {
if landscape && width >= 510. { // Account for both rounded values (up to 1024.0) and the unit
cols.push((Column::State, measure("Control only").min(width * 0.16))); // suffixes in the actual body font, independently of the live bytes.
let digit = ui.fonts(|fonts| {
('0'..='9')
.max_by(|a, b| {
fonts
.glyph_width(&font, *a)
.total_cmp(&fonts.glyph_width(&font, *b))
})
.unwrap_or('0')
});
let number = format!("{digit}{digit}{digit}{digit}.{digit}");
let bytes_width = format::BYTE_UNITS.iter().fold(0.0_f32, |w, suffix| {
w.max(measure(&format!("{number} {suffix} / {number} {suffix}")))
});
let floor = bytes_width.max(measure(Column::Traffic.title(unit)));
match unit {
Unit::Bytes => floor,
Unit::Packets => members
.iter()
.filter(|m| m.online)
.filter_map(|m| m.overlay)
.fold(floor, |w, p| {
w.max(measure(&traffic_pair(p.tx_packets, p.rx_packets, unit)))
}),
}
})
// An unusually long packet count can use the end of the device name,
// but always leave room for its status icon and disclosure.
.filter(|w| w + small_speed + 20. + text_width("…") + 3. + disclosure <= width);
let mut spare = available - traffic.unwrap_or_default();
let state = (landscape && width >= 510.).then(|| measure("Control only"));
let speed = if landscape && speed::WIDTH + address + rtt + state.unwrap_or_default() <= spare {
speed::WIDTH
} else {
small_speed
};
spare -= speed;
let mut cols = vec![(Column::Device, 0.), (Column::Speed, speed)];
for (column, want) in [(Column::Address, address), (Column::Rtt, rtt)] {
if spare >= want {
cols.push((column, want));
spare -= want;
}
} }
cols.push(( if let Some(w) = state.filter(|w| *w <= spare) {
Column::Address, cols.insert(2, (Column::State, w));
measure("255.255.255.255").min(width * if landscape { 0.27 } else { 0.35 }), spare -= w;
)); }
cols.push(( if let Some(w) = traffic {
Column::Rtt, cols.push((Column::Traffic, w));
measure("9999 ms").min(width * if landscape { 0.15 } else { 0.22 }),
));
if landscape && width >= 420. {
cols.push((
Column::Traffic,
measure(Column::Traffic.title(unit))
.max(measure("999 MB / 999 MB"))
.min(width * 0.29),
));
let mut spare = width - cols.iter().map(|c| c.1).sum::<f32>() - 122.;
for (column, desire) in [ for (column, desire) in [
(Column::Version, measure("v1.0.4-rc.1")), (Column::Version, measure("v1.0.4-rc.1")),
(Column::Path, measure("tcp-tls direct")), (Column::Path, measure("tcp-tls direct")),
@@ -90,7 +127,7 @@ fn columns(ui: &Ui, width: f32, landscape: bool, unit: Unit) -> Vec<(Column, f32
} }
let other: f32 = cols.iter().map(|c| c.1).sum(); let other: f32 = cols.iter().map(|c| c.1).sum();
// Reserve the disclosure arrow at the end, including on small split screens. // Reserve the disclosure arrow at the end, including on small split screens.
cols[0].1 = (width - other - 16.).max(0.); cols[0].1 = (width - other - disclosure).max(0.);
cols cols
} }
@@ -117,7 +154,7 @@ pub(super) fn roster(
let id = egui::Id::new(("expanded device", &network.network_id)); let id = egui::Id::new(("expanded device", &network.network_id));
let mut selected = ui.data(|d| d.get_temp::<String>(id)); let mut selected = ui.data(|d| d.get_temp::<String>(id));
let width = ui.available_width(); let width = ui.available_width();
let columns = columns(ui, width, widgets::landscape(ui.ctx()), unit); let columns = columns(ui, width, widgets::landscape(ui.ctx()), unit, members);
let font = egui::TextStyle::Body.resolve(ui.style()); let font = egui::TextStyle::Body.resolve(ui.style());
let size = vec2(width, ui.text_style_height(&egui::TextStyle::Body) + 9.); let size = vec2(width, ui.text_style_height(&egui::TextStyle::Body) + 9.);
ui.spacing_mut().item_spacing.y = 1.; ui.spacing_mut().item_spacing.y = 1.;
+8 -11
View File
@@ -217,27 +217,25 @@ fn activity(ui: &Ui, rect: Rect, color: Color32) {
// Round positive lower bounds down so the displayed minimum is supported by // Round positive lower bounds down so the displayed minimum is supported by
// the measurement, including near a precision or unit boundary. // the measurement, including near a precision or unit boundary.
fn rate_number(rate: SpeedRate, divisor: f64, precision: usize) -> String { fn detailed_rate(rate: SpeedRate, divisor: f64) -> String {
let mut value = rate.bps as f64 / divisor; let value = rate.bps as f64 / divisor;
if rate.lower_bound { if rate.lower_bound {
let scale = 10_f64.powi(precision as i32); format!("at least {:.2}", (value * 100.).floor() / 100.)
value = (value * scale).floor() / scale; } else {
format!("{value:.2}")
} }
format!("{value:.precision$}")
} }
fn compact_rate(rate: SpeedRate) -> String { fn compact_rate(rate: SpeedRate) -> String {
let bound = if rate.lower_bound { "≥" } else { "" };
let (unit, precision, suffix) = match rate.bps { let (unit, precision, suffix) = match rate.bps {
0 => return "0".into(), 0 => return "0".into(),
1..10_000 if rate.lower_bound => return ">0".into(),
1..10_000 => return "<0.01".into(), 1..10_000 => return "<0.01".into(),
10_000..1_000_000 => (1e6, 2, ""), 10_000..1_000_000 => (1e6, 2, ""),
1_000_000..10_000_000 => (1e6, 1, ""), 1_000_000..10_000_000 => (1e6, 1, ""),
10_000_000..10_000_000_000 => (1e6, 0, ""), 10_000_000..10_000_000_000 => (1e6, 0, ""),
_ => (1e9, 0, "k"), _ => (1e9, 0, "k"),
}; };
format!("{bound}{}{suffix}", rate_number(rate, unit, precision)) format!("{:.precision$}{suffix}", rate.bps as f64 / unit)
} }
fn tooltip( fn tooltip(
@@ -265,10 +263,9 @@ fn tooltip(
} else { } else {
(1e6, "Mbit/s") (1e6, "Mbit/s")
}; };
let bound = if rate.lower_bound { "at least " } else { "" };
hint.push_str(&format!( hint.push_str(&format!(
"\n{label} {bound}{} {suffix}", "\n{label} {} {suffix}",
rate_number(rate, divisor, 2) detailed_rate(rate, divisor)
)); ));
} }
} }
+6 -4
View File
@@ -178,15 +178,17 @@ fn live_and_completed_readings_keep_the_same_row_and_tapping_retests_a_non_exit_
); );
} }
let done = s.frame(&n, vec![]); let done = s.frame(&n, vec![]);
for value in ["125", "≥35"] { let down_text = format!("{} 125", icon::ARROW_DOWN);
let lines = positions(&done, |s| s.ends_with(value)); let up_text = format!("{} 36", icon::ARROW_UP);
for value in [&down_text, &up_text] {
let lines = positions(&done, |s| s == value);
assert_eq!(lines.len(), 1); assert_eq!(lines.len(), 1);
assert!((lines[0].x - button.x).abs() < 31.); assert!((lines[0].x - button.x).abs() < 31.);
assert!((lines[0].y - button.y).abs() < 12.); assert!((lines[0].y - button.y).abs() < 12.);
assert!(lines[0].x < width); assert!(lines[0].x < width);
} }
let down = positions(&done, |s| s.ends_with("125"))[0]; let down = positions(&done, |s| s == down_text)[0];
let up = positions(&done, |s| s.ends_with("≥35"))[0]; let up = positions(&done, |s| s == up_text)[0];
if width > 650. { if width > 650. {
assert!( assert!(
(down.y - up.y).abs() < 1. && down.x < up.x, (down.y - up.y).abs() < 1. && down.x < up.x,
+5 -3
View File
@@ -22,19 +22,21 @@ pub fn short(id: &str) -> String {
} }
} }
/// Display units for the whole range of the agent's 64-bit byte counters.
pub(crate) const BYTE_UNITS: [&str; 7] = ["B", "kB", "MB", "GB", "TB", "PB", "EB"];
/// A byte count in binary units. /// A byte count in binary units.
pub fn bytes(n: f64) -> String { pub fn bytes(n: f64) -> String {
const UNITS: [&str; 5] = ["B", "kB", "MB", "GB", "TB"];
let mut value = n.max(0.0); let mut value = n.max(0.0);
let mut unit = 0; let mut unit = 0;
while value >= 1024.0 && unit < UNITS.len() - 1 { while value >= 1024.0 && unit < BYTE_UNITS.len() - 1 {
value /= 1024.0; value /= 1024.0;
unit += 1; unit += 1;
} }
if unit == 0 { if unit == 0 {
format!("{} B", value as u64) format!("{} B", value as u64)
} else { } else {
format!("{value:.1} {}", UNITS[unit]) format!("{value:.1} {}", BYTE_UNITS[unit])
} }
} }
+106
View File
@@ -260,3 +260,109 @@ fn rotating_the_devices_view_keeps_the_peer_and_fits_traffic_and_states_on_scree
} }
assert!(label(&draw(portrait, 4., vec![]), "Endpoint ID").is_some()); assert!(label(&draw(portrait, 4., vec![]), "Endpoint ID").is_some());
} }
#[test]
fn compact_roster_reserves_the_full_tx_rx_pair_as_counters_grow() {
use egui::os::OperatingSystem::{Android, Mac};
for (os, width, font_size, density) in [
(Android, 480., 13., 1.),
(Mac, 600., 13., 2.),
(Mac, 740., 13., 1.),
(Android, 800., 19., 2.625),
] {
let ctx = Context::default();
ctx.set_os(os);
ctx.set_fonts(crate::app_fonts());
ctx.style_mut(|style| {
style
.text_styles
.insert(egui::TextStyle::Body, egui::FontId::proportional(font_size));
});
let mut net = NetworkReport {
name: "lab".into(),
peers: vec![PeerReport {
endpoint_id: "alpha".into(),
hostname: Some("alpha".into()),
agent_version: Some("1.0.6".into()),
..Default::default()
}],
..Default::default()
};
let mut input = egui::RawInput {
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, egui::vec2(width, 320.))),
..Default::default()
};
input
.viewports
.get_mut(&egui::ViewportId::ROOT)
.unwrap()
.native_pixels_per_point = Some(density);
let mut first_cell = None;
for (mut unit, tx, rx, expected) in [
(Unit::Bytes, 0, 0, "0 B / 0 B"),
(Unit::Bytes, 293_069, 294_400, "286.2 kB / 287.5 kB"),
(
Unit::Bytes,
(1 << 30) - 1,
(1 << 20) - 1,
"1024.0 MB / 1024.0 kB",
),
(Unit::Bytes, u64::MAX, 1 << 50, "16.0 EB / 1.0 PB"),
(Unit::Packets, 1_234_567, 7_654_321, "1234567 / 7654321"),
(
Unit::Packets,
u64::MAX,
u64::MAX - 1,
"18446744073709551615 / 18446744073709551614",
),
] {
net.overlay = Some(OverlayReport {
peers: vec![OverlayPeerReport {
endpoint_id: "alpha".into(),
tx_bytes: tx,
rx_bytes: rx,
tx_packets: tx,
rx_packets: rx,
..Default::default()
}],
..Default::default()
});
let output = ctx.run(input.clone(), |ctx| {
devices::show(
ctx,
&ReadOnly,
&mut unit,
(&mut None, &mut None),
&net,
"self",
&Traffic::default(),
);
});
let (text, cell) = output
.shapes
.iter()
.find_map(|s| match &s.shape {
egui::Shape::Text(t) if t.galley.text() == expected => Some((t, s.clip_rect)),
_ => None,
})
.unwrap_or_else(|| panic!("missing {expected} at {width}"));
assert!(!text.galley.elided, "{expected} truncated at {width}");
assert!(
cell.contains_rect(text.visual_bounding_rect()),
"{expected} clipped"
);
assert!(cell.left() >= 0. && cell.right() <= width);
if unit == Unit::Bytes {
let bounds = (cell.left(), cell.right());
assert_eq!(*first_cell.get_or_insert(bounds), bounds);
}
assert!(label(&output, "alpha").unwrap().right() <= cell.left());
let disclosure = label(&output, icon::CARET_RIGHT).unwrap();
assert!(cell.right() <= disclosure.left() && disclosure.right() <= width);
if let Some(version) = label(&output, "v1.0.6") {
assert!(cell.right() <= version.left() && version.right() <= disclosure.left());
}
}
}
}
+2 -2
View File
@@ -3,7 +3,7 @@ name = "tsunagi-wg-quic"
# Its own version, and deliberately separate from the wire version it # Its own version, and deliberately separate from the wire version it
# negotiates: a release here does not stop it talking to a peer on an older # negotiates: a release here does not stop it talking to a peer on an older
# build, because what peers compare is `ANNOUNCEMENT_VERSION`. # build, because what peers compare is `ANNOUNCEMENT_VERSION`.
version = "1.0.6" version = "1.0.7"
description = "The single internal WireGuard tunnel for tsunagi, independent of external carriers." description = "The single internal WireGuard tunnel for tsunagi, independent of external carriers."
edition.workspace = true edition.workspace = true
rust-version.workspace = true rust-version.workspace = true
@@ -11,7 +11,7 @@ license.workspace = true
repository.workspace = true repository.workspace = true
[dependencies] [dependencies]
tsunagi-core = { path = "../tsunagi-core", version = "1.0.6" } tsunagi-core = { path = "../tsunagi-core", version = "1.0.7" }
iroh.workspace = true iroh.workspace = true
tokio.workspace = true tokio.workspace = true
serde.workspace = true serde.workspace = true
+34
View File
@@ -2220,3 +2220,37 @@ async fn peer_speed_measures_both_wireguard_directions_and_can_be_repeated() {
a.shutdown().await; a.shutdown().await;
b.shutdown().await; b.shutdown().await;
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore = "throughput varies with CPU and runner load; run with --nocapture"]
async fn sample_encrypted_loopback_speed() {
use tsunagi::ipc::SpeedPhase;
let discovery = SharedMemoryDiscovery::new();
let (name, secret) = network("loopback-speed-sample");
let a = WgAgent::spawn(&discovery, "speeda").await;
let b = WgAgent::spawn(&discovery, "speedb").await;
let net = a.agent.join_network(&name, &secret).await.unwrap();
b.agent.join_network(&name, &secret).await.unwrap();
a.wait_for_tunnels(net, 1).await;
b.wait_for_tunnels(net, 1).await;
let peer = b.agent.endpoint_id();
for metered in [false, true, false, true] {
a.agent
.start_speed_test(net, Some(peer), metered)
.await
.unwrap();
let report = wait_until("both directions completed", || async {
let status = a.agent.network_status(net).await.ok()?.speed;
let p = status.peers.get(&peer.to_string())?;
matches!(p.phase, SpeedPhase::Done | SpeedPhase::Failed(_)).then(|| p.clone())
})
.await;
println!(
"metered={metered} down={:?} up={:?} bytes={} time={}ms",
report.down, report.up, report.bytes, report.elapsed_ms
);
assert_eq!(report.phase, SpeedPhase::Done);
}
a.shutdown().await;
b.shutdown().await;
}
+2 -2
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "tsunagi-wireguard" name = "tsunagi-wireguard"
version = "1.0.6" version = "1.0.7"
description = "Independent authenticated WireGuard and Amnezia UDP carriers for tsunagi." description = "Independent authenticated WireGuard and Amnezia UDP carriers for tsunagi."
edition.workspace = true edition.workspace = true
rust-version.workspace = true rust-version.workspace = true
@@ -8,7 +8,7 @@ license = "WTFPL AND Apache-2.0"
repository.workspace = true repository.workspace = true
[dependencies] [dependencies]
tsunagi-core = { path = "../tsunagi-core", version = "1.0.6" } tsunagi-core = { path = "../tsunagi-core", version = "1.0.7" }
iroh.workspace = true iroh.workspace = true
tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] } tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] }
serde.workspace = true serde.workspace = true
+6 -6
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "tsunagi" name = "tsunagi"
version = "1.0.6" version = "1.0.7"
description = "The tsunagi command line agent." description = "The tsunagi command line agent."
edition.workspace = true edition.workspace = true
rust-version.workspace = true rust-version.workspace = true
@@ -12,11 +12,11 @@ name = "tsng"
path = "src/main.rs" path = "src/main.rs"
[dependencies] [dependencies]
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.6" } tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.7" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.6", features = ["tun-device", "dns-publish"] } tsunagi-core = { path = "../tsunagi-core", version = "1.0.7", features = ["tun-device", "dns-publish"] }
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.6" } tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.7" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.6" } tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.7" }
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.6" } tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.7" }
iroh.workspace = true iroh.workspace = true
tokio = { version = "1.53", features = ["rt", "rt-multi-thread", "sync", "time", "macros", "signal"] } tokio = { version = "1.53", features = ["rt", "rt-multi-thread", "sync", "time", "macros", "signal"] }
tracing.workspace = true tracing.workspace = true
+1 -1
View File
@@ -34,7 +34,7 @@ let
in in
rustPlatform.buildRustPackage { rustPlatform.buildRustPackage {
pname = if withTray then "tsunagi" else "tsunagi-cli"; pname = if withTray then "tsunagi" else "tsunagi-cli";
version = "1.0.6"; version = "1.0.7";
src = lib.cleanSource ../.; src = lib.cleanSource ../.;
cargoLock.lockFile = ../Cargo.lock; cargoLock.lockFile = ../Cargo.lock;