Keep the devices window responsive and make traffic flows sortable

A waiting peer or speed-test animation in an immediate egui viewport
repainted the parent and its other windows. Each pass also supersampled
the same 64-pixel logo and handed the new allocation to the OS. Give
each Devices window its own repaint schedule. Wake it when status or
shared controls change, reuse the native icon, and skip measuring the
wide roster when its remembered minimum width exceeds the viewport.
Use the bundled Phosphor StopCircle for single and batch tests.

Bind incoming throughput probes to the signed address pair for the
running diagnostic. Cache its validity across packets under a routing
revision. A change of ownership, including removal or reassignment,
revalidates the pair under the routing read lock. This removes a lock
and a linear peer search from the steady-state receive path and keeps
the timing, byte limits and wire protocol compatible.

Give the traffic inspector a pinned header and compact, aligned rows
with readable text in both themes. The column chooser keeps the peer
visible on a narrow screen. Clicking a header sorts the complete
filtered capture with a stable cursor across pages. Maintain one sort
index on the window's scratch database and expire idle rates there.
Address sorting uses numeric IP and port values. Peer and network
sorting follows displayed names, including live name changes.

Bump the applications, Android package and Nix package to 1.0.8.
On macOS, verified formatting, workspace Clippy and all-target tests,
including real encrypted tests between local agents. Rendered the
monitor in light and dark desktop themes and at phone width. Built the
arm64 Android debug APK and cross-checked the Windows GNU target.
Across 500 optimized viewport updates, egui produced 500 native icon
replacements on 1.0.7 and zero with this change.
This commit is contained in:
Aleksandr Bogomiakov committed 2026-11-25 21:57:14 +02:00
1 parent b47acb8321
commit d8b7787430
27 files changed
+1500 -399

No files matched your search

+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-android"
version = "1.0.7"
version = "1.0.8"
description = "Android VPN client and egui views for tsunagi."
edition.workspace = true
rust-version.workspace = true
@@ -16,7 +16,7 @@ name = "vpn_source_probe"
crate-type = ["cdylib"]
[dependencies]
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.7" }
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.8" }
tsunagi-ui = { path = "../tsunagi-ui" }
tsunagi-core = { path = "../tsunagi-core" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic" }
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-awg"
version = "1.0.7"
version = "1.0.8"
description = "Ephemeral pairwise Amnezia transport for Tsunagi."
edition.workspace = true
rust-version.workspace = true
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-core"
version = "1.0.7"
version = "1.0.8"
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"
keywords = ["mesh", "p2p", "iroh", "networking"]
+15 -9
View File
@@ -15,6 +15,7 @@ use crate::dataplane::PluginCapability;
use crate::error::{Error, Result};
use crate::identity::NetworkId;
use crate::ipc::{SpeedBatchReport, SpeedPeerReport, SpeedPhase, SpeedRate, SpeedReport};
use crate::overlay::router::DiagnosticPeer;
use crate::proto::message::{ControlMessage, TransportPayload};
type Key = (NetworkId, EndpointId);
@@ -56,6 +57,7 @@ struct Channel {
key: Key,
id: u64,
limit: u32,
addresses: DiagnosticPeer,
handle: wire::Handle,
}
@@ -199,7 +201,8 @@ pub(super) fn receive_packet(
&& channel.key == (network, peer)
&& let Some(data) = wire::decode_packet(packet)
&& data.id == channel.id
&& inner.routes.peer_addresses(network, peer) == Some((data.destination, data.source))
&& (data.destination, data.source) == (channel.addresses.local, channel.addresses.remote)
&& channel.addresses.is_current(&inner.routes)
{
inner
.routes
@@ -219,21 +222,22 @@ fn config(
id: u64,
bytes: u32,
rtt: Option<Duration>,
) -> Option<wire::Config> {
let (local, remote) = inner.routes.peer_addresses(key.0, key.1)?;
) -> Option<(wire::Config, DiagnosticPeer)> {
let addresses = inner.routes.diagnostic_peer(key.0, key.1)?;
let ceiling = if inner.speed.metered.load(Ordering::Relaxed) {
wire::METERED_BYTES
} else {
wire::NORMAL_BYTES
};
Some(wire::Config {
let cfg = wire::Config {
id,
local,
remote,
local: addresses.local,
remote: addresses.remote,
mtu: u16::try_from(inner.config.interface_mtu).unwrap_or(u16::MAX),
byte_limit: bytes.min(ceiling),
rtt: rtt.unwrap_or(Duration::from_millis(100)),
})
};
Some((cfg, addresses))
}
pub(super) fn receive_control(
@@ -253,13 +257,14 @@ pub(super) fn receive_control(
{
return envelope(&wire::Control::Busy { id });
}
let cfg = config(inner, key, id, request.byte_limit, rtt())?;
let (cfg, addresses) = config(inner, key, id, request.byte_limit, rtt())?;
let limit = cfg.byte_limit;
let (handle, session) = wire::respond(cfg, request);
inner.speed.active.store(Some(Arc::new(Channel {
key,
id,
limit,
addresses,
handle,
})));
drop(jobs);
@@ -575,7 +580,7 @@ async fn run_outgoing(
p.endpoint_id == key.1 && (!exits_only || p.exit_node) && supported(&p.capabilities)
})?;
let id = rand::random();
let cfg = config(inner, key, id, limit, peer.data_rtt.or(peer.rtt))?;
let (cfg, addresses) = config(inner, key, id, limit, peer.data_rtt.or(peer.rtt))?;
let limit = cfg.byte_limit;
let (handle, session) = wire::initiate(cfg);
let io = TestIo::new(inner, key, Some(generation));
@@ -591,6 +596,7 @@ async fn run_outgoing(
key,
id,
limit,
addresses,
handle,
})));
}
+113 -6
View File
@@ -85,6 +85,44 @@ pub struct NetworkRoutes {
pub peers: Vec<(Ipv4Addr, EndpointId)>,
}
impl NetworkRoutes {
fn address_pair(&self, peer: EndpointId) -> Option<(Ipv4Addr, Ipv4Addr)> {
let local = self.local?;
let (remote, _) = self.peers.iter().find(|(_, owner)| *owner == peer)?;
Some((local, *remote))
}
}
/// The signed addresses negotiated for one running diagnostic. A new allocation can
/// invalidate either end, so an active probe must recheck them when ownership changes.
pub(crate) struct DiagnosticPeer {
network: NetworkId,
peer: EndpointId,
pub(crate) local: Ipv4Addr,
pub(crate) remote: Ipv4Addr,
// Even revision of the checked routing table, plus one if both addresses matched.
checked: AtomicU64,
}
impl DiagnosticPeer {
pub(crate) fn is_current(&self, table: &RoutingTable) -> bool {
let revision = table.address_revision.load(Ordering::Acquire);
let checked = self.checked.load(Ordering::Relaxed);
if checked & !1 == revision {
return checked & 1 != 0;
}
let networks = table.read();
let pair = networks
.get(&self.network)
.and_then(|n| n.address_pair(self.peer));
let valid = pair == Some((self.local, self.remote));
let revision = table.address_revision.load(Ordering::Relaxed);
self.checked
.store(revision | u64::from(valid), Ordering::Relaxed);
valid
}
}
/// Why a network cannot be added to the table.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum RouteError {
@@ -114,6 +152,8 @@ pub struct RoutingTable {
broadcast: ArcSwap<BroadcastTable>,
selected_exit: ArcSwapOption<SelectedExit>,
networks: RwLock<HashMap<NetworkId, NetworkRoutes>>,
/// Advanced by two under the routing write lock when signed address ownership changes.
address_revision: AtomicU64,
}
impl RoutingTable {
@@ -123,15 +163,20 @@ impl RoutingTable {
}
/// Exact local and signed remote addresses for a mesh diagnostic. Exit routes do not qualify.
pub(crate) fn peer_addresses(
pub(crate) fn diagnostic_peer(
&self,
network: NetworkId,
peer: EndpointId,
) -> Option<(Ipv4Addr, Ipv4Addr)> {
) -> Option<DiagnosticPeer> {
let networks = self.read();
let routes = networks.get(&network)?;
let (address, _) = routes.peers.iter().find(|(_, owner)| *owner == peer)?;
Some((routes.local?, *address))
let (local, remote) = networks.get(&network)?.address_pair(peer)?;
Some(DiagnosticPeer {
network,
peer,
local,
remote,
checked: AtomicU64::new(self.address_revision.load(Ordering::Relaxed) | 1),
})
}
fn read(&self) -> std::sync::RwLockReadGuard<'_, HashMap<NetworkId, NetworkRoutes>> {
@@ -198,7 +243,13 @@ impl RoutingTable {
if routes.exit.via.is_some() {
clear_other_exits(networks, network);
}
let ownership_changed = networks
.get(&network)
.is_none_or(|old| old.local != routes.local || old.peers != routes.peers);
networks.insert(network, routes);
if ownership_changed {
self.address_revision.fetch_add(2, Ordering::Release);
}
self.refresh_exit(networks);
self.broadcast
.store(Arc::new(BroadcastTable::build(networks)));
@@ -209,7 +260,9 @@ impl RoutingTable {
pub fn remove_network(&self, network: NetworkId) {
self.vips.remove_network(network);
let mut networks = self.write();
networks.remove(&network);
if networks.remove(&network).is_some() {
self.address_revision.fetch_add(2, Ordering::Release);
}
self.refresh_exit(&networks);
self.broadcast
.store(Arc::new(BroadcastTable::build(&networks)));
@@ -609,6 +662,60 @@ mod tests {
}
}
#[test]
fn a_running_diagnostic_tracks_signed_ownership_across_route_changes() {
let table = RoutingTable::new();
let id = network("diagnostic");
let other = network("other");
table.set_network(id, routes()).unwrap();
let bound = table.diagnostic_peer(id, peer(2)).unwrap();
assert_eq!((bound.local, bound.remote), (addr(1), addr(2)));
assert!(bound.is_current(&table));
assert!(table.diagnostic_peer(id, peer(9)).is_none());
assert!(table.set_network(other, routes()).is_err());
table.set_exit(
id,
ExitPolicy {
offer: true,
via: Some(peer(3)),
},
);
assert!(bound.is_current(&table));
let mut changed = routes();
changed.peers[1].0 = addr(9);
table.update_allocations(id, changed.clone()).unwrap();
assert!(bound.is_current(&table), "another member moved");
changed.peers[0].0 = addr(7);
table.update_allocations(id, changed).unwrap();
assert!(
!bound.is_current(&table),
"the old peer address is no longer owned"
);
assert!(!bound.is_current(&table));
let moved = table.diagnostic_peer(id, peer(2)).unwrap();
assert!(moved.is_current(&table));
table
.update_allocations(
id,
NetworkRoutes {
local: None,
..routes()
},
)
.unwrap();
assert!(!moved.is_current(&table));
assert!(table.diagnostic_peer(id, peer(2)).is_none());
table.update_allocations(id, routes()).unwrap();
assert!(bound.is_current(&table));
table.remove_network(id);
table.set_network(other, routes()).unwrap();
assert!(
!bound.is_current(&table),
"same member and IPs in a different network"
);
}
#[test]
fn a_packet_goes_to_the_member_that_holds_its_destination() {
let table = RoutingTable::new();
+6 -6
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-runtime"
version = "1.0.7"
version = "1.0.8"
description = "Built-in mesh transports and status reporting for native tsunagi agents."
edition.workspace = true
rust-version.workspace = true
@@ -8,11 +8,11 @@ license.workspace = true
repository.workspace = true
[dependencies]
tsunagi-core = { path = "../tsunagi-core", version = "1.0.7" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.7" }
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.7" }
tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.7" }
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.7" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.8" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.8" }
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.8" }
tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.8" }
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.8" }
tokio.workspace = true
tracing.workspace = true
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-tcp-tls"
version = "1.0.7"
version = "1.0.8"
description = "TCP TLS carrier for independently encrypted tsunagi mesh traffic."
edition.workspace = true
rust-version.workspace = true
@@ -8,7 +8,7 @@ license.workspace = true
repository.workspace = true
[dependencies]
tsunagi-core = { path = "../tsunagi-core", version = "1.0.7" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.8" }
iroh.workspace = true
tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] }
rustls = "0.23"
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-tray"
version = "1.0.7"
version = "1.0.8"
description = "Tray application to manage a running tsunagi agent."
edition.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 same local control interface the CLI uses, so it reuses these directly
# and never re-implements the protocol.
tsunagi-core = { path = "../tsunagi-core", version = "1.0.7" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.8" }
# Native, lightweight GUI — no web engine. eframe re-exports egui.
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).
+5 -4
View File
@@ -29,6 +29,7 @@ impl Client for AgentClient {
}
/// Handle the UI holds: send commands, read the latest snapshot.
#[derive(Clone)]
pub(crate) struct AgentClient {
tx: mpsc::UnboundedSender<Command>,
shared: Arc<Mutex<Snapshot>>,
@@ -122,7 +123,7 @@ async fn worker(
run(&resolve_socket(), command, &shared, &pending_copy, &ctx).await;
refresh(&shared, &ctx).await;
lock(&shared).busy = false;
ctx.request_repaint();
ctx.request_repaint_of(egui::ViewportId::ROOT);
}
}
}
@@ -145,7 +146,7 @@ async fn refresh(shared: &Arc<Mutex<Snapshot>>, ctx: &egui::Context) {
guard.at = Some(Instant::now());
guard.socket = socket;
}
ctx.request_repaint();
ctx.request_repaint_of(egui::ViewportId::ROOT);
}
/// Runs one command and records its outcome.
@@ -157,7 +158,7 @@ async fn run(
ctx: &egui::Context,
) {
lock(shared).busy = true;
ctx.request_repaint();
ctx.request_repaint_of(egui::ViewportId::ROOT);
let outcome: Result<String, String> = match command {
Command::SaveVip {
@@ -302,7 +303,7 @@ async fn run(
Some(outcome)
};
}
ctx.request_repaint();
ctx.request_repaint_of(egui::ViewportId::ROOT);
}
/// Where the GUI looks for the agent: `TSUNAGI_CONTROL_SOCKET` if set, else the
+135 -56
View File
@@ -5,7 +5,7 @@
//! and gone when the window is closed. The tray, which has to outlive the
//! window, lives in the other process; see [`crate::tray`].
use std::time::Duration;
use std::sync::{Arc, Mutex};
use eframe::egui;
@@ -17,14 +17,19 @@ use crate::ui::{self, UiState};
use tsunagi_ui::app_fonts;
#[derive(Default)]
struct Views {
state: UiState,
traffic: Traffic,
}
/// The window's state.
pub(crate) struct App {
agent: AgentClient,
runtime: tokio::runtime::Handle,
monitor: Option<crate::monitor::Monitor>,
state: UiState,
/// Traffic rates derived from successive snapshots.
traffic: Traffic,
views: Arc<Mutex<Views>>,
device_revision: Option<(u64, tsunagi_ui::stats::Unit, bool)>,
/// The snapshot generation last folded into `traffic`.
sampled: u64,
}
@@ -45,8 +50,8 @@ impl App {
agent,
runtime,
monitor: None,
state: UiState::default(),
traffic: Traffic::default(),
views: Default::default(),
device_revision: None,
sampled: 0,
})
}
@@ -55,50 +60,64 @@ impl App {
impl eframe::App for App {
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
let snapshot = self.agent.snapshot();
let mut views = self.views.lock().unwrap_or_else(|e| e.into_inner());
let Views { state, traffic } = &mut *views;
if snapshot.generation != self.sampled
&& let (Some(Ok(report)), Some(at)) = (&snapshot.status, snapshot.at)
{
self.traffic.observe(report, at);
traffic.observe(report, at);
self.sampled = snapshot.generation;
}
ui::draw(ctx, &self.agent, &mut self.state, &snapshot, &self.traffic);
if self.state.monitor_open {
ui::draw(ctx, &self.agent, state, &snapshot, traffic);
if state.monitor_open {
let monitor = self.monitor.get_or_insert_with(|| {
crate::monitor::Monitor::new(&self.runtime, self.agent.socket())
});
if !monitor.show(ctx, &snapshot) {
self.monitor = None;
self.state.monitor_open = false;
state.monitor_open = false;
}
}
self.show_devices_windows(ctx, &snapshot);
self.show_vip_windows(ctx, &snapshot);
self.show_about_window(ctx, &snapshot);
Self::show_vip_windows(ctx, &self.agent, state, &snapshot);
Self::show_about_window(ctx, &self.agent, state, &snapshot);
let revision = (snapshot.generation, state.unit, snapshot.busy);
let refresh = self.device_revision != Some(revision);
self.device_revision = Some(revision);
if let Some(Ok(report)) = &snapshot.status {
state
.open_devices
.retain(|id| report.networks.iter().any(|n| n.network_id == *id));
let open: Vec<_> = state.open_devices.iter().cloned().collect();
// The embedded fallback can run the child callback immediately.
drop(views);
self.show_devices_windows(ctx, report, &open, refresh);
}
// A secret the worker fetched for the clipboard: copy it here, on the
// UI thread that owns the clipboard, exactly once.
if let Some(secret) = self.agent.take_pending_copy() {
ctx.copy_text(secret);
}
// Keep ticking so fresh status is picked up.
ctx.request_repaint_after(Duration::from_millis(500));
}
}
impl App {
fn show_vip_windows(&mut self, ctx: &egui::Context, snapshot: &crate::agent::Snapshot) {
fn show_vip_windows(
ctx: &egui::Context,
agent: &AgentClient,
state: &mut UiState,
snapshot: &crate::agent::Snapshot,
) {
let Some(Ok(report)) = &snapshot.status else {
return;
};
let ids: Vec<_> = self.state.vip_windows.keys().cloned().collect();
let ids: Vec<_> = state.vip_windows.keys().cloned().collect();
for id in ids {
let Some(network) = report.networks.iter().find(|n| n.network_id == id) else {
self.state.vip_windows.remove(&id);
state.vip_windows.remove(&id);
continue;
};
let Some(state) = self.state.vip_windows.get_mut(&id) else {
let Some(editor) = state.vip_windows.get_mut(&id) else {
continue;
};
let builder = egui::ViewportBuilder::default()
@@ -111,13 +130,13 @@ impl App {
egui::ViewportId::from_hash_of(("vip", &id)),
builder,
|vctx, _| {
let close = crate::vip::show(vctx, &self.agent, state, network, snapshot);
let close = crate::vip::show(vctx, agent, editor, network, snapshot);
if close {
return false;
}
if vctx.input(|i| i.viewport().close_requested()) {
if state.dirty() {
state.request_close();
if editor.dirty() {
editor.request_close();
vctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
true
} else {
@@ -129,13 +148,18 @@ impl App {
},
);
if !keep {
self.state.vip_windows.remove(&id);
state.vip_windows.remove(&id);
}
}
}
/// Renders the About window while it is open.
fn show_about_window(&mut self, ctx: &egui::Context, snapshot: &crate::agent::Snapshot) {
if !self.state.about_open {
fn show_about_window(
ctx: &egui::Context,
agent: &AgentClient,
state: &mut UiState,
snapshot: &crate::agent::Snapshot,
) {
if !state.about_open {
return;
}
let builder = egui::ViewportBuilder::default()
@@ -144,7 +168,7 @@ impl App {
.with_icon(crate::icon::window())
.with_inner_size([560.0, 520.0])
.with_min_inner_size([380.0, 280.0]);
let socket = self.agent.socket();
let socket = agent.socket();
let keep = ctx.show_viewport_immediate(
egui::ViewportId::from_hash_of("about"),
builder,
@@ -154,50 +178,57 @@ impl App {
},
);
if !keep {
self.state.about_open = false;
state.about_open = false;
}
}
/// Renders one separate window per open network-devices view.
fn show_devices_windows(&mut self, ctx: &egui::Context, snapshot: &crate::agent::Snapshot) {
let Some(Ok(report)) = &snapshot.status else {
return;
};
let open: Vec<String> = self.state.open_devices.iter().cloned().collect();
fn show_devices_windows(
&self,
ctx: &egui::Context,
report: &Arc<tsunagi::ipc::StatusReport>,
open: &[String],
refresh: bool,
) {
for id in open {
let Some(network) = report.networks.iter().find(|n| n.network_id == id) else {
// The network is gone (left/forgotten); close its window.
self.state.open_devices.remove(&id);
let Some(index) = report.networks.iter().position(|n| n.network_id == *id) else {
continue;
};
let viewport_id = egui::ViewportId::from_hash_of(("devices", &id));
let viewport = egui::ViewportId::from_hash_of(("devices", id));
let builder = egui::ViewportBuilder::default()
.with_title(devices::title(network))
.with_title(devices::title(&report.networks[index]))
.with_app_id(crate::icon::APP_ID)
.with_icon(crate::icon::window())
.with_inner_size([1000.0, 640.0])
.with_min_inner_size([560.0, 400.0]);
let agent = &self.agent;
let traffic = &self.traffic;
// The window shares the single unit setting, so its toggle and the
// main window's stay in step.
let unit = &mut self.state.unit;
let confirm = &mut self.state.exit_confirm;
let forget_confirm = &mut self.state.forget_confirm;
let keep = ctx.show_viewport_immediate(viewport_id, builder, |vctx, _class| {
.with_inner_size([1000., 640.])
.with_min_inner_size([560., 400.]);
let views = self.views.clone();
let agent = self.agent.clone();
let report = report.clone();
ctx.show_viewport_deferred(viewport, builder, move |ctx, _| {
let mut views = views.lock().unwrap_or_else(|e| e.into_inner());
let Views { state, traffic } = &mut *views;
let network = &report.networks[index];
if ctx.input(|i| i.viewport().close_requested()) {
state.open_devices.remove(&network.network_id);
ctx.request_repaint_of(egui::ViewportId::ROOT);
return;
}
let old_unit = state.unit;
devices::show(
vctx,
agent,
unit,
(confirm, forget_confirm),
ctx,
&agent,
&mut state.unit,
(&mut state.exit_confirm, &mut state.forget_confirm),
network,
&report.endpoint_id,
traffic,
);
!vctx.input(|i| i.viewport().close_requested())
if old_unit != state.unit {
ctx.request_repaint_of(egui::ViewportId::ROOT);
}
});
if !keep {
self.state.open_devices.remove(&id);
if refresh {
ctx.request_repaint_of(viewport);
}
}
}
@@ -205,8 +236,56 @@ impl App {
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn device_frames_are_scheduled_independently_of_the_main_window() {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
let ctx = egui::Context::default();
ctx.set_embed_viewports(false);
let agent = AgentClient::spawn(runtime.handle(), ctx.clone());
let app = App {
agent,
runtime: runtime.handle().clone(),
monitor: None,
views: Default::default(),
sampled: 0,
device_revision: None,
};
let report = Arc::new(tsunagi::ipc::StatusReport {
networks: vec![tsunagi::ipc::NetworkReport {
network_id: "test-id".into(),
name: "lab".into(),
..Default::default()
}],
..Default::default()
});
let id = egui::ViewportId::from_hash_of(("devices", "test-id"));
let open = ["test-id".to_string()].into_iter().collect();
app.views.lock().unwrap().state.open_devices = open;
let out = ctx.run(Default::default(), |ctx| {
app.show_devices_windows(ctx, &report, &["test-id".to_string()], true);
});
assert!(out.viewport_output[&id].class == egui::ViewportClass::Deferred);
let draw = out.viewport_output[&id].viewport_ui_cb.as_ref().unwrap();
let mut input = egui::RawInput {
viewport_id: id,
..Default::default()
};
input
.viewports
.entry(id)
.or_default()
.events
.push(egui::ViewportEvent::Close);
let _ = ctx.run(input, |ctx| draw(ctx));
assert!(app.views.lock().unwrap().state.open_devices.is_empty());
}
#[test]
fn route_icons_have_an_embedded_font_in_the_app() {
let fonts = app_fonts();
+19 -6
View File
@@ -4,6 +4,7 @@
//! It is the same shape as `dist/linux/tsunagi.svg` (a disc, a ring, a dot).
use crate::watch::Health;
use std::sync::{Arc, LazyLock};
/// Normal operation. The colour of the logo itself.
const BLUE: [u8; 3] = [0x2f, 0x80, 0xd8];
@@ -89,12 +90,17 @@ pub(crate) fn tray(health: Health) -> Option<tray_icon::Icon> {
}
/// The icon of the application's windows.
pub(crate) fn window() -> eframe::egui::IconData {
eframe::egui::IconData {
rgba: rgba(BLUE),
width: SIZE,
height: SIZE,
}
pub(crate) fn window() -> Arc<eframe::egui::IconData> {
// egui compares viewport icons by Arc identity. Reuse both the pixels and
// their allocation so animating a row does not update a native window icon.
static ICON: LazyLock<Arc<eframe::egui::IconData>> = LazyLock::new(|| {
Arc::new(eframe::egui::IconData {
rgba: rgba(BLUE),
width: SIZE,
height: SIZE,
})
});
Arc::clone(&ICON)
}
#[cfg(test)]
@@ -122,6 +128,13 @@ mod tests {
assert_eq!(body, [GREEN[0], GREEN[1], GREEN[2], 255]);
}
#[test]
fn repainting_a_devices_viewport_does_not_ask_the_os_to_replace_its_icon() {
let viewport = || eframe::egui::ViewportBuilder::default().with_icon(window());
let (commands, recreate) = viewport().patch(viewport());
assert!(!recreate && commands.is_empty(), "{commands:?}");
}
#[test]
fn each_state_has_its_own_colour() {
let colours = [
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-ui"
version = "1.0.7"
version = "1.0.8"
description = "Shared egui widgets for the tray and Android clients."
edition.workspace = true
rust-version.workspace = true
@@ -10,7 +10,7 @@ publish = false
[dependencies]
postcard.workspace = true
rusqlite = { version = "0.40", features = ["bundled"] }
rusqlite = { version = "0.40", features = ["bundled", "functions"] }
tempfile.workspace = true
egui = "0.31"
egui-phosphor = "0.9"
+56 -4
View File
@@ -232,9 +232,20 @@ pub fn show(
egui::ScrollArea::vertical()
.auto_shrink([false, false])
.show(ui, |ui| {
let table = desktop_columns(ui, unit, network, &devices, traffic);
let required = table.widths.iter().sum::<f32>() + crate::table::GAP * 8.;
if required <= ui.available_width() {
// Remembered desktop widths only grow. While this window is compact,
// an animation frame need not format and measure all peers a second time.
let available = ui.available_width();
let id = egui::Id::new(("devices column widths", &network.network_id));
let fits = |w: &[f32; 9]| {
w[..8].iter().sum::<f32>() + MIN_PLOT_WIDTH + crate::table::GAP * 8.
<= available
};
let could_fit = ui
.data(|d| d.get_temp::<[f32; 9]>(id))
.is_none_or(|w| fits(&w));
let table =
could_fit.then(|| desktop_columns(ui, unit, network, &devices, traffic));
if let Some(table) = table.filter(|t| fits(&t.widths)) {
device_table(
ui,
network,
@@ -626,9 +637,11 @@ fn column_widths(ui: &egui::Ui, id: egui::Id) -> [f32; 9] {
})
}
const MIN_PLOT_WIDTH: f32 = 100.;
fn stretch_columns(mut widths: [f32; 9], available: f32) -> [f32; 9] {
let gaps = crate::table::GAP * (widths.len() - 1) as f32;
widths[8] = (available - gaps - widths[..8].iter().sum::<f32>()).clamp(100.0, 180.0);
widths[8] = (available - gaps - widths[..8].iter().sum::<f32>()).clamp(MIN_PLOT_WIDTH, 180.0);
widths
}
@@ -1555,6 +1568,45 @@ mod tests {
}
}
#[test]
fn compact_frames_skip_the_hidden_desktop_layout_until_the_window_grows() {
let ctx = egui::Context::default();
ctx.set_fonts(crate::app_fonts());
let id = egui::Id::new(("devices column widths", "lab"));
let mut net = NetworkReport {
network_id: "lab".into(),
members: vec![member("peer", true, DataPathReport::None)],
..Default::default()
};
let draw = |width, net: &NetworkReport| {
let _ = ctx.run(
egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(
egui::Pos2::ZERO,
egui::vec2(width, 600.),
)),
..Default::default()
},
|ctx| {
show(
ctx,
&ReadOnly,
&mut Unit::Bytes,
(&mut None, &mut None),
net,
"self",
&Traffic::default(),
)
},
);
ctx.data(|d| d.get_temp::<[f32; 9]>(id)).unwrap()
};
let first = draw(660., &net);
net.members[0].hostname = Some("a-much-longer-peer-name-for-the-wide-table".into());
assert_eq!(draw(660., &net), first);
assert!(draw(2300., &net)[0] > first[0]);
}
#[test]
fn a_long_relay_name_gets_its_full_column_width() {
let mut relay = member("near", true, DataPathReport::None);
+10 -3
View File
@@ -33,8 +33,15 @@ impl<'a> Controls<'a> {
let (label, help, available) = if self.running {
ui.ctx().request_repaint_after(Duration::from_millis(250));
let label = self.network.speed.batch.map_or_else(
|| format!("{} Stop test", icon::STOP),
|batch| format!("{} Stop {}/{}", icon::STOP, batch.done, batch.total),
|| format!("{} Stop test", icon::STOP_CIRCLE),
|batch| {
format!(
"{} Stop {}/{}",
icon::STOP_CIRCLE,
batch.done,
batch.total
)
},
);
(
label,
@@ -63,7 +70,7 @@ impl<'a> Controls<'a> {
let width = ui
.painter()
.layout_no_wrap(
format!("{} Stop 9999/9999", icon::STOP),
format!("{} Stop 9999/9999", icon::STOP_CIRCLE),
egui::TextStyle::Button.resolve(ui.style()),
ui.visuals().text_color(),
)
+3 -1
View File
@@ -273,7 +273,9 @@ fn exit_batch_requires_an_online_capable_exit_and_stops_in_its_own_network() {
s.click(&n, start);
n.speed.batch = Some(SpeedBatchReport { done: 0, total: 1 });
let batch = s.frame(&n, vec![]);
assert!(!positions(&batch, |s| s.contains("0/1")).is_empty());
assert!(!positions(&batch, |s| s == format!("{} Stop 0/1", icon::STOP_CIRCLE)).is_empty());
let font = egui::TextStyle::Button.resolve(&s.ctx.style());
assert!(s.ctx.fonts(|f| f.has_glyphs(&font, icon::STOP_CIRCLE)));
s.click(&n, positions(&batch, |s| s.contains("Stop"))[0]);
assert!(matches!(s.log.0.borrow().as_slice(), [
Command::StartSpeedTest { network_id, peer: None },
+140
View File
@@ -0,0 +1,140 @@
//! Fields shared by the table, its column chooser and the history ordering.
use super::{Names, endpoints, role_name};
use rusqlite::types::Value;
use tsunagi::traffic::{Flow, FlowKey, IpDetail};
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(super) enum Column {
Peer,
Network,
Near,
Far,
Protocol,
Role,
Sent,
Received,
SendRate,
ReceiveRate,
SentPackets,
ReceivedPackets,
Seen,
PeerId,
}
impl Column {
pub fn title(self) -> &'static str {
match self {
Self::Peer => "Peer",
Self::Network => "Network",
Self::Near => "Endpoint A",
Self::Far => "Endpoint B",
Self::Protocol => "Protocol",
Self::Role => "Role",
Self::Sent => "Sent",
Self::Received => "Received",
Self::SendRate => "TX rate",
Self::ReceiveRate => "RX rate",
Self::SentPackets => "TX packets",
Self::ReceivedPackets => "RX packets",
Self::Seen => "Last seen",
Self::PeerId => "Peer ID",
}
}
pub fn hint(self) -> &'static str {
match self {
Self::Peer => "Authenticated peer",
Self::Network => "Tsunagi network",
Self::Near => "Agent-side endpoint, or the first endpoint of an encrypted relay",
Self::Far => "Peer-side endpoint, or the second endpoint of an encrypted relay",
Self::Protocol => "IP protocol or transport session",
Self::Role => "How this agent handles the traffic",
Self::Sent => "Total bytes sent from A to B",
Self::Received => "Total bytes received from B to A",
Self::SendRate => "Bytes per second from A to B",
Self::ReceiveRate => "Bytes per second from B to A",
Self::SentPackets => "Packets sent from A to B",
Self::ReceivedPackets => "Packets received from B to A",
Self::Seen => "Time since the last observation",
Self::PeerId => "Public peer ID. Select a value to copy it.",
}
}
pub fn descending_first(self) -> bool {
matches!(
self,
Self::Sent
| Self::Received
| Self::SendRate
| Self::ReceiveRate
| Self::SentPackets
| Self::ReceivedPackets
| Self::Seen
)
}
pub fn sql(self) -> &'static str {
match self {
Self::Sent => "tx",
Self::Received => "rx",
Self::SendRate => "tx_rate",
Self::ReceiveRate => "rx_rate",
Self::SentPackets => "ntx",
Self::ReceivedPackets => "nrx",
Self::Seen => "last",
Self::PeerId => "peer",
_ => "flow_label(key)",
}
}
pub fn uses_names(self) -> bool {
matches!(self, Self::Peer | Self::Network | Self::Near | Self::Far)
}
// SQLite indexes this value only while sorting by a descriptive column.
// Numeric IPv4 address and port order is independent of their spelling.
pub fn label_key(self, key: &FlowKey, names: &Names) -> Value {
if let Flow::Ip {
near, far, detail, ..
} = key.flow
&& matches!(self, Self::Near | Self::Far)
{
let near_side = self == Self::Near;
let ip = u32::from_be_bytes(if near_side { near } else { far });
let port = match detail {
IpDetail::Ports(a, b) => 1 + i64::from(if near_side { a } else { b }),
_ => 0,
};
return Value::Integer((i64::from(ip) << 17) + port);
}
let label = match self {
Self::Peer => names.peer(&key.network, &key.peer),
Self::Network => names.network(&key.network),
Self::Near => endpoints(key, names).0,
Self::Far => endpoints(key, names).1,
Self::Protocol => endpoints(key, names).2,
Self::Role => role_name(key.role).into(),
_ => return Value::Null,
};
Value::Text(label.to_lowercase())
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) struct Sort {
pub column: Column,
pub descending: bool,
}
impl Default for Sort {
fn default() -> Self {
Self {
column: Column::Seen,
descending: true,
}
}
}
impl Sort {
pub fn select(&mut self, column: Column) {
self.descending = if self.column == column {
!self.descending
} else {
column.descending_first()
};
self.column = column;
}
}
+96 -11
View File
@@ -1,23 +1,34 @@
//! A private scratch database belongs to one window and one worker thread.
//! A capture with millions of flows uses disk, and the UI reads one page at a time.
use super::{Column, Names, Sort};
use rusqlite::functions::FunctionFlags;
use rusqlite::{Connection, params, params_from_iter, types::Value};
use std::path::Path;
use std::{path::Path, sync::Arc};
use tsunagi::traffic::{Flow, FlowDelta, Role};
pub(super) const PAGE_SIZE: usize = 64;
pub(super) const RATE_LIFETIME_MS: u64 = 1900;
const RETAIN_MS: u64 = 60_000;
#[derive(Default, Clone, PartialEq, Eq)]
#[derive(Default, Clone, PartialEq)]
pub(super) struct Filter {
pub network: Option<[u8; 32]>,
pub peer: Option<[u8; 32]>,
pub protocol: Option<u8>,
pub role: Option<Role>,
pub transport: bool,
pub before: Option<i64>,
pub sort: Sort,
pub before: Option<Cursor>,
}
#[derive(Clone, PartialEq)]
pub(super) struct Cursor {
value: Value,
id: i64,
}
pub(super) struct Row {
order_value: Value,
pub id: i64,
pub data: FlowDelta,
pub last: u64,
@@ -25,6 +36,14 @@ pub(super) struct Row {
pub tx_rate: f32,
pub rx_rate: f32,
}
impl Row {
pub fn cursor(&self) -> Cursor {
Cursor {
value: self.order_value.clone(),
id: self.id,
}
}
}
#[derive(Default)]
pub(super) struct Page {
pub rows: Vec<Row>,
@@ -33,6 +52,8 @@ pub(super) struct Page {
pub(super) struct History {
connection: Connection,
indexed: Option<Column>,
names: Arc<Names>,
}
// SQLite counters are signed 64-bit integers; clamp only at its representable maximum.
@@ -63,6 +84,7 @@ impl History {
tx INTEGER NOT NULL, rx INTEGER NOT NULL, ntx INTEGER NOT NULL, nrx INTEGER NOT NULL,
last INTEGER NOT NULL, sampled INTEGER NOT NULL, tx_rate REAL NOT NULL, rx_rate REAL NOT NULL
);
CREATE INDEX live_rates ON flow(sampled) WHERE tx_rate>0 OR rx_rate>0;
CREATE INDEX by_last ON flow(last);
CREATE INDEX by_layer ON flow(transport,id);
CREATE INDEX by_network ON flow(transport,network,id);
@@ -73,7 +95,52 @@ impl History {
// All platforms that pass a directory are Unix; unlink the open file so even
// force-stopping the activity releases it when the OS closes the descriptor.
drop(file);
Ok(Self { connection: db })
Ok(Self {
connection: db,
indexed: None,
names: Arc::default(),
})
}
pub fn use_names(&mut self, names: Arc<Names>) {
if !Arc::ptr_eq(&self.names, &names) {
self.names = names;
if self.indexed.is_some_and(Column::uses_names) {
self.indexed = None;
}
}
}
// One index serves the active ordering, including its stable tie-breaker.
// Long captures pay its setup cost once per change on the window worker.
fn prepare_order(&mut self, column: Column) -> rusqlite::Result<()> {
if self.indexed == Some(column) {
return Ok(());
}
self.connection
.execute_batch("DROP INDEX IF EXISTS by_view")?;
let expr = column.sql();
if expr == "flow_label(key)" {
let names = self.names.clone();
self.connection.create_scalar_function(
"flow_label",
1,
FunctionFlags::SQLITE_UTF8
| FunctionFlags::SQLITE_DETERMINISTIC
| FunctionFlags::SQLITE_INNOCUOUS,
move |ctx| {
let bytes = ctx.get_raw(0).as_blob()?;
let key = postcard::from_bytes(bytes)
.map_err(|e| rusqlite::Error::UserFunctionError(Box::new(e)))?;
Ok(column.label_key(&key, &names))
},
)?;
}
self.connection.execute_batch(&format!(
"CREATE INDEX by_view ON flow(transport,{expr},id)"
))?;
self.indexed = Some(column);
Ok(())
}
pub fn interrupt(&self) -> rusqlite::InterruptHandle {
@@ -122,6 +189,13 @@ impl History {
.map_err(|e| e.to_string())?;
}
}
if now >= RATE_LIFETIME_MS {
txn.execute(
"UPDATE flow SET tx_rate=0,rx_rate=0 WHERE sampled<=? AND (tx_rate>0 OR rx_rate>0)",
[integer(now - RATE_LIFETIME_MS)],
)
.map_err(|e| e.to_string())?;
}
if !keep && now >= RETAIN_MS {
txn.execute(
"DELETE FROM flow WHERE last <= ?1",
@@ -132,9 +206,12 @@ impl History {
txn.commit().map_err(|e| e.to_string())
}
pub fn page(&self, f: &Filter) -> Result<Page, String> {
let mut sql = String::from(
"SELECT id,key,tx,rx,ntx,nrx,last,sampled,tx_rate,rx_rate FROM flow WHERE transport=?",
pub fn page(&mut self, f: &Filter) -> Result<Page, String> {
self.prepare_order(f.sort.column)
.map_err(|e| e.to_string())?;
let expr = f.sort.column.sql();
let mut sql = format!(
"SELECT id,key,tx,rx,ntx,nrx,last,sampled,tx_rate,rx_rate,{expr} FROM flow WHERE transport=?"
);
let mut args = vec![Value::Integer(i64::from(f.transport))];
if let Some(n) = f.network {
@@ -153,11 +230,18 @@ impl History {
sql.push_str(" AND protocol=?");
args.push(Value::Integer(p.into()));
}
if let Some(cursor) = f.before {
sql.push_str(" AND id<?");
args.push(Value::Integer(cursor));
let (op, direction) = if f.sort.descending {
("<", "DESC")
} else {
(">", "ASC")
};
if let Some(cursor) = &f.before {
sql.push_str(&format!(" AND ({expr},id){op}(?,?)"));
args.extend([cursor.value.clone(), Value::Integer(cursor.id)]);
}
sql.push_str(" ORDER BY id DESC LIMIT ?");
sql.push_str(&format!(
" ORDER BY {expr} {direction},id {direction} LIMIT ?"
));
args.push(Value::Integer(PAGE_SIZE as i64 + 1));
let mut q = self
.connection
@@ -175,6 +259,7 @@ impl History {
})?;
Ok(Row {
id: r.get(0)?,
order_value: r.get(10)?,
data: FlowDelta {
key,
tx_bytes: r.get::<_, i64>(2)? as u64,
+112 -213
View File
@@ -1,17 +1,17 @@
//! Live traffic inspector shared by the tray and Android clients.
mod columns;
mod history;
mod table;
use columns::{Column, Sort};
#[cfg(test)]
mod tests;
mod worker;
use crate::{
format::{bytes, short},
widgets,
};
use egui::{RichText, Ui};
use crate::{format::short, widgets};
use egui::Ui;
use egui_phosphor::regular as icon;
use history::{Filter, Row};
use std::{collections::BTreeMap, net::Ipv4Addr, path::PathBuf, time::Duration};
use history::{Cursor, Filter};
use std::{collections::BTreeMap, net::Ipv4Addr, path::PathBuf, sync::Arc, time::Duration};
use tsunagi::{
NetworkId,
ipc::StatusReport,
@@ -22,12 +22,12 @@ pub use worker::Feed;
use worker::Worker;
type Id = [u8; 32];
#[derive(Default)]
#[derive(Clone, Default)]
struct Network {
name: String,
peers: BTreeMap<Id, String>,
}
#[derive(Default)]
#[derive(Clone, Default)]
struct Names {
networks: BTreeMap<Id, Network>,
generation: Option<u64>,
@@ -37,18 +37,25 @@ fn public_id(id: &Id) -> String {
id.iter().map(|b| format!("{b:02x}")).collect()
}
impl Names {
fn refresh(&mut self, report: Option<&StatusReport>, generation: u64) {
let Some(report) = report else { return };
fn refresh(&mut self, report: Option<&StatusReport>, generation: u64) -> bool {
let Some(report) = report else { return false };
if self.generation == Some(generation) {
return;
return false;
}
self.generation = Some(generation);
let mut changed = false;
for n in &report.networks {
let Ok(id) = n.network_id.parse::<NetworkId>() else {
continue;
};
let entry = self.networks.entry(*id.as_bytes()).or_default();
entry.name = n.name.clone();
if entry.name != n.name {
entry.name.clone_from(&n.name);
changed = true;
}
// Resolve duplicate membership and live entries first. A stale member name
// must not trigger a rebuild of a multi-day capture's index every poll.
let mut reported = BTreeMap::new();
for (key, name) in n
.members
.iter()
@@ -63,18 +70,32 @@ impl Names {
Some(report.hostname.as_str()),
)))
{
let label = reported.entry(key).or_default();
if let Some(name) = name.filter(|s| !s.is_empty()) {
*label = Some(name);
}
}
for (key, name) in reported {
if let Ok(peer) = key.parse::<EndpointId>() {
let label = name.filter(|s| !s.is_empty()).map(str::to_owned);
let current = entry
.peers
.entry(*peer.as_bytes())
.or_insert_with(|| short(key));
if let Some(label) = label {
*current = label;
use std::collections::btree_map::Entry;
match entry.peers.entry(*peer.as_bytes()) {
Entry::Vacant(e) => {
e.insert(name.map_or_else(|| short(key), str::to_owned));
changed = true;
}
Entry::Occupied(mut e) => {
if let Some(name) = name
&& name != e.get()
{
*e.get_mut() = name.into();
changed = true;
}
}
}
}
}
}
changed
}
fn network(&self, id: &Id) -> String {
let Some(n) = self.networks.get(id) else {
@@ -115,17 +136,6 @@ fn role_name(r: Role) -> &'static str {
Role::Relay => "Encrypted relay",
}
}
fn role_text(role: Role) -> String {
let glyph = match role {
Role::ViaExit => icon::SIGN_OUT,
Role::ServeExit => icon::SIGN_IN,
Role::Relay => icon::GIT_FORK,
Role::Broadcast => icon::BROADCAST,
Role::SpeedTest => icon::GAUGE,
_ => return role_name(role).to_owned(),
};
format!("{glyph} {}", role_name(role))
}
fn protocol(n: u8) -> String {
match n {
1 => "ICMP".into(),
@@ -189,8 +199,8 @@ pub struct Window {
names: Names,
filter: Filter,
keep: bool,
previous: Vec<Option<i64>>,
selected: Option<i64>,
previous: Vec<Option<Cursor>>,
column_page: usize,
}
impl Window {
/// Creates an empty view. Android supplies its application-private cache directory.
@@ -201,7 +211,7 @@ impl Window {
filter: Filter::default(),
keep: false,
previous: Vec::new(),
selected: None,
column_page: 0,
}
}
/// The endpoint into which this window's subscription feeds interval snapshots.
@@ -209,31 +219,57 @@ impl Window {
self.worker.feed.clone()
}
fn controls(&mut self, ui: &mut Ui) {
ui.horizontal_wrapped(|ui| {
let layer = self.filter.transport;
ui.selectable_value(&mut self.filter.transport, false, format!("{} IP flows", icon::ARROWS_LEFT_RIGHT));
ui.selectable_value(&mut self.filter.transport, true, format!("{} Transport", icon::GIT_FORK))
.on_hover_text("Authenticated control sessions and encrypted traffic relayed between peers");
if layer != self.filter.transport {
self.filter.role = None;
self.filter.protocol = None;
}
widgets::hint(ui.checkbox(&mut self.keep,"Keep until close"),
"Keep inactive flows for this window session. Otherwise they expire after 60 seconds.");
});
let width = ((ui.available_width() - ui.spacing().item_spacing.x) / 2.).clamp(60., 135.);
fn controls(&mut self, ui: &mut Ui, grid: &table::Grid) {
if ui.available_width() < 540. {
ui.horizontal(|ui| self.layers(ui));
ui.horizontal(|ui| self.history_controls(ui, grid));
} else {
ui.horizontal(|ui| {
self.layers(ui);
self.history_controls(ui, grid);
});
}
if ui.available_width() < 580. {
let width = ((ui.available_width() - ui.spacing().item_spacing.x) / 2.).max(60.);
ui.horizontal(|ui| self.identity_filters(ui, width));
ui.horizontal(|ui| self.flow_filters(ui, width));
} else {
ui.horizontal(|ui| {
self.identity_filters(ui, width);
self.flow_filters(ui, width);
self.identity_filters(ui, 135.);
self.flow_filters(ui, 135.);
});
}
}
fn layers(&mut self, ui: &mut Ui) {
let layer = self.filter.transport;
ui.selectable_value(
&mut self.filter.transport,
false,
format!("{} IP flows", icon::ARROWS_LEFT_RIGHT),
);
ui.selectable_value(
&mut self.filter.transport,
true,
format!("{} Transport", icon::GIT_FORK),
)
.on_hover_text(
"Authenticated control sessions and encrypted traffic relayed between peers",
);
if layer != self.filter.transport {
self.filter.role = None;
self.filter.protocol = None;
}
}
fn history_controls(&mut self, ui: &mut Ui, grid: &table::Grid) {
widgets::hint(
ui.checkbox(&mut self.keep, "Keep until close"),
"Keep inactive flows for this window session. Otherwise they expire after 60 seconds.",
);
grid.chooser(ui, &mut self.column_page);
}
fn identity_filters(&mut self, ui: &mut Ui, width: f32) {
let network = self.filter.network;
egui::ComboBox::from_id_salt("flow-network")
@@ -322,14 +358,18 @@ impl Window {
/// Draw the responsive inspector inside the current viewport.
pub fn show(&mut self, ui: &mut Ui, report: Option<&StatusReport>, generation: u64) {
self.names.refresh(report, generation);
if self.names.refresh(report, generation) {
self.worker.names(Arc::new(self.names.clone()));
}
table::style(ui);
let before = self.filter.clone();
let keep = self.keep;
self.controls(ui);
let grid = table::Grid::new(ui);
self.column_page = self.column_page.min(grid.pages.len() - 1);
self.controls(ui, &grid);
if self.filter != before {
self.filter.before = None;
self.previous.clear();
self.selected = None;
}
if self.filter != before || self.keep != keep {
self.worker.options(self.filter.clone(), self.keep);
@@ -346,40 +386,44 @@ impl Window {
}
ui.separator();
let now = self.worker.feed.elapsed();
let wide = ui.available_width() >= 690.;
if !self.previous.is_empty() || page.more {
ui.horizontal(|ui| {
ui.horizontal_wrapped(|ui| {
if ui
.add_enabled(
!self.previous.is_empty(),
egui::Button::new(format!("{} Newer", icon::CARET_LEFT)),
egui::Button::new(format!("{} Previous", icon::CARET_LEFT)),
)
.clicked()
&& let Some(cursor) = self.previous.pop()
{
self.filter.before = cursor;
self.selected = None;
self.worker.options(self.filter.clone(), self.keep);
}
ui.weak(format!("Page {}", self.previous.len() + 1));
ui.label(format!("Page {}", self.previous.len() + 1));
if ui
.add_enabled(
page.more,
egui::Button::new(format!("Older {}", icon::CARET_RIGHT)),
egui::Button::new(format!("Next {}", icon::CARET_RIGHT)),
)
.clicked()
&& let Some(r) = page.rows.last()
&& let Some(row) = page.rows.last()
{
self.previous.push(self.filter.before);
self.filter.before = Some(r.id);
self.selected = None;
self.previous.push(self.filter.before.clone());
self.filter.before = Some(row.cursor());
self.worker.options(self.filter.clone(), self.keep);
}
});
}
let columns = &grid.pages[self.column_page];
if let Some(column) = grid.header(ui, columns, self.filter.sort) {
self.filter.sort.select(column);
self.filter.before = None;
self.previous.clear();
self.worker.options(self.filter.clone(), self.keep);
}
if page.rows.is_empty() {
ui.add_space(14.);
ui.weak(if error.is_some() {
ui.add_space(10.);
ui.label(if error.is_some() {
"No captured flows in this view."
} else if self.filter.network.is_some()
|| self.filter.role.is_some()
@@ -391,160 +435,15 @@ impl Window {
"Listening for traffic…"
});
} else {
if wide {
desktop_header(ui);
}
egui::ScrollArea::vertical()
.id_salt("flow-rows")
.auto_shrink([false, false])
.show(ui, |ui| {
for row in &page.rows {
let chosen = self.selected == Some(row.id);
egui::Frame::new()
.inner_margin(egui::Margin::symmetric(5, 3))
.fill(if chosen {
ui.visuals().selection.bg_fill
} else if row.id % 2 == 0 {
ui.visuals().faint_bg_color
} else {
egui::Color32::TRANSPARENT
})
.show(ui, |ui| {
let summary = ui.scope(|ui| self.row(ui, row, now, wide)).response;
let selected = ui.interact(
summary.rect,
ui.id().with(("flow", row.id)),
egui::Sense::click(),
);
if selected.clicked() {
self.selected = if chosen { None } else { Some(row.id) };
}
if chosen {
ui.separator();
let key = &row.data.key;
let (a, b, p) = endpoints(key, &self.names);
ui.label(format!("{a} ↔ {b} · {p}"));
ui.label(format!(
"{} {} packets sent {} {} received",
icon::ARROW_UP,
row.data.tx_packets,
icon::ARROW_DOWN,
row.data.rx_packets
));
let id = public_id(&key.peer);
ui.horizontal_wrapped(|ui| {
ui.weak("Peer ID");
crate::format::copy_field(ui, &short(&id), &id);
});
}
});
.show_rows(ui, grid.row_height, page.rows.len(), |ui, visible| {
for index in visible {
grid.row(ui, columns, &page.rows[index], &self.names, now, index);
}
});
}
ui.ctx().request_repaint_after(Duration::from_secs(1));
}
fn row(&self, ui: &mut Ui, r: &Row, now: u64, wide: bool) {
let k = &r.data.key;
let (a, b, p) = endpoints(k, &self.names);
let network = self.names.network(&k.network);
let peer = self.names.peer(&k.network, &k.peer);
let role = role_text(k.role);
let current = now.saturating_sub(r.sampled) < 1900;
let rates = |n: f32| format!("{}/s", bytes(if current { n as f64 } else { 0. }));
let (tx, rx) = (bytes(r.data.tx_bytes as f64), bytes(r.data.rx_bytes as f64));
let age = ago(now.saturating_sub(r.last));
if wide {
let widths = widths(ui);
ui.horizontal(|ui| {
cell(ui, widths[0], &peer, &network);
cell(ui, widths[1], &a, &b);
cell(ui, widths[2], &p, &role);
cell(ui, widths[3], &tx, &rates(r.tx_rate));
cell(ui, widths[4], &rx, &rates(r.rx_rate));
cell(ui, widths[5], &age, "");
});
} else {
ui.set_min_width(ui.available_width());
ui.horizontal_wrapped(|ui| {
ui.strong(peer);
ui.weak(&network);
ui.label(role);
ui.weak(age);
});
ui.horizontal_wrapped(|ui| {
ui.label(&p);
ui.monospace(&a);
ui.weak("↔");
ui.monospace(&b);
});
ui.horizontal_wrapped(|ui| {
ui.label(format!("{} {tx}", icon::ARROW_UP))
.on_hover_text("Sent");
ui.weak(rates(r.tx_rate));
ui.separator();
ui.label(format!("{} {rx}", icon::ARROW_DOWN))
.on_hover_text("Received");
ui.weak(rates(r.rx_rate));
});
}
}
}
fn widths(ui: &Ui) -> [f32; 6] {
let usable = (ui.available_width() - ui.spacing().item_spacing.x * 5. - 4.).max(0.);
[0.18, 0.30, 0.18, 0.13, 0.13, 0.08].map(|s| s * usable)
}
fn cell(ui: &mut Ui, width: f32, one: &str, two: &str) {
ui.allocate_ui_with_layout(
egui::vec2(width, 0.),
egui::Layout::top_down(egui::Align::Min),
|ui| {
ui.add(egui::Label::new(one).truncate()).on_hover_text(one);
if !two.is_empty() {
ui.add(egui::Label::new(RichText::new(two).weak().small()).truncate())
.on_hover_text(two);
}
},
);
}
fn desktop_header(ui: &mut Ui) {
egui::Frame::new()
.inner_margin(egui::Margin::symmetric(5, 2))
.show(ui, |ui| {
let widths = widths(ui);
ui.horizontal(|ui| {
for ((title, hint), width) in [
("Peer / network", "Authenticated peer and local network"),
(
"Endpoints",
"This side ↔ peer side. Encrypted relay shows the two named endpoints.",
),
(
"Protocol / role",
"IP protocol or transport observation and forwarding role",
),
(
"↑ Sent",
"Total and rate toward the peer (first to second endpoint for relay)",
),
(
"↓ Received",
"Total and rate from the peer (second to first endpoint for relay)",
),
("Seen", "Time since last activity"),
]
.into_iter()
.zip(widths)
{
ui.add_sized(
[width, 17.],
egui::Label::new(RichText::new(title).small().weak())
.halign(egui::Align::Min)
.truncate(),
)
.on_hover_text(hint);
}
});
});
}
+444
View File
@@ -0,0 +1,444 @@
//! One shared column layout for the pinned header and the virtualized rows.
use super::{
Column, Names, Sort, ago, endpoints,
history::{RATE_LIFETIME_MS, Row},
public_id, role_name,
};
use crate::{
format::{bytes, short},
widgets,
};
use egui::{
Align, Align2, Color32, FontFamily, FontId, Layout, Rect, RichText, Sense, Ui, UiBuilder, pos2,
vec2,
};
use egui_phosphor::regular as icon;
const PAD: f32 = 8.;
const GAP: f32 = 12.;
struct Colors {
text: Color32,
secondary: Color32,
sent: Color32,
received: Color32,
header: Color32,
stripe: Color32,
}
impl Colors {
fn new(dark: bool) -> Self {
let tone = |dark_rgb: [u8; 3], light_rgb: [u8; 3]| {
let [r, g, b] = if dark { dark_rgb } else { light_rgb };
Color32::from_rgb(r, g, b)
};
Self {
text: tone([239, 244, 249], [27, 40, 53]),
secondary: tone([195, 207, 219], [62, 79, 96]),
sent: tone([140, 211, 255], [16, 89, 145]),
received: tone([145, 226, 185], [16, 102, 72]),
header: tone([42, 55, 68], [224, 234, 243]),
stripe: tone([35, 42, 49], [240, 245, 249]),
}
}
}
pub(super) fn style(ui: &mut Ui) {
let colors = Colors::new(ui.visuals().dark_mode);
let style = ui.style_mut();
for id in [egui::TextStyle::Body, egui::TextStyle::Button] {
if let Some(font) = style.text_styles.get_mut(&id) {
font.size = font.size.max(15.);
}
}
style.visuals.widgets.noninteractive.fg_stroke.color = colors.text;
style.visuals.widgets.inactive.fg_stroke.color = colors.text;
}
#[derive(Clone, Copy)]
pub(super) struct Slot {
column: Column,
left: f32,
width: f32,
}
pub(super) struct Grid {
pub pages: Vec<Vec<Slot>>,
pub row_height: f32,
width: f32,
body: FontId,
bold: FontId,
mono: FontId,
colors: Colors,
}
impl Grid {
pub fn new(ui: &Ui) -> Self {
use Column::*;
// Leave the same scroll gutter above and below, even while the bar animates.
let width = (ui.available_width() - ui.spacing().scroll.allocated_width()).max(1.);
let body = egui::FontSelection::Default.resolve(ui.style());
let bold = FontId::new(body.size, FontFamily::Name("Bold".into()));
let mono = FontId::monospace(body.size);
let measure = |s: &str, f: &FontId| {
ui.painter()
.layout_no_wrap(s.into(), f.clone(), Color32::WHITE)
.size()
.x
};
let height = ui.fonts(|f| {
f.row_height(&body)
.max(f.row_height(&bold))
.max(f.row_height(&mono))
});
let minimum = |col: Column| {
let sample = match col {
Near | Far => "255.255.255.255:65535",
Network => "network",
Protocol => "ICMP echo",
Role => "Serving exit",
Sent | Received => "1024.0 MB",
SendRate | ReceiveRate => "1024.0 MB/s",
SentPackets | ReceivedPackets => "99999999",
Seen => "Last seen",
PeerId => "0123456789ab…",
Peer => "device-name",
};
let font = if matches!(col, Near | Far | PeerId) {
&mono
} else {
&body
};
measure(sample, font)
.max(measure(col.title(), &bold) + 15.)
.ceil()
+ 2.
};
// Keep the peer visible on each column page. Put the most useful live
// numbers on the first page, then arrange each page in reading order.
let mut remaining = vec![
Sent,
Received,
Seen,
Far,
Near,
Protocol,
Role,
Network,
SendRate,
ReceiveRate,
SentPackets,
ReceivedPackets,
PeerId,
];
let inner = (width - 2. * PAD).max(1.);
let pinned = minimum(Peer).min(inner * 0.32);
let room = (inner - pinned - GAP).max(0.);
let mut pages = Vec::new();
while !remaining.is_empty() {
let mut fields = vec![(Peer, pinned)];
let mut free = room;
remaining.retain(|c| {
let w = minimum(*c).min(room);
if fields.len() == 1 || w <= free {
fields.push((*c, w));
free -= w + GAP;
false
} else {
true
}
});
fields.sort_by_key(|(c, _)| *c);
let weight = |c: Column| {
if matches!(c, Peer | Near | Far | Network | Role) {
2.
} else {
1.
}
};
let parts: f32 = fields.iter().map(|(c, _)| weight(*c)).sum();
let extra = (free + GAP).max(0.) / parts;
let mut x = PAD;
pages.push(
fields
.into_iter()
.map(|(column, w)| {
let slot = Slot {
column,
left: x,
width: w + extra * weight(column),
};
x += slot.width + GAP;
slot
})
.collect(),
);
}
Self {
pages,
row_height: height.ceil() + 8.,
width,
body,
bold,
mono,
colors: Colors::new(ui.visuals().dark_mode),
}
}
pub fn chooser(&self, ui: &mut Ui, page: &mut usize) {
if self.pages.len() == 1 {
return;
}
let response = egui::ComboBox::from_id_salt("traffic-columns")
.selected_text(format!(
"{} Columns {}/{}",
icon::COLUMNS,
*page + 1,
self.pages.len()
))
.show_ui(ui, |ui| {
ui.set_max_width((ui.ctx().screen_rect().width() - 45.).clamp(100., 400.));
ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Wrap);
for (i, slots) in self.pages.iter().enumerate() {
let fields = slots
.iter()
.skip(1)
.map(|s| s.column.title())
.collect::<Vec<_>>()
.join(" · ");
ui.selectable_value(page, i, fields);
}
})
.response;
widgets::hint(
response,
"Choose which columns to show. The peer stays visible.",
);
}
fn ink(&self, column: Column) -> Color32 {
match column {
Column::Sent | Column::SentPackets | Column::SendRate => self.colors.sent,
Column::Received | Column::ReceivedPackets | Column::ReceiveRate => {
self.colors.received
}
Column::Network | Column::Seen => self.colors.secondary,
_ => self.colors.text,
}
}
pub fn header(&self, ui: &mut Ui, slots: &[Slot], sort: Sort) -> Option<Column> {
let (row, _) =
ui.allocate_exact_size(vec2(self.width, self.row_height + 3.), Sense::hover());
ui.painter().rect_filled(row, 3., self.colors.header);
let mut clicked = None;
for slot in slots {
let col = slot.column;
let bounds = slot.rect(row);
let active = sort.column == col;
let mut text = bounds;
if active {
let right = numeric(col);
let x = if right {
text.min.x += 14.;
bounds.left()
} else {
text.max.x -= 14.;
bounds.right()
};
ui.painter().text(
pos2(x, row.center().y),
if right {
Align2::LEFT_CENTER
} else {
Align2::RIGHT_CENTER
},
if sort.descending {
icon::CARET_DOWN
} else {
icon::CARET_UP
},
self.body.clone(),
self.colors.text,
);
}
cell(
ui,
text,
col.title(),
&self.bold,
self.ink(col),
numeric(col),
);
let r = ui
.interact(
bounds,
ui.id().with(("sort traffic", col.title())),
Sense::click(),
)
.on_hover_cursor(egui::CursorIcon::PointingHand);
let direction = if active && sort.descending {
"descending"
} else {
"ascending"
};
let hint = if active {
format!("{} · Sorted {direction}. Select to reverse.", col.hint())
} else {
format!("{} · Select to sort.", col.hint())
};
r.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &hint));
if widgets::hint(r, &hint).clicked() {
clicked = Some(col);
}
}
clicked
}
pub fn row(&self, ui: &mut Ui, slots: &[Slot], r: &Row, names: &Names, now: u64, index: usize) {
let (row, _) = ui.allocate_exact_size(vec2(self.width, self.row_height), Sense::hover());
if index % 2 == 1 {
ui.painter().rect_filled(row, 0., self.colors.stripe);
}
let key = &r.data.key;
let (near, far, protocol) = endpoints(key, names);
let live = now.saturating_sub(r.sampled) < RATE_LIFETIME_MS;
for slot in slots {
use Column::*;
let col = slot.column;
let label = match col {
Peer => names.peer(&key.network, &key.peer),
Network => names.network(&key.network),
Near => near.clone(),
Far => far.clone(),
Protocol => protocol.clone(),
Role => role_name(key.role).into(),
Sent => bytes(r.data.tx_bytes as f64),
Received => bytes(r.data.rx_bytes as f64),
SendRate | ReceiveRate => {
let rate = if !live {
0.
} else if col == SendRate {
r.tx_rate
} else {
r.rx_rate
};
format!("{}/s", bytes(f64::from(rate)))
}
SentPackets => r.data.tx_packets.to_string(),
ReceivedPackets => r.data.rx_packets.to_string(),
Seen => ago(now.saturating_sub(r.last)),
PeerId => short(&public_id(&key.peer)),
};
let font = match col {
Peer => &self.bold,
Near | Far | PeerId => &self.mono,
_ => &self.body,
};
let bounds = slot.rect(row);
let response = cell(ui, bounds, &label, font, self.ink(col), numeric(col));
if col == PeerId {
let full = public_id(&key.peer);
let button = ui
.interact(
bounds,
ui.id().with(("copy flow peer", r.id)),
Sense::click(),
)
.on_hover_cursor(egui::CursorIcon::PointingHand);
button.widget_info(|| {
egui::WidgetInfo::labeled(egui::WidgetType::Button, true, "Copy peer ID")
});
if widgets::hint(button, &format!("Copy peer ID\n{full}")).clicked() {
ui.ctx().copy_text(full);
}
} else {
widgets::hint(response, &label);
}
}
}
}
impl Slot {
fn rect(&self, row: Rect) -> Rect {
Rect::from_min_size(
pos2(row.left() + self.left, row.top()),
vec2(self.width, row.height()),
)
}
}
fn numeric(c: Column) -> bool {
c.descending_first()
}
fn cell(
ui: &mut Ui,
bounds: Rect,
text: &str,
font: &FontId,
color: Color32,
right: bool,
) -> egui::Response {
let layout = if right {
Layout::right_to_left(Align::Center)
} else {
Layout::left_to_right(Align::Center)
};
// Glyph origins are snapped to physical pixels. Leave a point inside each
// edge so the overhang of a right-aligned digit or bold header stays visible.
let content = bounds.shrink2(vec2(1., 0.));
let mut child = ui.new_child(UiBuilder::new().max_rect(content).layout(layout));
child.set_clip_rect(ui.clip_rect().intersect(bounds));
child.add(
egui::Label::new(RichText::new(text).font(font.clone()).color(color))
.selectable(false)
.truncate(),
)
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeSet;
#[test]
fn all_columns_are_reachable_without_horizontal_scrolling() {
use Column::*;
let expected = BTreeSet::from([
Network,
Near,
Far,
Protocol,
Role,
Sent,
Received,
SendRate,
ReceiveRate,
SentPackets,
ReceivedPackets,
Seen,
PeerId,
]);
for size in [15., 20.] {
let ctx = egui::Context::default();
ctx.set_fonts(crate::app_fonts());
ctx.style_mut(|s| {
s.text_styles
.insert(egui::TextStyle::Body, FontId::proportional(size));
});
for width in [320., 480., 760., 920., 1600.] {
let input = egui::RawInput {
screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(width, 400.))),
..Default::default()
};
let _ = ctx.run(input, |ctx| {
egui::CentralPanel::default().show(ctx, |ui| {
style(ui);
let grid = Grid::new(ui);
let mut seen = BTreeSet::new();
for page in &grid.pages {
assert_eq!(page[0].column, Peer);
for slot in &page[1..] {
assert!(seen.insert(slot.column));
assert!(
slot.width > 0. && slot.left + slot.width <= grid.width + 0.1
);
}
}
assert_eq!(seen, expected);
});
});
}
}
}
}
+288 -41
View File
@@ -1,4 +1,4 @@
#![allow(clippy::unwrap_used)]
#![allow(clippy::unwrap_used, clippy::panic)]
use super::history::*;
use tsunagi::traffic::*;
@@ -42,7 +42,7 @@ fn window_history_expires_and_long_capture_is_paged_and_bidirectional() {
assert_eq!(p.rows.len(), PAGE_SIZE);
assert!(p.more);
let next = Filter {
before: Some(p.rows.last().unwrap().id),
before: Some(p.rows.last().unwrap().cursor()),
..filter.clone()
};
assert!(
@@ -133,48 +133,295 @@ fn private_cache_file_is_unlinked_and_remains_writable_across_transactions() {
}
#[test]
fn live_monitor_has_readable_rows_inside_phone_and_desktop_widths() {
use super::Window;
use std::time::{Duration, Instant};
let mut win = Window::new(None);
let feed = win.feed();
assert!(win.worker.view().0.rows.is_empty());
feed.sample(TrafficSnapshot {
flows: vec![sample(55201, true)],
interval_ms: 1_000,
omitted: 0,
});
let deadline = Instant::now() + Duration::from_secs(3);
while win.worker.view().0.rows.is_empty() {
assert!(Instant::now() < deadline, "worker did not publish the flow");
std::thread::yield_now();
}
for width in [320., 390., 720., 900.] {
let ctx = egui::Context::default();
ctx.set_fonts(crate::app_fonts());
let frame = ctx.run(
egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(
egui::Pos2::ZERO,
egui::vec2(width, 600.),
)),
..Default::default()
fn sorting_uses_the_entire_filtered_capture_and_pages_through_ties() {
use super::{Column, Sort};
let mut db = History::open(None).unwrap();
let mut data: Vec<_> = (0..150)
.map(|port| {
let mut flow = sample(port, true);
flow.tx_bytes = u64::from((port * 7) % 13) * 1024;
flow
})
.collect();
let mut foreign = sample(443, true);
foreign.key.network = [7; 32];
foreign.tx_bytes = 99_000_000;
data.push(foreign);
db.apply(&data, 1000, 1000, true).unwrap();
for descending in [false, true] {
let mut filter = Filter {
network: Some([1; 32]),
sort: Sort {
column: Column::Sent,
descending,
},
|ctx| {
egui::CentralPanel::default().show(ctx, |ui| {
win.show(ui, None, 0);
assert!(
ui.min_rect().right() <= width,
"monitor grew beyond {width}: {:?}",
ui.min_rect()
);
});
..Default::default()
};
let mut seen = Vec::new();
loop {
let page = db.page(&filter).unwrap();
seen.extend(page.rows.iter().map(|r| (r.data.tx_bytes, r.id)));
if !page.more {
break;
}
filter.before = Some(page.rows.last().unwrap().cursor());
}
assert_eq!(seen.len(), 150);
assert!(seen.windows(2).all(|pair| if descending {
pair[0] > pair[1]
} else {
pair[0] < pair[1]
}));
}
}
#[test]
fn a_stale_member_name_does_not_reindex_the_capture_every_refresh() {
use tsunagi::ipc::{MemberReport, NetworkReport, PeerReport, StatusReport};
let peer = tsunagi::identity::DeviceIdentity::from_secret_bytes(&[9; 32]).endpoint_id();
let network = tsunagi::NetworkId::from_bytes([3; 32]);
let mut report = StatusReport {
networks: vec![NetworkReport {
network_id: network.to_string(),
name: "lab".into(),
members: vec![MemberReport {
endpoint_id: peer.to_string(),
hostname: Some("old".into()),
..Default::default()
}],
peers: vec![PeerReport {
endpoint_id: peer.to_string(),
hostname: Some("current".into()),
..Default::default()
}],
..Default::default()
}],
..Default::default()
};
let mut names = super::Names::default();
assert!(names.refresh(Some(&report), 1));
assert_eq!(names.peer(network.as_bytes(), peer.as_bytes()), "current");
assert!(!names.refresh(Some(&report), 2));
report.networks[0].peers[0].hostname = None;
assert!(names.refresh(Some(&report), 3));
assert_eq!(names.peer(network.as_bytes(), peer.as_bytes()), "old");
}
#[test]
fn sorting_uses_display_names_numeric_endpoints_and_live_rates() {
use super::{Column, Names, Network, Sort};
use std::{collections::BTreeMap, sync::Arc};
let mut db = History::open(None).unwrap();
let first = sample(200, true);
let mut second = sample(9, true);
second.key.peer = [3; 32];
if let Flow::Ip { ref mut far, .. } = second.key.flow {
*far = [10, 0, 0, 10];
}
second.tx_bytes = 250;
let mut names = Names::default();
names.networks.insert(
[1; 32],
Network {
name: "lab".into(),
peers: BTreeMap::from([([2; 32], "zeta".into()), ([3; 32], "Alpha".into())]),
},
);
db.use_names(Arc::new(names.clone()));
db.apply(&[first.clone(), second.clone()], 1000, 1000, true)
.unwrap();
let filter = |column| Filter {
sort: Sort {
column,
descending: false,
},
..Default::default()
};
assert_eq!(
db.page(&filter(Column::Peer)).unwrap().rows[0]
.data
.key
.peer,
[3; 32]
);
names
.networks
.get_mut(&[1; 32])
.unwrap()
.peers
.insert([2; 32], "aardvark".into());
db.use_names(Arc::new(names));
for (column, id) in [(Column::Peer, 2), (Column::Near, 3), (Column::Far, 2)] {
assert_eq!(
db.page(&filter(column)).unwrap().rows[0].data.key.peer,
[id; 32]
);
}
db.apply(&[first], 3000, 1000, true).unwrap();
let speeds = db.page(&filter(Column::SendRate)).unwrap();
assert_eq!(
(speeds.rows[0].data.key.peer, speeds.rows[0].tx_rate),
([3; 32], 0.)
);
assert!(speeds.rows[1].tx_rate > 0.);
}
#[test]
fn monitor_rows_stay_on_one_line_and_headers_sort_in_both_themes() {
use super::{Column, Network, Window};
use egui::{Color32, Context, Event, Pos2, Rect, Shape, Theme};
use std::time::{Duration, Instant};
for (theme, width) in [
(Theme::Dark, 920.),
(Theme::Light, 920.),
(Theme::Dark, 320.),
] {
let ctx = Context::default();
ctx.set_theme(theme);
ctx.set_fonts(crate::app_fonts());
let mut win = Window::new(None);
win.names.networks.insert(
[1; 32],
Network {
name: "lab".into(),
peers: [([2; 32], "alder".into()), ([3; 32], "birch".into())].into(),
},
);
for value in ["10.0.0.1:55201", "10.0.0.2:443", "TCP", "Mesh"] {
assert!(frame.shapes.iter().any(|s|matches!(&s.shape,egui::Shape::Text(t) if t.galley.text().contains(value) && t.visual_bounding_rect().right()<=width)), "{value} outside {width}");
let left = sample(55201, true);
let mut right = sample(7, false);
right.key.peer = [3; 32];
let feed = win.feed();
assert!(win.worker.view().0.rows.is_empty());
feed.sample(TrafficSnapshot {
flows: vec![left, right],
interval_ms: 1000,
omitted: 0,
});
let wait = |win: &Window| {
let deadline = Instant::now() + Duration::from_secs(3);
while win.worker.view().0.rows.len() != 2 {
assert!(Instant::now() < deadline);
std::thread::yield_now();
}
};
wait(&win);
let draw = |win: &mut Window, events: Vec<Event>| {
ctx.run(
egui::RawInput {
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, egui::vec2(width, 480.))),
events,
..Default::default()
},
|ctx| {
egui::CentralPanel::default().show(ctx, |ui| {
win.show(ui, None, 0);
assert!(ui.min_rect().right() <= width);
});
},
)
};
let label = |frame: &egui::FullOutput, value: &str| {
frame
.shapes
.iter()
.find_map(|s| match &s.shape {
Shape::Text(t) if t.galley.text() == value => {
let section = &t.galley.job.sections[0].format;
assert!(
section.font_id.size >= 14.,
"{value} at {}",
section.font_id.size
);
assert!(
s.clip_rect.contains_rect(t.visual_bounding_rect()),
"{value} clipped at {width}: {:?} outside {:?}",
t.visual_bounding_rect(),
s.clip_rect
);
Some((
t.visual_bounding_rect(),
t.override_text_color.unwrap_or(section.color),
))
}
_ => None,
})
.unwrap_or_else(|| panic!("missing {value} at {width}"))
};
let click = |win: &mut Window, pos| {
for pressed in [true, false] {
draw(
win,
vec![
Event::PointerMoved(pos),
Event::PointerButton {
pos,
button: egui::PointerButton::Primary,
pressed,
modifiers: Default::default(),
},
],
);
}
wait(win);
};
let mut frame = draw(&mut win, vec![]);
let chooser = frame
.shapes
.iter()
.find_map(|s| match &s.shape {
Shape::Text(t) if t.galley.text().contains("Columns 1/") => {
Some(t.visual_bounding_rect())
}
_ => None,
})
.unwrap();
assert!(
chooser.right() < width,
"column chooser is outside the viewport at {width}"
);
let (peer, _) = label(&frame, "alder");
let (sent, ink) = label(&frame, "90 B");
let (header, _) = label(&frame, "Sent");
assert!((peer.center().y - sent.center().y).abs() < 2.);
assert!((label(&frame, "birch").0.center().y - peer.center().y).abs() < 34.);
assert!((sent.right() - header.right()).abs() < 2.);
assert!(sent.left() > width * 0.33 || width < 400.);
let bg = if theme == Theme::Dark {
Color32::from_gray(35)
} else {
Color32::from_gray(239)
};
let luminance = |c: Color32| {
let v = egui::Rgba::from(c);
0.2126 * v.r() + 0.7152 * v.g() + 0.0722 * v.b()
};
let (a, b) = (luminance(ink), luminance(bg));
assert!(
(a.max(b) + 0.05) / (a.min(b) + 0.05) >= 4.5,
"contrast of {ink:?} at {width}"
);
click(&mut win, peer.center());
frame = draw(&mut win, vec![]);
assert!(!frame.shapes.iter().any(
|s| matches!(&s.shape,Shape::Text(t) if t.galley.text().contains("packets sent"))
));
assert!(
(label(&frame, "birch").0.center().y - label(&frame, "alder").0.center().y).abs() < 34.
);
for descending in [true, false] {
click(&mut win, header.center());
assert_eq!(
(win.filter.sort.column, win.filter.sort.descending),
(Column::Sent, descending)
);
frame = draw(&mut win, vec![]);
assert_eq!(
label(&frame, "alder").0.top() < label(&frame, "birch").0.top(),
descending
);
}
drop(win);
assert!(!feed.sample(TrafficSnapshot::default()));
}
drop(win);
assert!(!feed.sample(TrafficSnapshot::default()));
}
+26 -7
View File
@@ -1,15 +1,19 @@
use super::history::{Filter, History, Page};
use super::{
Names,
history::{Filter, History, Page},
};
use std::{
collections::VecDeque,
path::PathBuf,
sync::{Arc, Condvar, Mutex, MutexGuard},
time::Instant,
time::{Duration, Instant},
};
use tsunagi::traffic::TrafficSnapshot;
struct Work {
samples: VecDeque<(u64, TrafficSnapshot)>,
filter: Filter,
names: Arc<Names>,
keep: bool,
dirty: bool,
closed: bool,
@@ -79,6 +83,7 @@ impl Worker {
state: Mutex::new(Work {
samples: VecDeque::new(),
filter: Filter::default(),
names: Arc::default(),
keep: false,
dirty: true,
closed: false,
@@ -110,6 +115,12 @@ impl Worker {
pub fn protocols(&self) -> Vec<u8> {
self.feed.0.lock().protocols.iter().copied().collect()
}
pub fn names(&self, names: Arc<Names>) {
let mut w = self.feed.0.lock();
w.names = names;
w.dirty = true;
self.feed.0.wake.notify_one();
}
pub fn options(&self, filter: Filter, keep: bool) {
let mut w = self.feed.0.lock();
if w.filter != filter {
@@ -142,18 +153,26 @@ fn run(shared: &Shared, directory: Option<PathBuf>) -> Result<(), String> {
let mut db = History::open(directory.as_deref())?;
shared.lock().interrupt = Some(db.interrupt());
loop {
let (mut samples, filter, keep) = {
let (mut samples, filter, keep, names) = {
let w = shared.lock();
let mut w = shared
let (mut w, _) = shared
.wake
.wait_while(w, |w| !w.closed && !w.dirty && w.samples.is_empty())
.wait_timeout_while(w, Duration::from_secs(1), |w| {
!w.closed && !w.dirty && w.samples.is_empty()
})
.unwrap_or_else(|e| e.into_inner());
if w.closed {
return Ok(());
}
w.dirty = false;
(std::mem::take(&mut w.samples), w.filter.clone(), w.keep)
(
std::mem::take(&mut w.samples),
w.filter.clone(),
w.keep,
w.names.clone(),
)
};
db.use_names(names.clone());
if samples.is_empty() {
db.apply(&[], shared.start.elapsed().as_millis() as u64, 0, keep)?;
}
@@ -162,7 +181,7 @@ fn run(shared: &Shared, directory: Option<PathBuf>) -> Result<(), String> {
}
let page = Arc::new(db.page(&filter)?);
let mut w = shared.lock();
if !w.closed && filter == w.filter {
if !w.closed && filter == w.filter && Arc::ptr_eq(&names, &w.names) {
w.page = page;
}
}
+2 -2
View File
@@ -3,7 +3,7 @@ name = "tsunagi-wg-quic"
# 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
# build, because what peers compare is `ANNOUNCEMENT_VERSION`.
version = "1.0.7"
version = "1.0.8"
description = "The single internal WireGuard tunnel for tsunagi, independent of external carriers."
edition.workspace = true
rust-version.workspace = true
@@ -11,7 +11,7 @@ license.workspace = true
repository.workspace = true
[dependencies]
tsunagi-core = { path = "../tsunagi-core", version = "1.0.7" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.8" }
iroh.workspace = true
tokio.workspace = true
serde.workspace = true
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-wireguard"
version = "1.0.7"
version = "1.0.8"
description = "Independent authenticated WireGuard and Amnezia UDP carriers for tsunagi."
edition.workspace = true
rust-version.workspace = true
@@ -8,7 +8,7 @@ license = "WTFPL AND Apache-2.0"
repository.workspace = true
[dependencies]
tsunagi-core = { path = "../tsunagi-core", version = "1.0.7" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.8" }
iroh.workspace = true
tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] }
serde.workspace = true
+6 -6
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi"
version = "1.0.7"
version = "1.0.8"
description = "The tsunagi command line agent."
edition.workspace = true
rust-version.workspace = true
@@ -12,11 +12,11 @@ name = "tsng"
path = "src/main.rs"
[dependencies]
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.7" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.7", features = ["tun-device", "dns-publish"] }
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.7" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.7" }
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.7" }
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.8" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.8", features = ["tun-device", "dns-publish"] }
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.8" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.8" }
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.8" }
iroh.workspace = true
tokio = { version = "1.53", features = ["rt", "rt-multi-thread", "sync", "time", "macros", "signal"] }
tracing.workspace = true