diff --git a/Cargo.lock b/Cargo.lock index 29d198c..c1ea7e8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6296,7 +6296,7 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" [[package]] name = "tsunagi" -version = "1.0.3" +version = "1.0.4" dependencies = [ "anstream", "anstyle", @@ -6320,7 +6320,7 @@ dependencies = [ [[package]] name = "tsunagi-android" -version = "1.0.3" +version = "1.0.4" dependencies = [ "bytes", "egui", @@ -6344,7 +6344,7 @@ dependencies = [ [[package]] name = "tsunagi-awg" -version = "1.0.3" +version = "1.0.4" dependencies = [ "bytes", "iroh", @@ -6359,7 +6359,7 @@ dependencies = [ [[package]] name = "tsunagi-core" -version = "1.0.3" +version = "1.0.4" dependencies = [ "arc-swap", "bytes", @@ -6402,7 +6402,7 @@ dependencies = [ [[package]] name = "tsunagi-runtime" -version = "1.0.3" +version = "1.0.4" dependencies = [ "tokio", "tracing", @@ -6415,7 +6415,7 @@ dependencies = [ [[package]] name = "tsunagi-tcp-tls" -version = "1.0.3" +version = "1.0.4" dependencies = [ "bytes", "caps", @@ -6435,7 +6435,7 @@ dependencies = [ [[package]] name = "tsunagi-tray" -version = "1.0.3" +version = "1.0.4" dependencies = [ "eframe", "egui-phosphor", @@ -6451,7 +6451,7 @@ dependencies = [ [[package]] name = "tsunagi-ui" -version = "1.0.3" +version = "1.0.4" dependencies = [ "egui", "egui-phosphor", @@ -6461,7 +6461,7 @@ dependencies = [ [[package]] name = "tsunagi-wg-quic" -version = "1.0.3" +version = "1.0.4" dependencies = [ "boringtun", "bytes", @@ -6488,7 +6488,7 @@ dependencies = [ [[package]] name = "tsunagi-wireguard" -version = "1.0.3" +version = "1.0.4" dependencies = [ "boringtun", "bytes", diff --git a/android/README.md b/android/README.md index 81256a3..160a263 100644 --- a/android/README.md +++ b/android/README.md @@ -16,7 +16,7 @@ cd android adb install -r app/build/outputs/apk/debug/app-debug.apk ``` -Open **tsunagi** to start the agent. On first launch, accept Android’s VPN permission prompt so the agent can create its mesh interface. Join with the existing network name and secret. The service continues when the activity closes. **About → Stop Tsunagi Agent** keeps it stopped across launches. After stopping or declining consent, tap **Start Tsunagi Agent** to enable automatic startup again. The app-private state directory holds the device identity and its saved networks. +Open **tsunagi** to start the agent. On first launch, accept Android’s VPN permission prompt so the agent can create its mesh interface. Join with the existing network name and secret. The service continues when the activity closes. Mesh changes update split DNS and the selected-exit notification in the background. Opening the activity also requests live traffic counters. **About → Stop Tsunagi Agent** keeps it stopped across launches. After stopping or declining consent, tap **Start Tsunagi Agent** to enable automatic startup again. The app-private state directory holds the device identity and its saved networks. The Rust agent owns one interface across the active networks. The Android service establishes the TUN and supplies its descriptor when addresses or exit routes change. Discovery and transport sockets use the selected physical network. TCP health checks bind to the VPN and the address of their own mesh network. The per-network transport selector offers `wg`, `awg`, `wg-quic` and `tcp-tls` in the same default order as the desktop. Each network retains its saved selection and priority. An advertised remote exit can carry the phone’s IPv4 internet traffic. diff --git a/android/app/build.gradle b/android/app/build.gradle index 1907be1..fcfd05e 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -24,7 +24,7 @@ android { targetSdk 35 testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner' versionCode providers.gradleProperty('tsunagiVersionCode').getOrElse('1').toInteger() - versionName providers.gradleProperty('tsunagiVersionName').getOrElse('1.0.3') + versionName providers.gradleProperty('tsunagiVersionName').getOrElse('1.0.4') ndk { abiFilters abi } } } diff --git a/crates/tsunagi-android/Cargo.toml b/crates/tsunagi-android/Cargo.toml index fcff594..cab09bf 100644 --- a/crates/tsunagi-android/Cargo.toml +++ b/crates/tsunagi-android/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "tsunagi-android" -version = "1.0.3" +version = "1.0.4" description = "Android VPN client and egui views for tsunagi." edition.workspace = true rust-version.workspace = true @@ -16,7 +16,7 @@ name = "vpn_source_probe" crate-type = ["cdylib"] [dependencies] -tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.3" } +tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.4" } tsunagi-ui = { path = "../tsunagi-ui" } tsunagi-core = { path = "../tsunagi-core" } tsunagi-wg-quic = { path = "../tsunagi-wg-quic" } diff --git a/crates/tsunagi-android/src/android/mod.rs b/crates/tsunagi-android/src/android/mod.rs index ac61aea..375643b 100644 --- a/crates/tsunagi-android/src/android/mod.rs +++ b/crates/tsunagi-android/src/android/mod.rs @@ -25,6 +25,7 @@ use tsunagi_wg_quic::{DEFAULT_MTU, WireguardConfig, WireguardPlugin}; struct Session { id: i64, + last_refresh: Option, commands: mpsc::Sender<(Request, Reply)>, state: watch::Receiver, underlay: watch::Sender>, @@ -39,10 +40,21 @@ fn current() -> std::sync::MutexGuard<'static, Option> { 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 { 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, diff --git a/crates/tsunagi-android/src/dns.rs b/crates/tsunagi-android/src/dns.rs index 917c173..9500267 100644 --- a/crates/tsunagi-android/src/dns.rs +++ b/crates/tsunagi-android/src/dns.rs @@ -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> { if query.len() > MAX_MESSAGE_LEN { diff --git a/crates/tsunagi-android/src/service.rs b/crates/tsunagi-android/src/service.rs index 1673bbd..249c360 100644 --- a/crates/tsunagi-android/src/service.rs +++ b/crates/tsunagi-android/src/service.rs @@ -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 { + snapshot(agent, wg, dns, None).await +} + +async fn snapshot( + agent: &Agent, + wg: Option<&WireguardPlugin>, + dns: &crate::dns::Resolver, + cached_zones: Option, ) -> tsunagi::Result { 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, 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); } diff --git a/crates/tsunagi-android/src/tests.rs b/crates/tsunagi-android/src/tests.rs index f270d61..f1c211c 100644 --- a/crates/tsunagi-android/src/tests.rs +++ b/crates/tsunagi-android/src/tests.rs @@ -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>, + predicate: impl Fn(&Option) -> bool, + ) -> Option { + 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] diff --git a/crates/tsunagi-awg/Cargo.toml b/crates/tsunagi-awg/Cargo.toml index a82acc1..bf34404 100644 --- a/crates/tsunagi-awg/Cargo.toml +++ b/crates/tsunagi-awg/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "tsunagi-awg" -version = "1.0.3" +version = "1.0.4" description = "Ephemeral pairwise Amnezia transport for Tsunagi." edition.workspace = true rust-version.workspace = true diff --git a/crates/tsunagi-awg/tests/pairs.rs b/crates/tsunagi-awg/tests/pairs.rs index 3669ed7..5c38d8f 100644 --- a/crates/tsunagi-awg/tests/pairs.rs +++ b/crates/tsunagi-awg/tests/pairs.rs @@ -532,6 +532,9 @@ struct FaultLink { sequence: AtomicU64, } impl PacketLink for FaultLink { + fn confirm_delivery(&self) { + self.raw.confirm_delivery(); + } fn network(&self) -> NetworkId { self.raw.network() } diff --git a/crates/tsunagi-core/Cargo.toml b/crates/tsunagi-core/Cargo.toml index ce0f90d..a649c75 100644 --- a/crates/tsunagi-core/Cargo.toml +++ b/crates/tsunagi-core/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "tsunagi-core" -version = "1.0.3" +version = "1.0.4" description = "Small private mesh networks: persistent agent identity, deterministic network spaces, an iroh control plane, signed state and a local DNS view." readme = "../../README.md" keywords = ["mesh", "p2p", "iroh", "networking"] diff --git a/crates/tsunagi-core/src/agent/mod.rs b/crates/tsunagi-core/src/agent/mod.rs index 19c7c6a..de7c9b7 100644 --- a/crates/tsunagi-core/src/agent/mod.rs +++ b/crates/tsunagi-core/src/agent/mod.rs @@ -106,6 +106,7 @@ struct Inner { /// Serialises start, stop, switching and conflict cleanup, including teardown. lifecycle: Arc>, range_changed: watch::Sender<()>, + roster_changed: watch::Sender<()>, range_task: std::sync::Mutex>>, accept_task: std::sync::Mutex>>, plugin_task: std::sync::Mutex>>, @@ -452,6 +453,7 @@ impl Agent { shutdown: Shutdown::new(), lifecycle: Arc::new(Mutex::new(())), range_changed, + roster_changed: watch::channel(()).0, range_task: std::sync::Mutex::new(None), accept_task: std::sync::Mutex::new(None), plugin_task: std::sync::Mutex::new(None), @@ -690,6 +692,7 @@ impl Agent { for sender in senders { let _ = sender.send(NetCommand::SetHostname(hostname.clone())).await; } + self.inner.roster_changed.send_replace(()); Ok(hostname) } @@ -706,6 +709,13 @@ impl Agent { self.inner.events.subscribe() } + /// Subscribe to changes affecting the mesh DNS roster or selected exit. + /// Changes coalesce. Read the current status after subscribing and again on + /// notification. Packet counters and routine control traffic do not wake subscribers. + pub fn watch_roster(&self) -> watch::Receiver<()> { + self.inner.roster_changed.subscribe() + } + /// Makes this agent a member of a network, activating it. /// /// The same `(name, secret)` always produces the same [`NetworkId`], on @@ -1019,6 +1029,7 @@ impl Agent { unreachable_data_peers: Arc::clone(&self.inner.config.unreachable_data_peers), ipv4_range: range, range_changed: self.inner.range_changed.clone(), + roster_changed: self.inner.roster_changed.clone(), }); networks.insert(network_id, handle); drop(networks); @@ -1030,6 +1041,7 @@ impl Agent { tunnel.on_network_activated(network_id); } + self.inner.roster_changed.send_replace(()); let _ = self.inner.events.send(Event::NetworkActivated { network: network_id, }); @@ -1097,6 +1109,7 @@ impl Agent { interface.sync_broadcast_rules().await; interface.sync_exit_rules().await; } + self.inner.roster_changed.send_replace(()); Ok(()) } @@ -1111,6 +1124,7 @@ impl Agent { self.stop_network_locked(network_id).await?; } self.inner.storage.remove_network(network_id).await?; + self.inner.roster_changed.send_replace(()); for plugin in &self.inner.config.carriers { plugin.on_network_forgotten(network_id); } diff --git a/crates/tsunagi-core/src/agent/network.rs b/crates/tsunagi-core/src/agent/network.rs index ed5b6d2..7aadfb6 100644 --- a/crates/tsunagi-core/src/agent/network.rs +++ b/crates/tsunagi-core/src/agent/network.rs @@ -38,8 +38,10 @@ use super::status::{ CandidateStatus, DataPath, HostnameConflict, MemberStatus, NetworkMetrics, NetworkState, NetworkStatus, PeerStatus, }; +use sync::{Changes, SyncKey}; mod selection; +mod sync; /// An inbound connection that already passed the handshake. #[derive(Debug)] @@ -205,6 +207,7 @@ pub(crate) struct RuntimeParams { pub(crate) ipv4_range: Option, /// Coalesced notifications to the agent's lifecycle manager. pub(crate) range_changed: tokio::sync::watch::Sender<()>, + pub(crate) roster_changed: tokio::sync::watch::Sender<()>, /// How data plane links are opened. `None` disables the data plane. pub(crate) transport: Option>, } @@ -429,10 +432,9 @@ struct Runtime { /// Snapshots received while dispatching, handled on the next loop pass. pending_state: Vec<(EndpointId, Vec)>, pending_retirements: Vec<(EndpointId, Vec)>, - pending_vips: Vec>, - vip_cursor: HashMap, - /// Next cleanup batch per live session; prevents queue pressure starving a suffix. - retirement_cursor: HashMap, + pending_vips: Vec<(EndpointId, Vec)>, + changes: Changes, + introductions: Vec, /// The highest version this agent has ever published for this network. own_version: u64, /// Whether the exit node in use was reachable when last looked at, so @@ -521,8 +523,8 @@ impl Runtime { pending_state: Vec::new(), pending_retirements: Vec::new(), pending_vips: Vec::new(), - vip_cursor: HashMap::new(), - retirement_cursor: HashMap::new(), + changes: Changes::default(), + introductions: Vec::new(), own_version: 0, exit_via_was_online: false, announced_exit: false, @@ -545,10 +547,14 @@ impl Runtime { let mut ticker = tokio::time::interval(self.params.discovery_interval); ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + // Long discovery intervals must not let live transit edges expire. + let mut reach_refresh = tokio::time::interval(REACH_EXPIRY / 3); + reach_refresh.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); loop { tokio::select! { biased; _ = self.shutdown.wait() => break, + _ = reach_refresh.tick(), if self.params.discovery_interval > REACH_EXPIRY / 3 => self.announce_reach(false), _ = self.hub.changed() => { self.ensure_links(); self.update_paths(); @@ -787,7 +793,6 @@ impl Runtime { // author, so the new version replaces the old name // rather than sitting beside it. self.ensure_own_claim().await; - self.broadcast_state(); } // Told to peers regardless, so a session that missed the // earlier announcement is not left with a stale name. @@ -894,12 +899,11 @@ impl Runtime { // the check is a comparison when nothing has changed. self.ensure_own_claim().await; self.report_hostname_taken(); - self.broadcast_vips(); - self.broadcast_retirements(); + self.flush_updates(); // The same timer repairs the relay picture: reachability is soft // state, repeated while it holds and forgotten when it stops. self.update_paths(); - self.announce_reach(true); + self.announce_reach(false); let mut candidates: Vec = Vec::new(); @@ -1210,6 +1214,7 @@ impl Runtime { } } + self.index_stored_state(); self.ensure_own_claim().await; self.publish_allocations().await; } @@ -1425,14 +1430,7 @@ impl Runtime { self.candidate_addrs.remove(&peer); self.publish_allocations().await; self.report_hostname_taken(); - let message = ControlMessage::Retirements { - markers: vec![marker], - }; - let peers: Vec<_> = self.sessions.keys().copied().collect(); - let peers_told = peers - .into_iter() - .filter(|peer| self.send_to(*peer, message.clone()).is_ok()) - .count(); + let peers_told = self.share_changes([SyncKey::Retirement(peer)]); Ok(super::ForgetNodeOutcome { target: peer, record_version: expected_version, @@ -1440,40 +1438,8 @@ impl Runtime { }) } - fn broadcast_retirements(&mut self) -> usize { - let markers = self.state.retirements(); - if markers.is_empty() { - return 0; - } - // Each proof has an encoded bound; reserve envelope/list overhead and - // chunk every marker, so a low-id prefix cannot starve later cleanup. - let batch = (self.params.limits.max_frame_len.saturating_sub(128) / MAX_RETIREMENT_LEN) - .max(1) - .min(self.params.limits.max_state_records.max(1)); - let mut delivered = HashSet::new(); - let peers: Vec<_> = self.sessions.keys().copied().collect(); - let chunks: Vec<_> = markers.chunks(batch).collect(); - for peer in peers { - let start = self.retirement_cursor.get(&peer).copied().unwrap_or(0) % chunks.len(); - for offset in 0..chunks.len() { - let index = (start + offset) % chunks.len(); - let message = ControlMessage::Retirements { - markers: chunks[index].to_vec(), - }; - if self.send_to(peer, message).is_err() { - self.retirement_cursor.insert(peer, index); - break; - } - delivered.insert(peer); - self.retirement_cursor - .insert(peer, (index + 1) % chunks.len()); - } - } - delivered.len() - } - async fn receive_retirements(&mut self, peer: EndpointId, markers: Vec) { - let mut changed = false; + let mut changed = Vec::new(); for marker in markers { let mut candidate = self.state.clone(); match candidate.merge_retirement( @@ -1495,11 +1461,7 @@ impl Runtime { } let target = marker.target.author_id().ok(); if let Err(err) = self.params.storage.put_retirement(marker).await { - self.emit(Event::PluginError { - network: self.network_id, - protocol: "state".into(), - reason: format!("cannot persist cleanup proof: {err}"), - }); + self.retry_signed_sync(peer, err); continue; } self.state = candidate; @@ -1511,14 +1473,16 @@ impl Runtime { self.dial_states.remove(&target); self.candidate_addrs.remove(&target); } - changed = true; + if let Some(target) = target { + changed.push(SyncKey::Retirement(target)); + } } - if changed { + if !changed.is_empty() { // A live target answers cleanup with a fresh claim; its identity // is still authenticated, and old hostname priority is not reused. self.ensure_own_claim().await; self.publish_allocations().await; - self.broadcast_retirements(); + self.share_changes(changed); } } @@ -1565,7 +1529,7 @@ impl Runtime { return; } } - self.broadcast_state(); + self.share_changes([SyncKey::Claim(self.local_id)]); } fn update_vips(&self) { @@ -1654,25 +1618,21 @@ impl Runtime { .storage .put_vip_fields( self.network_id, - snapshot.clone(), + snapshot, Some((*self.local_id.as_bytes(), version)), ) .await?; self.own_version = version; self.params.vips = candidate; self.update_vips(); - let peers: Vec<_> = self.sessions.keys().copied().collect(); - for peer in peers { - let _ = self.send_to( - peer, - ControlMessage::Vips { - entries: snapshot.clone(), - }, - ); - } + self.share_changes([SyncKey::Vip(config.id)]); Ok(self.params.routes.vips.statuses(self.network_id)) } - async fn receive_vips(&mut self, entries: Vec) -> Result<()> { + async fn receive_vips( + &mut self, + peer: EndpointId, + entries: Vec, + ) -> Result<()> { let Some(id) = entries.first().map(|e| e.vip.clone()) else { return Ok(()); }; @@ -1694,14 +1654,21 @@ impl Runtime { (own_seen > self.own_version).then_some((*self.local_id.as_bytes(), own_seen)); let snapshot = candidate.entries(&id); self.validate_vip_frame(&snapshot)?; - self.params + if let Err(err) = self + .params .storage .put_vip_fields(self.network_id, snapshot, counter) - .await?; + .await + { + self.retry_signed_sync(peer, err); + return Ok(()); + } self.own_version = self.own_version.max(own_seen); self.params.vips = candidate; self.update_vips(); - self.broadcast_vips(); + if changed { + self.share_changes([SyncKey::Vip(id)]); + } Ok(()) } fn validate_vip_frame(&self, entries: &[crate::vip::VipEntry]) -> Result<()> { @@ -1719,33 +1686,10 @@ impl Runtime { } Ok(()) } - fn broadcast_vips(&mut self) { - let ids = self.params.vips.ids(); - if ids.is_empty() { - return; - } - let peers: Vec<_> = self.sessions.keys().copied().collect(); - for peer in peers { - let start = self.vip_cursor.get(&peer).copied().unwrap_or(0) % ids.len(); - for step in 0..ids.len() { - let index = (start + step) % ids.len(); - let entries = self.params.vips.entries(&ids[index]); - if self - .send_to(peer, ControlMessage::Vips { entries }) - .is_err() - { - self.vip_cursor.insert(peer, index); - break; - } - self.vip_cursor.insert(peer, (index + 1) % ids.len()); - } - } - } - /// Handles snapshots collected while dispatching messages. async fn drain_pending_state(&mut self) { - for entries in std::mem::take(&mut self.pending_vips) { - if let Err(err) = self.receive_vips(entries).await { + for (peer, entries) in std::mem::take(&mut self.pending_vips) { + if let Err(err) = self.receive_vips(peer, entries).await { self.metrics.protocol_violations += 1; tracing::warn!(%err,"rejecting VIP snapshot"); } @@ -1759,29 +1703,33 @@ impl Runtime { self.report_hostname_taken(); } - /// Sends everything we know to every peer. - fn broadcast_state(&mut self) { - self.broadcast_vips(); - self.broadcast_retirements(); - let mut records = self.state.records(); - records.truncate(self.params.limits.max_state_records); - if records.is_empty() { - return; - } - let message = ControlMessage::State { records }; - let peers: Vec = self.sessions.keys().copied().collect(); - for peer in peers { - if let Err(err) = self.send_to(peer, message.clone()) { - tracing::debug!(%err, "could not queue a state snapshot"); - } + /// Reopening the affected reliable stream requests a full replay from + /// this replica. A local write failure must not silently acknowledge it. + fn retry_signed_sync(&self, peer: EndpointId, error: Error) { + self.emit(Event::PluginError { + network: self.network_id, + protocol: "state".into(), + reason: format!("cannot persist a signed update: {error}"), + }); + if let Some(session) = self.sessions.get(&peer) { + session + .conn + .close(1u32.into(), b"retry state synchronization"); } } /// Merges a snapshot from a peer. - async fn receive_state(&mut self, peer: EndpointId, records: Vec) { - let before = self.state.records(); - let (outcomes, errors) = self.state.merge_all(self.network_id, records); - + async fn receive_state(&mut self, peer: EndpointId, mut records: Vec) { + // Older peers can send a full snapshot on someone else's update. + // Exact copies of records already verified and committed are cheap. + records.retain(|r| r.author_id().ok().and_then(|a| self.state.get(&a)) != Some(r)); + if records.is_empty() { + return; + } + let mut authors: std::collections::BTreeSet<_> = + records.iter().filter_map(|r| r.author_id().ok()).collect(); + let mut candidate = self.state.clone(); + let (outcomes, errors) = candidate.merge_all(self.network_id, records); for err in errors { self.metrics.protocol_violations += 1; self.emit(Event::ProtocolViolation { @@ -1790,43 +1738,30 @@ impl Runtime { reason: format!("unusable signed record: {err}"), }); } - for outcome in &outcomes { - if *outcome == Merged::Conflicted { - self.emit(Event::PluginError { - network: self.network_id, - protocol: "overlay".into(), - reason: "two different records from one author at the same version; \ - a device key appears to be in use in two places" - .into(), - }); - } + if outcomes.contains(&Merged::Conflicted) { + self.emit(Event::PluginError { + network: self.network_id, + protocol: "overlay".into(), + reason: "two different records from one author at the same version; a device key appears to be in use in two places".into(), + }); } - - let changed = outcomes.iter().any(|outcome| { - matches!( - outcome, - Merged::Added | Merged::Updated | Merged::Conflicted - ) - }); - if !changed { + authors.retain(|author| self.state.get(author) != candidate.get(author)); + if authors.is_empty() { return; } - - for record in self.state.records() { - if record.author == *self.local_id.as_bytes() { - continue; - } - if let Err(err) = self.params.storage.put_signed_record(record).await { - tracing::debug!(%err, "cannot persist a record"); + for author in &authors { + if *author != self.local_id + && let Some(record) = candidate.get(author) + && let Err(err) = self.params.storage.put_signed_record(record.clone()).await + { + self.retry_signed_sync(peer, err); + return; } } - - // Somebody may have taken the address we were using. + self.state = candidate; + self.share_changes(authors.into_iter().map(SyncKey::Claim)); self.ensure_own_claim().await; self.publish_allocations().await; - if self.state.records() != before { - self.broadcast_state(); - } } fn broadcast_policy(&self) -> crate::overlay::broadcast::BroadcastPolicy { @@ -1863,6 +1798,7 @@ impl Runtime { .routes .update_exit(self.network_id, |exit| exit.via = via); self.exit_via_was_online = via.is_some(); + self.params.roster_changed.send_replace(()); Ok(()) } @@ -1907,6 +1843,7 @@ impl Runtime { return; } self.exit_via_was_online = online; + self.params.roster_changed.send_replace(()); if online { tracing::info!( network = %self.network_id, @@ -1979,6 +1916,7 @@ impl Runtime { } if self.published_range != Some(range) { self.published_range = Some(range); + self.params.roster_changed.send_replace(()); self.params.range_changed.send_replace(()); } @@ -2312,9 +2250,12 @@ impl Runtime { /// /// A device told about one member ends up talking to all of them: a /// network is a mesh, and which member happened to be named on a - /// command line should not decide who anybody talks to. Sent on every - /// round, because it is cheap, bounded and self-repairing. + /// command line should not decide who anybody talks to. A new stream or + /// a changed, bounded address list is enough to update a replica. fn introduce_peers(&mut self) { + if self.sessions.is_empty() || self.params.limits.max_state_records == 0 { + return; + } let mut hints: Vec = Vec::new(); // What this agent can see for itself: where each peer it is @@ -2363,21 +2304,48 @@ impl Runtime { endpoint: *self.local_id.as_bytes(), addrs: hint_addrs(&self.underlay_addr(self.params.adapter.addr())), }); - hints.truncate(self.params.limits.max_state_records); - if hints.is_empty() { - return; + hints.sort_unstable_by_key(|hint| hint.endpoint); + if hints != self.introductions { + let common = hints + .iter() + .zip(&self.introductions) + .take_while(|(a, b)| a == b) + .count(); + self.introductions = hints; + for session in self.sessions.values_mut() { + session.introductions_sent = session.introductions_sent.min(common); + } } - - let message = ControlMessage::Peers { peers: hints }; - let peers: Vec = self.sessions.keys().copied().collect(); - for peer in peers { - if let Err(err) = self.send_to(peer, message.clone()) { - tracing::debug!(%err, "could not queue an introduction"); + use crate::proto::message::{MAX_HINT_ADDR_LEN, MAX_HINT_ADDRS}; + let max_hint_size = 40 + MAX_HINT_ADDRS * (MAX_HINT_ADDR_LEN + 2); + let limits = &self.params.limits; + let batch = (limits.max_frame_len.saturating_sub(128) / max_hint_size) + .max(1) + .min(limits.max_state_records); + let pending: Vec<_> = self + .sessions + .values() + .filter(|s| s.introductions_sent < self.introductions.len()) + .map(|s| (s.peer, s.introductions_sent)) + .collect(); + for (peer, mut start) in pending { + while start < self.introductions.len() { + let end = (start + batch).min(self.introductions.len()); + let message = ControlMessage::Peers { + peers: self.introductions[start..end].to_vec(), + }; + if self.send_to(peer, message).is_err() { + break; + } + start = end; + } + if let Some(session) = self.sessions.get_mut(&peer) { + session.introductions_sent = start; } } } - /// Publishes only locally observed, protocol-specific transport edges. + /// Publish changed edges immediately and refresh soft state before peers expire it. fn announce_reach(&mut self, force: bool) { let live: HashSet<_> = self .links @@ -2390,18 +2358,33 @@ impl Runtime { }, ) .collect(); - if !force && live == self.announced_reach { + if force || live != self.announced_reach { + self.announced_reach = live; + for session in self.sessions.values_mut() { + session.reach_sent = None; + } + } + let pending: Vec<_> = self + .sessions + .values() + .filter(|s| { + s.reach_sent + .is_none_or(|last| last.elapsed() >= REACH_EXPIRY / 3) + }) + .map(|s| s.peer) + .collect(); + if pending.is_empty() { return; } - self.announced_reach = live.clone(); - let mut links: Vec<_> = live.into_iter().collect(); + let mut links: Vec<_> = self.announced_reach.iter().cloned().collect(); links.sort_by(|a, b| (&a.protocol, a.peer).cmp(&(&b.protocol, b.peer))); links.truncate(self.params.limits.max_state_records); let message = ControlMessage::Reachable { links }; - let peers: Vec<_> = self.sessions.keys().copied().collect(); - for peer in peers { - if let Err(err) = self.send_to(peer, message.clone()) { - tracing::debug!(%err, "could not queue a reachability announcement"); + for peer in pending { + if self.send_to(peer, message.clone()).is_ok() + && let Some(s) = self.sessions.get_mut(&peer) + { + s.reach_sent = Some(Instant::now()); } } } @@ -2626,8 +2609,6 @@ impl Runtime { /// Drops every link to a peer. fn drop_links_for(&mut self, peer: EndpointId) { self.tunnel_errors.remove(&peer); - self.retirement_cursor.remove(&peer); - self.vip_cursor.remove(&peer); self.reset_peer_data(peer, "peer session ended"); if let Some(tunnel) = &self.params.tunnel { tunnel.on_peer_gone(self.network_id, peer); @@ -2747,8 +2728,11 @@ impl Runtime { tracing::debug!(%err, "could not queue initial announcement"); } - self.broadcast_state(); + self.flush_peer(peer); + self.introduce_peers(); + self.announce_reach(false); + self.params.roster_changed.send_replace(()); self.emit(Event::PeerConnected { network: self.network_id, peer, @@ -2898,6 +2882,7 @@ impl Runtime { .or_insert_with(|| DialState::new(CandidateSource::Discovery)); state.in_flight = false; state.next_attempt = Instant::now() + policy.initial_delay; + self.params.roster_changed.send_replace(()); self.emit(Event::PeerDisconnected { network: self.network_id, peer, @@ -2921,6 +2906,7 @@ impl Runtime { return; } self.known_hostnames.insert(peer, hostname.to_string()); + self.params.roster_changed.send_replace(()); let storage = self.params.storage.clone(); let network_id = self.network_id; let hostname = hostname.to_string(); @@ -3024,7 +3010,7 @@ impl Runtime { tracing::debug!(%err, "could not queue pong"); } } - ControlMessage::Vips { entries } => self.pending_vips.push(entries.clone()), + ControlMessage::Vips { entries } => self.pending_vips.push((peer, entries.clone())), ControlMessage::State { records } => { self.pending_state.push((peer, records.clone())); } @@ -3038,6 +3024,7 @@ impl Runtime { let learned = self.learn_peers(peers); if learned > 0 { self.start_dials(); + self.introduce_peers(); } } // What that peer can reach, from that peer. Kept with the time diff --git a/crates/tsunagi-core/src/agent/network/sync.rs b/crates/tsunagi-core/src/agent/network/sync.rs new file mode 100644 index 0000000..9d6d9e9 --- /dev/null +++ b/crates/tsunagi-core/src/agent/network/sync.rs @@ -0,0 +1,152 @@ +//! Each ordered stream keeps a cursor into the latest signed state. A slow or +//! reconnecting peer can catch up without a per-peer backlog of signed frames. +use super::{ControlMessage, EndpointId, MAX_RETIREMENT_LEN, Runtime}; +use std::collections::BTreeMap; +use std::ops::Bound::{Excluded, Unbounded}; + +/// The stable identity of a signed object, including tombstones. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub(super) enum SyncKey { + Claim(EndpointId), + Retirement(EndpointId), + Vip(String), +} + +/// One entry per stored object, regardless of its edit count or the number of +/// peers. Revisions are local scheduling information, never persisted or sent. +#[derive(Default)] +pub(super) struct Changes { + latest: u64, + revisions: BTreeMap, + order: BTreeMap, +} + +impl Changes { + fn note(&mut self, key: SyncKey) { + self.latest += 1; + if let Some(previous) = self.revisions.insert(key.clone(), self.latest) { + self.order.remove(&previous); + } + self.order.insert(self.latest, key); + } + + fn after(&self, cursor: u64) -> impl Iterator { + self.order + .range((Excluded(cursor), Unbounded)) + .map(|(&revision, key)| (revision, key)) + } +} + +impl Runtime { + pub(super) fn index_stored_state(&mut self) { + for record in self.state.records() { + if let Ok(author) = record.author_id() { + self.changes.note(SyncKey::Claim(author)); + } + } + for marker in self.state.retirements() { + if let Ok(target) = marker.target.author_id() { + self.changes.note(SyncKey::Retirement(target)); + } + } + for id in self.params.vips.ids() { + self.changes.note(SyncKey::Vip(id)); + } + } + + pub(super) fn share_changes(&mut self, keys: impl IntoIterator) -> usize { + for key in keys { + self.changes.note(key); + } + self.params.roster_changed.send_replace(()); + self.flush_updates(); + self.sessions + .values() + .filter(|session| session.state_sent == self.changes.latest) + .count() + } + + pub(super) fn flush_updates(&mut self) { + let peers: Vec<_> = self + .sessions + .values() + .filter(|s| s.state_sent < self.changes.latest) + .map(|s| s.peer) + .collect(); + for peer in peers { + self.flush_peer(peer); + } + } + + pub(super) fn flush_peer(&mut self, peer: EndpointId) { + // A retirement contains a signed claim plus a second signature, so its + // size bound also covers a claim. VIPs are validated as complete frames. + let limits = &self.params.limits; + let batch = (limits.max_frame_len.saturating_sub(128) / MAX_RETIREMENT_LEN) + .max(1) + .min(limits.max_state_records.max(1)); + while let Some(session) = self.sessions.get(&peer) { + if session.outbound.capacity() == 0 { + break; + } + let cursor = session.state_sent; + let Some((mut through, first)) = self.changes.after(cursor).next() else { + break; + }; + let message = { + let pending = self.changes.after(cursor).take(batch); + match first { + SyncKey::Claim(_) => ControlMessage::State { + records: pending + .map_while(|(revision, key)| { + let SyncKey::Claim(id) = key else { return None }; + through = revision; + self.state.get(id).cloned() + }) + .collect(), + }, + SyncKey::Retirement(_) => ControlMessage::Retirements { + markers: pending + .map_while(|(revision, key)| { + let SyncKey::Retirement(id) = key else { + return None; + }; + through = revision; + self.state.retirement_of(id).cloned() + }) + .collect(), + }, + SyncKey::Vip(id) => ControlMessage::Vips { + entries: self.params.vips.entries(id), + }, + } + }; + if self.send_to(peer, message).is_err() { + break; + } + if let Some(session) = self.sessions.get_mut(&peer) { + session.state_sent = through; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn slow_and_returning_sessions_each_get_the_latest_revision() { + let mut index = Changes::default(); + let first = SyncKey::Vip("first".into()); + let second = SyncKey::Vip("second".into()); + index.note(first.clone()); + let sent = index.latest; + index.note(second.clone()); + index.note(first.clone()); + for cursor in [0, sent] { + let pending: Vec<_> = index.after(cursor).map(|(_, key)| key.clone()).collect(); + assert_eq!(pending, [second.clone(), first.clone()]); + } + assert_eq!(index.after(index.latest).count(), 0); + } +} diff --git a/crates/tsunagi-core/src/agent/session.rs b/crates/tsunagi-core/src/agent/session.rs index 3010770..c178e48 100644 --- a/crates/tsunagi-core/src/agent/session.rs +++ b/crates/tsunagi-core/src/agent/session.rs @@ -68,8 +68,12 @@ pub(crate) struct Session { pub(crate) role: Role, pub(crate) established: Instant, pub(crate) conn: Connection, - /// Already encoded frame payloads, so the runtime can account for the exact - /// number of control bytes it queues. + /// Last signed-state revision queued on this ordered stream. + pub(super) state_sent: u64, + /// Prefix of the current introduction list already queued on this stream. + pub(super) introductions_sent: usize, + pub(super) reach_sent: Option, + /// Already encoded frames, accounted for when queued. pub(crate) outbound: mpsc::Sender>>, pub(crate) hostname: Option, pub(crate) agent_version: Option, @@ -228,6 +232,9 @@ pub(crate) fn spawn( established: Instant::now(), conn, outbound: outbound_tx, + state_sent: 0, + introductions_sent: 0, + reach_sent: None, hostname: None, agent_version: None, capabilities: Vec::new(), diff --git a/crates/tsunagi-core/src/dataplane/transport/health.rs b/crates/tsunagi-core/src/dataplane/transport/health.rs index d278d7f..93de5c0 100644 --- a/crates/tsunagi-core/src/dataplane/transport/health.rs +++ b/crates/tsunagi-core/src/dataplane/transport/health.rs @@ -31,7 +31,7 @@ impl std::fmt::Debug for Settings { } } struct Samples { - pending: VecDeque<(u64, Instant)>, + pending: VecDeque<(u64, Instant, usize)>, recent: VecDeque>, last_reply: Option, } @@ -45,8 +45,8 @@ impl Samples { last_reply: None, } } - fn sent(&mut self, seq: u64, now: Instant) { - self.pending.push_back((seq, now)); + fn sent(&mut self, seq: u64, now: Instant, size: usize) { + self.pending.push_back((seq, now, size)); } fn record(&mut self, rtt: Option) { if self.recent.len() == WINDOW { @@ -54,9 +54,12 @@ impl Samples { } self.recent.push_back(rtt); } - fn acknowledge(&mut self, seq: u64, now: Instant) { - if let Some(i) = self.pending.iter().position(|(n, _)| *n == seq) - && let Some((_, sent)) = self.pending.remove(i) + fn acknowledge(&mut self, seq: u64, now: Instant, size: usize) -> bool { + if let Some(i) = self + .pending + .iter() + .position(|(n, _, expected)| *n == seq && *expected == size) + && let Some((_, sent, _)) = self.pending.remove(i) { let rtt = now.saturating_duration_since(sent); let success = rtt < PROBE_TIMEOUT; @@ -64,13 +67,15 @@ impl Samples { if success { self.last_reply = Some(now); } + return success; } + false } fn expire(&mut self, now: Instant) { while self .pending .front() - .is_some_and(|(_, at)| now.duration_since(*at) >= PROBE_TIMEOUT) + .is_some_and(|(_, at, _)| now.duration_since(*at) >= PROBE_TIMEOUT) { self.pending.pop_front(); self.record(None); @@ -160,7 +165,7 @@ impl HealthLink { sequence=sequence.wrapping_add(1); let size=raw.max_datagram_size(); let packet=probe(&settings,local,1,sequence,size.min(1000)); - samples.sent(sequence,now); + samples.sent(sequence,now,packet.len()); let _=raw.send(packet); } packet=raw.recv()=>{ @@ -170,7 +175,9 @@ impl HealthLink { if let Some((kind,seq))=verify(&settings,raw.peer(),&packet) { if kind==1 {let _=raw.send(probe(&settings,local,2,seq,packet.len()));} else if kind==2 && marker == Some(settings.marker) { - samples.acknowledge(seq, Instant::now()); + if samples.acknowledge(seq, Instant::now(), packet.len()) { + raw.confirm_delivery(); + } *lock(&link.quality) = samples.quality().map(|q| (settings.marker, q)); } } @@ -305,19 +312,29 @@ impl Drop for HealthLink { mod tests { #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use super::*; + #[test] + fn an_authenticated_short_reply_does_not_prove_full_size_delivery() { + let start = Instant::now(); + let mut samples = Samples::new(); + samples.sent(7, start, 1000); + assert!(!samples.acknowledge(7, start, 57)); + assert!(samples.quality().is_none()); + assert!(samples.acknowledge(7, start, 1000)); + } + #[test] fn quality_uses_matched_fresh_replies_and_keeps_losses_in_the_window() { let mut samples = Samples::new(); let start = Instant::now(); assert!(samples.quality().is_none()); for (seq, delay) in [(1, 10), (2, 30), (3, 250)] { - samples.sent(seq, start); - samples.acknowledge(seq, start + Duration::from_millis(delay)); + samples.sent(seq, start, 1000); + samples.acknowledge(seq, start + Duration::from_millis(delay), 1000); } - samples.acknowledge(1, start + Duration::from_secs(1)); - samples.sent(4, start); + assert!(!samples.acknowledge(1, start + Duration::from_secs(1), 1000)); + samples.sent(4, start, 1000); samples.expire(start + Duration::from_secs(3)); - samples.acknowledge(4, start + Duration::from_secs(4)); + assert!(!samples.acknowledge(4, start + Duration::from_secs(4), 1000)); let measured = samples.quality().unwrap(); assert_eq!(measured.rtt, Duration::from_millis(30)); assert_eq!((measured.samples, measured.losses), (3, 1)); @@ -326,8 +343,8 @@ mod tests { for seq in 5..25 { let sent = start + Duration::from_secs(seq); - samples.sent(seq, sent); - samples.acknowledge(seq, sent + Duration::from_millis(80)); + samples.sent(seq, sent, 1000); + samples.acknowledge(seq, sent + Duration::from_millis(80), 1000); } let recovered = samples.quality().unwrap(); assert_eq!(recovered.rtt, Duration::from_millis(80)); @@ -339,17 +356,17 @@ mod tests { let mut samples = Samples::new(); let now = Instant::now(); for seq in 0..20 { - samples.sent(seq, now); + samples.sent(seq, now, 1000); if seq % 5 == 0 { - samples.acknowledge(seq, now); + samples.acknowledge(seq, now, 1000); } } assert!(!samples.degraded()); samples.expire(now + Duration::from_secs(4)); assert!(samples.degraded()); for seq in 20..40 { - samples.sent(seq, now); - samples.acknowledge(seq, now); + samples.sent(seq, now, 1000); + samples.acknowledge(seq, now, 1000); } samples.expire(now + Duration::from_secs(4)); assert!(!samples.degraded()); diff --git a/crates/tsunagi-core/src/dataplane/transport/mod.rs b/crates/tsunagi-core/src/dataplane/transport/mod.rs index db4bd6b..bf76fef 100644 --- a/crates/tsunagi-core/src/dataplane/transport/mod.rs +++ b/crates/tsunagi-core/src/dataplane/transport/mod.rs @@ -150,6 +150,10 @@ pub trait PacketLink: Send + Sync + std::fmt::Debug + 'static { None } + /// The link monitor received a timely, authenticated answer to a data probe + /// on this very link. A carrier can use it in place of its own idle probe. + fn confirm_delivery(&self) {} + /// A short description of the path in use, for diagnostics. /// /// Reports what the transport actually knows. It must not invent a value. diff --git a/crates/tsunagi-core/tests/discovery.rs b/crates/tsunagi-core/tests/discovery.rs index 07b7864..51296e7 100644 --- a/crates/tsunagi-core/tests/discovery.rs +++ b/crates/tsunagi-core/tests/discovery.rs @@ -148,13 +148,21 @@ async fn being_told_about_one_member_is_enough_to_meet_them_all() { // Three that already know each other, and nothing that resolves by // network: no shared discovery here, only what members pass on. + // A single introduction fits each frame, including when three members + // already know the same bootstrap. No peer may get stuck behind the first. + let small_frames = |dir: &std::path::Path| { + let mut config = local_config(dir); + config.limits.max_state_records = 1; + config.limits.session_send_queue = 2; + config + }; let first_dir = tempfile::TempDir::new().unwrap(); - let first = Agent::spawn(local_config(first_dir.path())).await.unwrap(); + let first = Agent::spawn(small_frames(first_dir.path())).await.unwrap(); let network_id = first.join_network(&name, &secret).await.unwrap(); let second_dir = tempfile::TempDir::new().unwrap(); let second = Agent::spawn( - local_config(second_dir.path()) + small_frames(second_dir.path()) .with_discovery(Arc::new(StaticBootstrap::new([first.local_addr()]))), ) .await @@ -164,7 +172,7 @@ async fn being_told_about_one_member_is_enough_to_meet_them_all() { let third_dir = tempfile::TempDir::new().unwrap(); let third = Agent::spawn( - local_config(third_dir.path()) + small_frames(third_dir.path()) .with_discovery(Arc::new(StaticBootstrap::new([first.local_addr()]))), ) .await diff --git a/crates/tsunagi-core/tests/vip.rs b/crates/tsunagi-core/tests/vip.rs index 70ef918..c28f989 100644 --- a/crates/tsunagi-core/tests/vip.rs +++ b/crates/tsunagi-core/tests/vip.rs @@ -16,6 +16,97 @@ async fn view(agent: &Agent, network: NetworkId, id: &str) -> VipStatus { }) .await } + +#[tokio::test] +async fn a_local_storage_failure_is_repaired_from_the_peer_after_reconnect() { + use tsunagi::{StoragePaths, agent::Event, testing::wait_event}; + let discovery = SharedMemoryDiscovery::new(); + let a = TestAgent::spawn(&discovery).await.unwrap(); + let b = TestAgent::spawn(&discovery).await.unwrap(); + let (name, secret) = network("retry-signed-update"); + let id = a.agent.join_network(&name, &secret).await.unwrap(); + b.agent.join_network(&name, &secret).await.unwrap(); + wait_for_peers(&a.agent, id, 1).await; + let path = StoragePaths::under(b.dir.path()).state_db(); + let trigger = |sql: &'static str| { + let path = path.clone(); + tokio::task::spawn_blocking(move || { + rusqlite::Connection::open(path) + .unwrap() + .execute_batch(sql) + .unwrap() + }) + }; + trigger("CREATE TRIGGER reject_vip BEFORE INSERT ON vip_fields BEGIN SELECT RAISE(ABORT, 'test write failure'); END;").await.unwrap(); + let mut events = b.agent.subscribe(); + let vip = VipConfig::new("recover"); + a.agent + .save_vip(id, vip.clone(), None, false) + .await + .unwrap(); + wait_event(&mut events, |e| matches!(e, Event::PluginError { protocol, reason, .. } if protocol == "state" && reason.contains("test write failure")).then_some(())).await; + trigger("DROP TRIGGER reject_vip").await.unwrap(); + assert_eq!(view(&b.agent, id, &vip.id).await.config, vip); + a.stop().await; + b.stop().await; +} + +#[tokio::test] +async fn idle_maintenance_does_not_republish_acknowledged_mesh_state() { + use tsunagi::{agent::Event, proto::ControlMessage}; + let discovery = SharedMemoryDiscovery::new(); + let a = TestAgent::spawn(&discovery).await.unwrap(); + let b = TestAgent::spawn(&discovery).await.unwrap(); + let (name, secret) = network("quiet-mesh"); + let id = a.agent.join_network(&name, &secret).await.unwrap(); + b.agent.join_network(&name, &secret).await.unwrap(); + wait_for_peers(&a.agent, id, 1).await; + let vip = VipConfig::new("web"); + a.agent + .save_vip(id, vip.clone(), None, false) + .await + .unwrap(); + view(&b.agent, id, &vip.id).await; + let mut events = b.agent.subscribe(); + // Mark the end of each round on the same ordered control stream. + let last_hints = std::cell::RefCell::new(None); + for round in 0..4 { + a.agent.recheck_network(id).await.unwrap(); + a.agent + .send( + id, + b.agent.endpoint_id(), + ControlMessage::Ping { + seq: round, + payload: vec![], + }, + ) + .await + .unwrap(); + tsunagi::testing::wait_event(&mut events, |event| { + if let Event::MessageReceived { message, .. } = event { + match message { + ControlMessage::Ping { seq, .. } if *seq == round => return Some(()), + ControlMessage::Vips { .. } | ControlMessage::Reachable { .. } if round > 0 => { + panic!("republished unchanged state on maintenance round {round}") + } + ControlMessage::Peers { peers } => { + assert_ne!( + last_hints.replace(Some(peers.clone())).as_ref(), + Some(peers), + "unchanged introductions" + ); + } + _ => {} + } + } + None + }) + .await; + } + a.stop().await; + b.stop().await; +} #[tokio::test] async fn any_member_can_edit_services_and_an_offline_creator_is_not_required() { let discovery = SharedMemoryDiscovery::new(); diff --git a/crates/tsunagi-runtime/Cargo.toml b/crates/tsunagi-runtime/Cargo.toml index 9216b1b..e8e8cc8 100644 --- a/crates/tsunagi-runtime/Cargo.toml +++ b/crates/tsunagi-runtime/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "tsunagi-runtime" -version = "1.0.3" +version = "1.0.4" description = "Built-in mesh transports and status reporting for native tsunagi agents." edition.workspace = true rust-version.workspace = true @@ -8,11 +8,11 @@ license.workspace = true repository.workspace = true [dependencies] -tsunagi-core = { path = "../tsunagi-core", version = "1.0.3" } -tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.3" } -tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.3" } -tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.3" } -tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.3" } +tsunagi-core = { path = "../tsunagi-core", version = "1.0.4" } +tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.4" } +tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.4" } +tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.4" } +tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.4" } tokio.workspace = true tracing.workspace = true diff --git a/crates/tsunagi-tcp-tls/Cargo.toml b/crates/tsunagi-tcp-tls/Cargo.toml index 6f5c3f3..8fc7717 100644 --- a/crates/tsunagi-tcp-tls/Cargo.toml +++ b/crates/tsunagi-tcp-tls/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "tsunagi-tcp-tls" -version = "1.0.3" +version = "1.0.4" description = "TCP TLS carrier for independently encrypted tsunagi mesh traffic." edition.workspace = true rust-version.workspace = true @@ -8,7 +8,7 @@ license.workspace = true repository.workspace = true [dependencies] -tsunagi-core = { path = "../tsunagi-core", version = "1.0.3" } +tsunagi-core = { path = "../tsunagi-core", version = "1.0.4" } iroh.workspace = true tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] } rustls = "0.23" diff --git a/crates/tsunagi-tray/Cargo.toml b/crates/tsunagi-tray/Cargo.toml index b1a4c3c..1c70082 100644 --- a/crates/tsunagi-tray/Cargo.toml +++ b/crates/tsunagi-tray/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "tsunagi-tray" -version = "1.0.3" +version = "1.0.4" description = "Tray application to manage a running tsunagi agent." edition.workspace = true rust-version.workspace = true @@ -16,7 +16,7 @@ tsunagi-ui = { path = "../tsunagi-ui" } # The agent control client and the report types: the GUI is a thin client over # the same local control interface the CLI uses, so it reuses these directly # and never re-implements the protocol. -tsunagi-core = { path = "../tsunagi-core", version = "1.0.3" } +tsunagi-core = { path = "../tsunagi-core", version = "1.0.4" } # Native, lightweight GUI — no web engine. eframe re-exports egui. eframe = { version = "0.31", default-features = false, features = ["default_fonts", "glow", "wayland", "x11"] } # Cross-platform tray icon + menu (Windows tray, macOS menu bar, Linux SNI). diff --git a/crates/tsunagi-ui/Cargo.toml b/crates/tsunagi-ui/Cargo.toml index 369ac30..900a112 100644 --- a/crates/tsunagi-ui/Cargo.toml +++ b/crates/tsunagi-ui/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "tsunagi-ui" -version = "1.0.3" +version = "1.0.4" description = "Shared egui widgets for the tray and Android clients." edition.workspace = true rust-version.workspace = true diff --git a/crates/tsunagi-wg-quic/Cargo.toml b/crates/tsunagi-wg-quic/Cargo.toml index cb5cbd3..700d8cb 100644 --- a/crates/tsunagi-wg-quic/Cargo.toml +++ b/crates/tsunagi-wg-quic/Cargo.toml @@ -3,7 +3,7 @@ name = "tsunagi-wg-quic" # Its own version, and deliberately separate from the wire version it # negotiates: a release here does not stop it talking to a peer on an older # build, because what peers compare is `ANNOUNCEMENT_VERSION`. -version = "1.0.3" +version = "1.0.4" description = "The single internal WireGuard tunnel for tsunagi, independent of external carriers." edition.workspace = true rust-version.workspace = true @@ -11,7 +11,7 @@ license.workspace = true repository.workspace = true [dependencies] -tsunagi-core = { path = "../tsunagi-core", version = "1.0.3" } +tsunagi-core = { path = "../tsunagi-core", version = "1.0.4" } iroh.workspace = true tokio.workspace = true serde.workspace = true diff --git a/crates/tsunagi-wireguard/Cargo.toml b/crates/tsunagi-wireguard/Cargo.toml index 0dbbb86..67b9d9a 100644 --- a/crates/tsunagi-wireguard/Cargo.toml +++ b/crates/tsunagi-wireguard/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "tsunagi-wireguard" -version = "1.0.3" +version = "1.0.4" description = "Independent authenticated WireGuard and Amnezia UDP carriers for tsunagi." edition.workspace = true rust-version.workspace = true @@ -8,7 +8,7 @@ license = "WTFPL AND Apache-2.0" repository.workspace = true [dependencies] -tsunagi-core = { path = "../tsunagi-core", version = "1.0.3" } +tsunagi-core = { path = "../tsunagi-core", version = "1.0.4" } iroh.workspace = true tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] } serde.workspace = true diff --git a/crates/tsunagi-wireguard/src/session.rs b/crates/tsunagi-wireguard/src/session.rs index 9898083..5593e79 100644 --- a/crates/tsunagi-wireguard/src/session.rs +++ b/crates/tsunagi-wireguard/src/session.rs @@ -18,6 +18,27 @@ pub(crate) const MAX_PAYLOAD: usize = tsunagi::config::MAX_DATA_DATAGRAM; const CHUNK: usize = 700; const QUEUE: usize = 64; const WINDOW: Duration = Duration::from_secs(20); +const PROBE_TIMEOUT: Duration = Duration::from_secs(3); + +#[derive(Default)] +struct DeliveryChecks { + replies: AtomicU64, + last_shared: Mutex>, +} + +impl DeliveryChecks { + fn confirm_shared(&self, now: Instant) { + *self.last_shared.lock().unwrap_or_else(|e| e.into_inner()) = Some(now); + self.replies.fetch_add(1, Ordering::Relaxed); + } + + fn needs_probe(&self, now: Instant) -> bool { + self.last_shared + .lock() + .unwrap_or_else(|e| e.into_inner()) + .is_none_or(|last| now.saturating_duration_since(last) >= PROBE_TIMEOUT) + } +} pub(crate) struct PairLink { network: NetworkId, @@ -30,7 +51,7 @@ pub(crate) struct PairLink { closed: AtomicBool, remote: Mutex>, reason: Mutex>, - checks: Arc, + checks: Arc, } impl std::fmt::Debug for PairLink { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { @@ -42,7 +63,7 @@ impl std::fmt::Debug for PairLink { } impl PairLink { pub(crate) fn delivery_checks(&self) -> u64 { - self.checks.load(Ordering::Relaxed) + self.checks.replies.load(Ordering::Relaxed) } pub(crate) fn has_authenticated_path(&self) -> bool { match self.remote.lock() { @@ -99,6 +120,9 @@ impl PacketLink for PairLink { fn close(&self) { self.stop.send_replace(true); } + fn confirm_delivery(&self) { + self.checks.confirm_shared(Instant::now()); + } fn failure_reason(&self) -> Option { match self.reason.lock() { Ok(reason) => reason.clone(), @@ -145,7 +169,7 @@ pub(crate) fn start( closed: AtomicBool::new(false), remote: Mutex::new(None), reason: Mutex::new(None), - checks: Arc::new(AtomicU64::new(0)), + checks: Arc::default(), }); let weak = Arc::downgrade(&link); let checks = link.checks.clone(); @@ -198,7 +222,7 @@ struct Engine { assemblies: HashMap, started: Instant, last_authenticated: Instant, - checks: Arc, + checks: Arc, } enum ResultOwned { Wire(Vec), @@ -249,12 +273,23 @@ impl Engine { _=timer.tick()=>{ let result=own(self.tunn.update_timers(&mut scratch));self.process(result,None).await; if last_probe.elapsed()>=Duration::from_secs(1) { - last_probe=Instant::now();self.sequence=self.sequence.wrapping_add(1); - self.pending.push_back((self.sequence,Instant::now())); - let mut probe=vec![1];probe.extend_from_slice(&self.sequence.to_be_bytes()); - probe.resize(713,0);rand::fill(&mut probe[9..]);self.encrypt(&probe).await; + last_probe = Instant::now(); + if self.checks.needs_probe(last_probe) { + self.sequence = self.sequence.wrapping_add(1); + self.pending.push_back((self.sequence, last_probe)); + let mut probe = vec![1]; + probe.extend_from_slice(&self.sequence.to_be_bytes()); + probe.resize(713, 0); + rand::fill(&mut probe[9..]); + self.encrypt(&probe).await; + } else { + // A full-sized round trip passed through fragmentation and + // reassembly. The outer monitor owns loss accounting now. + self.samples.clear(); + self.pending.clear(); + } } - while self.pending.front().is_some_and(|(_,at)|at.elapsed()>=Duration::from_secs(3)) { + while self.pending.front().is_some_and(|(_,at)|at.elapsed()>=PROBE_TIMEOUT) { self.pending.pop_front();self.samples.push_back(false); } while self.samples.len()>20 {self.samples.pop_front();} @@ -363,7 +398,7 @@ impl Engine { { self.pending.remove(index); self.samples.push_back(true); - self.checks.fetch_add(1, Ordering::Relaxed); + self.checks.replies.fetch_add(1, Ordering::Relaxed); } } Some(3) => self.fragment(seq, payload), @@ -412,3 +447,22 @@ impl Engine { } } } + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + use super::*; + + #[test] + fn shared_delivery_replaces_native_probes_only_while_round_trips_succeed() { + let checks = DeliveryChecks::default(); + let start = Instant::now(); + assert!(checks.needs_probe(start)); + checks.confirm_shared(start); + assert!(!checks.needs_probe(start + Duration::from_secs(2))); + assert!(checks.needs_probe(start + Duration::from_secs(3))); + checks.confirm_shared(start + Duration::from_secs(4)); + assert!(!checks.needs_probe(start + Duration::from_secs(5))); + assert_eq!(checks.replies.load(Ordering::Relaxed), 2); + } +} diff --git a/crates/tsunagi/Cargo.toml b/crates/tsunagi/Cargo.toml index 44ed74d..2cf1981 100644 --- a/crates/tsunagi/Cargo.toml +++ b/crates/tsunagi/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "tsunagi" -version = "1.0.3" +version = "1.0.4" description = "The tsunagi command line agent." edition.workspace = true rust-version.workspace = true @@ -12,11 +12,11 @@ name = "tsng" path = "src/main.rs" [dependencies] -tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.3" } -tsunagi-core = { path = "../tsunagi-core", version = "1.0.3", features = ["tun-device", "dns-publish"] } -tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.3" } -tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.3" } -tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.3" } +tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.4" } +tsunagi-core = { path = "../tsunagi-core", version = "1.0.4", features = ["tun-device", "dns-publish"] } +tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.4" } +tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.4" } +tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.4" } iroh.workspace = true tokio = { version = "1.53", features = ["rt", "rt-multi-thread", "sync", "time", "macros", "signal"] } tracing.workspace = true diff --git a/docs/amnezia.md b/docs/amnezia.md index 3c221dc..4ce8df9 100644 --- a/docs/amnezia.md +++ b/docs/amnezia.md @@ -110,7 +110,11 @@ fresh private marker/key to the sender's endpoint id. Unanswered requests expire after three seconds. After a 20-second warmup, at least 15 completed observations and at least 60% loss in the last 20 observations retire a carrier. Probes are consumed at the carrier boundary and never enter the TUN or user IP counters. -AWG additionally checks encrypted outer delivery throughout the pair lifetime. +Both WG and AWG start with native encrypted probes. A timely authenticated +round trip on the full-sized carrier check also proves outer delivery, so it +replaces the native probe. Native probes resume after three seconds without +such a confirmation. Each peer still answers both types of probe independently, +including requests from 1.0.3 peers. Setup failure or persistent runtime loss advances to the next mutually supported carrier in the initiator's order. Earlier expired cooldowns do not jump ahead of diff --git a/docs/protocol.md b/docs/protocol.md index 53fabd5..1c5a48e 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -225,8 +225,8 @@ ignores it. Each row belongs to the authenticated sender and is replaced atomically, expires after 90 seconds, and is withdrawn on session closure. Only authenticated members enter the graph; local edges always come from actual links. -Announcements refresh on the existing control maintenance interval and are -sent immediately on link changes. Topology stays volatile, outside signed state. +Each new session receives the current edges. Link changes trigger an immediate +update, and unchanged edges are due for refresh after 30 seconds. Topology stays volatile, outside signed state. Version 5 also adds `hostname_since` to a signed hostname claim (signing domain `tsunagi-signed-record-v3`): a name belongs to whoever claimed it first. Stored diff --git a/docs/routing.md b/docs/routing.md index 205ea85..0112dd2 100644 --- a/docs/routing.md +++ b/docs/routing.md @@ -24,8 +24,8 @@ the selected link fails or its MTU is too small. The configured order selects the initial link. Peers with automatic carrier selection can then prefer a faster measured link for that neighbour. Every authenticated member enters the graph; a member in the middle needs no protocol in common -with either end, only a link to each. A snapshot refreshes on the maintenance -interval, expires after 90 seconds, and is withdrawn when the session ends. +with either end, only a link to each. A snapshot is due for refresh after 30 +seconds, expires after 90 seconds, and is withdrawn when the session ends. Link arrival, closure and changed announcements rebuild routes immediately. Unchanged announcements refresh their age without republishing the forwarding snapshot. diff --git a/docs/sync-model.md b/docs/sync-model.md index 18e3e27..e5c2708 100644 --- a/docs/sync-model.md +++ b/docs/sync-model.md @@ -90,9 +90,10 @@ is not a permanent identity ban or a change of secret. The marker and requester's own author counter commit in one SQLite transaction before publication. Receivers persist a verified marker before applying it. -Invalid proofs are rejected individually. Periodic bounded marker batches -rotate through each peer's send queue, including when a queue fills, so a -replica that missed an update can catch up without the requester being online. +Invalid proofs are rejected individually. Each authenticated stream receives +the current claims, markers and VIPs, then their changes. A per-session cursor +advances when a bounded frame enters the send queue. The next maintenance +round retries pending revisions, and a new session starts from the beginning. One strongest marker per target is retained, with a default limit of 1024 per network and 1024 bytes per encoded marker. New targets beyond that limit are diff --git a/docs/vip.md b/docs/vip.md index e060e70..b8aece7 100644 --- a/docs/vip.md +++ b/docs/vip.md @@ -142,8 +142,9 @@ Missing snapshot fields are never deletion. Saving validates the entire draft and checks the revision shown by the editor. The merged snapshot and author's counter commit together in SQLite before local routing changes or publication. Receivers verify and persist complete service -snapshots before exposing them. Periodic rotating snapshots repair queue loss -and returning replicas without requiring the creator online. Concurrent edits +snapshots before exposing them. Each session sends changed services and retries +when its send queue has room. Reconnecting replicas receive all retained +services and tombstones from any member. Concurrent edits made before participants have seen each other can still merge after a save. A merged configuration exceeding listener/backend limits is reported as an error and excluded from routing rather than selected according to arrival order. diff --git a/nix/package.nix b/nix/package.nix index c4ac961..c130475 100644 --- a/nix/package.nix +++ b/nix/package.nix @@ -34,7 +34,7 @@ let in rustPlatform.buildRustPackage { pname = if withTray then "tsunagi" else "tsunagi-cli"; - version = "1.0.3"; + version = "1.0.4"; src = lib.cleanSource ../.; cargoLock.lockFile = ../Cargo.lock;