Add an on-demand traffic monitor to the tray and Android
Show bidirectional IP conversations with network and peer names, ports, traffic roles, packet totals and directional rates. Aggregate ICMP echoes by address pair. Attribute exit requests and replies from each endpoint's perspective and match VIP traffic on the client-facing side of NAT. Keep authenticated control sessions and opaque relay pairs in a transport view. Each open window owns a bounded interval subscription. The idle path only checks whether a reader exists. Contended writers can use another lane, and observations lost under load are counted without delaying forwarding. Use a dedicated local control connection on desktop and a service handle on Android. Closing or backgrounding the Android screen releases capture. The local IPC format advances to 28. Existing mesh peers and databases remain compatible. Accumulate intervals off the render thread in a private temporary SQLite database. Expire inactive rows after a minute or retain them until close. Indexed, cursor-based pages keep long sessions out of UI memory. Closing the window interrupts pending queries and releases the scratch database. On macOS arm64, workspace formatting and strict Clippy passed. The locked all-targets workspace suite passed 641 tests with five opt-in tests ignored. Coverage includes real WireGuard exit traffic in both directions, local IPC lifetime, Android pause/resume, relay opacity, VIP translation, bounded capture, simulated three-day retention and 320–900 point layouts. The Windows GNU workspace cross-check and the offline Android arm64 debug APK build passed. Windows and Android hardware were not exercised.
This commit is contained in:
1 parent
7afed15f76
commit
e3b74babba
42 files changed
+2476
-31
No files matched your search
@@ -38,7 +38,15 @@ fn with_display<T: Default>(f: impl FnOnce(&mut Display) -> T) -> T {
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
extern "system" fn Java_cy_hexor_tsunagi_Native_surface(mut env: JNIEnv, _: JObject) {
|
||||
extern "system" fn Java_cy_hexor_tsunagi_Native_pauseTraffic(_: JNIEnv, _: JObject) {
|
||||
with_display(|d| d.ui.pause_monitor());
|
||||
}
|
||||
#[unsafe(no_mangle)]
|
||||
extern "system" fn Java_cy_hexor_tsunagi_Native_surface(
|
||||
mut env: JNIEnv,
|
||||
_: JObject,
|
||||
cache: JString,
|
||||
) {
|
||||
// SAFETY: GLSurfaceView invokes this callback on the GL thread with its ES3 context current.
|
||||
let gl = unsafe {
|
||||
glow::Context::from_loader_function_cstr(|name| eglGetProcAddress(name.as_ptr()))
|
||||
@@ -52,9 +60,10 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_surface(mut env: JNIEnv, _: JObj
|
||||
};
|
||||
let ctx = egui::Context::default();
|
||||
crate::view::configure(&ctx);
|
||||
let cache = env.get_string(&cache).ok().map(String::from);
|
||||
DISPLAY.with_borrow_mut(|d| {
|
||||
// If Android discarded the old EGL context, its GPU resources are already gone.
|
||||
let ui = d
|
||||
let mut ui = d
|
||||
.take()
|
||||
.map(|old| {
|
||||
// A rotation can recreate EGL. Keep expanded peers and scroll positions
|
||||
@@ -64,6 +73,9 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_surface(mut env: JNIEnv, _: JObj
|
||||
old.ui
|
||||
})
|
||||
.unwrap_or_default();
|
||||
if let Some(cache) = cache {
|
||||
ui.set_cache_dir(cache.into());
|
||||
}
|
||||
*d = Some(Display {
|
||||
painter,
|
||||
ctx,
|
||||
@@ -112,6 +124,7 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_draw(
|
||||
let output = d.ctx.run(input, |ctx| {
|
||||
action = d.ui.draw(ctx, &state, super::send).or(action);
|
||||
});
|
||||
d.ui.poll_monitor(|| super::submit(crate::service::Request::WatchTraffic));
|
||||
if let Some(action) = action {
|
||||
let method = match action {
|
||||
SystemAction::Start => "startAgent",
|
||||
|
||||
@@ -62,12 +62,15 @@ fn status() -> State {
|
||||
state
|
||||
}
|
||||
fn send(cmd: tsunagi_ui::client::Command) -> Result<Response, String> {
|
||||
submit(Request::Action(cmd))
|
||||
}
|
||||
fn submit(request: Request) -> Result<Response, String> {
|
||||
let (reply, result) = oneshot::channel();
|
||||
current()
|
||||
.as_ref()
|
||||
.ok_or("Tsunagi Agent stopped")?
|
||||
.commands
|
||||
.try_send((Request::Action(cmd), reply))
|
||||
.try_send((request, reply))
|
||||
.map_err(|_| "Tsunagi Agent is busy or stopped".to_owned())?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! The Android application. Mesh state belongs to one service-owned Rust agent.
|
||||
|
||||
pub mod dns;
|
||||
mod monitor;
|
||||
pub mod plan;
|
||||
|
||||
#[cfg(target_os = "android")]
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
//! The GL thread holds a service subscription only while the inspector is visible.
|
||||
use crate::service::{Outcome, Response};
|
||||
use std::{
|
||||
path::PathBuf,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tokio::sync::oneshot::error::TryRecvError;
|
||||
use tsunagi::traffic::TrafficSubscription;
|
||||
use tsunagi_ui::monitor::Window;
|
||||
|
||||
pub(super) struct Monitor {
|
||||
pub view: Window,
|
||||
pending: Option<Response>,
|
||||
subscription: Option<TrafficSubscription>,
|
||||
next: Instant,
|
||||
failed: bool,
|
||||
}
|
||||
impl Monitor {
|
||||
pub fn new(cache: Option<PathBuf>) -> Self {
|
||||
Self {
|
||||
view: Window::new(cache),
|
||||
pending: None,
|
||||
subscription: None,
|
||||
next: Instant::now(),
|
||||
failed: false,
|
||||
}
|
||||
}
|
||||
pub fn pause(&mut self) {
|
||||
self.pending = None;
|
||||
self.subscription = None;
|
||||
}
|
||||
pub fn poll(&mut self, open: impl FnOnce() -> Result<Response, String>) {
|
||||
if self.failed {
|
||||
return;
|
||||
}
|
||||
if let Some(sub) = &self.subscription {
|
||||
if Instant::now() >= self.next {
|
||||
self.next = Instant::now() + Duration::from_secs(1);
|
||||
if !self.view.feed().sample(sub.snapshot()) {
|
||||
self.pause();
|
||||
self.failed = true;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
let result = match &mut self.pending {
|
||||
Some(rx) => match rx.try_recv() {
|
||||
Ok(Ok(Outcome::Traffic(sub))) => {
|
||||
// Time spent in the background must expire old rows before new traffic can refresh them.
|
||||
self.view.feed().sample(Default::default());
|
||||
self.subscription = Some(sub);
|
||||
self.next = Instant::now() + Duration::from_secs(1);
|
||||
self.pending = None;
|
||||
return;
|
||||
}
|
||||
Ok(Err(e)) => Err(e),
|
||||
Err(TryRecvError::Empty) => return,
|
||||
_ => Err("Tsunagi Agent stopped".into()),
|
||||
},
|
||||
None => open().map(|r| self.pending = Some(r)),
|
||||
};
|
||||
if let Err(e) = result {
|
||||
self.pending = None;
|
||||
self.failed = true;
|
||||
self.view.feed().error(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,8 @@ use zeroize::Zeroizing;
|
||||
|
||||
/// A platform notification or user gesture.
|
||||
pub enum Request {
|
||||
/// A visible monitor requested its own fresh observation interval.
|
||||
WatchTraffic,
|
||||
/// A command from the same form used by the tray.
|
||||
Action(Command),
|
||||
/// The visible activity requested current counters.
|
||||
@@ -150,6 +152,8 @@ pub(crate) async fn wait_for_exit_offer(
|
||||
|
||||
/// Private reply delivered only to the UI that requested the action.
|
||||
pub enum Outcome {
|
||||
/// Owned by one traffic screen and dropped when capture stops.
|
||||
Traffic(tsunagi::traffic::TrafficSubscription),
|
||||
/// The agent has applied the action.
|
||||
Applied,
|
||||
/// Revisions returned by a successful signed write.
|
||||
@@ -346,6 +350,10 @@ pub async fn serve(
|
||||
let Some((request, reply)) = command else { break };
|
||||
let refresh_zones = !matches!(request, Request::Refresh);
|
||||
let result = match request {
|
||||
Request::WatchTraffic => {
|
||||
let _ = reply.send(agent.subscribe_traffic().map(Outcome::Traffic));
|
||||
continue;
|
||||
}
|
||||
Request::Refresh => Ok(Outcome::Applied),
|
||||
Request::Action(cmd) => {
|
||||
if matches!(cmd, Command::Join { .. } | Command::Leave { .. } | Command::SetActive { .. }) {
|
||||
|
||||
@@ -44,6 +44,28 @@ async fn a_hidden_service_waits_for_mesh_changes_and_visible_stats_are_on_demand
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(matches!(*snapshots.borrow_and_update(), State::Ready(..)));
|
||||
// Occupy the other reader slots so this test observes the real service subscription
|
||||
// being acquired on screen open and released on both background and close.
|
||||
let other_windows: Vec<_> = (0..3)
|
||||
.map(|_| phone.agent.subscribe_traffic().unwrap())
|
||||
.collect();
|
||||
let mut monitor = crate::monitor::Monitor::new(None);
|
||||
for _ in 0..2 {
|
||||
monitor.poll(|| {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
commands.try_send((Request::WatchTraffic, tx)).unwrap();
|
||||
Ok(rx)
|
||||
});
|
||||
tsunagi::testing::wait_until("the visible Android monitor subscribed", || async {
|
||||
phone.agent.subscribe_traffic().is_err().then_some(())
|
||||
})
|
||||
.await;
|
||||
monitor.poll(|| panic!("a visible monitor must reuse its subscription"));
|
||||
monitor.pause();
|
||||
assert!(phone.agent.subscribe_traffic().is_ok());
|
||||
}
|
||||
drop((monitor, other_windows));
|
||||
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(2200), snapshots.changed())
|
||||
.await
|
||||
|
||||
@@ -20,6 +20,7 @@ enum Page {
|
||||
#[default]
|
||||
Home,
|
||||
About,
|
||||
Monitor,
|
||||
Join,
|
||||
Devices(String),
|
||||
Vips(String),
|
||||
@@ -38,6 +39,7 @@ impl Page {
|
||||
match self {
|
||||
Self::Home => "tsunagi",
|
||||
Self::About => "About",
|
||||
Self::Monitor => "Traffic monitor",
|
||||
Self::Join => "Join a network",
|
||||
Self::Devices(_) => "Devices",
|
||||
Self::Vips(_) => "VIP",
|
||||
@@ -85,6 +87,8 @@ struct Pending {
|
||||
#[derive(Default)]
|
||||
pub struct Phone {
|
||||
page: Page,
|
||||
monitor: Option<crate::monitor::Monitor>,
|
||||
cache_dir: Option<std::path::PathBuf>,
|
||||
forms: UiState,
|
||||
traffic: Traffic,
|
||||
snapshot: Snapshot,
|
||||
@@ -108,7 +112,24 @@ pub fn configure(ctx: &Context) {
|
||||
}
|
||||
|
||||
impl Phone {
|
||||
/// Private directory available to a window's temporary SQLite database.
|
||||
pub fn set_cache_dir(&mut self, path: std::path::PathBuf) {
|
||||
self.cache_dir = Some(path);
|
||||
}
|
||||
/// Release the agent subscription immediately when the activity goes into the background.
|
||||
pub fn pause_monitor(&mut self) {
|
||||
if let Some(m) = &mut self.monitor {
|
||||
m.pause();
|
||||
}
|
||||
}
|
||||
/// Poll the service only while a traffic screen is visible.
|
||||
pub fn poll_monitor(&mut self, open: impl FnOnce() -> Result<Response, String>) {
|
||||
if let Some(m) = &mut self.monitor {
|
||||
m.poll(open);
|
||||
}
|
||||
}
|
||||
fn home(&mut self) {
|
||||
self.monitor = None;
|
||||
if let Some(previous) = self.before_picker.take() {
|
||||
self.forms.exit_confirm = None;
|
||||
self.page = previous;
|
||||
@@ -331,7 +352,7 @@ impl Phone {
|
||||
}
|
||||
Some(report)
|
||||
} else {
|
||||
if self.page.network().is_some() || self.page == Page::Join {
|
||||
if self.page.network().is_some() || matches!(self.page, Page::Join | Page::Monitor) {
|
||||
self.home();
|
||||
}
|
||||
self.snapshot = Snapshot::default();
|
||||
@@ -361,6 +382,11 @@ impl Phone {
|
||||
self.page = Page::About;
|
||||
}
|
||||
if report.is_some() {
|
||||
if tsunagi_ui::widgets::icon_button(ui, icon::PULSE, "Traffic monitor")
|
||||
.clicked()
|
||||
{
|
||||
self.page = Page::Monitor;
|
||||
}
|
||||
ui.selectable_value(&mut self.forms.unit, Unit::Bytes, "bytes");
|
||||
ui.selectable_value(&mut self.forms.unit, Unit::Packets, "pkts");
|
||||
}
|
||||
@@ -381,7 +407,19 @@ impl Phone {
|
||||
.page
|
||||
.network()
|
||||
.and_then(|id| report?.networks.iter().find(|n| n.network_id == id));
|
||||
if self.page != Page::Monitor {
|
||||
self.monitor = None;
|
||||
}
|
||||
match (&self.page, selected) {
|
||||
(Page::Monitor, _) => {
|
||||
let m = self
|
||||
.monitor
|
||||
.get_or_insert_with(|| crate::monitor::Monitor::new(self.cache_dir.clone()));
|
||||
egui::CentralPanel::default().show(ctx, |ui| {
|
||||
m.view
|
||||
.show(ui, report.map(|r| r.as_ref()), self.snapshot.generation)
|
||||
});
|
||||
}
|
||||
(Page::About, _) => about::show(ctx, None, &self.snapshot),
|
||||
(Page::Vips(id), Some(network)) => {
|
||||
let editor = self.forms.vip_windows.entry(id.clone()).or_default();
|
||||
|
||||
Reference in new issue
Block a user