Add a Rust Android mesh client with shared tray views
Run one agent for all joined networks behind Android's VPN service. Share transport registration and reporting with the CLI, and move the tray's egui forms into a Rust UI crate. Phones use compact device rows and a full-width exit picker with RTT and data path. All four transports retain their per-network selection and priority. The phone consumes remote IPv4 exits and keeps the existing desktop identity and wire protocols. Send discovery and transport traffic over the physical network and bind VIP TCP health checks to the mesh. Build local DNS zones from the same signed membership and VIP records on desktop and Android. Answer UDP and TCP queries on the VPN, keep unknown mesh names local, and resolve public names through Android's underlying resolver, including with an exit. Show an ongoing notification for the selected exit. Guard its disconnect action against a stale selection and keep mesh routing and DNS alive when it removes the default route. Remove the app notification in mesh-only mode. Document Android 14's unlocked-device swipe behavior. Checked formatting and ran locked all-target workspace Clippy with warnings denied and tests on macOS (547 passed, 2 ignored). Built the arm64 debug APK. A physical Pixel resolved a mesh member and a Kubernetes VIP, answered UDP and TCP DNS, and reached the API over TLS (HTTP 401 without credentials). On a separate Android emulator the notification action removed the default route and notice while mesh DNS still worked.
This commit is contained in:
1 parent
9dec056349
commit
ef67e1c0ae
70 files changed
+6199
-1181
No files matched your search
@@ -0,0 +1,183 @@
|
||||
//! The About window: what this software is, and what it is talking to.
|
||||
//!
|
||||
//! Compact on purpose — one table for the client, one for the agent. The agent
|
||||
//! half is whatever the agent says about itself, so a client and an agent that
|
||||
//! are not the same build show up as such.
|
||||
|
||||
use tsunagi::ipc::{PrivilegeReport, StatusReport};
|
||||
|
||||
use crate::client::Snapshot;
|
||||
use crate::format;
|
||||
|
||||
const REPOSITORY: &str = env!("CARGO_PKG_REPOSITORY");
|
||||
const AUTHOR: &str = "AB <tsunagi@hexor.cy>";
|
||||
const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
/// Draws the window body into its viewport.
|
||||
pub fn show(ctx: &egui::Context, socket: Option<&std::path::Path>, snapshot: &Snapshot) {
|
||||
egui::CentralPanel::default().show(ctx, |ui| {
|
||||
// Long paths and a taller agent table must scroll rather than be cut.
|
||||
egui::ScrollArea::both()
|
||||
.auto_shrink([false, false])
|
||||
.show(ui, |ui| body(ui, socket, snapshot));
|
||||
});
|
||||
}
|
||||
|
||||
fn body(ui: &mut egui::Ui, socket: Option<&std::path::Path>, snapshot: &Snapshot) {
|
||||
{
|
||||
ui.horizontal(|ui| {
|
||||
ui.heading("tsunagi");
|
||||
ui.label(egui::RichText::new(VERSION).small().weak());
|
||||
});
|
||||
ui.label("Peer-to-peer mesh network with no server.");
|
||||
ui.add_space(6.0);
|
||||
|
||||
section(ui, "client");
|
||||
grid(ui, "about client", |ui| {
|
||||
row(ui, "repository", |ui| {
|
||||
ui.hyperlink(REPOSITORY);
|
||||
});
|
||||
row(ui, "author", |ui| {
|
||||
format::copy_field(ui, AUTHOR, AUTHOR);
|
||||
});
|
||||
row(ui, "license", |ui| {
|
||||
ui.label(env!("CARGO_PKG_LICENSE"));
|
||||
});
|
||||
row(ui, "build", |ui| {
|
||||
ui.label(format!(
|
||||
"{} {} · {}",
|
||||
std::env::consts::OS,
|
||||
std::env::consts::ARCH,
|
||||
if cfg!(debug_assertions) {
|
||||
"debug"
|
||||
} else {
|
||||
"release"
|
||||
}
|
||||
));
|
||||
});
|
||||
});
|
||||
|
||||
ui.add_space(8.0);
|
||||
section(ui, "agent");
|
||||
let socket = socket.map(|p| p.display().to_string());
|
||||
match &snapshot.status {
|
||||
None => {
|
||||
grid(ui, "about agent", |ui| {
|
||||
if let Some(socket) = &socket {
|
||||
row(ui, "socket", |ui| format::copy_field(ui, socket, socket));
|
||||
}
|
||||
row(ui, "state", |ui| {
|
||||
ui.label("connecting…");
|
||||
});
|
||||
});
|
||||
}
|
||||
Some(Err(error)) => {
|
||||
grid(ui, "about agent", |ui| {
|
||||
if let Some(socket) = &socket {
|
||||
row(ui, "socket", |ui| format::copy_field(ui, socket, socket));
|
||||
}
|
||||
row(ui, "state", |ui| {
|
||||
ui.colored_label(egui::Color32::from_rgb(0xd8, 0x4a, 0x3a), "unreachable");
|
||||
});
|
||||
row(ui, "reason", |ui| {
|
||||
ui.add(egui::Label::new(error).wrap());
|
||||
});
|
||||
});
|
||||
}
|
||||
Some(Ok(report)) => agent_table(ui, socket.as_deref(), report),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn agent_table(ui: &mut egui::Ui, socket: Option<&str>, report: &StatusReport) {
|
||||
grid(ui, "about agent", |ui| {
|
||||
if let Some(socket) = socket {
|
||||
row(ui, "socket", |ui| format::copy_field(ui, socket, socket));
|
||||
}
|
||||
row(ui, "state", |ui| {
|
||||
ui.colored_label(egui::Color32::from_rgb(0x3c, 0xb0, 0x4a), "connected");
|
||||
});
|
||||
row(ui, "version", |ui| {
|
||||
if report.version.is_empty() {
|
||||
ui.weak("unknown");
|
||||
} else if report.version == VERSION {
|
||||
ui.label(&report.version);
|
||||
} else {
|
||||
ui.colored_label(
|
||||
egui::Color32::from_rgb(0xd8, 0x9a, 0x2a),
|
||||
format!("{} (client is {VERSION})", report.version),
|
||||
);
|
||||
}
|
||||
});
|
||||
if !report.protocols.is_empty() {
|
||||
row(ui, "protocols", |ui| {
|
||||
ui.label(report.protocols.join(" · "));
|
||||
});
|
||||
}
|
||||
row(ui, "endpoint id", |ui| {
|
||||
format::copy_field(ui, &format::short(&report.endpoint_id), &report.endpoint_id);
|
||||
});
|
||||
row(ui, "hostname", |ui| {
|
||||
ui.label(&report.hostname);
|
||||
});
|
||||
if !report.program.is_empty() {
|
||||
row(ui, "binary", |ui| {
|
||||
format::copy_field(ui, &report.program, &report.program);
|
||||
});
|
||||
}
|
||||
if !report.state_dir.is_empty() {
|
||||
row(ui, "state dir", |ui| {
|
||||
format::copy_field(ui, &report.state_dir, &report.state_dir);
|
||||
});
|
||||
row(ui, "cache dir", |ui| {
|
||||
format::copy_field(ui, &report.cache_dir, &report.cache_dir);
|
||||
});
|
||||
}
|
||||
row(ui, "interface", |ui| match &report.privilege {
|
||||
PrivilegeReport::Unknown => {
|
||||
ui.weak("unknown");
|
||||
}
|
||||
PrivilegeReport::Available => {
|
||||
ui.label(if socket.is_some() {
|
||||
"can be managed (CAP_NET_ADMIN)"
|
||||
} else {
|
||||
"Android VPN service"
|
||||
});
|
||||
}
|
||||
PrivilegeReport::Missing(_) => {
|
||||
ui.colored_label(egui::Color32::from_rgb(0xd8, 0x9a, 0x2a), "no privileges");
|
||||
}
|
||||
PrivilegeReport::Unsupported => {
|
||||
ui.label("not supported on this platform");
|
||||
}
|
||||
});
|
||||
row(ui, "cache", |ui| {
|
||||
ui.label(if report.cache_healthy {
|
||||
"usable"
|
||||
} else {
|
||||
"unavailable"
|
||||
});
|
||||
});
|
||||
row(ui, "listening", |ui| {
|
||||
ui.label(report.bound_sockets.join(", "));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn section(ui: &mut egui::Ui, title: &str) {
|
||||
ui.label(egui::RichText::new(title).strong());
|
||||
}
|
||||
|
||||
fn grid(ui: &mut egui::Ui, id: &str, add: impl FnOnce(&mut egui::Ui)) {
|
||||
egui::Grid::new(id)
|
||||
.num_columns(2)
|
||||
.spacing([12.0, 3.0])
|
||||
.show(ui, add);
|
||||
}
|
||||
|
||||
/// One label/value line of a table.
|
||||
fn row(ui: &mut egui::Ui, label: &str, value: impl FnOnce(&mut egui::Ui)) {
|
||||
ui.weak(label);
|
||||
value(ui);
|
||||
ui.end_row();
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
//! Commands and observations shared by both graphical clients.
|
||||
use std::{path::PathBuf, time::Instant};
|
||||
use tsunagi::ipc::StatusReport;
|
||||
|
||||
/// A request from the UI to the agent.
|
||||
pub enum Command {
|
||||
/// Commit one complete VIP draft if its revision is current.
|
||||
SaveVip {
|
||||
/// Local acknowledgement token for this Save.
|
||||
token: String,
|
||||
/// Exact network identity.
|
||||
network_id: String,
|
||||
/// Complete edited configuration.
|
||||
config: tsunagi::vip::VipConfig,
|
||||
/// Revision originally opened in the form.
|
||||
expected: Option<String>,
|
||||
/// Retire this revision when saved.
|
||||
delete: bool,
|
||||
},
|
||||
/// Retire the exact offline-node claim selected in the devices window.
|
||||
ForgetNode {
|
||||
/// Exact network identity.
|
||||
network_id: String,
|
||||
/// Selected member identity.
|
||||
peer: String,
|
||||
/// Observed claim version.
|
||||
expected_version: u64,
|
||||
},
|
||||
/// Replace the network's enabled protocols in preference order.
|
||||
SetProtocols {
|
||||
/// Exact network identity.
|
||||
network_id: String,
|
||||
/// Enabled transports in preference order.
|
||||
protocols: Vec<String>,
|
||||
},
|
||||
/// Stop serving a network, or start serving it again.
|
||||
SetActive {
|
||||
/// Exact network identity.
|
||||
network_id: String,
|
||||
/// Whether to run the network.
|
||||
active: bool,
|
||||
},
|
||||
/// Turn local broadcast participation on or off for a network.
|
||||
SetBroadcast {
|
||||
/// Exact network identity.
|
||||
network_id: String,
|
||||
/// Requested local setting.
|
||||
enabled: bool,
|
||||
},
|
||||
/// Offer this device as an exit node in a network, or stop.
|
||||
SetExitOffer {
|
||||
/// Exact network identity.
|
||||
network_id: String,
|
||||
/// Requested local setting.
|
||||
enabled: bool,
|
||||
},
|
||||
/// Send all this device's internet traffic through a member of a
|
||||
/// network, or (`None`) back the ordinary way.
|
||||
SetExitNode {
|
||||
/// Exact network identity.
|
||||
network_id: String,
|
||||
/// Selected member identity.
|
||||
peer: Option<String>,
|
||||
},
|
||||
/// Join a network, or start one already configured.
|
||||
Join {
|
||||
/// Network name.
|
||||
name: String,
|
||||
/// Locally supplied join secret.
|
||||
secret: zeroize::Zeroizing<String>,
|
||||
},
|
||||
/// Leave a network entirely.
|
||||
Leave {
|
||||
/// Exact network identity.
|
||||
network_id: String,
|
||||
},
|
||||
/// Change the hostname this device announces.
|
||||
SetHostname(String),
|
||||
/// Fetch a network's shared secret and place it on the clipboard.
|
||||
CopySecret {
|
||||
/// Exact network identity.
|
||||
network_id: String,
|
||||
},
|
||||
}
|
||||
|
||||
/// Response to one revision-checked VIP write.
|
||||
#[derive(Clone)]
|
||||
pub struct VipSaveResult {
|
||||
/// Request being acknowledged.
|
||||
pub token: String,
|
||||
/// Current VIPs or the error for this draft.
|
||||
pub result: Result<Vec<tsunagi::vip::VipStatus>, String>,
|
||||
}
|
||||
/// Current observations and last command outcome from a local agent.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct Snapshot {
|
||||
/// Most recent saved draft.
|
||||
pub vip_result: Option<VipSaveResult>,
|
||||
/// The last status, or the reason it could not be read (agent down, no
|
||||
/// permission on the socket, …).
|
||||
pub status: Option<Result<std::sync::Arc<StatusReport>, String>>,
|
||||
/// The outcome of the most recent command, for a transient banner.
|
||||
pub last_action: Option<Result<String, String>>,
|
||||
/// Whether a command is currently being executed.
|
||||
pub busy: bool,
|
||||
/// Bumped each time `status` is refreshed, so the UI can tell new data from
|
||||
/// a repaint of the same data and sample traffic rates only on change.
|
||||
pub generation: u64,
|
||||
/// When this status was read, for computing rates between refreshes.
|
||||
pub at: Option<Instant>,
|
||||
/// The socket the last request went to.
|
||||
pub socket: PathBuf,
|
||||
}
|
||||
|
||||
/// Delivers a user gesture to the owning worker without blocking the UI.
|
||||
pub trait Client {
|
||||
/// Queue an action from a form.
|
||||
fn send(&self, command: Command);
|
||||
/// An earlier action is waiting for an acknowledgement.
|
||||
fn busy(&self) -> bool;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,193 @@
|
||||
//! One line per member and one expanded detail block, with no horizontal scroller.
|
||||
use super::{
|
||||
AMBER, Device, ExitConfirm, ForgetConfirm, NetworkReport, Traffic, Unit, data_path_text,
|
||||
devices, exit, forget_button, format, icon, rtt_text, tunnel_cell,
|
||||
};
|
||||
|
||||
pub(super) fn roster(
|
||||
ui: &mut egui::Ui,
|
||||
network: &NetworkReport,
|
||||
own_id: &str,
|
||||
traffic: &Traffic,
|
||||
unit: Unit,
|
||||
(exit, forget): (&mut Option<ExitConfirm>, &mut Option<ForgetConfirm>),
|
||||
) {
|
||||
let members = devices(network, own_id);
|
||||
let online = members.iter().filter(|m| m.online).count();
|
||||
ui.strong(format!(
|
||||
"devices ({} online / {} known)",
|
||||
online,
|
||||
members.len()
|
||||
));
|
||||
let id = ui.make_persistent_id(("expanded device", &network.network_id));
|
||||
let mut selected = ui.data(|d| d.get_temp::<String>(id));
|
||||
let width = ui.available_width();
|
||||
let font = egui::TextStyle::Body.resolve(ui.style());
|
||||
let measure = |s: &str| {
|
||||
ui.painter()
|
||||
.layout_no_wrap(s.to_owned(), font.clone(), ui.visuals().text_color())
|
||||
.size()
|
||||
.x
|
||||
};
|
||||
let rtt_x = width - (measure("9999 ms") + 18.0).min(width * 0.25);
|
||||
let ip_x = rtt_x - (measure("255.255.255.255") + 14.0).min(width * 0.40);
|
||||
let offsets = [16.0, ip_x, rtt_x];
|
||||
let size = egui::vec2(width, ui.text_style_height(&egui::TextStyle::Body) + 8.0);
|
||||
ui.spacing_mut().item_spacing.y = 1.0;
|
||||
let (header, _) = ui.allocate_exact_size(size, egui::Sense::hover());
|
||||
for (x, title) in offsets.into_iter().zip(["device", "IPv4", "RTT"]) {
|
||||
ui.painter().text(
|
||||
header.left_center() + egui::vec2(x, 0.),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
title,
|
||||
font.clone(),
|
||||
ui.visuals().weak_text_color(),
|
||||
);
|
||||
}
|
||||
for (index, member) in members.iter().enumerate() {
|
||||
let (row, _) = ui.allocate_exact_size(size, egui::Sense::hover());
|
||||
let response = ui.interact(row, id.with(member.id), egui::Sense::click());
|
||||
if response.clicked() {
|
||||
selected = (selected.as_deref() != Some(member.id)).then(|| member.id.to_owned());
|
||||
}
|
||||
let open = selected.as_deref() == Some(member.id);
|
||||
if open || index % 2 == 0 {
|
||||
ui.painter().rect_filled(
|
||||
row,
|
||||
2.0,
|
||||
if open {
|
||||
ui.visuals().widgets.hovered.weak_bg_fill
|
||||
} else {
|
||||
ui.visuals().faint_bg_color
|
||||
},
|
||||
);
|
||||
}
|
||||
let dot = row.left_center() + egui::vec2(6., 0.);
|
||||
if member.online {
|
||||
ui.painter().circle_filled(dot, 3., exit::GOOD);
|
||||
} else {
|
||||
ui.painter().circle_stroke(
|
||||
dot,
|
||||
3.,
|
||||
egui::Stroke::new(1.0_f32, ui.visuals().weak_text_color()),
|
||||
);
|
||||
}
|
||||
let name = member.name();
|
||||
let rtt = rtt_text(member.control_rtt_ms);
|
||||
let labels = [
|
||||
name.as_str(),
|
||||
member.address.as_deref().unwrap_or("—"),
|
||||
rtt.as_str(),
|
||||
];
|
||||
let color = if member.online {
|
||||
ui.visuals().text_color()
|
||||
} else {
|
||||
ui.visuals().weak_text_color()
|
||||
};
|
||||
for ((x, end), label) in offsets
|
||||
.into_iter()
|
||||
.zip([ip_x, rtt_x, width - 13.0])
|
||||
.zip(labels)
|
||||
{
|
||||
let mut job =
|
||||
egui::text::LayoutJob::simple_singleline(label.into(), font.clone(), color);
|
||||
job.wrap.max_rows = 1;
|
||||
job.wrap.max_width = (end - x - 4.0).max(0.0);
|
||||
job.wrap.break_anywhere = true;
|
||||
let galley = ui.painter().layout_job(job);
|
||||
let origin = row.left_center() + egui::vec2(x, -galley.size().y * 0.5);
|
||||
ui.painter().galley(origin, galley, color);
|
||||
}
|
||||
ui.painter().text(
|
||||
row.right_center(),
|
||||
egui::Align2::RIGHT_CENTER,
|
||||
if open {
|
||||
icon::CARET_DOWN
|
||||
} else {
|
||||
icon::CARET_RIGHT
|
||||
},
|
||||
font.clone(),
|
||||
ui.visuals().weak_text_color(),
|
||||
);
|
||||
if open {
|
||||
ui.push_id(member.id, |ui| {
|
||||
details(ui, network, member, traffic, unit, exit, forget)
|
||||
});
|
||||
}
|
||||
}
|
||||
ui.data_mut(|d| match selected {
|
||||
Some(member) => d.insert_temp(id, member),
|
||||
None => d.remove::<String>(id),
|
||||
});
|
||||
}
|
||||
|
||||
fn details(
|
||||
ui: &mut egui::Ui,
|
||||
network: &NetworkReport,
|
||||
member: &Device<'_>,
|
||||
traffic: &Traffic,
|
||||
unit: Unit,
|
||||
exit: &mut Option<ExitConfirm>,
|
||||
forget: &mut Option<ForgetConfirm>,
|
||||
) {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.weak(if member.online { "online" } else { "offline" });
|
||||
if let Some(name) = &member.copy {
|
||||
format::copy_field(ui, &member.name(), name);
|
||||
}
|
||||
if let Some(address) = &member.address {
|
||||
format::copy_field(ui, address, address);
|
||||
}
|
||||
});
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.weak("Endpoint ID");
|
||||
format::copy_field(ui, &format::short(member.id), member.id);
|
||||
});
|
||||
let (path, _) = data_path_text(member.path, member.via_name.as_deref(), member.online);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(path);
|
||||
tunnel_cell(ui, member);
|
||||
});
|
||||
if let Some(error) = member.data_error {
|
||||
ui.colored_label(AMBER, error);
|
||||
}
|
||||
if let Some((taken, holder)) = &member.name_taken {
|
||||
ui.colored_label(AMBER, format!("Name {taken} belongs to {holder}."));
|
||||
}
|
||||
if let Some(peer) = member.overlay {
|
||||
let series = traffic.peer(&network.network_id, &peer.public_key);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(format!(
|
||||
"TX {} · {} pkts",
|
||||
format::bytes(peer.tx_bytes as f64),
|
||||
peer.tx_packets
|
||||
));
|
||||
ui.label(format!(
|
||||
"RX {} · {} pkts",
|
||||
format::bytes(peer.rx_bytes as f64),
|
||||
peer.rx_packets
|
||||
));
|
||||
ui.weak(format::series_rate(series, unit));
|
||||
});
|
||||
format::sparkline(ui, series, unit, 22.);
|
||||
}
|
||||
if (member.exit_node || member.in_use)
|
||||
&& ui
|
||||
.button(if member.in_use {
|
||||
"Stop using exit node"
|
||||
} else {
|
||||
"Use exit node"
|
||||
})
|
||||
.clicked()
|
||||
{
|
||||
*exit = Some(ExitConfirm {
|
||||
network_id: network.network_id.clone(),
|
||||
peer_id: member.id.into(),
|
||||
name: member.name(),
|
||||
stop: member.in_use,
|
||||
main: false,
|
||||
});
|
||||
}
|
||||
forget_button(ui, member, network, forget);
|
||||
ui.separator();
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
//! The remote-exit chooser. Each radio row is one touch target, including its telemetry.
|
||||
use super::{ExitConfirm, devices, rtt_text};
|
||||
use crate::exit;
|
||||
use egui::{Align2, FontId, Pos2, Rect, Sense, Ui};
|
||||
use tsunagi::ipc::{DataPathReport, NetworkReport};
|
||||
|
||||
/// Draw the selectable exits for one network and return a choice for confirmation.
|
||||
pub fn choose_exit(ui: &mut Ui, network: &NetworkReport, own: &str) -> Option<ExitConfirm> {
|
||||
ui.heading(&network.name);
|
||||
if let Some(rules) = &network.exit.client_rules
|
||||
&& !rules.ok
|
||||
{
|
||||
ui.colored_label(exit::LOUD, &rules.detail);
|
||||
}
|
||||
let width = ui.available_width();
|
||||
let (header, _) = ui.allocate_exact_size(egui::vec2(width, 22.), Sense::hover());
|
||||
let columns = Columns::new(header);
|
||||
let muted = ui.visuals().weak_text_color();
|
||||
for (x, label) in [
|
||||
(columns.name, "Exit node"),
|
||||
(columns.rtt, "RTT"),
|
||||
(columns.path, "Path"),
|
||||
] {
|
||||
ui.painter().text(
|
||||
egui::pos2(x, header.center().y),
|
||||
Align2::LEFT_CENTER,
|
||||
label,
|
||||
egui::TextStyle::Small.resolve(ui.style()),
|
||||
muted,
|
||||
);
|
||||
}
|
||||
let current = network.exit.via.as_deref();
|
||||
let mut choice = None;
|
||||
let local = Row {
|
||||
peer: None,
|
||||
name: "No exit node",
|
||||
address: None,
|
||||
rtt: None,
|
||||
path: "Local",
|
||||
transport: None,
|
||||
selected: current.is_none(),
|
||||
};
|
||||
if local.draw(ui, &network.network_id)
|
||||
&& let Some(id) = current
|
||||
{
|
||||
choice = Some(ExitConfirm::stop_from_tile(network, id));
|
||||
}
|
||||
let mut candidates = devices(network, own);
|
||||
candidates.retain(|d| d.exit_node || d.in_use);
|
||||
candidates.sort_by_key(|d| !d.in_use);
|
||||
if let Some(id) = current
|
||||
&& !candidates.iter().any(|d| d.id == id)
|
||||
{
|
||||
Row {
|
||||
peer: Some(id),
|
||||
name: &exit::name_of(network, id),
|
||||
address: None,
|
||||
rtt: None,
|
||||
path: "Offline",
|
||||
transport: None,
|
||||
selected: true,
|
||||
}
|
||||
.draw(ui, &network.network_id);
|
||||
}
|
||||
for candidate in &candidates {
|
||||
let name = candidate.name();
|
||||
let relayed;
|
||||
let (path, transport) = if !candidate.online {
|
||||
("Offline", None)
|
||||
} else if candidate.in_use && !network.exit.via_online || candidate.data_error.is_some() {
|
||||
("Unavailable", None)
|
||||
} else {
|
||||
match candidate.path {
|
||||
Some(DataPathReport::Direct { transport }) => ("Direct", Some(transport.as_str())),
|
||||
Some(DataPathReport::Relayed { hops, .. }) => {
|
||||
relayed = format!("{hops} hops");
|
||||
("Relayed", Some(relayed.as_str()))
|
||||
}
|
||||
_ => ("Connecting", None),
|
||||
}
|
||||
};
|
||||
let row = Row {
|
||||
peer: Some(candidate.id),
|
||||
name: &name,
|
||||
address: candidate.address.as_deref(),
|
||||
rtt: candidate.control_rtt_ms,
|
||||
path,
|
||||
transport,
|
||||
selected: candidate.in_use,
|
||||
};
|
||||
if row.draw(ui, &network.network_id) && !candidate.in_use {
|
||||
choice = Some(ExitConfirm {
|
||||
network_id: network.network_id.clone(),
|
||||
peer_id: candidate.id.into(),
|
||||
name,
|
||||
stop: false,
|
||||
main: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
if !candidates.iter().any(|d| d.exit_node) {
|
||||
ui.weak("No connected peers offer an exit node.");
|
||||
}
|
||||
choice
|
||||
}
|
||||
|
||||
struct Columns {
|
||||
name: f32,
|
||||
rtt: f32,
|
||||
path: f32,
|
||||
}
|
||||
impl Columns {
|
||||
fn new(rect: Rect) -> Self {
|
||||
let path = rect.right() - (rect.width() * 0.24).clamp(66., 110.);
|
||||
Self {
|
||||
name: rect.left() + 31.,
|
||||
rtt: path - 61.,
|
||||
path,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Row<'a> {
|
||||
peer: Option<&'a str>,
|
||||
name: &'a str,
|
||||
address: Option<&'a str>,
|
||||
rtt: Option<u64>,
|
||||
path: &'a str,
|
||||
transport: Option<&'a str>,
|
||||
selected: bool,
|
||||
}
|
||||
impl Row<'_> {
|
||||
fn draw(&self, ui: &mut Ui, network: &str) -> bool {
|
||||
let font = egui::TextStyle::Body.resolve(ui.style());
|
||||
let small = egui::TextStyle::Small.resolve(ui.style());
|
||||
let height = (font.size + small.size + 18.).max(52.);
|
||||
let (rect, _) =
|
||||
ui.allocate_exact_size(egui::vec2(ui.available_width(), height), Sense::hover());
|
||||
let id = ui.make_persistent_id(("exit choice", network, self.peer));
|
||||
let response = ui.interact(rect, id, Sense::click());
|
||||
response.widget_info(|| {
|
||||
egui::WidgetInfo::selected(
|
||||
egui::WidgetType::RadioButton,
|
||||
true,
|
||||
self.selected,
|
||||
self.name,
|
||||
)
|
||||
});
|
||||
let visuals = ui.style().interact_selectable(&response, self.selected);
|
||||
let painter = ui.painter();
|
||||
if self.selected || response.hovered() || response.has_focus() {
|
||||
painter.rect_filled(rect, 3., visuals.weak_bg_fill);
|
||||
}
|
||||
painter.hline(
|
||||
rect.x_range(),
|
||||
rect.bottom(),
|
||||
ui.visuals().widgets.noninteractive.bg_stroke,
|
||||
);
|
||||
let dot = rect.left_center() + egui::vec2(15., 0.);
|
||||
painter.circle_stroke(dot, 6., visuals.fg_stroke);
|
||||
if self.selected {
|
||||
painter.circle_filled(dot, 3., visuals.text_color());
|
||||
}
|
||||
let c = Columns::new(rect);
|
||||
let center = rect.center().y;
|
||||
let muted = ui.visuals().weak_text_color();
|
||||
let line = |x: f32, end: f32, y: f32, value: &str, font: &FontId, color| {
|
||||
let mut job =
|
||||
egui::text::LayoutJob::simple_singleline(value.into(), font.clone(), color);
|
||||
job.wrap.max_rows = 1;
|
||||
job.wrap.break_anywhere = true;
|
||||
job.wrap.max_width = (end - x - 5.).max(0.);
|
||||
let text = painter.layout_job(job);
|
||||
painter.galley(Pos2::new(x, y - text.size().y * 0.5), text, color);
|
||||
};
|
||||
let pair = |x, end, label, detail: Option<&str>| {
|
||||
let y = if detail.is_some() {
|
||||
center - small.size * 0.55
|
||||
} else {
|
||||
center
|
||||
};
|
||||
line(x, end, y, label, &font, visuals.text_color());
|
||||
if let Some(detail) = detail {
|
||||
line(x, end, center + font.size * 0.65, detail, &small, muted);
|
||||
}
|
||||
};
|
||||
pair(c.name, c.rtt, self.name, self.address);
|
||||
line(
|
||||
c.rtt,
|
||||
c.path,
|
||||
center,
|
||||
&rtt_text(self.rtt),
|
||||
&font,
|
||||
visuals.text_color(),
|
||||
);
|
||||
pair(c.path, rect.right(), self.path, self.transport);
|
||||
response.clicked()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
use super::choose_exit;
|
||||
use egui::{CentralPanel, Context, Event, PointerButton, Pos2, RawInput, Rect, Shape};
|
||||
use tsunagi::ipc::{DataPathReport, ExitReport, MemberReport, NetworkReport, PeerReport};
|
||||
|
||||
#[test]
|
||||
fn exit_table_fits_phone_widths_and_the_whole_row_selects_the_exact_peer() {
|
||||
let mut network = NetworkReport {
|
||||
name: "lab".into(),
|
||||
network_id: "network-id".into(),
|
||||
exit: ExitReport {
|
||||
via: Some("old-id".into()),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
for (id, name, offer) in [
|
||||
("new-id", "west", true),
|
||||
("self", "my-phone", true),
|
||||
("ordinary", "worker", false),
|
||||
] {
|
||||
network.peers.push(PeerReport {
|
||||
endpoint_id: id.into(),
|
||||
hostname: Some(name.into()),
|
||||
rtt_ms: Some(37),
|
||||
path: DataPathReport::Direct {
|
||||
transport: "wg".into(),
|
||||
},
|
||||
exit_node: offer,
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
network.members.push(MemberReport {
|
||||
endpoint_id: "old-id".into(),
|
||||
hostname: Some("east".into()),
|
||||
..Default::default()
|
||||
});
|
||||
network.members.push(MemberReport {
|
||||
endpoint_id: "new-id".into(),
|
||||
hostname: Some("west".into()),
|
||||
overlay_address_v4: Some("10.9.0.4".into()),
|
||||
..Default::default()
|
||||
});
|
||||
for width in [320., 430.] {
|
||||
let ctx = Context::default();
|
||||
let frame = |events| {
|
||||
let mut chosen = None;
|
||||
let out = ctx.run(
|
||||
RawInput {
|
||||
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, egui::vec2(width, 640.))),
|
||||
events,
|
||||
..Default::default()
|
||||
},
|
||||
|ctx| {
|
||||
CentralPanel::default().show(ctx, |ui| {
|
||||
chosen = choose_exit(ui, &network, "self");
|
||||
});
|
||||
},
|
||||
);
|
||||
(out, chosen)
|
||||
};
|
||||
let (out, initial) = frame(Vec::new());
|
||||
assert!(initial.is_none());
|
||||
let labels: Vec<_> = out
|
||||
.shapes
|
||||
.iter()
|
||||
.filter_map(|s| match &s.shape {
|
||||
Shape::Text(t) => Some((t.galley.text(), t.visual_bounding_rect())),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
for text in [
|
||||
"No exit node",
|
||||
"east",
|
||||
"west",
|
||||
"10.9.0.4",
|
||||
"37 ms",
|
||||
"Direct",
|
||||
"wg",
|
||||
"Offline",
|
||||
] {
|
||||
assert!(
|
||||
labels.iter().any(|(label, _)| *label == text),
|
||||
"missing {text}"
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
!labels
|
||||
.iter()
|
||||
.any(|(label, _)| matches!(*label, "my-phone" | "worker"))
|
||||
);
|
||||
assert!(
|
||||
labels
|
||||
.iter()
|
||||
.all(|(_, r)| r.left() >= 0. && r.right() <= width + 1.)
|
||||
);
|
||||
let y = |name| {
|
||||
labels
|
||||
.iter()
|
||||
.find(|(label, _)| *label == name)
|
||||
.unwrap()
|
||||
.1
|
||||
.center()
|
||||
.y
|
||||
};
|
||||
assert!(y("west") - y("east") >= 44.);
|
||||
let tap = |name| {
|
||||
let pos = egui::pos2(width - 14., y(name) + 8.0);
|
||||
frame(vec![
|
||||
Event::PointerMoved(pos),
|
||||
Event::PointerButton {
|
||||
pos,
|
||||
button: PointerButton::Primary,
|
||||
pressed: true,
|
||||
modifiers: Default::default(),
|
||||
},
|
||||
]);
|
||||
frame(vec![Event::PointerButton {
|
||||
pos,
|
||||
button: PointerButton::Primary,
|
||||
pressed: false,
|
||||
modifiers: Default::default(),
|
||||
}])
|
||||
.1
|
||||
};
|
||||
assert!(tap("east").is_none());
|
||||
let select = tap("west").unwrap();
|
||||
assert!(!select.stop);
|
||||
assert_eq!(
|
||||
(select.network_id.as_str(), select.peer_id.as_str()),
|
||||
("network-id", "new-id")
|
||||
);
|
||||
let stop = tap("No exit node").unwrap();
|
||||
assert!(stop.stop);
|
||||
assert_eq!(stop.peer_id, "old-id");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
//! Exit nodes as the windows show them: what to call one, and what is wrong
|
||||
//! with the ones in play.
|
||||
|
||||
use tsunagi::ipc::NetworkReport;
|
||||
|
||||
use crate::format;
|
||||
|
||||
/// An exit node that is working.
|
||||
pub(crate) const GOOD: egui::Color32 = egui::Color32::from_rgb(0x3c, 0xb0, 0x4a);
|
||||
/// Something about exit nodes the user has to look at.
|
||||
pub(crate) const LOUD: egui::Color32 = egui::Color32::from_rgb(0xe0, 0x4a, 0x3c);
|
||||
|
||||
/// What to run to turn kernel forwarding on, which the agent never does.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(crate) const FORWARDING_COMMAND: &str = "sudo sysctl -w net.inet.ip.forwarding=1";
|
||||
#[cfg(target_os = "windows")]
|
||||
pub(crate) const FORWARDING_COMMAND: &str =
|
||||
"Get-NetIPInterface | Set-NetIPInterface -Forwarding Enabled";
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||||
pub(crate) const FORWARDING_COMMAND: &str = "sudo sysctl -w net.ipv4.ip_forward=1";
|
||||
|
||||
/// One thing wrong, loud enough to read at a glance.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Warning {
|
||||
pub(crate) text: String,
|
||||
/// A command the user will want, copied by clicking the warning.
|
||||
pub(crate) copy: Option<&'static str>,
|
||||
}
|
||||
|
||||
/// What to call a device in a network, even while it is away.
|
||||
pub fn name_of(network: &NetworkReport, id: &str) -> String {
|
||||
network
|
||||
.peers
|
||||
.iter()
|
||||
.find(|peer| peer.endpoint_id == id)
|
||||
.and_then(|peer| peer.hostname.clone())
|
||||
.or_else(|| {
|
||||
network
|
||||
.members
|
||||
.iter()
|
||||
.find(|member| member.endpoint_id == id)
|
||||
.and_then(|member| member.hostname.clone())
|
||||
})
|
||||
.unwrap_or_else(|| format::short(id))
|
||||
}
|
||||
|
||||
/// Everything wrong with a network's exit-node settings, most urgent first.
|
||||
pub(crate) fn warnings(network: &NetworkReport) -> Vec<Warning> {
|
||||
let exit = &network.exit;
|
||||
let mut out = Vec::new();
|
||||
|
||||
if let Some(via) = &exit.via {
|
||||
let name = name_of(network, via);
|
||||
if !exit.via_online {
|
||||
out.push(Warning {
|
||||
text: format!(
|
||||
"exit node {name} is offline — your internet traffic is blocked until it \
|
||||
returns; stop using it from the devices window"
|
||||
),
|
||||
copy: None,
|
||||
});
|
||||
} else {
|
||||
match &exit.client_rules {
|
||||
Some(rules) if rules.ok => {}
|
||||
Some(rules) => out.push(Warning {
|
||||
text: format!(
|
||||
"the routes to exit node {name} are incomplete: {}",
|
||||
rules.detail
|
||||
),
|
||||
copy: None,
|
||||
}),
|
||||
None => out.push(Warning {
|
||||
text: format!("the routes to exit node {name} are not installed"),
|
||||
copy: None,
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if exit.offering {
|
||||
match &exit.offer_rules {
|
||||
Some(rules) if !rules.ok => out.push(Warning {
|
||||
text: format!("exit node: its rules are incomplete: {}", rules.detail),
|
||||
copy: None,
|
||||
}),
|
||||
None => out.push(Warning {
|
||||
text: "exit node: its rules are not installed yet".to_string(),
|
||||
copy: None,
|
||||
}),
|
||||
Some(_) => {}
|
||||
}
|
||||
if exit.forwarding == Some(false) {
|
||||
out.push(Warning {
|
||||
text: format!("exit node: kernel forwarding is OFF — run: {FORWARDING_COMMAND}"),
|
||||
copy: Some(FORWARDING_COMMAND),
|
||||
});
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tsunagi::ipc::{ExitReport, PeerReport, RuleSetReport};
|
||||
|
||||
fn network(exit: ExitReport) -> NetworkReport {
|
||||
NetworkReport {
|
||||
peers: vec![PeerReport {
|
||||
data_error: None,
|
||||
endpoint_id: "abcdef0123456789".into(),
|
||||
hostname: Some("music".into()),
|
||||
exit_node: true,
|
||||
..Default::default()
|
||||
}],
|
||||
exit,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn ok() -> Option<RuleSetReport> {
|
||||
Some(RuleSetReport {
|
||||
ok: true,
|
||||
detail: "ok".into(),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_network_with_no_exit_settings_has_nothing_to_warn_about() {
|
||||
assert!(warnings(&network(ExitReport::default())).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lost_exit_node_says_the_traffic_is_blocked() {
|
||||
let found = warnings(&network(ExitReport {
|
||||
via: Some("abcdef0123456789".into()),
|
||||
via_online: false,
|
||||
client_rules: ok(),
|
||||
..Default::default()
|
||||
}));
|
||||
assert_eq!(found.len(), 1);
|
||||
assert!(
|
||||
found[0].text.contains("music is offline"),
|
||||
"{}",
|
||||
found[0].text
|
||||
);
|
||||
assert!(found[0].text.contains("blocked"), "{}", found[0].text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_working_exit_node_is_quiet_and_forwarding_off_gives_the_command() {
|
||||
let working = ExitReport {
|
||||
via: Some("abcdef0123456789".into()),
|
||||
via_online: true,
|
||||
client_rules: ok(),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(warnings(&network(working)).is_empty());
|
||||
|
||||
let offering = warnings(&network(ExitReport {
|
||||
offering: true,
|
||||
offer_rules: ok(),
|
||||
forwarding: Some(false),
|
||||
..Default::default()
|
||||
}));
|
||||
assert_eq!(offering.len(), 1);
|
||||
assert_eq!(offering[0].copy, Some(FORWARDING_COMMAND));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
//! Formatting and small shared widgets: humanized ages, byte sizes and rates,
|
||||
//! a fixed-size sparkline, and a click-to-copy field with a green-flash feedback.
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::stats::{Series, Unit};
|
||||
|
||||
/// Sparkline accent.
|
||||
const ACCENT: egui::Color32 = egui::Color32::from_rgb(0x2f, 0x80, 0xd8);
|
||||
/// The green a field flashes to when its value is copied.
|
||||
const COPIED_GREEN: egui::Color32 = egui::Color32::from_rgb(0x3c, 0xb0, 0x4a);
|
||||
/// How long the copy flash takes to fade back to normal.
|
||||
const FLASH: Duration = Duration::from_secs(1);
|
||||
|
||||
/// A short, readable prefix of a long identifier (char-safe, no panic).
|
||||
pub fn short(id: &str) -> String {
|
||||
const KEEP: usize = 12;
|
||||
if id.chars().count() <= KEEP {
|
||||
id.to_string()
|
||||
} else {
|
||||
format!("{}…", id.chars().take(KEEP).collect::<String>())
|
||||
}
|
||||
}
|
||||
|
||||
/// A byte count in binary units.
|
||||
pub fn bytes(n: f64) -> String {
|
||||
const UNITS: [&str; 5] = ["B", "kB", "MB", "GB", "TB"];
|
||||
let mut value = n.max(0.0);
|
||||
let mut unit = 0;
|
||||
while value >= 1024.0 && unit < UNITS.len() - 1 {
|
||||
value /= 1024.0;
|
||||
unit += 1;
|
||||
}
|
||||
if unit == 0 {
|
||||
format!("{} B", value as u64)
|
||||
} else {
|
||||
format!("{value:.1} {}", UNITS[unit])
|
||||
}
|
||||
}
|
||||
|
||||
/// A rate in the chosen unit, per second.
|
||||
pub fn rate(value: f32, unit: Unit) -> String {
|
||||
match unit {
|
||||
Unit::Packets => {
|
||||
if value >= 1000.0 {
|
||||
format!("{:.1}k pkt/s", value / 1000.0)
|
||||
} else {
|
||||
format!("{value:.0} pkt/s")
|
||||
}
|
||||
}
|
||||
Unit::Bytes => format!("{}/s", bytes(f64::from(value))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The current rate of a series as a string, or a dash when unsampled.
|
||||
pub fn series_rate(series: Option<&Series>, unit: Unit) -> String {
|
||||
series.map_or_else(|| "—".to_string(), |s| rate(s.rate(unit), unit))
|
||||
}
|
||||
|
||||
/// A label whose text is `display` and which copies `value` to the clipboard
|
||||
/// when clicked. Feedback is a green flash that fades back over a second — the
|
||||
/// text itself never changes, so a dense table does not reflow on a copy.
|
||||
pub fn copy_field(ui: &mut egui::Ui, display: &str, value: &str) {
|
||||
let id = ui.make_persistent_id(("copy", value, display));
|
||||
let copied_at: Option<Instant> = ui.memory(|memory| memory.data.get_temp(id));
|
||||
// 1.0 right after the click, fading to 0.0 a second later.
|
||||
let flash = copied_at.and_then(|at| {
|
||||
let elapsed = at.elapsed().as_secs_f32();
|
||||
let span = FLASH.as_secs_f32();
|
||||
(elapsed < span).then(|| 1.0 - elapsed / span)
|
||||
});
|
||||
|
||||
let text = match flash {
|
||||
Some(factor) => {
|
||||
let base = ui.visuals().text_color();
|
||||
egui::RichText::new(display).color(lerp_color(base, COPIED_GREEN, factor))
|
||||
}
|
||||
None => egui::RichText::new(display),
|
||||
};
|
||||
let response = ui
|
||||
.add(egui::Label::new(text).sense(egui::Sense::click()))
|
||||
.on_hover_cursor(egui::CursorIcon::PointingHand)
|
||||
.on_hover_text("click to copy");
|
||||
if response.clicked() {
|
||||
ui.ctx().copy_text(value.to_owned());
|
||||
ui.memory_mut(|memory| memory.data.insert_temp(id, Instant::now()));
|
||||
}
|
||||
if flash.is_some() {
|
||||
// Animate the fade smoothly until it completes.
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
}
|
||||
|
||||
/// Linear blend between two colours, `t` in `0.0..=1.0` toward `b`.
|
||||
fn lerp_color(a: egui::Color32, b: egui::Color32, t: f32) -> egui::Color32 {
|
||||
let t = t.clamp(0.0, 1.0);
|
||||
let mix = |x: u8, y: u8| (f32::from(x) + (f32::from(y) - f32::from(x)) * t).round() as u8;
|
||||
egui::Color32::from_rgb(mix(a.r(), b.r()), mix(a.g(), b.g()), mix(a.b(), b.b()))
|
||||
}
|
||||
|
||||
/// A fixed-height sparkline of a series' recent rate, with the peak (top-left)
|
||||
/// and current value (bottom-right) overlaid. The space is always reserved —
|
||||
/// even with no data — so the layout never jumps when data arrives.
|
||||
pub fn sparkline(ui: &mut egui::Ui, series: Option<&Series>, unit: Unit, height: f32) {
|
||||
let width = ui.available_width();
|
||||
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, height), egui::Sense::hover());
|
||||
let painter = ui.painter_at(rect);
|
||||
let visuals = ui.visuals();
|
||||
painter.rect_filled(rect, 2.0, visuals.extreme_bg_color);
|
||||
|
||||
let Some(series) = series else {
|
||||
painter.text(
|
||||
rect.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
"no data yet",
|
||||
egui::FontId::proportional(10.0),
|
||||
visuals.weak_text_color(),
|
||||
);
|
||||
return;
|
||||
};
|
||||
|
||||
let history = series.history(unit);
|
||||
let peak = history.iter().copied().fold(1.0_f32, f32::max);
|
||||
if history.len() >= 2 {
|
||||
let count = history.len();
|
||||
let points: Vec<egui::Pos2> = history
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, value)| {
|
||||
let x = rect.left() + rect.width() * (i as f32 / (count - 1) as f32);
|
||||
let y = rect.bottom() - 2.0 - (rect.height() - 12.0) * (value / peak);
|
||||
egui::pos2(x, y)
|
||||
})
|
||||
.collect();
|
||||
painter.add(egui::Shape::line(
|
||||
points,
|
||||
egui::Stroke::new(1.5_f32, ACCENT),
|
||||
));
|
||||
}
|
||||
|
||||
painter.text(
|
||||
rect.left_top() + egui::vec2(4.0, 2.0),
|
||||
egui::Align2::LEFT_TOP,
|
||||
format!("peak {}", rate(peak, unit)),
|
||||
egui::FontId::proportional(9.0),
|
||||
visuals.weak_text_color(),
|
||||
);
|
||||
painter.text(
|
||||
rect.right_bottom() + egui::vec2(-4.0, -2.0),
|
||||
egui::Align2::RIGHT_BOTTOM,
|
||||
rate(series.rate(unit), unit),
|
||||
egui::FontId::proportional(10.0),
|
||||
visuals.strong_text_color(),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,412 @@
|
||||
//! Shared compact network tiles, device header and join form.
|
||||
use crate::{
|
||||
client::{Client, Command},
|
||||
devices, exit, format,
|
||||
stats::{Traffic, Unit},
|
||||
};
|
||||
use egui_phosphor::regular as icon;
|
||||
use std::collections::BTreeSet;
|
||||
use tsunagi::ipc::{NetworkReport, StatusReport};
|
||||
use zeroize::{Zeroize, Zeroizing};
|
||||
|
||||
const BAD: egui::Color32 = egui::Color32::from_rgb(0xd0, 0x4a, 0x3c);
|
||||
/// A neutral, not-garish red for the Leave button.
|
||||
const LEAVE_RED: egui::Color32 = egui::Color32::from_rgb(0xa8, 0x3a, 0x3a);
|
||||
|
||||
/// Join form fields.
|
||||
#[derive(Default)]
|
||||
pub struct JoinForm {
|
||||
/// Visible network name.
|
||||
pub name: String,
|
||||
/// User-entered network secret.
|
||||
pub secret: Zeroizing<String>,
|
||||
}
|
||||
|
||||
/// Local UI state kept across frames.
|
||||
pub struct UiState {
|
||||
/// Join form draft.
|
||||
pub join: JoinForm,
|
||||
/// Whether rates and sparklines are shown in packets or bytes.
|
||||
pub unit: Unit,
|
||||
/// An in-progress hostname edit (`None` when not editing).
|
||||
pub host_edit: Option<String>,
|
||||
/// Network ids whose devices window is open.
|
||||
pub open_devices: BTreeSet<String>,
|
||||
/// Per-network VIP drafts.
|
||||
pub vip_windows: std::collections::BTreeMap<String, crate::vip::Window>,
|
||||
/// Whether the About window is open.
|
||||
pub about_open: bool,
|
||||
/// An exit-node choice waiting for the user to confirm it.
|
||||
pub exit_confirm: Option<devices::ExitConfirm>,
|
||||
/// A selected offline claim waiting for cleanup confirmation.
|
||||
pub forget_confirm: Option<devices::ForgetConfirm>,
|
||||
}
|
||||
|
||||
impl Default for UiState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
join: JoinForm::default(),
|
||||
unit: Unit::Packets,
|
||||
host_edit: None,
|
||||
open_devices: BTreeSet::new(),
|
||||
vip_windows: Default::default(),
|
||||
about_open: false,
|
||||
exit_confirm: None,
|
||||
forget_confirm: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The device header: id (with a copy button) and an editable hostname.
|
||||
pub fn draw_header(
|
||||
ui: &mut egui::Ui,
|
||||
agent: &dyn Client,
|
||||
state: &mut UiState,
|
||||
report: &StatusReport,
|
||||
) {
|
||||
ui.add_space(4.0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.weak("device");
|
||||
// Clicking the shortened id copies the full one.
|
||||
format::copy_field(ui, &format::short(&report.endpoint_id), &report.endpoint_id);
|
||||
});
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
ui.weak("host");
|
||||
match &mut state.host_edit {
|
||||
None => {
|
||||
ui.label(&report.hostname);
|
||||
if ui
|
||||
.small_button(icon::PENCIL_SIMPLE)
|
||||
.on_hover_text("rename")
|
||||
.clicked()
|
||||
{
|
||||
state.host_edit = Some(report.hostname.clone());
|
||||
}
|
||||
}
|
||||
Some(buffer) => {
|
||||
let response = ui.add(egui::TextEdit::singleline(buffer).desired_width(150.0));
|
||||
let submit = (response.lost_focus()
|
||||
&& ui.input(|i| i.key_pressed(egui::Key::Enter)))
|
||||
|| ui.small_button(icon::CHECK).on_hover_text("save").clicked();
|
||||
if submit {
|
||||
agent.send(Command::SetHostname(buffer.trim().to_string()));
|
||||
state.host_edit = None;
|
||||
} else if ui.small_button(icon::X).on_hover_text("cancel").clicked() {
|
||||
state.host_edit = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if !report.cache_healthy {
|
||||
ui.colored_label(
|
||||
egui::Color32::from_rgb(0xd9, 0x9a, 0x00),
|
||||
"cache unavailable",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// One compact network tile.
|
||||
pub fn draw_network(
|
||||
ui: &mut egui::Ui,
|
||||
agent: &dyn Client,
|
||||
state: &mut UiState,
|
||||
traffic: &Traffic,
|
||||
network: &NetworkReport,
|
||||
report: &StatusReport,
|
||||
offer_exit: bool,
|
||||
) -> bool {
|
||||
let mut pick_exit = false;
|
||||
ui.add_space(6.0);
|
||||
egui::Frame::group(ui.style()).show(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
format::copy_field(ui, network.name.as_str(), &network.name);
|
||||
if ui.button("VIP").clicked(){state.vip_windows.entry(network.network_id.clone()).or_default();}
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let leave =
|
||||
egui::Button::new(egui::RichText::new("Leave").color(egui::Color32::WHITE))
|
||||
.fill(LEAVE_RED);
|
||||
if ui.add(leave).clicked() {
|
||||
agent.send(Command::Leave {
|
||||
network_id: network.network_id.clone(),
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
let address = network.overlay.as_ref().and_then(|o| o.address.as_ref());
|
||||
let series = traffic.network(&network.network_id);
|
||||
|
||||
egui::Grid::new(("net", &network.network_id))
|
||||
.num_columns(2)
|
||||
.spacing([10.0, 3.0])
|
||||
.show(ui, |ui| {
|
||||
ui.weak("id");
|
||||
format::copy_field(ui, &format::short(&network.network_id), &network.network_id);
|
||||
ui.end_row();
|
||||
|
||||
if let Some(range) = &network.range {
|
||||
ui.weak("range");
|
||||
format::copy_field(ui, range, range);
|
||||
ui.end_row();
|
||||
}
|
||||
if let Some(address) = address {
|
||||
ui.weak("addr");
|
||||
format::copy_field(ui, address, address);
|
||||
ui.end_row();
|
||||
}
|
||||
ui.weak("peers");
|
||||
ui.label(format!(
|
||||
"{} online · {} known",
|
||||
devices::online_count(network, &report.endpoint_id),
|
||||
devices::known_count(network, &report.endpoint_id)
|
||||
));
|
||||
ui.end_row();
|
||||
});
|
||||
|
||||
draw_protocols(ui, agent, network, &report.available_protocols);
|
||||
|
||||
format::sparkline(ui, series, state.unit, 34.0);
|
||||
|
||||
if !network.range_conflicts.is_empty() {
|
||||
ui.colored_label(BAD, "Stopped: overlapping network ranges");
|
||||
for conflict in &network.range_conflicts {
|
||||
ui.label(format!("{} ({}) uses {}", conflict.name, conflict.network_id, conflict.range));
|
||||
}
|
||||
ui.label("Switching suspends these networks until this network stops, then resumes them automatically.");
|
||||
if network.auto_start { ui.weak("This network will resume automatically when its range is free."); }
|
||||
}
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
if !network.active && !network.range_conflicts.is_empty() {
|
||||
if ui.button("Switch to this network").clicked() {
|
||||
agent.send(Command::SetActive { network_id: network.network_id.clone(), active: true });
|
||||
}
|
||||
if network.auto_start && ui.button("Keep stopped").clicked() {
|
||||
agent.send(Command::SetActive { network_id: network.network_id.clone(), active: false });
|
||||
}
|
||||
} else {
|
||||
let mut active = network.active;
|
||||
if ui.checkbox(&mut active, "active").changed() {
|
||||
agent.send(Command::SetActive {
|
||||
network_id: network.network_id.clone(),
|
||||
active,
|
||||
});
|
||||
}
|
||||
}
|
||||
let mut broadcast = network.broadcast;
|
||||
if ui.checkbox(&mut broadcast, "broadcast").changed() {
|
||||
agent.send(Command::SetBroadcast {
|
||||
network_id: network.network_id.clone(),
|
||||
enabled: broadcast,
|
||||
});
|
||||
}
|
||||
if !offer_exit && ui.button("Exit node…").clicked() { pick_exit = true; }
|
||||
let mut offering = network.exit.offering;
|
||||
if offer_exit && ui
|
||||
.checkbox(&mut offering, "exit node")
|
||||
.on_hover_text(
|
||||
"let other members send all their internet traffic through this \
|
||||
device, which can see it",
|
||||
)
|
||||
.changed()
|
||||
{
|
||||
agent.send(Command::SetExitOffer {
|
||||
network_id: network.network_id.clone(),
|
||||
enabled: offering,
|
||||
});
|
||||
}
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
// In the bottom left corner while this device sends its traffic through
|
||||
// somebody: green while that works, red while it does not.
|
||||
if let Some(via) = &network.exit.via {
|
||||
let color = if network.exit.via_online {
|
||||
exit::GOOD
|
||||
} else {
|
||||
exit::LOUD
|
||||
};
|
||||
let response = ui
|
||||
.add(
|
||||
egui::Label::new(
|
||||
egui::RichText::new(icon::SIGN_OUT).size(18.0).color(color),
|
||||
)
|
||||
.sense(egui::Sense::click()),
|
||||
)
|
||||
.on_hover_cursor(egui::CursorIcon::PointingHand)
|
||||
.on_hover_text(format!(
|
||||
"exit node: {} — click to stop",
|
||||
exit::name_of(network, via)
|
||||
));
|
||||
if response.clicked() {
|
||||
state.exit_confirm = Some(devices::ExitConfirm::stop_from_tile(network, via));
|
||||
}
|
||||
}
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.button("Show devices").clicked() {
|
||||
state.open_devices.insert(network.network_id.clone());
|
||||
}
|
||||
if ui
|
||||
.button(format!("{} Copy secret", icon::COPY))
|
||||
.on_hover_text("copy this network's secret to the clipboard")
|
||||
.clicked()
|
||||
{
|
||||
agent.send(Command::CopySecret {
|
||||
network_id: network.network_id.clone(),
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
for warning in exit::warnings(network) {
|
||||
draw_exit_warning(ui, &warning);
|
||||
}
|
||||
});
|
||||
pick_exit
|
||||
}
|
||||
|
||||
fn draw_protocols(
|
||||
ui: &mut egui::Ui,
|
||||
agent: &dyn Client,
|
||||
network: &NetworkReport,
|
||||
available: &[tsunagi::ipc::ProtocolReport],
|
||||
) {
|
||||
let summary = if network.protocols.is_empty() {
|
||||
"none".into()
|
||||
} else {
|
||||
network.protocols.join(", ")
|
||||
};
|
||||
egui::CollapsingHeader::new(format!("data transports {summary}"))
|
||||
.id_salt(("protocols", &network.network_id))
|
||||
.show(ui, |ui| {
|
||||
ui.weak("Preference order; changes apply immediately and are saved.");
|
||||
let mut selected = network.protocols.clone();
|
||||
let mut changed = false;
|
||||
ui.add_enabled_ui(!agent.busy(), |ui| {
|
||||
// Enabled items follow the user's preference; unchecked items
|
||||
// follow the agent's catalog. The worker refreshes after edits.
|
||||
let ordered: Vec<_> = network
|
||||
.protocols
|
||||
.iter()
|
||||
.filter_map(|name| available.iter().find(|p| &p.name == name))
|
||||
.chain(
|
||||
available
|
||||
.iter()
|
||||
.filter(|p| !network.protocols.contains(&p.name)),
|
||||
)
|
||||
.collect();
|
||||
for protocol in ordered {
|
||||
ui.horizontal(|ui| {
|
||||
let mut on = selected.contains(&protocol.name);
|
||||
if ui.checkbox(&mut on, &protocol.name).changed() {
|
||||
if on {
|
||||
selected.push(protocol.name.clone());
|
||||
} else {
|
||||
selected.retain(|p| p != &protocol.name);
|
||||
}
|
||||
changed = true;
|
||||
}
|
||||
if let Some(index) = selected.iter().position(|p| p == &protocol.name) {
|
||||
if ui
|
||||
.add_enabled(index > 0, egui::Button::new(icon::ARROW_UP))
|
||||
.on_hover_text("prefer earlier")
|
||||
.clicked()
|
||||
{
|
||||
selected.swap(index, index - 1);
|
||||
changed = true;
|
||||
}
|
||||
if ui
|
||||
.add_enabled(
|
||||
index + 1 < selected.len(),
|
||||
egui::Button::new(icon::ARROW_DOWN),
|
||||
)
|
||||
.on_hover_text("prefer later")
|
||||
.clicked()
|
||||
{
|
||||
selected.swap(index, index + 1);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.indent(("description", &network.network_id, &protocol.name), |ui| {
|
||||
ui.weak(&protocol.summary);
|
||||
});
|
||||
}
|
||||
});
|
||||
if selected.is_empty() {
|
||||
ui.weak("Control only; no IP traffic in this network.");
|
||||
}
|
||||
if changed {
|
||||
agent.send(Command::SetProtocols {
|
||||
network_id: network.network_id.clone(),
|
||||
protocols: selected,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// A prominent line about an exit node. One that carries a command copies it
|
||||
/// when clicked.
|
||||
fn draw_exit_warning(ui: &mut egui::Ui, warning: &exit::Warning) {
|
||||
let text = egui::RichText::new(format!("{} {}", icon::WARNING, warning.text))
|
||||
.color(exit::LOUD)
|
||||
.strong();
|
||||
let label = egui::Label::new(text).wrap();
|
||||
match warning.copy {
|
||||
Some(command) => {
|
||||
let response = ui
|
||||
.add(label.sense(egui::Sense::click()))
|
||||
.on_hover_cursor(egui::CursorIcon::PointingHand)
|
||||
.on_hover_text("click to copy the command");
|
||||
if response.clicked() {
|
||||
ui.ctx().copy_text(command.to_owned());
|
||||
}
|
||||
}
|
||||
None => {
|
||||
ui.add(label);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The join form: aligned name and secret, a generate button, and Join.
|
||||
pub fn draw_join(ui: &mut egui::Ui, agent: &dyn Client, join: &mut JoinForm) {
|
||||
const INPUT_WIDTH: f32 = 208.0;
|
||||
ui.label("Join or create a network");
|
||||
egui::Grid::new("join")
|
||||
.num_columns(2)
|
||||
.spacing([8.0, 6.0])
|
||||
.show(ui, |ui| {
|
||||
ui.label("name");
|
||||
ui.add(egui::TextEdit::singleline(&mut join.name).desired_width(INPUT_WIDTH));
|
||||
ui.end_row();
|
||||
|
||||
ui.label("secret");
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(
|
||||
egui::TextEdit::singleline(&mut *join.secret)
|
||||
.id("join-secret".into())
|
||||
.desired_width(INPUT_WIDTH - 26.0)
|
||||
.password(true),
|
||||
);
|
||||
if ui
|
||||
.button(icon::SHUFFLE)
|
||||
.on_hover_text("Generate a new random secret")
|
||||
.clicked()
|
||||
{
|
||||
join.secret = tsunagi::identity::NetworkSecret::generate().encode();
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
});
|
||||
|
||||
let ready = !join.name.trim().is_empty() && !join.secret.trim().is_empty();
|
||||
if ui
|
||||
.add_enabled(ready, egui::Button::new("Join / create"))
|
||||
.clicked()
|
||||
{
|
||||
agent.send(Command::Join {
|
||||
name: join.name.trim().to_string(),
|
||||
secret: Zeroizing::new(join.secret.trim().to_owned()),
|
||||
});
|
||||
join.secret.zeroize();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
//! Shared presentation for the egui clients.
|
||||
pub mod about;
|
||||
pub mod client;
|
||||
pub mod devices;
|
||||
mod exit;
|
||||
pub mod format;
|
||||
pub mod home;
|
||||
pub mod listeners;
|
||||
pub mod stats;
|
||||
mod table;
|
||||
pub mod vip;
|
||||
mod vip_status;
|
||||
|
||||
/// Install the tray's regular Phosphor glyphs alongside egui's standard fonts.
|
||||
pub fn app_fonts() -> egui::FontDefinitions {
|
||||
let mut fonts = egui::FontDefinitions::default();
|
||||
egui_phosphor::add_to_fonts(&mut fonts, egui_phosphor::Variant::Regular);
|
||||
fonts
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
//! Editor for the listener and backend portion of a shared VIP draft.
|
||||
use tsunagi::vip::{Backend, Listener, Protocol, VipConfig};
|
||||
|
||||
/// Edit local draft fields. Callers own validation, signed revision and Save.
|
||||
pub fn edit(ui: &mut egui::Ui, config: &mut VipConfig, members: &[(String, String)]) {
|
||||
let mut remove = None;
|
||||
for (index, listener) in config.listeners.iter_mut().enumerate() {
|
||||
ui.push_id(&listener.id, |ui| {
|
||||
egui::Frame::group(ui.style()).show(ui, |ui| {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
egui::ComboBox::from_id_salt("protocol")
|
||||
.selected_text(listener.protocol.to_string())
|
||||
.show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut listener.protocol, Protocol::Tcp, "TCP");
|
||||
ui.selectable_value(&mut listener.protocol, Protocol::Udp, "UDP");
|
||||
});
|
||||
port_field(ui, "Port", &mut listener.port);
|
||||
if ui.button("Remove listener").clicked() {
|
||||
remove = Some(index);
|
||||
}
|
||||
});
|
||||
if listener.protocol == Protocol::Tcp {
|
||||
ui.checkbox(&mut listener.port_check, "Active TCP port checks");
|
||||
} else {
|
||||
ui.weak("UDP health uses path probes and explicit port errors.");
|
||||
}
|
||||
ui.collapsing("Checks and flow expiry", |ui| {
|
||||
egui::Grid::new("settings").show(ui, |ui| {
|
||||
macro_rules! setting {
|
||||
($label:literal, $value:ident, $range:expr) => {
|
||||
ui.label($label);
|
||||
ui.add(egui::DragValue::new(&mut listener.$value).range($range));
|
||||
ui.end_row();
|
||||
};
|
||||
}
|
||||
setting!("Check interval, ms", check_interval_ms, 250..=3_600_000);
|
||||
setting!("Check timeout, ms", check_timeout_ms, 100..=60_000);
|
||||
setting!("Failures before exclusion", failure_threshold, 1..=255);
|
||||
setting!("Successes before recovery", recovery_threshold, 1..=255);
|
||||
setting!("Flow idle timeout, seconds", idle_timeout_secs, 1..=604800);
|
||||
});
|
||||
});
|
||||
let mut remove_backend = None;
|
||||
for (i, backend) in listener.backends.iter_mut().enumerate() {
|
||||
ui.push_id(i, |ui| {
|
||||
let width = ui.available_width().min(240.0);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
let selected = members
|
||||
.iter()
|
||||
.find(|(id, _)| id == &backend.peer)
|
||||
.map(|(_, label)| label.to_owned())
|
||||
.unwrap_or_else(|| crate::format::short(&backend.peer));
|
||||
egui::ComboBox::from_id_salt("node")
|
||||
.width(width)
|
||||
.truncate()
|
||||
.selected_text(selected)
|
||||
.show_ui(ui, |ui| {
|
||||
for (id, label) in members {
|
||||
ui.selectable_value(&mut backend.peer, id.clone(), label);
|
||||
}
|
||||
});
|
||||
port_field(ui, "Target port", &mut backend.port);
|
||||
if ui.button("Remove").clicked() {
|
||||
remove_backend = Some(i);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
if let Some(i) = remove_backend {
|
||||
listener.backends.remove(i);
|
||||
}
|
||||
if ui.button("+ Backend").clicked() {
|
||||
listener.backends.push(Backend {
|
||||
peer: members
|
||||
.first()
|
||||
.map(|(id, _)| id.clone())
|
||||
.unwrap_or_default(),
|
||||
port: listener.port,
|
||||
});
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
if let Some(i) = remove {
|
||||
config.listeners.remove(i);
|
||||
}
|
||||
if ui.button("+ Listener").clicked() {
|
||||
config.listeners.push(Listener::new(Protocol::Tcp, 443));
|
||||
}
|
||||
}
|
||||
fn port_field(ui: &mut egui::Ui, label: &str, value: &mut u16) {
|
||||
ui.label(label);
|
||||
ui.add(egui::DragValue::new(value).range(1..=65535));
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
//! Traffic rates derived from successive status snapshots.
|
||||
//!
|
||||
//! The agent reports cumulative packet and byte counters, not rates. The GUI
|
||||
//! samples them each time a fresh snapshot arrives and turns the deltas into
|
||||
//! per-second rates plus short rolling histories for sparklines. One series per
|
||||
//! key: a network total, and each peer within it. Both packets and bytes are
|
||||
//! tracked so the UI can switch between them.
|
||||
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::time::Instant;
|
||||
|
||||
use tsunagi::ipc::{OverlayPeerReport, StatusReport};
|
||||
|
||||
/// How many rate samples to keep for a sparkline.
|
||||
const HISTORY: usize = 60;
|
||||
|
||||
/// Which quantity a rate or history is of.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Unit {
|
||||
/// Packets per second.
|
||||
Packets,
|
||||
/// Bytes per second.
|
||||
Bytes,
|
||||
}
|
||||
|
||||
/// One series' rolling packet and byte rates.
|
||||
#[derive(Default)]
|
||||
pub struct Series {
|
||||
last: Option<(Instant, Counters)>,
|
||||
packets_rate: f32,
|
||||
bytes_rate: f32,
|
||||
packets_history: VecDeque<f32>,
|
||||
bytes_history: VecDeque<f32>,
|
||||
}
|
||||
|
||||
impl Series {
|
||||
/// Samples a single cumulative counter pair (VIP histories own their lifetime).
|
||||
pub fn sample(&mut self, now: Instant, packets: u64, bytes: u64) {
|
||||
self.sample_peer(
|
||||
now,
|
||||
Counters {
|
||||
epoch: 0,
|
||||
tx_packets: packets,
|
||||
tx_bytes: bytes,
|
||||
rx_packets: 0,
|
||||
rx_bytes: 0,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
fn sample_peer(&mut self, now: Instant, counters: Counters) {
|
||||
if let Some((then, previous)) = self.last {
|
||||
let dt = now.saturating_duration_since(then).as_secs_f32();
|
||||
// Ignore duplicate/out-of-order observations without changing the baseline.
|
||||
if dt <= 0.0 {
|
||||
return;
|
||||
}
|
||||
if counters.epoch == previous.epoch
|
||||
&& counters.tx_packets >= previous.tx_packets
|
||||
&& counters.rx_packets >= previous.rx_packets
|
||||
&& counters.tx_bytes >= previous.tx_bytes
|
||||
&& counters.rx_bytes >= previous.rx_bytes
|
||||
{
|
||||
self.record(
|
||||
(counters.tx_packets - previous.tx_packets) as f32 / dt
|
||||
+ (counters.rx_packets - previous.rx_packets) as f32 / dt,
|
||||
(counters.tx_bytes - previous.tx_bytes) as f32 / dt
|
||||
+ (counters.rx_bytes - previous.rx_bytes) as f32 / dt,
|
||||
);
|
||||
} else {
|
||||
// A counter reset is a new baseline, never traffic.
|
||||
*self = Self::default();
|
||||
}
|
||||
}
|
||||
self.last = Some((now, counters));
|
||||
}
|
||||
|
||||
fn record(&mut self, packets: f32, bytes: f32) {
|
||||
self.packets_rate = packets;
|
||||
self.bytes_rate = bytes;
|
||||
push(&mut self.packets_history, packets);
|
||||
push(&mut self.bytes_history, bytes);
|
||||
}
|
||||
|
||||
/// The current rate in the chosen unit.
|
||||
pub fn rate(&self, unit: Unit) -> f32 {
|
||||
match unit {
|
||||
Unit::Packets => self.packets_rate,
|
||||
Unit::Bytes => self.bytes_rate,
|
||||
}
|
||||
}
|
||||
|
||||
/// The rolling history in the chosen unit.
|
||||
pub fn history(&self, unit: Unit) -> &VecDeque<f32> {
|
||||
match unit {
|
||||
Unit::Packets => &self.packets_history,
|
||||
Unit::Bytes => &self.bytes_history,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn push(history: &mut VecDeque<f32>, value: f32) {
|
||||
history.push_back(value);
|
||||
while history.len() > HISTORY {
|
||||
history.pop_front();
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
/// Cumulative tunnel counters in one peer epoch.
|
||||
pub struct Counters {
|
||||
/// Counter reset generation.
|
||||
pub epoch: u64,
|
||||
/// Sent packets.
|
||||
pub tx_packets: u64,
|
||||
/// Received packets.
|
||||
pub rx_packets: u64,
|
||||
/// Sent bytes.
|
||||
pub tx_bytes: u64,
|
||||
/// Received bytes.
|
||||
pub rx_bytes: u64,
|
||||
}
|
||||
|
||||
impl From<&OverlayPeerReport> for Counters {
|
||||
fn from(peer: &OverlayPeerReport) -> Self {
|
||||
Self {
|
||||
epoch: peer.counter_epoch,
|
||||
tx_packets: peer.tx_packets,
|
||||
rx_packets: peer.rx_packets,
|
||||
tx_bytes: peer.tx_bytes,
|
||||
rx_bytes: peer.rx_bytes,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// All traffic series, keyed by a stable string.
|
||||
#[derive(Default)]
|
||||
pub struct Traffic {
|
||||
series: HashMap<String, Series>,
|
||||
}
|
||||
|
||||
impl Traffic {
|
||||
/// Folds a fresh snapshot into the rates. Call once per new generation.
|
||||
pub fn observe(&mut self, report: &StatusReport, now: Instant) {
|
||||
self.observe_peers(
|
||||
report.networks.iter().filter_map(|network| {
|
||||
Some((
|
||||
network.network_id.as_str(),
|
||||
network
|
||||
.overlay
|
||||
.as_ref()?
|
||||
.peers
|
||||
.iter()
|
||||
.map(|p| (p.public_key.as_str(), Counters::from(p))),
|
||||
))
|
||||
}),
|
||||
now,
|
||||
);
|
||||
}
|
||||
|
||||
/// Sample live per-peer counters from either an in-process agent or IPC.
|
||||
pub fn observe_peers<'a, I>(
|
||||
&mut self,
|
||||
networks: impl IntoIterator<Item = (&'a str, I)>,
|
||||
now: Instant,
|
||||
) where
|
||||
I: IntoIterator<Item = (&'a str, Counters)>,
|
||||
{
|
||||
let mut active = HashSet::new();
|
||||
for (network, peers) in networks {
|
||||
let (mut packets_rate, mut bytes_rate) = (0.0, 0.0);
|
||||
for (peer, counters) in peers {
|
||||
let key = peer_key(network, peer);
|
||||
// Duplicate rows are not additional traffic.
|
||||
if !active.insert(key.clone()) {
|
||||
continue;
|
||||
}
|
||||
let series = self.series.entry(key).or_default();
|
||||
series.sample_peer(now, counters);
|
||||
packets_rate += series.rate(Unit::Packets);
|
||||
bytes_rate += series.rate(Unit::Bytes);
|
||||
}
|
||||
// Sum rates, not cumulative counters of a changing set of peers.
|
||||
let key = net_key(network);
|
||||
active.insert(key.clone());
|
||||
self.series
|
||||
.entry(key)
|
||||
.or_default()
|
||||
.record(packets_rate, bytes_rate);
|
||||
}
|
||||
self.series.retain(|key, _| active.contains(key));
|
||||
}
|
||||
|
||||
/// The network-total series, if sampled.
|
||||
pub fn network(&self, network_id: &str) -> Option<&Series> {
|
||||
self.series.get(&net_key(network_id))
|
||||
}
|
||||
|
||||
/// One peer's series, if sampled.
|
||||
pub fn peer(&self, network_id: &str, public_key: &str) -> Option<&Series> {
|
||||
self.series.get(&peer_key(network_id, public_key))
|
||||
}
|
||||
}
|
||||
|
||||
fn net_key(network_id: &str) -> String {
|
||||
format!("net:{network_id}")
|
||||
}
|
||||
|
||||
fn peer_key(network_id: &str, public_key: &str) -> String {
|
||||
format!("peer:{network_id}:{public_key}")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::time::Duration;
|
||||
use tsunagi::ipc::{NetworkReport, OverlayPeerReport, OverlayReport};
|
||||
|
||||
fn peer(key: &str, bytes: u64) -> OverlayPeerReport {
|
||||
OverlayPeerReport {
|
||||
public_key: key.into(),
|
||||
tx_bytes: bytes,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn report(peers: Vec<OverlayPeerReport>) -> StatusReport {
|
||||
StatusReport {
|
||||
networks: vec![NetworkReport {
|
||||
network_id: "network".into(),
|
||||
overlay: Some(OverlayReport {
|
||||
peers,
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn joining_peer_does_not_add_its_past_traffic_to_the_network_rate() {
|
||||
let mut traffic = Traffic::default();
|
||||
let now = Instant::now();
|
||||
traffic.observe(&report(vec![peer("a", 100)]), now);
|
||||
traffic.observe(
|
||||
&report(vec![peer("a", 120), peer("b", 100_000_000_000)]),
|
||||
now + Duration::from_secs(1),
|
||||
);
|
||||
assert_eq!(
|
||||
traffic.network("network").map(|s| s.rate(Unit::Bytes)),
|
||||
Some(20.0)
|
||||
);
|
||||
traffic.observe(
|
||||
&report(vec![peer("a", 150), peer("b", 100_000_000_040)]),
|
||||
now + Duration::from_secs(2),
|
||||
);
|
||||
assert_eq!(
|
||||
traffic.network("network").map(|s| s.rate(Unit::Bytes)),
|
||||
Some(70.0)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn departed_peers_and_removed_networks_do_not_keep_stale_rates() {
|
||||
let mut traffic = Traffic::default();
|
||||
let now = Instant::now();
|
||||
traffic.observe(&report(vec![peer("a", 100)]), now);
|
||||
traffic.observe(&report(vec![peer("a", 140)]), now + Duration::from_secs(1));
|
||||
traffic.observe(&report(vec![]), now + Duration::from_secs(2));
|
||||
assert!(traffic.peer("network", "a").is_none());
|
||||
assert_eq!(
|
||||
traffic.network("network").map(|s| s.rate(Unit::Bytes)),
|
||||
Some(0.0)
|
||||
);
|
||||
traffic.observe(&StatusReport::default(), now + Duration::from_secs(3));
|
||||
assert!(traffic.network("network").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restarted_counters_are_a_new_baseline_even_if_they_already_exceed_the_old_value() {
|
||||
let mut traffic = Traffic::default();
|
||||
let now = Instant::now();
|
||||
let mut old = peer("a", 100);
|
||||
old.counter_epoch = 1;
|
||||
traffic.observe(&report(vec![old]), now);
|
||||
let mut restarted = peer("a", 100_000_000_000);
|
||||
restarted.counter_epoch = 2;
|
||||
traffic.observe(
|
||||
&report(vec![restarted.clone()]),
|
||||
now + Duration::from_secs(1),
|
||||
);
|
||||
assert_eq!(
|
||||
traffic.peer("network", "a").map(|s| s.rate(Unit::Bytes)),
|
||||
Some(0.0)
|
||||
);
|
||||
restarted.tx_bytes += 80;
|
||||
traffic.observe(&report(vec![restarted]), now + Duration::from_secs(2));
|
||||
assert_eq!(
|
||||
traffic.network("network").map(|s| s.rate(Unit::Bytes)),
|
||||
Some(80.0)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_in_one_direction_cannot_be_hidden_by_growth_in_the_other() {
|
||||
let mut traffic = Traffic::default();
|
||||
let now = Instant::now();
|
||||
let mut old = peer("a", 100);
|
||||
old.rx_bytes = 1000;
|
||||
traffic.observe(&report(vec![old]), now);
|
||||
let mut reset = peer("a", 50);
|
||||
reset.rx_bytes = 10_000;
|
||||
traffic.observe(&report(vec![reset]), now + Duration::from_secs(1));
|
||||
assert_eq!(
|
||||
traffic.network("network").map(|s| s.rate(Unit::Bytes)),
|
||||
Some(0.0)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
//! Fixed row geometry for dense live tables. Children cannot resize a row or
|
||||
//! paint into its neighbours; the enclosing scroll area owns overflow.
|
||||
|
||||
pub(crate) const GAP: f32 = 10.0;
|
||||
|
||||
pub(crate) fn row(
|
||||
ui: &mut egui::Ui,
|
||||
id: impl std::hash::Hash,
|
||||
widths: &[f32],
|
||||
stripe: bool,
|
||||
mut cell: impl FnMut(usize, &mut egui::Ui),
|
||||
) {
|
||||
let font = egui::FontSelection::Default.resolve(ui.style());
|
||||
let text_height = ui.fonts(|fonts| fonts.row_height(&font));
|
||||
let height = ui.spacing().interact_size.y.max(text_height) + 10.0;
|
||||
let width = widths.iter().sum::<f32>() + GAP * widths.len().saturating_sub(1) as f32;
|
||||
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, height), egui::Sense::hover());
|
||||
if stripe {
|
||||
ui.painter()
|
||||
.rect_filled(rect, 2.0, ui.visuals().faint_bg_color);
|
||||
}
|
||||
let mut x = rect.left();
|
||||
for (column, width) in widths.iter().enumerate() {
|
||||
let bounds = egui::Rect::from_min_size(
|
||||
egui::pos2(x, rect.top() + 3.0),
|
||||
egui::vec2(*width, height - 6.0),
|
||||
);
|
||||
let mut child = ui.new_child(
|
||||
egui::UiBuilder::new()
|
||||
.id_salt((&id, column))
|
||||
.max_rect(bounds)
|
||||
.layout(egui::Layout::left_to_right(egui::Align::Center)),
|
||||
);
|
||||
child.set_clip_rect(ui.clip_rect().intersect(bounds));
|
||||
child.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate);
|
||||
cell(column, &mut child);
|
||||
x += width + GAP;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn oversized_content_is_clipped_to_its_cell_at_every_scale() {
|
||||
for size in [13.0, 20.0, 28.0] {
|
||||
let ctx = egui::Context::default();
|
||||
ctx.style_mut(|style| {
|
||||
style.override_font_id = Some(egui::FontId::proportional(size));
|
||||
});
|
||||
let output = ctx.run(egui::RawInput::default(), |ctx| {
|
||||
egui::CentralPanel::default().show(ctx, |ui| {
|
||||
for index in 0..4 {
|
||||
row(ui, index, &[90.0, 120.0], index % 2 == 0, |column, ui| {
|
||||
if column == 0 {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("very long device name that cannot fit");
|
||||
ui.button("Forget").on_hover_text("Forget");
|
||||
});
|
||||
} else {
|
||||
ui.label(format!("row {index}"));
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
let mut previous_bottom = 0.0;
|
||||
for index in 0..4 {
|
||||
let shape = output.shapes.iter().find(|shape| matches!(&shape.shape, egui::Shape::Text(t) if t.galley.text() == format!("row {index}"))).unwrap();
|
||||
let egui::Shape::Text(text) = &shape.shape else {
|
||||
unreachable!()
|
||||
};
|
||||
assert!(text.visual_bounding_rect().top() >= previous_bottom);
|
||||
assert!(
|
||||
shape.clip_rect.contains_rect(text.visual_bounding_rect()),
|
||||
"font {size}: clip {:?}, text {:?}",
|
||||
shape.clip_rect,
|
||||
text.visual_bounding_rect()
|
||||
);
|
||||
assert!(shape.clip_rect.left() >= 108.0);
|
||||
previous_bottom = shape.clip_rect.bottom();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,407 @@
|
||||
//! Per-network VIP editor. Drafts never issue commands until Save is pressed.
|
||||
use crate::client::{Client, Command, Snapshot};
|
||||
use crate::vip_status;
|
||||
use tsunagi::ipc::NetworkReport;
|
||||
use tsunagi::vip::VipConfig;
|
||||
#[cfg(test)]
|
||||
use tsunagi::vip::{Listener, Protocol};
|
||||
#[derive(Clone)]
|
||||
struct Draft {
|
||||
config: VipConfig,
|
||||
original: VipConfig,
|
||||
revision: Option<String>,
|
||||
delete: bool,
|
||||
}
|
||||
impl Draft {
|
||||
fn new(config: VipConfig, revision: Option<String>) -> Self {
|
||||
Self {
|
||||
original: config.clone(),
|
||||
config,
|
||||
revision,
|
||||
delete: false,
|
||||
}
|
||||
}
|
||||
fn dirty(&self) -> bool {
|
||||
self.revision.is_none() || self.delete || self.config != self.original
|
||||
}
|
||||
}
|
||||
#[derive(Default)]
|
||||
/// A network’s edit draft, selection and traffic history.
|
||||
pub struct Window {
|
||||
draft: Option<Draft>,
|
||||
pending: Option<String>,
|
||||
error: Option<String>,
|
||||
close_question: bool,
|
||||
close_after_save: bool,
|
||||
live: vip_status::View,
|
||||
configure: bool,
|
||||
generation: u64,
|
||||
acknowledged_generation: Option<u64>,
|
||||
}
|
||||
impl Window {
|
||||
/// Ask whether to discard an outstanding draft.
|
||||
pub fn request_close(&mut self) {
|
||||
self.close_question = true;
|
||||
self.close_after_save = true;
|
||||
}
|
||||
/// Whether closing needs confirmation.
|
||||
pub fn dirty(&self) -> bool {
|
||||
self.draft.as_ref().is_some_and(Draft::dirty) || self.pending.is_some()
|
||||
}
|
||||
}
|
||||
/// Render the editor and overview. Returns true when its view can close.
|
||||
pub fn show(
|
||||
ctx: &egui::Context,
|
||||
agent: &dyn Client,
|
||||
state: &mut Window,
|
||||
n: &NetworkReport,
|
||||
snapshot: &Snapshot,
|
||||
) -> bool {
|
||||
if state.generation == 0
|
||||
&& state.draft.is_none()
|
||||
&& let [vip] = n.vips.as_slice()
|
||||
{
|
||||
state.draft = Some(Draft::new(vip.config.clone(), Some(vip.revision.clone())));
|
||||
}
|
||||
if state.generation != snapshot.generation {
|
||||
state.generation = snapshot.generation;
|
||||
if let Some(at) = snapshot.at {
|
||||
state.live.observe(n, at);
|
||||
}
|
||||
}
|
||||
if let Some(result) = &snapshot.vip_result
|
||||
&& state.pending.as_deref() == Some(result.token.as_str())
|
||||
{
|
||||
state.pending = None;
|
||||
state.acknowledged_generation = Some(snapshot.generation);
|
||||
match &result.result {
|
||||
Ok(vips) => {
|
||||
if let Some(draft) = &state.draft {
|
||||
state.draft = vips
|
||||
.iter()
|
||||
.find(|v| v.config.id == draft.config.id)
|
||||
.map(|v| Draft::new(v.config.clone(), Some(v.revision.clone())));
|
||||
}
|
||||
state.error = None;
|
||||
}
|
||||
Err(error) => {
|
||||
state.error = Some(error.clone());
|
||||
state.close_after_save = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut close = state.close_after_save && !state.dirty();
|
||||
let mut discard_new = false;
|
||||
egui::CentralPanel::default().show(ctx, |ui| {
|
||||
ui.heading(format!("VIP · {}", n.name));
|
||||
ui.weak("Configuration is shared with every member. Changes take effect only after Save.");
|
||||
if state.close_question {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label("Unsaved changes.");
|
||||
if ui
|
||||
.add_enabled(
|
||||
state.pending.is_none(),
|
||||
egui::Button::new("Discard and close"),
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
state.draft = None;
|
||||
state.close_question = false;
|
||||
close = true;
|
||||
}
|
||||
if ui.button("Keep editing").clicked() {
|
||||
state.close_question = false;
|
||||
state.close_after_save = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
if let Some(error) = &state.error {
|
||||
ui.colored_label(egui::Color32::LIGHT_RED, error);
|
||||
}
|
||||
ui.separator();
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
for vip in &n.vips {
|
||||
let selected = state
|
||||
.draft
|
||||
.as_ref()
|
||||
.is_some_and(|d| d.config.id == vip.config.id);
|
||||
if ui.selectable_label(selected, &vip.config.name).clicked() {
|
||||
if state.dirty() {
|
||||
state.error = Some(
|
||||
"Save or discard the current draft before selecting another VIP."
|
||||
.into(),
|
||||
);
|
||||
} else {
|
||||
state.draft =
|
||||
Some(Draft::new(vip.config.clone(), Some(vip.revision.clone())));
|
||||
state.error = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
if ui.button("+ New VIP").clicked() {
|
||||
if state.dirty() {
|
||||
state.error = Some("Save or discard the current draft first.".into());
|
||||
} else {
|
||||
state.draft = Some(Draft::new(VipConfig::new(""), None));
|
||||
state.configure = true;
|
||||
state.error = None;
|
||||
}
|
||||
}
|
||||
});
|
||||
let Some(draft) = &mut state.draft else {
|
||||
ui.label("Select a VIP or create one.");
|
||||
return;
|
||||
};
|
||||
let current = n.vips.iter().find(|v| v.config.id == draft.config.id);
|
||||
if state.pending.is_none()
|
||||
&& state.acknowledged_generation != Some(snapshot.generation)
|
||||
&& !draft.dirty()
|
||||
&& let Some(current) = current
|
||||
&& draft.revision.as_ref() != Some(¤t.revision)
|
||||
{
|
||||
*draft = Draft::new(current.config.clone(), Some(current.revision.clone()));
|
||||
}
|
||||
let changed =
|
||||
current.is_some_and(|v| draft.revision.as_ref().is_some_and(|r| r != &v.revision));
|
||||
if changed {
|
||||
ui.colored_label(
|
||||
egui::Color32::YELLOW,
|
||||
"This VIP changed on the network. Reload before saving; your draft is retained.",
|
||||
);
|
||||
}
|
||||
if draft.revision.is_some() && current.is_none() {
|
||||
ui.colored_label(
|
||||
egui::Color32::YELLOW,
|
||||
"This VIP was removed on the network. The draft cannot overwrite its deletion.",
|
||||
);
|
||||
}
|
||||
let busy = state.pending.is_some();
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
let valid = draft.config.validate(&tsunagi::Limits::default());
|
||||
if !n.active {
|
||||
ui.weak("Start the network to save changes.");
|
||||
}
|
||||
if ui
|
||||
.add_enabled(
|
||||
n.active
|
||||
&& !busy
|
||||
&& draft.dirty()
|
||||
&& !changed
|
||||
&& (valid.is_ok() || draft.delete),
|
||||
egui::Button::new("Save"),
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
let token = VipConfig::new("").id;
|
||||
state.pending = Some(token.clone());
|
||||
agent.send(Command::SaveVip {
|
||||
token,
|
||||
network_id: n.network_id.clone(),
|
||||
config: draft.config.clone(),
|
||||
expected: draft.revision.clone(),
|
||||
delete: draft.delete,
|
||||
});
|
||||
}
|
||||
if ui
|
||||
.add_enabled(!busy, egui::Button::new("Discard / reload"))
|
||||
.clicked()
|
||||
{
|
||||
if let Some(v) = current {
|
||||
*draft = Draft::new(v.config.clone(), Some(v.revision.clone()));
|
||||
} else {
|
||||
discard_new = true;
|
||||
}
|
||||
state.error = None;
|
||||
}
|
||||
if busy {
|
||||
ui.spinner();
|
||||
ui.label("Saving…");
|
||||
} else if draft.dirty() {
|
||||
ui.weak("Unsaved changes");
|
||||
}
|
||||
if let Err(error) = valid {
|
||||
ui.colored_label(egui::Color32::LIGHT_RED, error.to_string());
|
||||
}
|
||||
});
|
||||
ui.separator();
|
||||
ui.horizontal(|ui| {
|
||||
ui.selectable_value(&mut state.configure, false, "Overview");
|
||||
ui.selectable_value(&mut state.configure, true, "Configuration");
|
||||
});
|
||||
egui::ScrollArea::vertical()
|
||||
.auto_shrink([false, false])
|
||||
.show(ui, |ui| {
|
||||
if state.configure {
|
||||
ui.add_enabled_ui(!busy, |ui| {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label("Name");
|
||||
ui.add(
|
||||
egui::TextEdit::singleline(&mut draft.config.name)
|
||||
.id(egui::Id::new(("vip-name", &draft.config.id))),
|
||||
);
|
||||
ui.weak(format!(".{}", n.name));
|
||||
});
|
||||
if draft.revision.is_some() {
|
||||
ui.checkbox(&mut draft.delete, "Delete this VIP when saved");
|
||||
}
|
||||
if !draft.delete {
|
||||
edit_listeners(ui, &mut draft.config, n);
|
||||
}
|
||||
});
|
||||
} else if let Some(current) = current {
|
||||
vip_status::show(ui, current, n, &mut state.live);
|
||||
} else {
|
||||
ui.weak("Save this VIP to see its live status.");
|
||||
}
|
||||
});
|
||||
});
|
||||
if discard_new {
|
||||
state.draft = None;
|
||||
state.error = None;
|
||||
}
|
||||
close
|
||||
}
|
||||
fn edit_listeners(ui: &mut egui::Ui, config: &mut VipConfig, n: &NetworkReport) {
|
||||
let members = n
|
||||
.members
|
||||
.iter()
|
||||
.map(|m| {
|
||||
(
|
||||
m.endpoint_id.clone(),
|
||||
format!(
|
||||
"{} ({})",
|
||||
m.hostname.as_deref().unwrap_or("unnamed"),
|
||||
crate::format::short(&m.endpoint_id)
|
||||
),
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
crate::listeners::edit(ui, config, &members);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
use super::*;
|
||||
use tsunagi::vip::VipStatus;
|
||||
#[test]
|
||||
fn editing_the_actual_form_sends_nothing_until_save_is_clicked() {
|
||||
let (tx, commands) = std::sync::mpsc::channel();
|
||||
struct TestClient(std::sync::mpsc::Sender<Command>);
|
||||
impl Client for TestClient {
|
||||
fn send(&self, command: Command) {
|
||||
self.0.send(command).unwrap();
|
||||
}
|
||||
fn busy(&self) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
let agent = TestClient(tx);
|
||||
let ctx = egui::Context::default();
|
||||
let mut config = VipConfig::new("api");
|
||||
config.listeners.push(Listener::new(Protocol::Tcp, 443));
|
||||
let mut state = Window {
|
||||
draft: Some(Draft::new(config.clone(), Some("revision".into()))),
|
||||
configure: true,
|
||||
..Default::default()
|
||||
};
|
||||
let network = NetworkReport {
|
||||
active: true,
|
||||
name: "lab".into(),
|
||||
vips: vec![VipStatus {
|
||||
config: config.clone(),
|
||||
revision: "revision".into(),
|
||||
address: None,
|
||||
error: None,
|
||||
listeners: vec![],
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
let snapshot = Snapshot::default();
|
||||
let frame = |events: Vec<egui::Event>, state: &mut Window| {
|
||||
ctx.run(
|
||||
egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(1000., 800.),
|
||||
)),
|
||||
events,
|
||||
..Default::default()
|
||||
},
|
||||
|ctx| {
|
||||
show(ctx, &agent, state, &network, &snapshot);
|
||||
},
|
||||
)
|
||||
};
|
||||
frame(vec![], &mut state);
|
||||
ctx.memory_mut(|m| m.request_focus(egui::Id::new(("vip-name", &config.id))));
|
||||
frame(vec![egui::Event::Text("new".into())], &mut state);
|
||||
assert!(state.dirty());
|
||||
assert_ne!(state.draft.as_ref().unwrap().config.name, config.name);
|
||||
assert!(commands.try_recv().is_err());
|
||||
assert_eq!(network.vips[0].config, config);
|
||||
fn save_position(shape: &egui::Shape) -> Option<egui::Pos2> {
|
||||
match shape {
|
||||
egui::Shape::Text(text) if text.galley.text() == "Save" => {
|
||||
Some(text.pos + text.galley.rect.center().to_vec2())
|
||||
}
|
||||
egui::Shape::Vec(shapes) => shapes.iter().find_map(save_position),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
// Save was disabled before this edit; allow the next layout to register
|
||||
// its now-enabled hit target before dispatching the pointer press.
|
||||
let ready = frame(vec![], &mut state);
|
||||
let position = ready
|
||||
.shapes
|
||||
.iter()
|
||||
.find_map(|s| save_position(&s.shape))
|
||||
.unwrap();
|
||||
frame(
|
||||
vec![
|
||||
egui::Event::PointerMoved(position),
|
||||
egui::Event::PointerButton {
|
||||
pos: position,
|
||||
button: egui::PointerButton::Primary,
|
||||
pressed: true,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
},
|
||||
],
|
||||
&mut state,
|
||||
);
|
||||
frame(
|
||||
vec![egui::Event::PointerButton {
|
||||
pos: position,
|
||||
button: egui::PointerButton::Primary,
|
||||
pressed: false,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
}],
|
||||
&mut state,
|
||||
);
|
||||
let Command::SaveVip {
|
||||
config: saved,
|
||||
expected,
|
||||
delete,
|
||||
..
|
||||
} = commands.try_recv().unwrap()
|
||||
else {
|
||||
panic!("Save must submit one complete VIP draft");
|
||||
};
|
||||
assert_ne!(saved.name, config.name);
|
||||
assert_eq!(expected.as_deref(), Some("revision"));
|
||||
assert!(!delete);
|
||||
assert!(commands.try_recv().is_err());
|
||||
}
|
||||
#[test]
|
||||
fn all_listener_settings_render_without_a_live_agent() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut cfg = VipConfig::new("api");
|
||||
cfg.listeners.push(Listener::new(Protocol::Tcp, 443));
|
||||
cfg.listeners.push(Listener::new(Protocol::Udp, 53));
|
||||
let n = NetworkReport::default();
|
||||
let _ = ctx.run(egui::RawInput::default(), |ctx| {
|
||||
egui::CentralPanel::default().show(ctx, |ui| edit_listeners(ui, &mut cfg, &n));
|
||||
});
|
||||
assert_eq!(cfg.listeners.len(), 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,923 @@
|
||||
//! Local VIP observations, kept apart from editable configuration drafts.
|
||||
use std::collections::BTreeMap;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use tsunagi::ipc::NetworkReport;
|
||||
use tsunagi::vip::{Backend, BackendStatus, Counters, ListenerStatus, Protocol, VipStatus};
|
||||
|
||||
use crate::{
|
||||
format,
|
||||
stats::{Series, Unit},
|
||||
table,
|
||||
};
|
||||
|
||||
const ACTIVE: egui::Color32 = egui::Color32::from_rgb(73, 190, 133);
|
||||
const NEXT: egui::Color32 = egui::Color32::from_rgb(78, 157, 237);
|
||||
const WARN: egui::Color32 = egui::Color32::from_rgb(225, 170, 73);
|
||||
const BAD: egui::Color32 = egui::Color32::from_rgb(228, 112, 112);
|
||||
|
||||
#[derive(Default)]
|
||||
struct Rates {
|
||||
tx: Series,
|
||||
rx: Series,
|
||||
total: Series,
|
||||
at: Option<Instant>,
|
||||
}
|
||||
impl Rates {
|
||||
fn sample(&mut self, at: Instant, c: &Counters) {
|
||||
self.tx.sample(at, c.tx_packets, c.tx_bytes);
|
||||
self.rx.sample(at, c.rx_packets, c.rx_bytes);
|
||||
self.total.sample(
|
||||
at,
|
||||
c.tx_packets.saturating_add(c.rx_packets),
|
||||
c.tx_bytes.saturating_add(c.rx_bytes),
|
||||
);
|
||||
self.at = Some(at);
|
||||
}
|
||||
fn active(&self, now: Instant) -> bool {
|
||||
self.at
|
||||
.is_some_and(|at| now.saturating_duration_since(at) <= Duration::from_secs(5))
|
||||
&& self.total.rate(Unit::Packets) > 0.0
|
||||
}
|
||||
}
|
||||
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
struct Key(String, String, u16, String, u16);
|
||||
fn key(v: &VipStatus, l: &ListenerStatus, b: &Backend) -> Key {
|
||||
// Listener identity separates counter histories when a port is recreated.
|
||||
let listener = v
|
||||
.config
|
||||
.listeners
|
||||
.iter()
|
||||
.find(|entry| entry.protocol == l.protocol && entry.port == l.port)
|
||||
.map(|entry| entry.id.clone())
|
||||
.unwrap_or_else(|| l.protocol.to_string());
|
||||
Key(
|
||||
v.config.id.clone(),
|
||||
listener,
|
||||
l.port,
|
||||
b.peer.clone(),
|
||||
b.port,
|
||||
)
|
||||
}
|
||||
struct Camera {
|
||||
layout_width: f32,
|
||||
rect: egui::Rect,
|
||||
members: Vec<Backend>,
|
||||
}
|
||||
impl Default for Camera {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
layout_width: 0.0,
|
||||
rect: egui::Rect::NOTHING,
|
||||
members: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(crate) struct View {
|
||||
totals: BTreeMap<String, Rates>,
|
||||
backends: BTreeMap<Key, Rates>,
|
||||
cameras: BTreeMap<(String, String, u16), Camera>,
|
||||
selected: Option<Key>,
|
||||
unit: Unit,
|
||||
}
|
||||
impl Default for View {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
totals: BTreeMap::new(),
|
||||
backends: BTreeMap::new(),
|
||||
cameras: BTreeMap::new(),
|
||||
selected: None,
|
||||
unit: Unit::Bytes,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl View {
|
||||
pub(crate) fn observe(&mut self, network: &NetworkReport, at: Instant) {
|
||||
self.totals
|
||||
.retain(|id, _| network.vips.iter().any(|v| &v.config.id == id));
|
||||
let mut present = std::collections::BTreeSet::new();
|
||||
for v in &network.vips {
|
||||
let mut counters = Counters::default();
|
||||
for l in &v.listeners {
|
||||
counters.tx_packets = counters.tx_packets.saturating_add(l.counters.tx_packets);
|
||||
counters.rx_packets = counters.rx_packets.saturating_add(l.counters.rx_packets);
|
||||
counters.tx_bytes = counters.tx_bytes.saturating_add(l.counters.tx_bytes);
|
||||
counters.rx_bytes = counters.rx_bytes.saturating_add(l.counters.rx_bytes);
|
||||
for b in &l.backends {
|
||||
let key = key(v, l, &b.backend);
|
||||
self.backends
|
||||
.entry(key.clone())
|
||||
.or_default()
|
||||
.sample(at, &b.counters);
|
||||
present.insert(key);
|
||||
}
|
||||
}
|
||||
self.totals
|
||||
.entry(v.config.id.clone())
|
||||
.or_default()
|
||||
.sample(at, &counters);
|
||||
}
|
||||
self.backends.retain(|key, _| present.contains(key));
|
||||
if self
|
||||
.selected
|
||||
.as_ref()
|
||||
.is_some_and(|key| !present.contains(key))
|
||||
{
|
||||
self.selected = None;
|
||||
}
|
||||
self.cameras.retain(|(id, protocol, port), _| {
|
||||
network.vips.iter().any(|v| {
|
||||
&v.config.id == id
|
||||
&& v.listeners
|
||||
.iter()
|
||||
.any(|l| l.protocol.to_string() == *protocol && l.port == *port)
|
||||
})
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn name<'a>(n: &'a NetworkReport, id: &'a str) -> &'a str {
|
||||
n.members
|
||||
.iter()
|
||||
.find(|m| m.endpoint_id == id)
|
||||
.and_then(|m| m.hostname.as_deref())
|
||||
.unwrap_or(id)
|
||||
}
|
||||
fn backend_name(n: &NetworkReport, b: &Backend) -> String {
|
||||
format!("{}:{}", name(n, &b.peer), b.port)
|
||||
}
|
||||
fn rtt(b: &BackendStatus) -> String {
|
||||
b.rtt_us
|
||||
.map_or_else(|| "—".into(), |us| format!("{:.2} ms", us as f64 / 1000.0))
|
||||
}
|
||||
fn health_color(state: &str) -> egui::Color32 {
|
||||
match state {
|
||||
"ready" => ACTIVE,
|
||||
"checking port" | "measuring RTT" | "draining" => WARN,
|
||||
_ => BAD,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn show(ui: &mut egui::Ui, v: &VipStatus, n: &NetworkReport, view: &mut View) {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.heading(format!("{}.{}", v.config.name, n.name));
|
||||
ui.weak("Traffic seen by this device");
|
||||
ui.selectable_value(&mut view.unit, Unit::Bytes, "bytes");
|
||||
ui.selectable_value(&mut view.unit, Unit::Packets, "pkts");
|
||||
});
|
||||
if let Some(error) = &v.error {
|
||||
ui.colored_label(BAD, error);
|
||||
}
|
||||
let total = view.totals.get(&v.config.id);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
metric(
|
||||
ui,
|
||||
"TX",
|
||||
&format::series_rate(total.map(|r| &r.tx), view.unit),
|
||||
);
|
||||
metric(
|
||||
ui,
|
||||
"RX",
|
||||
&format::series_rate(total.map(|r| &r.rx), view.unit),
|
||||
);
|
||||
let flows: u64 = v
|
||||
.listeners
|
||||
.iter()
|
||||
.flat_map(|l| &l.backends)
|
||||
.map(|b| u64::from(b.active_flows))
|
||||
.sum();
|
||||
metric(ui, "Open flows", &flows.to_string());
|
||||
});
|
||||
format::sparkline(ui, total.map(|r| &r.total), view.unit, 64.0);
|
||||
ui.add_space(8.0);
|
||||
if v.listeners.is_empty() {
|
||||
ui.weak("No listeners configured. Add one in Configuration.");
|
||||
}
|
||||
for l in &v.listeners {
|
||||
ui.push_id(
|
||||
(
|
||||
"vip live listener",
|
||||
&v.config.id,
|
||||
l.protocol.to_string(),
|
||||
l.port,
|
||||
),
|
||||
|ui| {
|
||||
egui::Frame::group(ui.style()).show(ui, |ui| {
|
||||
ui.set_min_width((ui.available_width() - 2.0).max(0.0));
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.heading(format!("{}/{}", l.protocol, l.port));
|
||||
ui.weak("New connections:");
|
||||
if let Some(b) = &l.selected {
|
||||
ui.colored_label(NEXT, backend_name(n, b));
|
||||
} else {
|
||||
ui.colored_label(WARN, "No eligible backend");
|
||||
}
|
||||
});
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
metric(ui, "TX", &format::bytes(l.counters.tx_bytes as f64));
|
||||
metric(ui, "RX", &format::bytes(l.counters.rx_bytes as f64));
|
||||
metric(
|
||||
ui,
|
||||
"Packets TX / RX",
|
||||
&format!("{} / {}", l.counters.tx_packets, l.counters.rx_packets),
|
||||
);
|
||||
metric(ui, "Drops", &l.counters.dropped.to_string());
|
||||
if l.protocol == Protocol::Udp {
|
||||
metric(ui, "Failovers", &l.counters.failovers.to_string());
|
||||
}
|
||||
});
|
||||
ui.separator();
|
||||
diagram(ui, v, l, n, view);
|
||||
ui.add_space(6.0);
|
||||
egui::ScrollArea::horizontal()
|
||||
.id_salt("backend table scroll")
|
||||
.auto_shrink([false, true])
|
||||
.show(ui, |ui| {
|
||||
backend_table(ui, v, l, n, view);
|
||||
});
|
||||
if let Some(b) = l
|
||||
.backends
|
||||
.iter()
|
||||
.find(|b| view.selected.as_ref() == Some(&key(v, l, &b.backend)))
|
||||
{
|
||||
egui::Frame::group(ui.style()).show(ui, |ui| {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.strong(backend_name(n, &b.backend));
|
||||
ui.colored_label(health_color(&b.state), &b.state);
|
||||
ui.weak(format!("{} open flows", b.active_flows));
|
||||
if let Some(age) = b.measurement_age_ms {
|
||||
ui.weak(format!(
|
||||
"RTT measured {:.1}s ago",
|
||||
age as f64 / 1000.0
|
||||
));
|
||||
} else {
|
||||
ui.weak("No RTT measurement yet");
|
||||
}
|
||||
});
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.weak("Node");
|
||||
format::copy_field(
|
||||
ui,
|
||||
&format::short(&b.backend.peer),
|
||||
&b.backend.peer,
|
||||
);
|
||||
if let Some(address) = n
|
||||
.members
|
||||
.iter()
|
||||
.find(|m| m.endpoint_id == b.backend.peer)
|
||||
.and_then(|m| m.overlay_address_v4.as_deref())
|
||||
{
|
||||
ui.weak("Address");
|
||||
format::copy_field(ui, address, address);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
ui.add_space(8.0);
|
||||
}
|
||||
ui.collapsing("Internal address and identity", |ui| {
|
||||
egui::Grid::new(("vip identity", &v.config.id)).show(ui, |ui| {
|
||||
ui.weak("Address");
|
||||
if let Some(address) = v.address {
|
||||
format::copy_field(ui, &address.to_string(), &address.to_string());
|
||||
} else {
|
||||
ui.weak("Not allocated");
|
||||
}
|
||||
ui.end_row();
|
||||
ui.weak("ID");
|
||||
format::copy_field(ui, &v.config.id, &v.config.id);
|
||||
ui.end_row();
|
||||
});
|
||||
});
|
||||
}
|
||||
fn metric(ui: &mut egui::Ui, title: &str, value: &str) {
|
||||
ui.horizontal(|ui| {
|
||||
ui.weak(title);
|
||||
ui.strong(value);
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
}
|
||||
|
||||
fn backend_table(
|
||||
ui: &mut egui::Ui,
|
||||
v: &VipStatus,
|
||||
l: &ListenerStatus,
|
||||
n: &NetworkReport,
|
||||
view: &mut View,
|
||||
) {
|
||||
let headers = [
|
||||
"Backend",
|
||||
"Health",
|
||||
"Route",
|
||||
"RTT",
|
||||
"Flows",
|
||||
"TX / RX",
|
||||
"TX / RX rate",
|
||||
"Traffic",
|
||||
];
|
||||
let mut widths = [170.0_f32, 110.0, 100.0, 90.0, 50.0, 160.0, 160.0, 160.0];
|
||||
// Measure every value before layout, including long identities and counters.
|
||||
let values: Vec<_> = l
|
||||
.backends
|
||||
.iter()
|
||||
.map(|b| {
|
||||
let rates = view.backends.get(&key(v, l, &b.backend));
|
||||
let route = if rates.is_some_and(|r| r.active(Instant::now())) {
|
||||
"Traffic"
|
||||
} else if l.selected.as_ref() == Some(&b.backend) {
|
||||
"Next flow"
|
||||
} else {
|
||||
"—"
|
||||
};
|
||||
[
|
||||
backend_name(n, &b.backend),
|
||||
b.state.clone(),
|
||||
route.into(),
|
||||
rtt(b),
|
||||
b.active_flows.to_string(),
|
||||
format!(
|
||||
"{} / {}",
|
||||
format::bytes(b.counters.tx_bytes as f64),
|
||||
format::bytes(b.counters.rx_bytes as f64)
|
||||
),
|
||||
format!(
|
||||
"{} / {}",
|
||||
format::series_rate(rates.map(|r| &r.tx), view.unit),
|
||||
format::series_rate(rates.map(|r| &r.rx), view.unit)
|
||||
),
|
||||
]
|
||||
})
|
||||
.collect();
|
||||
for (column, width) in widths.iter_mut().enumerate().take(7) {
|
||||
let font = egui::FontSelection::Default.resolve(ui.style());
|
||||
for text in
|
||||
std::iter::once(headers[column]).chain(values.iter().map(|row| row[column].as_str()))
|
||||
{
|
||||
*width = width.max(
|
||||
ui.fonts(|f| {
|
||||
f.layout_no_wrap(text.to_owned(), font.clone(), egui::Color32::WHITE)
|
||||
.size()
|
||||
.x
|
||||
}) + 12.0,
|
||||
);
|
||||
}
|
||||
}
|
||||
let widths_id = ui.id().with("backend column widths");
|
||||
if let Some(previous) = ui.memory(|memory| memory.data.get_temp::<[f32; 8]>(widths_id)) {
|
||||
for (width, previous) in widths.iter_mut().zip(previous) {
|
||||
*width = width.max(previous);
|
||||
}
|
||||
}
|
||||
ui.memory_mut(|memory| memory.data.insert_temp(widths_id, widths));
|
||||
let fixed = widths.iter().sum::<f32>() + table::GAP * 7.0;
|
||||
widths[7] += (ui.available_width() - fixed).max(0.0);
|
||||
table::row(ui, "backend headers", &widths, false, |column, ui| {
|
||||
ui.weak(headers[column]);
|
||||
});
|
||||
for (index, b) in l.backends.iter().enumerate() {
|
||||
let key = key(v, l, &b.backend);
|
||||
let rates = view.backends.get(&key);
|
||||
table::row(
|
||||
ui,
|
||||
&key,
|
||||
&widths,
|
||||
index % 2 == 0,
|
||||
|column, ui| match column {
|
||||
0 => {
|
||||
if ui
|
||||
.selectable_label(view.selected.as_ref() == Some(&key), &values[index][0])
|
||||
.clicked()
|
||||
{
|
||||
view.selected = Some(key.clone());
|
||||
}
|
||||
}
|
||||
1 => {
|
||||
ui.colored_label(health_color(&b.state), &values[index][1])
|
||||
.on_hover_text(&b.state);
|
||||
}
|
||||
2 => {
|
||||
ui.colored_label(
|
||||
if values[index][2] == "Traffic" {
|
||||
ACTIVE
|
||||
} else {
|
||||
NEXT
|
||||
},
|
||||
&values[index][2],
|
||||
)
|
||||
.on_hover_text(
|
||||
if l.selected.as_ref() == Some(&b.backend) {
|
||||
"Selected for new connections. Existing flows can use other backends."
|
||||
} else {
|
||||
"Traffic during the latest sample interval."
|
||||
},
|
||||
);
|
||||
}
|
||||
3..=6 => {
|
||||
ui.label(&values[index][column]);
|
||||
}
|
||||
_ => format::sparkline(ui, rates.map(|r| &r.total), view.unit, 24.0),
|
||||
},
|
||||
);
|
||||
}
|
||||
if l.backends.is_empty() {
|
||||
ui.weak("No backends. Add a node and target port in Configuration.");
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Branch {
|
||||
active: bool,
|
||||
next: bool,
|
||||
}
|
||||
fn branch(l: &ListenerStatus, b: &BackendStatus, rates: Option<&Rates>, now: Instant) -> Branch {
|
||||
Branch {
|
||||
active: rates.is_some_and(|r| r.active(now)),
|
||||
next: l.selected.as_ref() == Some(&b.backend),
|
||||
}
|
||||
}
|
||||
|
||||
fn diagram(
|
||||
ui: &mut egui::Ui,
|
||||
v: &VipStatus,
|
||||
l: &ListenerStatus,
|
||||
n: &NetworkReport,
|
||||
view: &mut View,
|
||||
) {
|
||||
let camera = view
|
||||
.cameras
|
||||
.entry((v.config.id.clone(), l.protocol.to_string(), l.port))
|
||||
.or_default();
|
||||
let members: Vec<_> = l.backends.iter().map(|b| b.backend.clone()).collect();
|
||||
let compact = ui.available_width() < 540.0;
|
||||
let width = if compact {
|
||||
ui.available_width().max(240.0)
|
||||
} else {
|
||||
860.0
|
||||
};
|
||||
let pitch = if compact { 66.0 } else { 92.0 };
|
||||
let height = (members.len().max(1) as f32 * pitch + 32.0).max(160.0);
|
||||
let bounds = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, height));
|
||||
if camera.members != members
|
||||
|| !camera.rect.is_positive()
|
||||
|| (camera.layout_width - width).abs() > 1.0
|
||||
{
|
||||
camera.rect = bounds;
|
||||
camera.layout_width = width;
|
||||
camera.members = members;
|
||||
}
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
legend(ui, "Traffic", ACTIVE, true);
|
||||
legend(ui, "Next new flow", NEXT, false);
|
||||
ui.weak(if compact {
|
||||
"Tap a backend · pinch to zoom"
|
||||
} else {
|
||||
"Click a backend · drag to pan · Ctrl+scroll to zoom"
|
||||
});
|
||||
if ui.small_button("Fit").clicked() {
|
||||
camera.rect = bounds;
|
||||
}
|
||||
});
|
||||
let size = egui::vec2(ui.available_width(), height.clamp(160.0, 360.0));
|
||||
let (outer, _) = ui.allocate_exact_size(size, egui::Sense::hover());
|
||||
ui.painter()
|
||||
.rect_filled(outer, 6.0, ui.visuals().extreme_bg_color);
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().id_salt("vip graph").max_rect(outer));
|
||||
egui::Scene::new()
|
||||
.zoom_range(0.05..=1.5)
|
||||
.max_inner_size(bounds.size())
|
||||
.show(&mut child, &mut camera.rect, |ui| {
|
||||
ui.set_min_size(bounds.size());
|
||||
let center = height / 2.0;
|
||||
let rect = |x, y, w, h| egui::Rect::from_min_size(egui::pos2(x, y), egui::vec2(w, h));
|
||||
let (source, listener) = if compact {
|
||||
let w = width * 0.40;
|
||||
(
|
||||
rect(8.0, center - 65.0, w, 52.0),
|
||||
rect(8.0, center + 12.0, w, 52.0),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
rect(18.0, center - 32.0, 204.0, 64.0),
|
||||
rect(290.0, center - 32.0, 146.0, 64.0),
|
||||
)
|
||||
};
|
||||
let active = l.backends.iter().any(|b| {
|
||||
view.backends
|
||||
.get(&key(v, l, &b.backend))
|
||||
.is_some_and(|r| r.active(Instant::now()))
|
||||
});
|
||||
edge(
|
||||
ui,
|
||||
if compact {
|
||||
source.center_bottom()
|
||||
} else {
|
||||
source.right_center()
|
||||
},
|
||||
if compact {
|
||||
listener.center_top()
|
||||
} else {
|
||||
listener.left_center()
|
||||
},
|
||||
if active { ACTIVE } else { NEXT },
|
||||
active,
|
||||
);
|
||||
node(
|
||||
ui,
|
||||
source,
|
||||
&format!("{}.{}", v.config.name, n.name),
|
||||
"This device",
|
||||
NEXT,
|
||||
false,
|
||||
);
|
||||
node(
|
||||
ui,
|
||||
listener,
|
||||
&format!("{}/{}", l.protocol, l.port),
|
||||
"Listener",
|
||||
NEXT,
|
||||
false,
|
||||
);
|
||||
for (index, b) in l.backends.iter().enumerate() {
|
||||
let key = key(v, l, &b.backend);
|
||||
let rates = view.backends.get(&key);
|
||||
let state = branch(l, b, rates, Instant::now());
|
||||
let rect = if compact {
|
||||
rect(
|
||||
width * 0.51,
|
||||
10.0 + index as f32 * pitch,
|
||||
width * 0.49 - 8.0,
|
||||
56.0,
|
||||
)
|
||||
} else {
|
||||
rect(558.0, 24.0 + index as f32 * pitch, 278.0, 68.0)
|
||||
};
|
||||
let color = if state.active {
|
||||
ACTIVE
|
||||
} else if state.next {
|
||||
NEXT
|
||||
} else if b.state == "ready" {
|
||||
ui.visuals().weak_text_color()
|
||||
} else {
|
||||
health_color(&b.state)
|
||||
};
|
||||
edge(
|
||||
ui,
|
||||
listener.right_center(),
|
||||
rect.left_center(),
|
||||
color,
|
||||
state.active,
|
||||
);
|
||||
if state.next {
|
||||
ui.painter().circle_stroke(
|
||||
rect.left_center(),
|
||||
5.0,
|
||||
egui::Stroke::new(2.0_f32, NEXT),
|
||||
);
|
||||
}
|
||||
let response = ui
|
||||
.interact(rect, ui.id().with((&key.3, key.4)), egui::Sense::click())
|
||||
.on_hover_cursor(egui::CursorIcon::PointingHand)
|
||||
.on_hover_text(format!(
|
||||
"{}\n{} · RTT {}\n{} open flows\n{}{}",
|
||||
backend_name(n, &b.backend),
|
||||
b.state,
|
||||
rtt(b),
|
||||
b.active_flows,
|
||||
if state.active {
|
||||
"Traffic in latest sample. "
|
||||
} else {
|
||||
""
|
||||
},
|
||||
if state.next {
|
||||
"Selected for new connections."
|
||||
} else {
|
||||
""
|
||||
}
|
||||
));
|
||||
if response.clicked() {
|
||||
view.selected = Some(key.clone());
|
||||
}
|
||||
let detail = format!("{} · {} · {} flows", b.state, rtt(b), b.active_flows);
|
||||
node(
|
||||
ui,
|
||||
rect,
|
||||
&backend_name(n, &b.backend),
|
||||
&detail,
|
||||
color,
|
||||
view.selected.as_ref() == Some(&key) || response.hovered(),
|
||||
);
|
||||
}
|
||||
if l.backends.is_empty() {
|
||||
ui.painter().text(
|
||||
egui::pos2(if compact { width * 0.52 } else { 570.0 }, center),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
"No backends",
|
||||
egui::FontId::proportional(15.0),
|
||||
ui.visuals().weak_text_color(),
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
fn legend(ui: &mut egui::Ui, text: &str, color: egui::Color32, filled: bool) {
|
||||
ui.horizontal(|ui| {
|
||||
let (rect, _) = ui.allocate_exact_size(egui::vec2(12.0, 12.0), egui::Sense::hover());
|
||||
if filled {
|
||||
ui.painter().circle_filled(rect.center(), 4.0, color);
|
||||
} else {
|
||||
ui.painter()
|
||||
.circle_stroke(rect.center(), 4.0, egui::Stroke::new(1.5_f32, color));
|
||||
}
|
||||
ui.colored_label(color, text);
|
||||
});
|
||||
}
|
||||
fn node(
|
||||
ui: &egui::Ui,
|
||||
rect: egui::Rect,
|
||||
title: &str,
|
||||
detail: &str,
|
||||
color: egui::Color32,
|
||||
selected: bool,
|
||||
) {
|
||||
let painter = ui.painter_at(rect);
|
||||
painter.rect_filled(rect, 8.0, ui.visuals().widgets.inactive.bg_fill);
|
||||
painter.rect_stroke(
|
||||
rect.shrink(1.0),
|
||||
8.0,
|
||||
egui::Stroke::new(if selected { 3.0_f32 } else { 1.5_f32 }, color),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
text_line(
|
||||
&painter,
|
||||
rect.min + egui::vec2(12.0, 9.0),
|
||||
title,
|
||||
16.0,
|
||||
ui.visuals().strong_text_color(),
|
||||
rect.width() - 24.0,
|
||||
);
|
||||
text_line(
|
||||
&painter,
|
||||
rect.min + egui::vec2(12.0, 34.0),
|
||||
detail,
|
||||
12.0,
|
||||
ui.visuals().text_color(),
|
||||
rect.width() - 24.0,
|
||||
);
|
||||
}
|
||||
fn text_line(
|
||||
painter: &egui::Painter,
|
||||
position: egui::Pos2,
|
||||
text: &str,
|
||||
size: f32,
|
||||
color: egui::Color32,
|
||||
width: f32,
|
||||
) {
|
||||
let mut job = egui::text::LayoutJob::simple_singleline(
|
||||
text.into(),
|
||||
egui::FontId::proportional(size),
|
||||
color,
|
||||
);
|
||||
job.wrap.max_width = width;
|
||||
job.wrap.max_rows = 1;
|
||||
job.wrap.break_anywhere = true;
|
||||
painter.galley(position, painter.layout_job(job), color);
|
||||
}
|
||||
fn edge(ui: &egui::Ui, start: egui::Pos2, end: egui::Pos2, color: egui::Color32, active: bool) {
|
||||
let delta = end - start;
|
||||
let direction = if delta.x.abs() < 1.0 {
|
||||
egui::Vec2::Y
|
||||
} else {
|
||||
egui::Vec2::X
|
||||
};
|
||||
let bend = direction * delta.dot(direction) * 0.5;
|
||||
let curve = egui::epaint::CubicBezierShape::from_points_stroke(
|
||||
[start, start + bend, end - bend, end],
|
||||
false,
|
||||
egui::Color32::TRANSPARENT,
|
||||
egui::Stroke::new(if active { 3.0_f32 } else { 1.5_f32 }, color),
|
||||
);
|
||||
ui.painter().add(curve.clone());
|
||||
if active {
|
||||
let t = ui.input(|i| i.time) as f32 * 0.5 % 1.0;
|
||||
let position = curve.sample(t);
|
||||
ui.painter().circle_filled(position, 4.0, color);
|
||||
ui.ctx().request_repaint_after(Duration::from_millis(40));
|
||||
}
|
||||
ui.painter().arrow(
|
||||
end - direction * 12.0,
|
||||
direction * 10.0,
|
||||
egui::Stroke::new(1.5_f32, color),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
use super::*;
|
||||
use tsunagi::vip::{Listener, VipConfig};
|
||||
fn fixture() -> (NetworkReport, VipStatus) {
|
||||
let mut config = VipConfig::new("k8s");
|
||||
config.listeners.push(Listener::new(Protocol::Tcp, 6443));
|
||||
let backends: Vec<_> = ["ai", "master", "music"]
|
||||
.into_iter()
|
||||
.map(|peer| BackendStatus {
|
||||
backend: Backend {
|
||||
peer: peer.into(),
|
||||
port: 7443,
|
||||
},
|
||||
state: "ready".into(),
|
||||
rtt_us: Some(4500),
|
||||
measurement_age_ms: Some(500),
|
||||
active_flows: 5,
|
||||
counters: Counters::default(),
|
||||
})
|
||||
.collect();
|
||||
let v = VipStatus {
|
||||
config,
|
||||
revision: "r1".into(),
|
||||
address: None,
|
||||
error: None,
|
||||
listeners: vec![ListenerStatus {
|
||||
protocol: Protocol::Tcp,
|
||||
port: 6443,
|
||||
selected: Some(backends[0].backend.clone()),
|
||||
backends,
|
||||
counters: Counters::default(),
|
||||
}],
|
||||
};
|
||||
let n = NetworkReport {
|
||||
name: "test".into(),
|
||||
vips: vec![v.clone()],
|
||||
..Default::default()
|
||||
};
|
||||
(n, v)
|
||||
}
|
||||
#[test]
|
||||
fn traffic_branches_are_sampled_independently_of_new_flow_selection_and_open_flows() {
|
||||
let (mut n, _) = fixture();
|
||||
let now = Instant::now();
|
||||
let mut view = View::default();
|
||||
view.observe(&n, now);
|
||||
n.vips[0].listeners[0].backends[2].counters.tx_packets = 20;
|
||||
n.vips[0].listeners[0].backends[2].counters.tx_bytes = 4000;
|
||||
n.vips[0].listeners[0].counters.tx_packets = 20;
|
||||
n.vips[0].listeners[0].counters.tx_bytes = 4000;
|
||||
view.observe(&n, now + Duration::from_secs(2));
|
||||
let v = &n.vips[0];
|
||||
let l = &v.listeners[0];
|
||||
let selected = branch(
|
||||
l,
|
||||
&l.backends[0],
|
||||
view.backends.get(&key(v, l, &l.backends[0].backend)),
|
||||
now + Duration::from_secs(2),
|
||||
);
|
||||
let carrying = branch(
|
||||
l,
|
||||
&l.backends[2],
|
||||
view.backends.get(&key(v, l, &l.backends[2].backend)),
|
||||
now + Duration::from_secs(2),
|
||||
);
|
||||
assert!(selected.next && !selected.active);
|
||||
assert!(carrying.active && !carrying.next);
|
||||
assert_eq!(view.totals[&v.config.id].total.rate(Unit::Bytes), 2000.0);
|
||||
assert!(
|
||||
!view.backends[&key(v, l, &l.backends[2].backend)].active(now + Duration::from_secs(8))
|
||||
);
|
||||
view.observe(&n, now + Duration::from_secs(4));
|
||||
assert!(
|
||||
!view.backends[&key(v, l, &l.backends[2].backend)].active(now + Duration::from_secs(4))
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn removed_services_and_backends_release_history_selection_and_cameras() {
|
||||
let (mut n, v) = fixture();
|
||||
let mut view = View::default();
|
||||
view.observe(&n, Instant::now());
|
||||
view.selected = Some(key(
|
||||
&v,
|
||||
&v.listeners[0],
|
||||
&v.listeners[0].backends[0].backend,
|
||||
));
|
||||
n.vips.clear();
|
||||
view.observe(&n, Instant::now());
|
||||
assert!(
|
||||
view.backends.is_empty()
|
||||
&& view.totals.is_empty()
|
||||
&& view.selected.is_none()
|
||||
&& view.cameras.is_empty()
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn clicking_a_scene_node_selects_its_backend_without_changing_configuration() {
|
||||
let (n, v) = fixture();
|
||||
let ctx = egui::Context::default();
|
||||
let mut view = View::default();
|
||||
let frame = |view: &mut View, events| {
|
||||
ctx.run(
|
||||
egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(1000.0, 600.0),
|
||||
)),
|
||||
events,
|
||||
..Default::default()
|
||||
},
|
||||
|ctx| {
|
||||
egui::CentralPanel::default()
|
||||
.show(ctx, |ui| diagram(ui, &v, &v.listeners[0], &n, view));
|
||||
},
|
||||
)
|
||||
};
|
||||
frame(&mut view, vec![]);
|
||||
let output = frame(&mut view, vec![]);
|
||||
let pos = output
|
||||
.shapes
|
||||
.iter()
|
||||
.find_map(|s| match &s.shape {
|
||||
egui::Shape::Text(t) if t.galley.text() == "music:7443" => {
|
||||
Some(t.pos + egui::vec2(20.0, 10.0))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.expect("scene draws the backend node");
|
||||
for pressed in [true, false] {
|
||||
frame(
|
||||
&mut view,
|
||||
vec![
|
||||
egui::Event::PointerMoved(pos),
|
||||
egui::Event::PointerButton {
|
||||
pos,
|
||||
button: egui::PointerButton::Primary,
|
||||
pressed,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
},
|
||||
],
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
view.selected
|
||||
== Some(key(
|
||||
&v,
|
||||
&v.listeners[0],
|
||||
&v.listeners[0].backends[2].backend
|
||||
))
|
||||
);
|
||||
assert_eq!(n.vips[0].config, v.config);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_counters_and_recreated_listeners_do_not_inherit_active_traffic() {
|
||||
let (mut n, _) = fixture();
|
||||
let mut view = View::default();
|
||||
let at = Instant::now();
|
||||
n.vips[0].listeners[0].backends[0].counters.tx_packets = 100;
|
||||
view.observe(&n, at);
|
||||
n.vips[0].listeners[0].backends[0].counters.tx_packets = 0;
|
||||
view.observe(&n, at + Duration::from_secs(2));
|
||||
let v = &n.vips[0];
|
||||
let l = &v.listeners[0];
|
||||
assert!(
|
||||
!view.backends[&key(v, l, &l.backends[0].backend)].active(at + Duration::from_secs(2))
|
||||
);
|
||||
n.vips[0].config.listeners[0].id = "new listener".into();
|
||||
n.vips[0].listeners[0].backends[0].counters.tx_packets = 200;
|
||||
view.observe(&n, at + Duration::from_secs(4));
|
||||
let v = &n.vips[0];
|
||||
let l = &v.listeners[0];
|
||||
assert!(
|
||||
!view.backends[&key(v, l, &l.backends[0].backend)].active(at + Duration::from_secs(4))
|
||||
);
|
||||
assert_eq!(view.backends.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_tables_and_scenes_render_at_narrow_and_wide_sizes() {
|
||||
let (n, v) = fixture();
|
||||
let ctx = egui::Context::default();
|
||||
let mut view = View::default();
|
||||
for width in [360.0, 412.0, 650.0, 1000.0, 1800.0, 360.0] {
|
||||
for _ in 0..2 {
|
||||
let _ = ctx.run(
|
||||
egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(width, 1000.0),
|
||||
)),
|
||||
..Default::default()
|
||||
},
|
||||
|ctx| {
|
||||
egui::CentralPanel::default().show(ctx, |ui| {
|
||||
egui::ScrollArea::vertical().show(ui, |ui| show(ui, &v, &n, &mut view));
|
||||
assert!(
|
||||
ui.min_rect().right() <= width + 1.0,
|
||||
"VIP content expands the window at {width}"
|
||||
);
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user