Reduce idle mesh traffic and Android background work for 1.0.4
A phone keeping its mesh online was paying for two data-path probe exchanges per WG or AWG link, repeated control snapshots, and a full Android status and DNS rebuild every two seconds while the activity was closed. Let a timely, authenticated reply of the requested size on the physical carrier satisfy its native delivery check. Keep the full-sized probe, RTT window, loss thresholds, roaming, and independent silence detection. Resume native probes when shared confirmations go stale and answer both probe formats throughout the lifetime of the pair. Index the latest signed objects once per network. Each reliable session sends a full snapshot on connect and advances its cursor only when a frame enters its send queue. Reopen the affected stream if a replica cannot persist a received update. Send canonical peer hints in bounded batches, publish changed edges immediately, and refresh reachability ahead of its 90-second expiry. The scheduling revisions live in memory and peers use the existing wire formats and database schema. Drive Android DNS and selected-exit notifications from coalesced roster changes. The visible activity requests fresh counters, reusing the current DNS zones. Set the workspace, Android, and Nix package versions to 1.0.4. Formatting and strict workspace Clippy passed on macOS arm64. The locked workspace suite passed 594 tests with four opt-in checks ignored. Both Android instrumentation tests passed on an API 37 arm64 emulator. Tested mixed 1.0.3/1.0.4 pairs on WG and AWG. In a 30-second idle WG comparison, one endpoint's combined UDP bytes fell from 220950 to 138596 and its control messages from 24 to 2. Physical phone discharge and native Linux and Windows runs remain unverified.
This commit is contained in:
1 parent
8c4c2fa34e
commit
50c0ecea45
33 files changed
+781
-294
No files matched your search
@@ -25,6 +25,7 @@ use tsunagi_wg_quic::{DEFAULT_MTU, WireguardConfig, WireguardPlugin};
|
||||
|
||||
struct Session {
|
||||
id: i64,
|
||||
last_refresh: Option<std::time::Instant>,
|
||||
commands: mpsc::Sender<(Request, Reply)>,
|
||||
state: watch::Receiver<State>,
|
||||
underlay: watch::Sender<Vec<std::net::IpAddr>>,
|
||||
@@ -39,10 +40,21 @@ fn current() -> std::sync::MutexGuard<'static, Option<Session>> {
|
||||
SESSION.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
fn status() -> State {
|
||||
current()
|
||||
.as_ref()
|
||||
.map(|s| s.state.borrow().clone())
|
||||
.unwrap_or_default()
|
||||
let mut current = current();
|
||||
let Some(session) = current.as_mut() else {
|
||||
return State::Off;
|
||||
};
|
||||
if session
|
||||
.last_refresh
|
||||
.is_none_or(|last| last.elapsed() >= std::time::Duration::from_secs(2))
|
||||
&& session
|
||||
.commands
|
||||
.try_send((Request::Refresh, oneshot::channel().0))
|
||||
.is_ok()
|
||||
{
|
||||
session.last_refresh = Some(std::time::Instant::now());
|
||||
}
|
||||
session.state.borrow().clone()
|
||||
}
|
||||
fn send(cmd: tsunagi_ui::client::Command) -> Result<Response, String> {
|
||||
let (reply, result) = oneshot::channel();
|
||||
@@ -227,6 +239,7 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_start(
|
||||
})?;
|
||||
*slot = Some(Session {
|
||||
id,
|
||||
last_refresh: None,
|
||||
commands,
|
||||
state: state_rx,
|
||||
underlay,
|
||||
|
||||
@@ -46,11 +46,7 @@ impl Resolver {
|
||||
let view = tsunagi::dns::RosterZones::from_networks(networks);
|
||||
let names = view.zones.names() as u32;
|
||||
self.replace(Some(view.zones));
|
||||
let address = *self.listening.borrow();
|
||||
tsunagi::ipc::DnsReport {
|
||||
listening: address.map(|ip| format!("{ip}:53")).into_iter().collect(),
|
||||
publish_error: (address.is_none() && !view.labels.is_empty())
|
||||
.then(|| "Waiting for a VPN interface with a DNS address.".into()),
|
||||
zones: view.labels,
|
||||
zone_warnings: view.warnings,
|
||||
names,
|
||||
@@ -58,6 +54,17 @@ impl Resolver {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn with_listener(
|
||||
&self,
|
||||
mut report: tsunagi::ipc::DnsReport,
|
||||
) -> tsunagi::ipc::DnsReport {
|
||||
let address = *self.listening.borrow();
|
||||
report.listening = address.map(|ip| format!("{ip}:53")).into_iter().collect();
|
||||
report.publish_error = (address.is_none() && !report.zones.is_empty())
|
||||
.then(|| "Waiting for a VPN interface with a DNS address.".into());
|
||||
report
|
||||
}
|
||||
|
||||
/// Answer a local DNS request. Slow public lookups never block a mesh answer.
|
||||
pub async fn answer(&self, query: &[u8]) -> Option<Vec<u8>> {
|
||||
if query.len() > MAX_MESSAGE_LEN {
|
||||
|
||||
@@ -3,7 +3,7 @@ use std::{sync::Arc, time::Instant};
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use tsunagi::{
|
||||
Agent, NetworkName, NetworkSecret,
|
||||
ipc::{PrivilegeReport, ProtocolReport, StatusReport},
|
||||
ipc::{DnsReport, PrivilegeReport, ProtocolReport, StatusReport},
|
||||
vip::VipStatus,
|
||||
};
|
||||
use tsunagi_ui::client::Command;
|
||||
@@ -14,6 +14,8 @@ use zeroize::Zeroizing;
|
||||
pub enum Request {
|
||||
/// A command from the same form used by the tray.
|
||||
Action(Command),
|
||||
/// The visible activity requested current counters.
|
||||
Refresh,
|
||||
/// The physical network changed.
|
||||
NetworkChanged,
|
||||
/// Disable only the exit identified by the notification the user tapped.
|
||||
@@ -176,13 +178,22 @@ pub async fn report(
|
||||
agent: &Agent,
|
||||
wg: Option<&WireguardPlugin>,
|
||||
dns: &crate::dns::Resolver,
|
||||
) -> tsunagi::Result<StatusReport> {
|
||||
snapshot(agent, wg, dns, None).await
|
||||
}
|
||||
|
||||
async fn snapshot(
|
||||
agent: &Agent,
|
||||
wg: Option<&WireguardPlugin>,
|
||||
dns: &crate::dns::Resolver,
|
||||
cached_zones: Option<DnsReport>,
|
||||
) -> tsunagi::Result<StatusReport> {
|
||||
let status = agent.status().await?;
|
||||
let overlay = agent.overlay();
|
||||
Ok(StatusReport {
|
||||
networks: tsunagi_runtime::report::networks(&status, overlay.as_ref(), wg),
|
||||
overlay_config_error: overlay.and_then(|state| state.address_error),
|
||||
dns: Some(dns.refresh(&status.networks)),
|
||||
dns: Some(dns.with_listener(cached_zones.unwrap_or_else(|| dns.refresh(&status.networks)))),
|
||||
endpoint_id: status.endpoint_id.to_string(),
|
||||
hostname: status.hostname,
|
||||
bound_sockets: status
|
||||
@@ -218,16 +229,20 @@ pub async fn serve(
|
||||
mut stop: watch::Receiver<bool>,
|
||||
mut publish_exit: impl FnMut(Option<&ExitNotice>),
|
||||
) {
|
||||
let mut poll = tokio::time::interval(std::time::Duration::from_secs(2));
|
||||
poll.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||
let mut roster = agent.watch_roster();
|
||||
roster.mark_changed(); // Load the initial zones before waiting for any actions.
|
||||
let mut cached_zones = None;
|
||||
let mut retry = false;
|
||||
let mut published_exit = None;
|
||||
loop {
|
||||
let reply = tokio::select! {
|
||||
let (reply, mut refresh_zones) = tokio::select! {
|
||||
biased;
|
||||
_ = stop.wait_for(|stopped| *stopped) => break,
|
||||
_ = async { drop(stop.wait_for(|stopped| *stopped).await) } => break,
|
||||
command = commands.recv() => {
|
||||
let Some((request, reply)) = command else { break };
|
||||
let refresh_zones = !matches!(request, Request::Refresh);
|
||||
let result = match request {
|
||||
Request::Refresh => Ok(Outcome::Applied),
|
||||
Request::Action(cmd) => {
|
||||
if matches!(cmd, Command::Join { .. } | Command::Leave { .. } | Command::SetActive { .. }) {
|
||||
dns.replace(None);
|
||||
@@ -242,21 +257,39 @@ pub async fn serve(
|
||||
Request::DisconnectExit {network, peer} => disconnect_exit(&agent, &network, &peer).await
|
||||
.map(|()| Outcome::Applied).map_err(|e| e.to_string()),
|
||||
};
|
||||
Some((reply, result))
|
||||
(Some((reply, result)), refresh_zones)
|
||||
}
|
||||
_ = poll.tick() => None,
|
||||
changed = roster.changed() => {
|
||||
if changed.is_err() { break; }
|
||||
(None, true)
|
||||
}
|
||||
_ = tokio::time::sleep(std::time::Duration::from_secs(2)), if retry => (None, true),
|
||||
};
|
||||
state.send_replace(match report(&agent, Some(&wg), &dns).await {
|
||||
Ok(report) => {
|
||||
let notice = exit_notice(&report);
|
||||
if published_exit.as_ref() != Some(¬ice) {
|
||||
publish_exit(notice.as_ref());
|
||||
published_exit = Some(notice);
|
||||
// A command may itself have changed the roster. Consume notifications
|
||||
// before taking the snapshot so changes during the read stay pending.
|
||||
refresh_zones |= roster.has_changed().unwrap_or(false);
|
||||
if refresh_zones {
|
||||
roster.borrow_and_update();
|
||||
cached_zones = None;
|
||||
}
|
||||
state.send_replace(
|
||||
match snapshot(&agent, Some(&wg), &dns, cached_zones.take()).await {
|
||||
Ok(report) => {
|
||||
retry = false;
|
||||
cached_zones.clone_from(&report.dns);
|
||||
let notice = exit_notice(&report);
|
||||
if published_exit.as_ref() != Some(¬ice) {
|
||||
publish_exit(notice.as_ref());
|
||||
published_exit = Some(notice);
|
||||
}
|
||||
State::Ready(Arc::new(report), Instant::now())
|
||||
}
|
||||
State::Ready(Arc::new(report), Instant::now())
|
||||
}
|
||||
Err(error) => State::Error(error.to_string()),
|
||||
});
|
||||
Err(error) => {
|
||||
retry = true;
|
||||
State::Error(error.to_string())
|
||||
}
|
||||
},
|
||||
);
|
||||
if let Some((reply, outcome)) = reply {
|
||||
let _ = reply.send(outcome);
|
||||
}
|
||||
|
||||
@@ -8,9 +8,79 @@ fn addr(octet: u8) -> Cidr {
|
||||
Cidr::new(IpAddr::V4(Ipv4Addr::new(10, octet, 42, 19)), 24).unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_hidden_service_waits_for_mesh_changes_and_visible_stats_are_on_demand() {
|
||||
use crate::service::{Request, State, serve};
|
||||
use std::time::Duration;
|
||||
use tokio::sync::{mpsc, oneshot, watch};
|
||||
use tsunagi::{
|
||||
discovery::SharedMemoryDiscovery,
|
||||
testing::{TestAgent, network},
|
||||
};
|
||||
use tsunagi_wg_quic::{WireguardConfig, WireguardPlugin};
|
||||
let discovery = SharedMemoryDiscovery::new();
|
||||
let phone = TestAgent::spawn(&discovery).await.unwrap();
|
||||
let wg = WireguardPlugin::open(WireguardConfig::new(phone.dir.path().join("wg")))
|
||||
.await
|
||||
.unwrap();
|
||||
let (state, mut snapshots) = watch::channel(State::Starting);
|
||||
let (stop, stopped) = watch::channel(false);
|
||||
let (commands, requests) = mpsc::channel(4);
|
||||
let agent = phone.agent.clone();
|
||||
let task = tokio::spawn(async move {
|
||||
serve(
|
||||
agent,
|
||||
wg,
|
||||
crate::dns::Resolver::new(|_| None),
|
||||
requests,
|
||||
&state,
|
||||
stopped,
|
||||
|_| {},
|
||||
)
|
||||
.await;
|
||||
});
|
||||
tokio::time::timeout(Duration::from_secs(5), snapshots.changed())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(matches!(*snapshots.borrow_and_update(), State::Ready(..)));
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(2200), snapshots.changed())
|
||||
.await
|
||||
.is_err(),
|
||||
"a hidden, idle service rebuilt the status"
|
||||
);
|
||||
let (tx, rx) = oneshot::channel();
|
||||
commands.send((Request::Refresh, tx)).await.unwrap();
|
||||
rx.await.unwrap().unwrap();
|
||||
assert!(snapshots.has_changed().unwrap());
|
||||
let (name, secret) = network("background-mesh");
|
||||
phone.agent.join_network(&name, &secret).await.unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(5), snapshots.wait_for(|s| {
|
||||
matches!(s, State::Ready(r, _) if r.dns.as_ref().is_some_and(|d| d.zones.iter().any(|z| z == "background-mesh")))
|
||||
})).await.unwrap().unwrap();
|
||||
stop.send_replace(true);
|
||||
task.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn notification_tracks_the_selected_exit_and_a_stale_disconnect_keeps_the_current_route() {
|
||||
use crate::service::{disconnect_exit, exit_notice, report};
|
||||
use crate::service::{ExitNotice, State, disconnect_exit, serve};
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use tsunagi_wg_quic::{WireguardConfig, WireguardPlugin};
|
||||
async fn notice_matching(
|
||||
notices: &mut watch::Receiver<Option<ExitNotice>>,
|
||||
predicate: impl Fn(&Option<ExitNotice>) -> bool,
|
||||
) -> Option<ExitNotice> {
|
||||
tokio::time::timeout(
|
||||
std::time::Duration::from_secs(5),
|
||||
notices.wait_for(predicate),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.clone()
|
||||
}
|
||||
use tsunagi::{
|
||||
discovery::SharedMemoryDiscovery,
|
||||
testing::{TestAgent, network, wait_until},
|
||||
@@ -43,10 +113,32 @@ async fn notification_tracks_the_selected_exit_and_a_stale_disconnect_keeps_the_
|
||||
.then_some(())
|
||||
})
|
||||
.await;
|
||||
let dns = crate::dns::Resolver::new(|_| None);
|
||||
assert!(exit_notice(&report(&phone.agent, None, &dns).await.unwrap()).is_none());
|
||||
let wg = WireguardPlugin::open(WireguardConfig::new(phone.dir.path().join("wg")))
|
||||
.await
|
||||
.unwrap();
|
||||
let agent = phone.agent.clone();
|
||||
let (_commands, requests) = mpsc::channel(4);
|
||||
let (stop, stopped) = watch::channel(false);
|
||||
let (published, mut notices) = watch::channel(None);
|
||||
let task = tokio::spawn(async move {
|
||||
let (state, _) = watch::channel(State::Starting);
|
||||
serve(
|
||||
agent,
|
||||
wg,
|
||||
crate::dns::Resolver::new(|_| None),
|
||||
requests,
|
||||
&state,
|
||||
stopped,
|
||||
|notice| {
|
||||
published.send_replace(notice.cloned());
|
||||
},
|
||||
)
|
||||
.await;
|
||||
});
|
||||
phone.agent.set_exit_via(id, Some(peer)).await.unwrap();
|
||||
let notice = exit_notice(&report(&phone.agent, None, &dns).await.unwrap()).unwrap();
|
||||
let notice = notice_matching(&mut notices, |n| n.as_ref().is_some_and(|n| n.online))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(notice.name, "gateway");
|
||||
assert_eq!(notice.network_name, "travel");
|
||||
assert!(notice.online);
|
||||
@@ -61,21 +153,20 @@ async fn notification_tracks_the_selected_exit_and_a_stale_disconnect_keeps_the_
|
||||
phone.agent.network_status(id).await.unwrap().exit_via,
|
||||
Some(peer)
|
||||
);
|
||||
exit.stop().await;
|
||||
wait_until(
|
||||
"offline exit remains selected in the notification",
|
||||
|| async {
|
||||
let report = report(&phone.agent, None, &dns).await.ok()?;
|
||||
exit_notice(&report).filter(|n| !n.online)
|
||||
},
|
||||
)
|
||||
exit.agent.set_hostname("renamed-gateway").await.unwrap();
|
||||
notice_matching(&mut notices, |n| {
|
||||
n.as_ref().is_some_and(|n| n.name == "renamed-gateway")
|
||||
})
|
||||
.await;
|
||||
exit.stop().await;
|
||||
notice_matching(&mut notices, |n| n.as_ref().is_some_and(|n| !n.online)).await;
|
||||
disconnect_exit(&phone.agent, ¬ice.network, ¬ice.peer)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(exit_notice(&report(&phone.agent, None, &dns).await.unwrap()).is_none());
|
||||
notice_matching(&mut notices, Option::is_none).await;
|
||||
assert!(phone.agent.is_active(id).await);
|
||||
phone.stop().await;
|
||||
stop.send_replace(true);
|
||||
task.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
Reference in new issue
Block a user