Files
tsunagi/crates/tsunagi-core/src/ipc/traffic.rs
T
Aleksandr Bogomiakov e3b74babba 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.
2026-11-25 20:19:40 +02:00

74 lines
2.4 KiB
Rust

//! A dedicated local connection is the lifetime of one traffic window.
use super::{
EXCHANGE_TIMEOUT, Error, Path, Request, Response, Result, read_message, transport,
write_message,
};
use crate::traffic::{TrafficSnapshot, TrafficSubscription};
use std::{future::Future, time::Duration};
use tokio::io::{AsyncRead, AsyncWrite};
#[cfg(unix)]
type Socket = tokio::net::UnixStream;
#[cfg(windows)]
type Socket = tokio::net::windows::named_pipe::NamedPipeClient;
async fn bounded<T>(duration: Duration, f: impl Future<Output = Result<T>>) -> Result<T> {
tokio::time::timeout(duration, f)
.await
.map_err(|_| Error::Timeout {
what: "local traffic monitor".into(),
})?
}
/// A local monitor stream. Dropping it releases the agent's interval buffer.
pub struct TrafficStream(Socket);
impl TrafficStream {
/// Starts observing now, independently of any other open window.
pub async fn open(path: &Path) -> Result<Self> {
bounded(EXCHANGE_TIMEOUT, async {
let mut socket = transport::connect(path).await?;
write_message(&mut socket, &Request::WatchTraffic).await?;
match read_message(&mut socket).await? {
Response::TrafficReady => Ok(Self(socket)),
Response::Error(reason) => Err(Error::TrafficMonitor(reason)),
_ => Err(Error::TrafficMonitor(
"Unexpected answer opening traffic monitor".into(),
)),
}
})
.await
}
/// Drains only this reader's interval.
pub async fn snapshot(&mut self) -> Result<TrafficSnapshot> {
bounded(EXCHANGE_TIMEOUT, async {
write_message(&mut self.0, &0u8).await?;
read_message(&mut self.0).await
})
.await
}
}
pub(super) async fn serve<S: AsyncRead + AsyncWrite + Unpin>(
mut socket: S,
sub: TrafficSubscription,
) -> Result<()> {
bounded(
EXCHANGE_TIMEOUT,
write_message(&mut socket, &Response::TrafficReady),
)
.await?;
loop {
// A wedged or suspended client cannot keep the collector running indefinitely.
let token: u8 = bounded(Duration::from_secs(15), read_message(&mut socket)).await?;
if token != 0 {
return Err(Error::TrafficMonitor("Invalid monitor poll".into()));
}
bounded(
EXCHANGE_TIMEOUT,
write_message(&mut socket, &sub.snapshot()),
)
.await?;
}
}