From a25e7d384e6314e2ac4c166531c81eedda7ace97 Mon Sep 17 00:00:00 2001 From: DeFiDude <59237470+DeFiDude@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:43:00 -0700 Subject: [PATCH] interfaces: TCP and Backbone clients report why they cannot connect in interface stats --- CHANGELOG.md | 1 + api/snapshots/rns-transport.txt | 4 + api/stability.json | 4 +- crates/rns-interface/src/backbone.rs | 153 ++++++++++--- crates/rns-interface/src/tcp.rs | 299 +++++++++++++++++++++++--- crates/rns-runtime/src/rpc.rs | 10 + crates/rns-transport/src/actor/mod.rs | 4 + crates/rns-transport/src/actor/rpc.rs | 2 + crates/rns-transport/src/messages.rs | 10 + 9 files changed, 428 insertions(+), 59 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a290475..77b4e80 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ## Unreleased - Bluetooth Peer runs in Gateway mode, so a node with transport on looks up the paths its Bluetooth peers ask for that it doesn't know yet. Nodes with transport off behave as before. +- TCP and Backbone client interfaces report why they can't connect: `last_connect_error` (`refused`, `timed_out`, `dns`, `unreachable`, `closed_by_peer`, or `other`) and `connect_failures` in the interface stats, so an application can tell a hub that refuses or closes the connection from one still connecting. The shared-instance RPC doesn't carry them. - I2P interfaces log their `.b32.i2p` address once reachable, at loglevel 5 or higher, as Python Reticulum does. - Announce handler events carry `emitted`, the time the announcer stamped into the announce, so an application can tell an older cached announce in a path response from a newer one. `AnnounceHandlerEvent` struct literals need the new field. diff --git a/api/snapshots/rns-transport.txt b/api/snapshots/rns-transport.txt index 1b8d29d..015e4a0 100644 --- a/api/snapshots/rns-transport.txt +++ b/api/snapshots/rns-transport.txt @@ -1409,9 +1409,11 @@ pub fn rns_transport::messages::InterfaceIdentity::new(impl core::convert::Into< pub struct rns_transport::messages::InterfaceInspectionSnapshot pub rns_transport::messages::InterfaceInspectionSnapshot::active_clients: core::option::Option pub rns_transport::messages::InterfaceInspectionSnapshot::blocked_ips: core::option::Option +pub rns_transport::messages::InterfaceInspectionSnapshot::connect_failures: u32 pub rns_transport::messages::InterfaceInspectionSnapshot::i2p_b32: core::option::Option pub rns_transport::messages::InterfaceInspectionSnapshot::i2p_connectable: core::option::Option pub rns_transport::messages::InterfaceInspectionSnapshot::i2p_tunnel_state: core::option::Option +pub rns_transport::messages::InterfaceInspectionSnapshot::last_connect_error: core::option::Option<&'static str> pub rns_transport::messages::InterfaceInspectionSnapshot::peers: core::option::Option pub rns_transport::messages::InterfaceInspectionSnapshot::radio: alloc::vec::Vec<(&'static str, rns_transport::messages::InterfaceStatValue)> pub rns_transport::messages::InterfaceInspectionSnapshot::tx_buffered: u64 @@ -1470,6 +1472,7 @@ pub rns_transport::messages::InterfaceStatRpcEntry::burst_activated: f64 pub rns_transport::messages::InterfaceStatRpcEntry::burst_active: bool pub rns_transport::messages::InterfaceStatRpcEntry::burst_count: core::option::Option pub rns_transport::messages::InterfaceStatRpcEntry::clients: core::option::Option +pub rns_transport::messages::InterfaceStatRpcEntry::connect_failures: u32 pub rns_transport::messages::InterfaceStatRpcEntry::gravity: i64 pub rns_transport::messages::InterfaceStatRpcEntry::held_announces: u64 pub rns_transport::messages::InterfaceStatRpcEntry::i2p_b32: core::option::Option @@ -1483,6 +1486,7 @@ pub rns_transport::messages::InterfaceStatRpcEntry::ifac_size: core::option::Opt pub rns_transport::messages::InterfaceStatRpcEntry::ifac_violations: u64 pub rns_transport::messages::InterfaceStatRpcEntry::incoming_announce_frequency: f64 pub rns_transport::messages::InterfaceStatRpcEntry::incoming_pr_frequency: f64 +pub rns_transport::messages::InterfaceStatRpcEntry::last_connect_error: core::option::Option pub rns_transport::messages::InterfaceStatRpcEntry::mode: alloc::string::String pub rns_transport::messages::InterfaceStatRpcEntry::mtu: u32 pub rns_transport::messages::InterfaceStatRpcEntry::name: alloc::string::String diff --git a/api/stability.json b/api/stability.json index 1e3c9ec..813dc8e 100644 --- a/api/stability.json +++ b/api/stability.json @@ -51,8 +51,8 @@ "tier": "provisional", "compatibility": "reviewed-snapshot", "snapshot": "api/snapshots/rns-transport.txt", - "itemCount": 2161, - "sha256": "486f79c541ecec9e815cd082aec536dfd805acb4947498a7efde8c25632f56a2" + "itemCount": 2165, + "sha256": "92f431ad69a4cc7e4d3df343a3a287682bac7ea97af6cd7b7958df5d1042b09a" }, { "name": "rns-link", diff --git a/crates/rns-interface/src/backbone.rs b/crates/rns-interface/src/backbone.rs index 1da62fc..b271f72 100644 --- a/crates/rns-interface/src/backbone.rs +++ b/crates/rns-interface/src/backbone.rs @@ -18,6 +18,7 @@ use tokio::sync::mpsc; use crate::hdlc; use crate::socket_tuning::{set_keepalive_tuned, set_socket_buffers}; +use crate::tcp::{ConnectDiagnostics, ConnectError}; use crate::traits::{ ByteCounter, InterfaceDirection, InterfaceHandle, InterfaceId, InterfaceMode, TunnelIdentity, handoff_accepted_interface, open_client_connection, python_address_name, python_host, @@ -411,7 +412,7 @@ async fn backbone_read_loop( online: Arc, rxb: ByteCounter, (bitrate, ifac_size): (u64, usize), -) { +) -> ConnectError { // ReceiveBuffer(HW_MTU, HEADER_MINSIZE, HW_MTU + ifac_size) (BackboneInterface.py). let hw_mtu = crate::tcp::hardware_mtu(bitrate, None) as usize; let mut deframer = hdlc::HdlcDeframer::with_limits( @@ -421,6 +422,7 @@ async fn backbone_read_loop( ); // Large buffer to amortise syscalls. let mut buf = vec![0u8; 65536]; + let mut ended = ConnectError::ClosedByPeer; loop { match reader.read(&mut buf).await { Ok(0) => { @@ -443,17 +445,19 @@ async fn backbone_read_loop( if transport_tx.send(msg).await.is_err() { tracing::warn!(interface_id, "transport channel closed"); online.store(false, Ordering::SeqCst); - return; + return ConnectError::Other; } } } Err(e) => { tracing::warn!(interface_id, error = %e, "backbone read error"); + ended = ConnectError::from_io(&e); break; } } } online.store(false, Ordering::SeqCst); + ended } /// Per-connection dataplane egress control state (Python `_dp_ec_*`). @@ -543,12 +547,16 @@ struct EgressState { } impl EgressState { - fn inspection(state: Arc) -> InterfaceInspectionSource { - InterfaceInspectionSource::new(move || InterfaceInspectionSnapshot { - tx_stalled: state.stalled.load(Ordering::Relaxed), - tx_buffered: state.buffered.load(Ordering::Relaxed), + fn snapshot(&self) -> InterfaceInspectionSnapshot { + InterfaceInspectionSnapshot { + tx_stalled: self.stalled.load(Ordering::Relaxed), + tx_buffered: self.buffered.load(Ordering::Relaxed), ..InterfaceInspectionSnapshot::default() - }) + } + } + + fn inspection(state: Arc) -> InterfaceInspectionSource { + InterfaceInspectionSource::new(move || state.snapshot()) } } @@ -560,7 +568,7 @@ async fn backbone_write_loop( txb: &ByteCounter, name: &str, state: &EgressState, -) { +) -> ConnectError { let started = tokio::time::Instant::now(); let mut control = EgressControl::new(0.0); let mut tick = tokio::time::interval_at(started + DP_EC_INTERVAL, DP_EC_INTERVAL); @@ -583,12 +591,12 @@ async fn backbone_write_loop( DP_EC_DEAD_TIME, name, ); - return; + return ConnectError::Other; } } result = async { writer.write(chunk.as_deref().unwrap_or_default()).await }, if chunk.is_some() => { match result { - Ok(0) => return, + Ok(0) => return ConnectError::ClosedByPeer, Ok(n) => { let written = n as u64; sent += written; @@ -605,12 +613,12 @@ async fn backbone_write_loop( } Err(e) => { tracing::warn!(name = %name, error = %e, "backbone write error"); - return; + return ConnectError::from_io(&e); } } } item = rx.recv() => { - let Some(data) = item else { return }; + let Some(data) = item else { return ConnectError::Other }; let frame = Bytes::from(hdlc::frame(&data)); let len = frame.len() as u64; if control.stalled() || buffered + len > TX_HWM { @@ -633,6 +641,7 @@ async fn backbone_write_loop( /// Run one connection: the reader and the egress-controlled writer share a /// task, so either side ending (or the task being aborted) closes the socket. +/// Returns how the connection ended. #[allow(clippy::too_many_arguments)] async fn backbone_connection( stream: TcpStream, @@ -645,14 +654,15 @@ async fn backbone_connection( name: &str, state: &EgressState, sizing: (u64, usize), -) { +) -> ConnectError { let (reader, mut writer) = stream.into_split(); - tokio::select! { - _ = backbone_read_loop(reader, interface_id, transport_tx, online.clone(), rxb, sizing) => {} - _ = backbone_write_loop(&mut writer, rx, &txb, name, state) => {} - } + let ended = tokio::select! { + ended = backbone_read_loop(reader, interface_id, transport_tx, online.clone(), rxb, sizing) => ended, + ended = backbone_write_loop(&mut writer, rx, &txb, name, state) => ended, + }; state.buffered.store(0, Ordering::Relaxed); online.store(false, Ordering::SeqCst); + ended } /// Resolve `host:port` preferring the configured address family. @@ -916,20 +926,35 @@ fn spawn_backbone_server_on_listener( }) } -/// Resolve and connect, each step bounded by `timeout`. +/// Resolve and connect, each step bounded by `timeout`, naming the failure. async fn connect_backbone_target( config: &BackboneClientConfig, timeout: Duration, -) -> std::io::Result { - let target = tokio::time::timeout( +) -> Result { + use std::io::{Error, ErrorKind}; + let target = match tokio::time::timeout( timeout, resolve_target(&config.target_host, config.target_port, config.prefer_ipv6), ) .await - .map_err(|_| std::io::Error::new(std::io::ErrorKind::TimedOut, "resolve timed out"))??; - tokio::time::timeout(timeout, TcpStream::connect(target)) - .await - .map_err(|_| std::io::Error::new(std::io::ErrorKind::TimedOut, "connect timed out"))? + { + Ok(Ok(target)) => target, + Ok(Err(e)) => return Err((ConnectError::Dns, e)), + Err(_) => { + return Err(( + ConnectError::Dns, + Error::new(ErrorKind::TimedOut, "resolve timed out"), + )); + } + }; + match tokio::time::timeout(timeout, TcpStream::connect(target)).await { + Ok(Ok(stream)) => Ok(stream), + Ok(Err(e)) => Err((ConnectError::from_io(&e), e)), + Err(_) => Err(( + ConnectError::TimedOut, + Error::new(ErrorKind::TimedOut, "connect timed out"), + )), + } } pub async fn spawn_backbone_client( @@ -967,6 +992,8 @@ pub async fn spawn_backbone_client_observed( let identity = InterfaceIdentity::new(&python_name, &config.name, "BackboneClientInterface"); let egress = Arc::new(EgressState::default()); let task_egress = egress.clone(); + let diagnostics = Arc::new(ConnectDiagnostics::default()); + let task_diagnostics = diagnostics.clone(); let (teardown_tx, teardown) = crate::tcp::ClientTeardown::channel(); // Python connects once, synchronously, before the interface is handed to // transport (BackboneInterface.py). @@ -977,7 +1004,7 @@ pub async fn spawn_backbone_client_observed( connect_backbone_target(&config, initial_timeout), ) .await - .unwrap_or_else(|_| Err(std::io::ErrorKind::TimedOut.into())), + .unwrap_or_else(|_| Err((ConnectError::TimedOut, std::io::ErrorKind::TimedOut.into()))), ); if matches!(initial_attempt, Some(Ok(_))) { online.store(true, Ordering::SeqCst); @@ -1006,14 +1033,16 @@ pub async fn spawn_backbone_client_observed( }; let stream = match attempt { Ok(s) => s, - Err(e) => { + Err((error, e)) => { tracing::warn!(name = %config.name, error = %e, "backbone connect failed"); + task_diagnostics.failed(error); continue; } }; tune_stream(&stream); attempts = 0; + task_diagnostics.connected(); // Python synthesizes on every connection (BackboneInterface.py, // :1019). let synthesis = config @@ -1022,7 +1051,7 @@ pub async fn spawn_backbone_client_observed( .and_then(|identity| identity.synthesis(&python_name)); open_client_connection(&rx, &transport_tx, synthesis, &online2).await; - { + let ended = { let mut outbound = rx.lock().await; backbone_connection( stream, @@ -1036,9 +1065,10 @@ pub async fn spawn_backbone_client_observed( &task_egress, sizing, ) - .await; - } + .await + }; online2.store(false, Ordering::SeqCst); + task_diagnostics.disconnected(ended); tracing::info!( name = %config.name, @@ -1068,7 +1098,10 @@ pub async fn spawn_backbone_client_observed( online, rxb: Some(shared_rxb), txb: Some(shared_txb), - inspection: Some(EgressState::inspection(egress).with_identity(identity)), + inspection: Some( + InterfaceInspectionSource::new(move || diagnostics.snapshot(egress.snapshot())) + .with_identity(identity), + ), tx, read_task, }, @@ -1391,6 +1424,66 @@ mod tests { .snapshot() } + /// What a client of an upstream hub sees once the hub blocks its IP: + /// accepted, then closed at once. + #[tokio::test] + async fn client_stats_report_a_hub_that_closes_at_once() { + let (transport_tx, _transport_rx) = mpsc::channel::(8); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let server = tokio::spawn(async move { + loop { + drop(listener.accept().await.unwrap()); + } + }); + + let config = BackboneClientConfig::new("bb-closed", "127.0.0.1", port); + let handle = spawn_backbone_client(config, 81, transport_tx) + .await + .unwrap(); + handle.owner.mark_registered(); + + let deadline = tokio::time::Instant::now() + Duration::from_secs(8); + let snapshot = loop { + let snapshot = inspection_snapshot(&handle); + if snapshot.last_connect_error == Some("closed_by_peer") { + break snapshot; + } + assert!(tokio::time::Instant::now() < deadline, "{snapshot:?}"); + tokio::time::sleep(Duration::from_millis(20)).await; + }; + assert!(snapshot.connect_failures >= 1); + assert!(!snapshot.tx_stalled); + handle.read_task.abort(); + server.abort(); + } + + #[tokio::test] + async fn client_stats_report_a_refused_connect() { + let (transport_tx, _transport_rx) = mpsc::channel::(8); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + drop(listener); + + let config = BackboneClientConfig::new("bb-refused", "127.0.0.1", port); + let handle = spawn_backbone_client(config, 82, transport_tx) + .await + .unwrap(); + handle.owner.mark_registered(); + + let deadline = tokio::time::Instant::now() + Duration::from_secs(8); + loop { + let snapshot = inspection_snapshot(&handle); + if snapshot.last_connect_error == Some("refused") { + assert_eq!(snapshot.connect_failures, 1); + break; + } + assert!(tokio::time::Instant::now() < deadline, "{snapshot:?}"); + tokio::time::sleep(Duration::from_millis(20)).await; + } + handle.read_task.abort(); + } + #[test] fn test_backbone_server_config() { let cfg = BackboneServerConfig::new("backbone0", "0.0.0.0", 4243); diff --git a/crates/rns-interface/src/tcp.rs b/crates/rns-interface/src/tcp.rs index 2a337f9..651ed60 100644 --- a/crates/rns-interface/src/tcp.rs +++ b/crates/rns-interface/src/tcp.rs @@ -344,6 +344,141 @@ pub fn frame_for_tcp(data: &[u8], kiss_framing: bool) -> Vec { use crate::socket_tuning::set_socket_buffers; +/// Why a reconnecting client's attempt failed, as its interface stats name it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum ConnectError { + Refused, + TimedOut, + Dns, + Unreachable, + ClosedByPeer, + Other, +} + +impl ConnectError { + pub(crate) fn as_str(self) -> &'static str { + match self { + Self::Refused => "refused", + Self::TimedOut => "timed_out", + Self::Dns => "dns", + Self::Unreachable => "unreachable", + Self::ClosedByPeer => "closed_by_peer", + Self::Other => "other", + } + } + + pub(crate) fn from_io(error: &std::io::Error) -> Self { + use std::io::ErrorKind; + match error.kind() { + ErrorKind::ConnectionRefused => Self::Refused, + ErrorKind::TimedOut => Self::TimedOut, + ErrorKind::HostUnreachable + | ErrorKind::NetworkUnreachable + | ErrorKind::NetworkDown + | ErrorKind::AddrNotAvailable => Self::Unreachable, + ErrorKind::ConnectionReset + | ErrorKind::ConnectionAborted + | ErrorKind::BrokenPipe + | ErrorKind::UnexpectedEof => Self::ClosedByPeer, + _ => Self::Other, + } + } +} + +/// A connection that ends sooner is a failed attempt, `closed_by_peer` when the +/// server ended it: an upstream Backbone hub accepts and at once closes an IP it +/// blocks, and counts connections this short as fast flaps. +pub(crate) const CONNECTION_STAYS_UP: std::time::Duration = + crate::backbone::FAST_FLAPPING_THRESHOLD; + +/// The connect outcome a reconnecting client reports in its interface stats. +#[derive(Debug, Default)] +pub(crate) struct ConnectDiagnostics(std::sync::Mutex); + +#[derive(Debug, Default)] +struct ConnectState { + last_error: Option, + failures: u32, + connected_at: Option, +} + +impl ConnectState { + fn stayed_up(&self) -> bool { + self.connected_at + .is_some_and(|at| at.elapsed() >= CONNECTION_STAYS_UP) + } + + fn fail(&mut self, error: ConnectError) { + self.last_error = Some(error); + self.failures = self.failures.saturating_add(1); + } +} + +impl ConnectDiagnostics { + fn state(&self) -> std::sync::MutexGuard<'_, ConnectState> { + self.0 + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } + + pub(crate) fn failed(&self, error: ConnectError) { + self.state().fail(error); + } + + pub(crate) fn connected(&self) { + self.state().connected_at = Some(std::time::Instant::now()); + } + + /// `ended` names how the connection closed. + pub(crate) fn disconnected(&self, ended: ConnectError) { + let mut state = self.state(); + if state.stayed_up() { + state.last_error = None; + state.failures = 0; + } else { + state.fail(ended); + } + state.connected_at = None; + } + + pub(crate) fn snapshot( + &self, + mut snapshot: InterfaceInspectionSnapshot, + ) -> InterfaceInspectionSnapshot { + let state = self.state(); + if !state.stayed_up() { + snapshot.last_connect_error = state.last_error.map(ConnectError::as_str); + snapshot.connect_failures = state.failures; + } + snapshot + } +} + +/// `TcpStream::connect(addr)` within [`INITIAL_CONNECT_TIMEOUT`], naming the failure. +async fn connect_tcp_target(addr: &str) -> Result { + use std::io::{Error, ErrorKind}; + let deadline = + tokio::time::Instant::now() + std::time::Duration::from_secs(INITIAL_CONNECT_TIMEOUT); + let addrs: Vec = + match tokio::time::timeout_at(deadline, tokio::net::lookup_host(addr)).await { + Ok(Ok(addrs)) => addrs.collect(), + Ok(Err(error)) => return Err((ConnectError::Dns, error)), + Err(_) => return Err((ConnectError::Dns, ErrorKind::TimedOut.into())), + }; + if addrs.is_empty() { + return Err(( + ConnectError::Dns, + Error::new(ErrorKind::NotFound, "could not resolve to any address"), + )); + } + match tokio::time::timeout_at(deadline, TcpStream::connect(&addrs[..])).await { + Ok(Ok(stream)) => Ok(stream), + Ok(Err(error)) => Err((ConnectError::from_io(&error), error)), + Err(_) => Err((ConnectError::TimedOut, ErrorKind::TimedOut.into())), + } +} + +/// Returns how the connection ended. async fn tcp_read_loop( mut reader: tokio::net::tcp::OwnedReadHalf, interface_id: InterfaceId, @@ -352,7 +487,8 @@ async fn tcp_read_loop( kiss_framing: bool, hw_mtu: usize, ifac_size: usize, -) { +) -> ConnectError { + let mut ended = ConnectError::ClosedByPeer; let mut buf = [0u8; 32768]; if kiss_framing { @@ -378,12 +514,13 @@ async fn tcp_read_loop( }); if transport_tx.send(msg).await.is_err() { tracing::warn!(interface_id, "transport channel closed"); - return; + return ConnectError::Other; } } } Err(e) => { tracing::warn!(interface_id, error = %e, "TCP read error"); + ended = ConnectError::from_io(&e); break; } } @@ -421,18 +558,20 @@ async fn tcp_read_loop( }); if transport_tx.send(msg).await.is_err() { tracing::warn!(interface_id, "transport channel closed"); - return; + return ConnectError::Other; } } } Err(e) => { tracing::warn!(interface_id, error = %e, "TCP read error"); + ended = ConnectError::from_io(&e); break; } } } } state.online.store(false, Ordering::SeqCst); + ended } async fn tcp_write_loop( @@ -544,21 +683,17 @@ pub async fn spawn_tcp_client_observed( let python_name = config.python_name(); let identity = InterfaceIdentity::new(&python_name, &config.name, "TCPClientInterface"); let (teardown_tx, teardown) = ClientTeardown::channel(); + let diagnostics = Arc::new(ConnectDiagnostics::default()); + let task_diagnostics = diagnostics.clone(); + let addr = format!("{}:{}", config.target_host, config.target_port); // Python connects once, synchronously, before the interface is handed to // transport (TCPInterface.py). - let mut initial_attempt = Some( - tokio::time::timeout( - std::time::Duration::from_secs(INITIAL_CONNECT_TIMEOUT), - TcpStream::connect(format!("{}:{}", config.target_host, config.target_port)), - ) - .await, - ); - if matches!(initial_attempt, Some(Ok(Ok(_)))) { + let mut initial_attempt = Some(connect_tcp_target(&addr).await); + if matches!(initial_attempt, Some(Ok(_))) { online.store(true, Ordering::SeqCst); } let read_task = tokio::spawn(async move { let max_tries = config.max_reconnect_tries; - let addr = format!("{}:{}", config.target_host, config.target_port); // Every attempt after the first follows a failure or an outage. let mut attempted = false; // Retries within the current outage (TCPInterface.py). @@ -577,22 +712,13 @@ pub async fn spawn_tcp_client_observed( attempted = true; let attempt = match initial_attempt.take() { Some(attempt) => attempt, - None => { - tokio::time::timeout( - std::time::Duration::from_secs(INITIAL_CONNECT_TIMEOUT), - TcpStream::connect(&addr), - ) - .await - } + None => connect_tcp_target(&addr).await, }; let stream = match attempt { - Ok(Ok(s)) => s, - Ok(Err(e)) => { + Ok(s) => s, + Err((error, e)) => { tracing::warn!(name = %config.name, error = %e, "TCP connect failed"); - continue; - } - Err(_) => { - tracing::warn!(name = %config.name, "TCP connect timed out"); + task_diagnostics.failed(error); continue; } }; @@ -606,6 +732,7 @@ pub async fn spawn_tcp_client_observed( let state = TcpInterfaceState::with_shared_counters(task_rxb.clone(), task_txb.clone()); state.online.store(true, Ordering::SeqCst); attempts = 0; + task_diagnostics.connected(); // Python synthesizes on every non-KISS connection // (TCPInterface.py). let synthesis = config @@ -631,7 +758,7 @@ pub async fn spawn_tcp_client_observed( } }); - tcp_read_loop( + let ended = tcp_read_loop( reader, id, transport_tx.clone(), @@ -643,6 +770,7 @@ pub async fn spawn_tcp_client_observed( .await; online2.store(false, Ordering::SeqCst); + task_diagnostics.disconnected(ended); fwd_handle.abort(); let _ = fwd_handle.await; @@ -673,7 +801,12 @@ pub async fn spawn_tcp_client_observed( online, rxb: Some(shared_rxb), txb: Some(shared_txb), - inspection: Some(InterfaceInspectionSource::identified(identity)), + inspection: Some( + InterfaceInspectionSource::new(move || { + diagnostics.snapshot(InterfaceInspectionSnapshot::default()) + }) + .with_identity(identity), + ), tx, read_task, }, @@ -1042,6 +1175,118 @@ mod tests { handle.read_task.abort(); } + async fn connect_error( + handle: &InterfaceHandle, + expected: &str, + ) -> InterfaceInspectionSnapshot { + let source = handle.inspection.as_ref().unwrap(); + let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(8); + loop { + let snapshot = source.snapshot(); + if snapshot.last_connect_error == Some(expected) { + return snapshot; + } + assert!( + tokio::time::Instant::now() < deadline, + "expected {expected}, got {snapshot:?}" + ); + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + } + + #[tokio::test] + async fn stats_report_a_refused_connect() { + let (transport_tx, _transport_rx) = mpsc::channel::(8); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + drop(listener); + + let config = TcpClientConfig::new("tcp-refused", "127.0.0.1", port); + let handle = spawn_tcp_client(config, 78, transport_tx).await.unwrap(); + handle.owner.mark_registered(); + + let snapshot = connect_error(&handle, "refused").await; + assert_eq!(snapshot.connect_failures, 1); + handle.read_task.abort(); + } + + #[tokio::test] + async fn stats_report_a_name_that_does_not_resolve() { + let (transport_tx, _transport_rx) = mpsc::channel::(8); + let config = TcpClientConfig::new("tcp-dns", "no-such-host.invalid", 4242); + let handle = spawn_tcp_client(config, 80, transport_tx).await.unwrap(); + handle.owner.mark_registered(); + + connect_error(&handle, "dns").await; + handle.read_task.abort(); + } + + /// An upstream Backbone hub accepts a blocked IP and closes it at once. + #[tokio::test] + async fn stats_report_a_server_that_closes_at_once() { + let (transport_tx, _transport_rx) = mpsc::channel::(8); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let server = tokio::spawn(async move { + loop { + drop(listener.accept().await.unwrap()); + } + }); + + let config = TcpClientConfig::new("tcp-closed", "127.0.0.1", port); + let handle = spawn_tcp_client(config, 79, transport_tx).await.unwrap(); + handle.owner.mark_registered(); + + let snapshot = connect_error(&handle, "closed_by_peer").await; + assert!(snapshot.connect_failures >= 1); + handle.read_task.abort(); + server.abort(); + } + + #[test] + fn connect_diagnostics_clear_once_a_connection_stays_up() { + let diagnostics = ConnectDiagnostics::default(); + let report = |d: &ConnectDiagnostics| { + let s = d.snapshot(InterfaceInspectionSnapshot::default()); + (s.last_connect_error, s.connect_failures) + }; + assert_eq!(report(&diagnostics), (None, 0)); + + diagnostics.failed(ConnectError::TimedOut); + diagnostics.failed(ConnectError::Refused); + assert_eq!(report(&diagnostics), (Some("refused"), 2)); + + // Still on probation: the last failure stands until the link stays up. + diagnostics.connected(); + assert_eq!(report(&diagnostics), (Some("refused"), 2)); + diagnostics.disconnected(ConnectError::ClosedByPeer); + assert_eq!(report(&diagnostics), (Some("closed_by_peer"), 3)); + + let Some(earlier) = std::time::Instant::now().checked_sub(CONNECTION_STAYS_UP) else { + return; + }; + diagnostics.connected(); + diagnostics.state().connected_at = Some(earlier); + assert_eq!(report(&diagnostics), (None, 0)); + diagnostics.disconnected(ConnectError::ClosedByPeer); + assert_eq!(report(&diagnostics), (None, 0)); + } + + #[test] + fn connect_errors_classify_io_errors() { + use std::io::{Error, ErrorKind}; + for (kind, expected) in [ + (ErrorKind::ConnectionRefused, "refused"), + (ErrorKind::TimedOut, "timed_out"), + (ErrorKind::HostUnreachable, "unreachable"), + (ErrorKind::NetworkUnreachable, "unreachable"), + (ErrorKind::ConnectionReset, "closed_by_peer"), + (ErrorKind::PermissionDenied, "other"), + ] { + assert_eq!(ConnectError::from_io(&Error::from(kind)).as_str(), expected); + } + } + #[test] fn test_frame_for_tcp_hdlc() { let data = b"test packet"; diff --git a/crates/rns-runtime/src/rpc.rs b/crates/rns-runtime/src/rpc.rs index 5239d79..6136351 100644 --- a/crates/rns-runtime/src/rpc.rs +++ b/crates/rns-runtime/src/rpc.rs @@ -3343,6 +3343,16 @@ mod tests { assert!(!contains_string_key(&raw, "blocked_ips")); } + #[test] + fn connect_diagnostics_stay_off_the_python_rpc() { + let plain = encode_response(&RpcResponse::InterfaceStats(vec![interface_stat_entry()])); + let mut entry = interface_stat_entry(); + entry.last_connect_error = Some("closed_by_peer".to_string()); + entry.connect_failures = 4; + let encoded = encode_response(&RpcResponse::InterfaceStats(vec![entry])).unwrap(); + assert_eq!(encoded, plain.unwrap()); + } + #[test] fn interface_stats_ignore_blocked_ip_lists_and_never_reencode_them() { let upstream = py_dict(vec![( diff --git a/crates/rns-transport/src/actor/mod.rs b/crates/rns-transport/src/actor/mod.rs index 0a7777d..74ef493 100644 --- a/crates/rns-transport/src/actor/mod.rs +++ b/crates/rns-transport/src/actor/mod.rs @@ -8083,6 +8083,8 @@ mod tests { InterfaceInspectionSnapshot { active_clients: Some(7), blocked_ips: Some(2), + last_connect_error: Some("refused"), + connect_failures: 3, ..Default::default() } })); @@ -8096,6 +8098,8 @@ mod tests { assert_eq!(calls.load(std::sync::atomic::Ordering::Relaxed), 1); assert_eq!(stats[0].clients, Some(7)); assert_eq!(stats[0].blocked_ips, Some(2)); + assert_eq!(stats[0].last_connect_error.as_deref(), Some("refused")); + assert_eq!(stats[0].connect_failures, 3); } #[test] diff --git a/crates/rns-transport/src/actor/rpc.rs b/crates/rns-transport/src/actor/rpc.rs index 56d7b88..6f781b6 100644 --- a/crates/rns-transport/src/actor/rpc.rs +++ b/crates/rns-transport/src/actor/rpc.rs @@ -174,6 +174,8 @@ impl TransportActor { tx_stalled: inspection.tx_stalled, tx_buffered: inspection.tx_buffered, radio: inspection.radio, + last_connect_error: inspection.last_connect_error.map(str::to_string), + connect_failures: inspection.connect_failures, }) }) .collect(); diff --git a/crates/rns-transport/src/messages.rs b/crates/rns-transport/src/messages.rs index 56a81fb..b8a2f28 100644 --- a/crates/rns-transport/src/messages.rs +++ b/crates/rns-transport/src/messages.rs @@ -51,6 +51,9 @@ pub struct InterfaceInspectionSnapshot { /// Python `tx_stalled` and `len(transmit_buffer)` in bytes. pub tx_stalled: bool, pub tx_buffered: u64, + /// See [`InterfaceStatRpcEntry::last_connect_error`]. + pub last_connect_error: Option<&'static str>, + pub connect_failures: u32, } /// How Python names an interface: `str(interface)`, `interface.name` and @@ -1365,6 +1368,13 @@ pub struct InterfaceStatRpcEntry { pub tx_buffered: u64, /// Driver radio keys; these replace the generic `rssi`/`snr`/`signal_quality`. pub radio: Vec<(&'static str, InterfaceStatValue)>, + /// Why a reconnecting TCP or Backbone client's latest attempt failed: + /// `refused`, `timed_out`, `dns`, `unreachable`, `closed_by_peer` or + /// `other`; `None` once a connection stays up. Rust-only: the + /// shared-instance RPC does not carry it or `connect_failures`. + pub last_connect_error: Option, + /// Consecutive failed attempts since the last connection that stayed up. + pub connect_failures: u32, } /// Python's top-level `get_interface_stats()` counters (Reticulum.py,