diff --git a/api/fixtures/Cargo.lock b/api/fixtures/Cargo.lock index 9b734a8..3c5c28e 100644 --- a/api/fixtures/Cargo.lock +++ b/api/fixtures/Cargo.lock @@ -375,6 +375,7 @@ dependencies = [ "thiserror 2.0.20", "tokio", "tracing", + "unicode-general-category", "unicode-normalization", ] @@ -941,6 +942,12 @@ version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" +[[package]] +name = "unicode-general-category" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2281c8c1d221438e373249e065ca4989c4c36952c211ff21a0ee91c44a3869e7" + [[package]] name = "unicode-ident" version = "1.0.24" diff --git a/crates/lxmf-core/src/handlers.rs b/crates/lxmf-core/src/handlers.rs index 42c65b0..0ca72da 100644 --- a/crates/lxmf-core/src/handlers.rs +++ b/crates/lxmf-core/src/handlers.rs @@ -950,7 +950,7 @@ impl PropagationRequestHandler { (Value::String("incoming".into()), Value::from(peer.incoming)), ( Value::String("unhandled".into()), - Value::from(peer.unhandled_messages() as u64), + Value::from(peer.unhandled_message_count() as u64), ), ]); peer_entries.push((Value::Binary(hash.to_vec()), peer_map)); diff --git a/crates/lxmf-core/src/link_delivery.rs b/crates/lxmf-core/src/link_delivery.rs index 430ee25..40a7d6a 100644 --- a/crates/lxmf-core/src/link_delivery.rs +++ b/crates/lxmf-core/src/link_delivery.rs @@ -19,6 +19,7 @@ use bytes::Bytes; use rns_crypto::ed25519::{Ed25519PrivateKey, Ed25519PublicKey}; use rns_link::constants::ESTABLISHMENT_TIMEOUT_PER_HOP; use rns_link::link::{CloseReason, Link, LinkAction, LinkState}; +use rns_link::stamp::{LinkRequestStamper, LinkStampPolicy}; use rns_protocol::resource::{ InboundTransfer, LazyMultiSegmentOutbound, MAX_EFFICIENT_SIZE, MAX_RESOURCE_SIZE, MAX_SEGMENTS, MultiSegmentInbound, OutboundResource, OutboundTransfer, ResourceError, TransferAction, @@ -534,6 +535,8 @@ pub enum LinkDeliveryStartError { InvalidTiming, TransportFull, TransportClosed, + /// The link request stamp could not be generated in time. + StampFailure, } impl fmt::Display for LinkDeliveryStartError { @@ -542,6 +545,7 @@ impl fmt::Display for LinkDeliveryStartError { Self::InvalidTiming => f.write_str("invalid link establishment timing"), Self::TransportFull => f.write_str("transport full"), Self::TransportClosed => f.write_str("transport closed"), + Self::StampFailure => f.write_str("link request stamp generation failed"), } } } @@ -935,6 +939,7 @@ pub struct LinkDeliveryManager { transport_ready: Option, delivery_events: VecDeque, resource_counters: ResourceDispatchCounters, + link_stamper: LinkRequestStamper, } impl LinkDeliveryManager { @@ -983,9 +988,16 @@ impl LinkDeliveryManager { transport_ready: None, delivery_events: VecDeque::new(), resource_counters: ResourceDispatchCounters::default(), + link_stamper: LinkRequestStamper::without_recall(LinkStampPolicy::default()), } } + /// Stamp new link requests with this stamper's policy and announced costs. + /// The default stamps only when `always_stamp_lrs` is set. + pub fn set_link_request_stamper(&mut self, stamper: LinkRequestStamper) { + self.link_stamper = stamper; + } + /// Register the embedding task's waker for inbound delivery events and /// local admission/lifecycle acknowledgements. `Ready` means call /// [`Self::drain_events`] and [`Self::tick`]; it is not delivery success. @@ -1672,7 +1684,12 @@ impl LinkDeliveryManager { } = options; let msg_hash = Some(message.message_id()); let packed_override_kind = packed_override.is_some(); - let (mut link, request_data) = Link::new_initiator(dest_hash, hops); + let Ok((mut link, request_data)) = self.link_stamper.new_initiator(dest_hash, hops) else { + return Err(LinkDeliveryStartFailure { + error: LinkDeliveryStartError::StampFailure, + message: Box::new(message), + }); + }; if link .try_extend_establishment_timeout(timing.first_hop_timeout().as_secs_f64()) .is_err() diff --git a/crates/lxmf-core/src/peer.rs b/crates/lxmf-core/src/peer.rs index 2607513..9edf06c 100644 --- a/crates/lxmf-core/src/peer.rs +++ b/crates/lxmf-core/src/peer.rs @@ -73,6 +73,24 @@ struct StoredPeerV2 { metadata: Option>>, last_heard: f64, alive: bool, + #[serde(default)] + link_establishment_rate: f64, + #[serde(default)] + sync_transfer_rate: f64, + #[serde(default)] + last_sync_attempt: f64, + #[serde(default)] + offered: u64, + #[serde(default)] + outgoing: u64, + #[serde(default)] + incoming: u64, + #[serde(default)] + rx_bytes: u64, + #[serde(default)] + tx_bytes: u64, + #[serde(default)] + unhandled_ids: Option>>, } /// Immutable inputs for one outbound propagation offer. @@ -96,6 +114,8 @@ pub struct OutboundOfferPolicy { pub autopeered: bool, pub is_static: bool, pub metadata: Option>>, + /// Messages queued for this peer; `None` offers every live store entry. + pub unhandled_messages: Option>, } impl OutboundOfferPolicy { @@ -119,6 +139,7 @@ impl OutboundOfferPolicy { autopeered: false, is_static: false, metadata: None, + unhandled_messages: None, } } @@ -156,8 +177,6 @@ pub struct LxmPeer { pub state: PeerState, pub sync_strategy: SyncStrategy, pub last_sync: f64, - unhandled_count: u32, - unhandled_count_cached: bool, pub unreachable_count: u32, pub autopeered: bool, pub stamp_cost: Option, @@ -198,6 +217,8 @@ pub struct LxmPeer { pub is_static: bool, /// Message hashes already handled by this peer, for sync filtering. pub handled_messages: HashSet, + /// Messages distributed to this peer and not yet handled by it. + pub unhandled_messages: HashSet, } impl LxmPeer { @@ -208,8 +229,6 @@ impl LxmPeer { state: PeerState::Idle, sync_strategy: SyncStrategy::default(), last_sync: 0.0, - unhandled_count: 0, - unhandled_count_cached: false, unreachable_count: 0, autopeered: false, stamp_cost: None, @@ -221,8 +240,8 @@ impl LxmPeer { currently_transferring_messages: None, link_alive: false, created_at: now, - last_heard: now, - alive: true, + last_heard: 0.0, + alive: false, peering_timebase: 0.0, link_establishment_rate: 0.0, sync_transfer_rate: 0.0, @@ -238,6 +257,7 @@ impl LxmPeer { last_offer_generation: 0, is_static: false, handled_messages: HashSet::new(), + unhandled_messages: HashSet::new(), } } @@ -288,6 +308,8 @@ impl LxmPeer { peer.peering_cost = peering_cost.unwrap_or(PEERING_COST); peer.metadata = bounded_peer_metadata(metadata); peer.autopeered = true; + peer.alive = true; + peer.last_heard = now_f64(); peer } @@ -388,18 +410,19 @@ impl LxmPeer { OutboundOfferPolicy::from(self) } - pub fn add_unhandled_message(&mut self) { - self.unhandled_count_cached = false; - self.unhandled_count += 1; + /// Queue a message for this peer unless it already handled it. + pub fn add_unhandled_message(&mut self, hash: &PropagationTransientId) { + if !self.handled_messages.contains(hash) { + self.unhandled_messages.insert(*hash); + } } - pub fn unhandled_messages(&self) -> u32 { - self.unhandled_count + pub fn remove_unhandled_message(&mut self, hash: &PropagationTransientId) { + self.unhandled_messages.remove(hash); } - pub fn set_unhandled_count(&mut self, count: u32) { - self.unhandled_count = count; - self.unhandled_count_cached = true; + pub fn unhandled_message_count(&self) -> usize { + self.unhandled_messages.len() } pub fn heard(&mut self) { @@ -411,6 +434,7 @@ impl LxmPeer { pub fn add_handled_message(&mut self, hash: &PropagationTransientId) { self.handled_messages.insert(*hash); + self.unhandled_messages.remove(hash); } pub fn has_handled(&self, hash: &PropagationTransientId) -> bool { @@ -429,6 +453,9 @@ impl LxmPeer { pub fn to_bytes_with_handled(&self) -> Vec { let mut handled: Vec> = self.handled_messages.iter().map(|h| h.to_vec()).collect(); handled.sort(); + let mut unhandled: Vec> = + self.unhandled_messages.iter().map(|h| h.to_vec()).collect(); + unhandled.sort(); let data = StoredPeerV2 { version: STORED_PEER_VERSION, destination_hash: self.destination_hash.to_vec(), @@ -449,6 +476,15 @@ impl LxmPeer { metadata: self.metadata.clone(), last_heard: self.last_heard, alive: self.alive, + link_establishment_rate: self.link_establishment_rate, + sync_transfer_rate: self.sync_transfer_rate, + last_sync_attempt: self.last_sync_attempt, + offered: self.offered, + outgoing: self.outgoing, + incoming: self.incoming, + rx_bytes: self.rx_bytes, + tx_bytes: self.tx_bytes, + unhandled_ids: Some(unhandled), }; rmp_serde::to_vec_named(&data).unwrap_or_default() } @@ -457,8 +493,15 @@ impl LxmPeer { /// /// [`to_bytes_with_handled`]: Self::to_bytes_with_handled pub fn from_bytes_with_handled(data: &[u8]) -> Option { + Self::decode_stored(data).map(|(peer, _)| peer) + } + + /// Decode a stored peer and report whether the record predates per-peer + /// unhandled sets, when every unhandled store entry was offered. + pub(crate) fn decode_stored(data: &[u8]) -> Option<(Self, bool)> { if let Ok(stored) = rmp_serde::from_slice::(data) { - return Self::from_stored_v2(stored); + let legacy = stored.unhandled_ids.is_none(); + return Self::from_stored_v2(stored).map(|peer| (peer, legacy)); } let ( @@ -478,6 +521,9 @@ impl LxmPeer { let mut dest_hash = [0u8; 16]; dest_hash.copy_from_slice(&dest_hash_vec); let mut peer = Self::new(dest_hash); + // The legacy record kept no liveness; treat the peer as just heard. + peer.alive = true; + peer.last_heard = now_f64(); peer.last_sync = last_sync; peer.unreachable_count = unreachable_count; peer.peering_cost = peering_cost; @@ -497,7 +543,7 @@ impl LxmPeer { } }) .collect(); - Some(peer) + Some((peer, true)) } fn from_stored_v2(stored: StoredPeerV2) -> Option { @@ -525,20 +571,57 @@ impl LxmPeer { peer.metadata = stored.metadata; peer.last_heard = stored.last_heard; peer.alive = stored.alive; + peer.link_establishment_rate = stored.link_establishment_rate; + peer.sync_transfer_rate = stored.sync_transfer_rate; + peer.last_sync_attempt = stored.last_sync_attempt; + peer.offered = stored.offered; + peer.outgoing = stored.outgoing; + peer.incoming = stored.incoming; + peer.rx_bytes = stored.rx_bytes; + peer.tx_bytes = stored.tx_bytes; peer.handled_messages = stored .handled_ids .into_iter() .filter_map(|value| value.try_into().ok()) .collect(); + peer.unhandled_messages = stored + .unhandled_ids + .unwrap_or_default() + .into_iter() + .filter_map(|value| value.try_into().ok()) + .collect(); Some(peer) } pub fn mark_unreachable(&mut self) { self.unreachable_count += 1; - let now = now_f64(); - if now - self.last_heard > MAX_UNREACHABLE as f64 { + } + + /// Opening checks of Python `LXMPeer.sync()`: record the attempt and + /// report whether the backoff has elapsed. An attempt during backoff + /// marks a peer not heard since its last attempt as unreachable. + pub fn sync_attempt(&mut self, now: f64) -> bool { + self.last_sync_attempt = now; + if now > self.next_sync_attempt { + return true; + } + if self.last_sync_attempt > self.last_heard { self.alive = false; } + false + } + + /// A path request for this peer went unanswered within + /// [`PATH_REQUEST_GRACE`]; defer the sync as Python `LXMPeer.sync()` does. + pub fn path_request_failed(&mut self, now: f64) { + self.sync_backoff += SYNC_BACKOFF_STEP as f64; + self.next_sync_attempt = now + self.sync_backoff; + self.alive = false; + } + + /// Whether this peer has been silent longer than [`MAX_UNREACHABLE`]. + pub fn unreachable_too_long(&self, now: f64) -> bool { + now > self.last_heard + MAX_UNREACHABLE as f64 } pub fn should_sync(&self) -> bool { @@ -648,6 +731,7 @@ impl LxmPeer { self.next_sync_attempt = 0.0; self.last_heard = now_f64(); self.alive = true; + self.sync_backoff = 0.0; self.link_alive = true; } @@ -702,68 +786,46 @@ impl From<&LxmPeer> for OutboundOfferPolicy { autopeered: peer.autopeered, is_static: peer.is_static, metadata: peer.metadata.clone(), + unhandled_messages: Some(peer.unhandled_messages.clone()), } } } -/// Return the input index of an idle peer with unhandled messages. +/// Choose the next peer to sync as Python `LXMRouter.sync_peers()` does. /// -/// Alive peers take priority: sort them by descending transfer rate and choose -/// the first. This selection is deterministic; adding unknown-speed peers to -/// the candidate pool does not randomize the choice as Python `sync_peers()` does. -/// If no alive peer qualifies, choose the first unresponsive peer whose backoff -/// has elapsed. Backoff is not checked in the alive-peer branch. -pub fn select_sync_peer(peers: &[&LxmPeer]) -> Option { - if peers.is_empty() { - return None; - } +/// Alive idle peers with unhandled messages form the waiting pool; the pick is +/// random among the [`FASTEST_N_RANDOM_POOL`] fastest of them plus as many +/// peers of unknown speed. With no waiting peer, the pick is random among +/// unreachable idle peers whose backoff has elapsed. Returns an input index. +pub fn select_sync_peer(peers: &[&LxmPeer], now: f64) -> Option { + use rand::seq::SliceRandom; - let mut alive_with_unhandled: Vec<(usize, &LxmPeer)> = peers - .iter() - .enumerate() - .filter(|(_, p)| p.alive && p.state == PeerState::Idle && p.unhandled_messages() > 0) - .map(|(i, p)| (i, *p)) + let candidate = + |peer: &LxmPeer| peer.state == PeerState::Idle && !peer.unhandled_messages.is_empty(); + let mut waiting: Vec = (0..peers.len()) + .filter(|&i| candidate(peers[i]) && peers[i].alive) .collect(); - - if !alive_with_unhandled.is_empty() { - alive_with_unhandled.sort_by(|a, b| { - b.1.sync_transfer_rate - .partial_cmp(&a.1.sync_transfer_rate) - .unwrap_or(std::cmp::Ordering::Equal) - }); - - let pool_size = alive_with_unhandled.len().min(FASTEST_N_RANDOM_POOL); - - let unknown_speed: Vec<(usize, &LxmPeer)> = alive_with_unhandled + let pool: Vec = if !waiting.is_empty() { + let unknown_speed: Vec = waiting .iter() - .filter(|(_, p)| p.sync_transfer_rate == 0.0) .copied() + .filter(|&i| peers[i].sync_transfer_rate == 0.0) .collect(); - - let mut pool: Vec = alive_with_unhandled[..pool_size] - .iter() - .map(|(i, _)| *i) - .collect(); - for (i, _) in unknown_speed.iter().take(pool_size) { - if !pool.contains(i) { - pool.push(*i); - } - } - - // Deterministic first-of-pool pick; callers that want randomization do it themselves. - return pool.into_iter().next(); - } - - let unresponsive: Vec<(usize, &LxmPeer)> = peers - .iter() - .enumerate() - .filter(|(_, p)| { - !p.alive && p.state == PeerState::Idle && p.unhandled_messages() > 0 && p.should_sync() - }) - .map(|(i, p)| (i, *p)) - .collect(); - - unresponsive.first().map(|(i, _)| *i) + waiting.sort_by(|&a, &b| { + peers[b] + .sync_transfer_rate + .total_cmp(&peers[a].sync_transfer_rate) + }); + waiting.truncate(FASTEST_N_RANDOM_POOL); + let fastest = waiting.len(); + waiting.extend(unknown_speed.into_iter().take(fastest)); + waiting + } else { + (0..peers.len()) + .filter(|&i| candidate(peers[i]) && !peers[i].alive && now > peers[i].next_sync_attempt) + .collect() + }; + pool.choose(&mut rand::thread_rng()).copied() } fn now_f64() -> f64 { @@ -786,7 +848,8 @@ mod tests { let peer = LxmPeer::new([0xAA; 16]); assert_eq!(peer.state, PeerState::Idle); assert_eq!(peer.sync_strategy, SyncStrategy::Persistent); - assert!(peer.alive); + assert!(!peer.alive); + assert_eq!(peer.last_heard, 0.0); assert_eq!(peer.unreachable_count, 0); } @@ -985,10 +1048,29 @@ mod tests { } #[test] - fn test_mark_unreachable() { + fn sync_attempt_during_backoff_marks_unheard_peer_unreachable() { let mut peer = LxmPeer::new([0; 16]); - peer.last_heard = 0.0; - peer.mark_unreachable(); + peer.alive = true; + peer.last_heard = 100.0; + peer.next_sync_attempt = 500.0; + assert!(!peer.sync_attempt(200.0)); + assert_eq!(peer.last_sync_attempt, 200.0); + assert!(!peer.alive); + + peer.alive = true; + peer.last_heard = 300.0; + assert!(!peer.sync_attempt(250.0)); + assert!(peer.alive, "a peer heard after the attempt stays alive"); + assert!(peer.sync_attempt(600.0)); + } + + #[test] + fn unanswered_path_request_adds_backoff_and_marks_unreachable() { + let mut peer = LxmPeer::new([0; 16]); + peer.alive = true; + peer.path_request_failed(1000.0); + assert_eq!(peer.sync_backoff, SYNC_BACKOFF_STEP as f64); + assert_eq!(peer.next_sync_attempt, 1000.0 + SYNC_BACKOFF_STEP as f64); assert!(!peer.alive); } @@ -1044,11 +1126,16 @@ mod tests { #[test] fn test_add_unhandled() { let mut peer = LxmPeer::new([0; 16]); - assert_eq!(peer.unhandled_messages(), 0); + assert_eq!(peer.unhandled_message_count(), 0); - peer.add_unhandled_message(); - peer.add_unhandled_message(); - assert_eq!(peer.unhandled_messages(), 2); + peer.add_unhandled_message(&tid(1)); + peer.add_unhandled_message(&tid(1)); + peer.add_unhandled_message(&tid(2)); + assert_eq!(peer.unhandled_message_count(), 2); + + peer.add_handled_message(&tid(1)); + peer.add_unhandled_message(&tid(1)); + assert_eq!(peer.unhandled_message_count(), 1); } #[test] @@ -1096,30 +1183,31 @@ mod tests { #[test] fn test_select_sync_peer_basic() { let mut peer1 = LxmPeer::new([0x01; 16]); - peer1.add_unhandled_message(); - peer1.sync_transfer_rate = 100.0; + peer1.add_unhandled_message(&tid(1)); + peer1.alive = true; let mut peer2 = LxmPeer::new([0x02; 16]); - peer2.add_unhandled_message(); - peer2.sync_transfer_rate = 200.0; + peer2.add_unhandled_message(&tid(1)); + peer2.next_sync_attempt = f64::MAX; let peers: Vec<&LxmPeer> = vec![&peer1, &peer2]; - let selected = select_sync_peer(&peers); - assert!(selected.is_some()); - assert_eq!(selected.unwrap(), 1); + assert_eq!(select_sync_peer(&peers, 1.0), Some(0)); + peer1.alive = false; + let peers: Vec<&LxmPeer> = vec![&peer1, &peer2]; + assert_eq!(select_sync_peer(&peers, 1.0), Some(0)); } #[test] fn test_select_sync_peer_empty() { let peers: Vec<&LxmPeer> = vec![]; - assert!(select_sync_peer(&peers).is_none()); + assert!(select_sync_peer(&peers, 1.0).is_none()); } #[test] fn test_select_sync_peer_no_unhandled() { let peer = LxmPeer::new([0x01; 16]); let peers: Vec<&LxmPeer> = vec![&peer]; - assert!(select_sync_peer(&peers).is_none()); + assert!(select_sync_peer(&peers, 1.0).is_none()); } #[test] diff --git a/crates/lxmf-core/src/propagation_client.rs b/crates/lxmf-core/src/propagation_client.rs index 8242790..3f29f26 100644 --- a/crates/lxmf-core/src/propagation_client.rs +++ b/crates/lxmf-core/src/propagation_client.rs @@ -30,6 +30,7 @@ use std::time::{Duration, Instant}; use bytes::Bytes; use rns_crypto::ed25519::{Ed25519PrivateKey, Ed25519PublicKey}; use rns_link::link::{CloseReason, Link, LinkAction}; +use rns_link::stamp::{LinkRequestStamper, LinkStampPolicy}; use rns_protocol::resource::{ InboundTransfer, MAX_EFFICIENT_SIZE, MAX_RESOURCE_SIZE, MAX_SEGMENTS, MultiSegmentInbound, OutboundTransfer, RANDOM_HASH_SIZE, ResourceError, TransferAction, @@ -39,7 +40,7 @@ use rns_transport::link_messages::DestinationEvent; use rns_transport::messages::{ InterfaceId, LinkEndpointBindResult, LinkEndpointBinding, LinkEndpointLifecycleEvent, LinkEndpointRole, LinkEndpointSendResult, LinkEndpointUnbindResult, OutboundRequest, - TransportMessage, + TransportMessage, TransportQuery, TransportQueryResponse, }; use tokio::sync::{mpsc, oneshot}; @@ -55,6 +56,8 @@ use crate::types::PropagationTransientId; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum PropagationClientState { Idle, + /// Checking for, or waiting on, a path to the node before linking. + PathRequested, LinkEstablishing, LinkEstablished, /// `/get` with `[None, None]` sent. @@ -70,6 +73,8 @@ pub enum PropagationClientState { /// At least one downloaded item lacked durable local acceptance in this cycle. Partial, Complete, + /// No path to the node arrived within the path timeout. + NoPath, Failed, } @@ -227,6 +232,7 @@ pub struct PropagationClient { receiving_for: Option, identity_pub: Option<[u8; 64]>, identity_key: Option, + link_stamper: LinkRequestStamper, /// Phase 1 response: transient IDs the server has. available_messages: Vec>, /// Messages we already have locally. @@ -269,8 +275,17 @@ pub struct PropagationClient { started_at: Option, timeout: Duration, identified: bool, + path_query: Option>, + bitrate_query: Option>, + path_requested_at: Option, + path_timeout: Duration, } +/// Python `Reticulum.MINIMUM_BITRATE`. +const MINIMUM_BITRATE: u64 = 5; +/// Python `LXMRouter.PR_PATH_TIMEOUT`, in seconds. +pub const PR_PATH_TIMEOUT: u64 = 10; + impl PropagationClient { pub fn new( transport_tx: mpsc::Sender, @@ -299,6 +314,7 @@ impl PropagationClient { receiving_for: None, identity_pub, identity_key, + link_stamper: LinkRequestStamper::without_recall(LinkStampPolicy::default()), available_messages: Vec::new(), local_messages: HashSet::new(), local_message_expiry: HashMap::new(), @@ -334,9 +350,19 @@ impl PropagationClient { started_at: None, timeout: Duration::from_secs(120), identified: false, + path_query: None, + bitrate_query: None, + path_requested_at: None, + path_timeout: Duration::ZERO, } } + /// Stamp new link requests with this stamper's policy and announced costs. + /// The default stamps only when `always_stamp_lrs` is set. + pub fn set_link_request_stamper(&mut self, stamper: LinkRequestStamper) { + self.link_stamper = stamper; + } + pub fn set_propagation_node(&mut self, dest_hash: [u8; 16]) { self.outbound_propagation_node = Some(dest_hash); } @@ -548,6 +574,7 @@ impl PropagationClient { self.status.state, PropagationClientState::Complete | PropagationClientState::Partial + | PropagationClientState::NoPath | PropagationClientState::Failed ) { return false; @@ -585,6 +612,7 @@ impl PropagationClient { PropagationClientState::Idle | PropagationClientState::Complete | PropagationClientState::Partial + | PropagationClientState::NoPath | PropagationClientState::Failed ) { return false; @@ -593,6 +621,7 @@ impl PropagationClient { self.status.state, PropagationClientState::Complete | PropagationClientState::Partial + | PropagationClientState::NoPath | PropagationClientState::Failed ) { self.cleanup(); @@ -601,8 +630,126 @@ impl PropagationClient { if !self.pending_transport.is_empty() { return false; } + // LXMRouter.request_messages_from_propagation_node: link only once a path is known. + if !self.query_path(node_hash) { + return false; + } + self.status = PropagationTransferStatus { + state: PropagationClientState::PathRequested, + ..PropagationTransferStatus::default() + }; + self.max_messages = max_messages.filter(|limit| *limit > 0); + true + } - let (link, request_data) = Link::new_initiator(node_hash, 1); + fn query_path(&mut self, node_hash: [u8; 16]) -> bool { + let (response_tx, response_rx) = oneshot::channel(); + if !self.queue_transport(TransportMessage::Rpc { + query: TransportQuery::HasPath { dest: node_hash }, + response_tx, + }) { + return false; + } + self.path_query = Some(response_rx); + true + } + + /// LXMRouter.__request_messages_path_job: request a path once, wait up to + /// `max(PR_PATH_TIMEOUT, path_request_wait())`, then link or end in `NoPath`. + fn poll_path_wait(&mut self) { + if self.status.state != PropagationClientState::PathRequested { + return; + } + let Some(node_hash) = self.outbound_propagation_node else { + self.fail(); + return; + }; + if let Some(receiver) = self.bitrate_query.as_mut() { + match receiver.try_recv() { + Ok(TransportQueryResponse::InterfaceStats(interfaces)) => { + self.bitrate_query = None; + let lowest = interfaces + .iter() + .filter(|interface| interface.online && interface.bitrate > 0) + .map(|interface| interface.bitrate) + .min(); + // Transport.medium_path_timeout + if let Some(lowest) = lowest { + let medium = 2.0 + * ((rns_wire::constants::MTU * 8) as f64 + / lowest.max(MINIMUM_BITRATE) as f64) + + rns_wire::constants::DEFAULT_PER_HOP_TIMEOUT; + self.path_timeout = self.path_timeout.max(Duration::from_secs_f64(medium)); + } + } + Err(oneshot::error::TryRecvError::Empty) => {} + Ok(_) | Err(oneshot::error::TryRecvError::Closed) => self.bitrate_query = None, + } + } + let Some(receiver) = self.path_query.as_mut() else { + return; + }; + let has_path = match receiver.try_recv() { + Ok(TransportQueryResponse::BoolResult(has_path)) => has_path, + Err(oneshot::error::TryRecvError::Empty) => return, + Ok(_) | Err(oneshot::error::TryRecvError::Closed) => { + self.path_query = None; + self.fail(); + return; + } + }; + self.path_query = None; + if has_path { + self.bitrate_query = None; + self.path_requested_at = None; + if !self.establish_link(node_hash) { + self.fail(); + } + return; + } + match self.path_requested_at { + None => { + tracing::debug!( + node = %hex_encode(&node_hash), + "no path known for message download from propagation node, requesting path" + ); + if !self.queue_transport(TransportMessage::RequestPath { + destination_hash: node_hash, + }) { + self.fail(); + return; + } + let (response_tx, response_rx) = oneshot::channel(); + if self.queue_transport(TransportMessage::Rpc { + query: TransportQuery::GetInterfaceStats, + response_tx, + }) { + self.bitrate_query = Some(response_rx); + } + self.path_requested_at = Some(Instant::now()); + self.path_timeout = Duration::from_secs(PR_PATH_TIMEOUT.max(PATH_REQUEST_WAIT)); + } + Some(requested_at) if requested_at.elapsed() >= self.path_timeout => { + tracing::debug!("propagation node path request timed out"); + self.cleanup(); + self.status = PropagationTransferStatus { + state: PropagationClientState::NoPath, + ..PropagationTransferStatus::default() + }; + return; + } + Some(_) => {} + } + if !self.query_path(node_hash) { + self.fail(); + } + } + + fn establish_link(&mut self, node_hash: [u8; 16]) -> bool { + let Ok((link, request_data)) = self.link_stamper.new_initiator(node_hash, 1) else { + tracing::warn!("propagation client link request stamp generation failed"); + return false; + }; let link_id = link.link_id; if !self.queue_transport(TransportMessage::RegisterDestination { @@ -657,7 +804,6 @@ impl PropagationClient { self.endpoint_release_queued = false; self.pending_endpoint_bind = None; self.started_at = Some(Instant::now()); - self.max_messages = max_messages.filter(|limit| *limit > 0); self.identified = false; self.available_messages.clear(); self.received_messages.clear(); @@ -2016,6 +2162,7 @@ impl PropagationClient { self.cleanup(); return; } + self.poll_path_wait(); self.poll_admissions(); if let Some(started) = self.started_at @@ -2087,7 +2234,7 @@ impl PropagationClient { } match self.status.state { - PropagationClientState::Idle => {} + PropagationClientState::Idle | PropagationClientState::PathRequested => {} PropagationClientState::LinkEstablishing => {} PropagationClientState::LinkEstablished => { if !self.identified { @@ -2106,6 +2253,7 @@ impl PropagationClient { | PropagationClientState::AwaitingAdmission => {} PropagationClientState::Complete | PropagationClientState::Partial + | PropagationClientState::NoPath | PropagationClientState::Failed => { self.cleanup(); } @@ -2573,6 +2721,9 @@ impl PropagationClient { fn cleanup(&mut self) { self.link_request_result = None; + self.path_query = None; + self.bitrate_query = None; + self.path_requested_at = None; self.pending_transport .retain(|message| !matches!(message, TransportMessage::SendLinkRequest { .. })); self.revoke_admissions(); @@ -2786,7 +2937,7 @@ mod tests { let mut client = PropagationClient::new(tx, None, None); client.set_propagation_node([0xBB; 16]); - assert!(client.start_download()); + start_with_path(&mut client, &mut rx); assert_eq!( client.status.state, PropagationClientState::LinkEstablishing @@ -2805,6 +2956,84 @@ mod tests { )); } + fn start_with_path(client: &mut PropagationClient, rx: &mut mpsc::Receiver) { + assert!(client.start_download()); + answer_path_query(rx, true); + client.tick(); + } + + fn answer_path_query(rx: &mut mpsc::Receiver, has_path: bool) -> bool { + let mut requested_path = false; + while let Ok(message) = rx.try_recv() { + match message { + TransportMessage::Rpc { + query: TransportQuery::HasPath { .. }, + response_tx, + } => { + let _ = response_tx.send(TransportQueryResponse::BoolResult(has_path)); + } + TransportMessage::Rpc { + query: TransportQuery::GetInterfaceStats, + response_tx, + } => { + let _ = response_tx.send(TransportQueryResponse::InterfaceStats(Vec::new())); + } + TransportMessage::RequestPath { .. } => requested_path = true, + TransportMessage::SendLinkRequest { .. } => panic!("link request without a path"), + _ => {} + } + } + requested_path + } + + #[test] + fn download_waits_for_a_node_path_before_linking() { + let (tx, mut rx) = mpsc::channel(64); + let mut client = PropagationClient::new(tx, None, None); + client.set_propagation_node([0xB6; 16]); + assert!(client.start_download()); + assert_eq!(client.state(), PropagationClientState::PathRequested); + assert!(!answer_path_query(&mut rx, false)); + client.tick(); + assert!( + answer_path_query(&mut rx, false), + "missing path is requested" + ); + client.tick(); + assert!(!answer_path_query(&mut rx, true), "path is requested once"); + assert_eq!(client.state(), PropagationClientState::PathRequested); + client.tick(); + assert_eq!(client.state(), PropagationClientState::LinkEstablishing); + assert!(matches!( + rx.try_recv().unwrap(), + TransportMessage::RegisterDestination { .. } + )); + assert!(matches!( + rx.try_recv().unwrap(), + TransportMessage::SendLinkRequest { .. } + )); + + let (tx, mut rx) = mpsc::channel(64); + let mut client = PropagationClient::new(tx, None, None); + client.set_propagation_node([0xB7; 16]); + assert!(client.start_download()); + answer_path_query(&mut rx, false); + client.tick(); + assert!(answer_path_query(&mut rx, false)); + client.tick(); + assert_eq!( + client.path_timeout, + Duration::from_secs(PR_PATH_TIMEOUT.max(PATH_REQUEST_WAIT)) + ); + client.path_requested_at = Some(ago_or_skip!(client.path_timeout)); + answer_path_query(&mut rx, false); + client.tick(); + assert_eq!(client.state(), PropagationClientState::NoPath); + assert!(client.link.is_none()); + assert!(client.acknowledge_transfer()); + assert!(client.start_download(), "a later cycle may retry"); + } + #[test] fn start_download_rejects_a_closed_transport_instead_of_false_success() { let (tx, rx) = mpsc::channel(1); @@ -2827,12 +3056,15 @@ mod tests { client.set_propagation_node([0xB2; 16]); assert!(client.start_download()); - assert_eq!(client.pending_transport.len(), 2); + assert_eq!(client.pending_transport.len(), 1); assert!(matches!( rx.try_recv().unwrap(), TransportMessage::DeregisterDestination { .. } )); client.tick(); + answer_path_query(&mut rx, true); + client.tick(); + assert_eq!(client.pending_transport.len(), 1); assert!(matches!( rx.try_recv().unwrap(), TransportMessage::RegisterDestination { .. } @@ -2896,7 +3128,7 @@ mod tests { let mut client = PropagationClient::new(tx, None, None); client.set_propagation_node([0xBC; 16]); - assert!(client.start_download()); + start_with_path(&mut client, &mut rx); while rx.try_recv().is_ok() {} assert!(!client.start_download()); @@ -3400,10 +3632,10 @@ mod tests { #[test] fn test_timeout_fails() { - let (tx, _rx) = mpsc::channel(64); + let (tx, mut rx) = mpsc::channel(64); let mut client = PropagationClient::new(tx, None, None); client.set_propagation_node([0xCC; 16]); - client.start_download(); + start_with_path(&mut client, &mut rx); assert_eq!( client.status.state, PropagationClientState::LinkEstablishing @@ -3442,7 +3674,7 @@ mod tests { let (tx, mut rx) = mpsc::channel(64); let mut client = PropagationClient::new(tx, None, None); client.set_propagation_node([0xDD; 16]); - client.start_download(); + start_with_path(&mut client, &mut rx); while rx.try_recv().is_ok() {} client.status.state = PropagationClientState::Complete; diff --git a/crates/lxmf-core/src/propagation_node.rs b/crates/lxmf-core/src/propagation_node.rs index 7fef243..9d43a82 100644 --- a/crates/lxmf-core/src/propagation_node.rs +++ b/crates/lxmf-core/src/propagation_node.rs @@ -414,6 +414,13 @@ impl ValidatedOpaquePropagationBlob { pub fn transient_id(&self) -> PropagationTransientId { self.transient_id } + /// Stored image length: message data plus the 32-byte stamp. + pub fn len(&self) -> usize { + self.bytes.len() + } + pub fn is_empty(&self) -> bool { + self.bytes.is_empty() + } pub fn stamp_value(&self) -> f64 { self.stamp_value } @@ -551,6 +558,8 @@ pub(crate) struct PreparedSyncOffer { pub generation: u64, pub selected_ids: Vec, pub terminal_handled_ids: Vec, + /// Below the peer's stamp requirement: dropped from its unhandled set only. + pub dropped_unhandled_ids: Vec, pub generation_exhausted: bool, } @@ -560,6 +569,7 @@ pub(crate) enum InstallPreparedSyncOffer { offer: SyncOffer, generation: u64, terminal_handled_ids: Vec, + dropped_unhandled_ids: Vec, generation_exhausted: bool, }, Stale, @@ -590,6 +600,9 @@ pub(crate) fn prepare_sync_offer_snapshot( } let mut candidates = snapshot.candidates; + if let Some(unhandled) = snapshot.policy.unhandled_messages.as_ref() { + candidates.retain(|candidate| unhandled.contains(&candidate.transient_id)); + } candidates.sort_by(|left, right| { left.weight .total_cmp(&right.weight) @@ -599,13 +612,14 @@ pub(crate) fn prepare_sync_offer_snapshot( let mut cumulative_size = INITIAL_STRUCTURE_OVERHEAD; let mut selected_ids = Vec::new(); let mut terminal_handled_ids = Vec::new(); + let mut dropped_unhandled_ids = Vec::new(); let mut cumulative_deferred = false; for candidate in candidates { if handled_messages.contains(&candidate.transient_id) { continue; } if candidate.stamp_value < snapshot.policy.minimum_stamp_cost { - terminal_handled_ids.push(candidate.transient_id); + dropped_unhandled_ids.push(candidate.transient_id); continue; } @@ -638,6 +652,7 @@ pub(crate) fn prepare_sync_offer_snapshot( generation: snapshot.generation, selected_ids, terminal_handled_ids, + dropped_unhandled_ids, generation_exhausted, } } @@ -1150,20 +1165,15 @@ impl PropagationNode { .count() } - /// Count live store entries not yet handled by one peer. The daemon's - /// generation scheduler does not maintain `LxmPeer`'s legacy cached - /// unhandled counter, so control status must derive this from the same - /// authoritative store used to prepare offers. + /// Count a peer's queued messages that are still live in the store, as + /// Python derives `unhandled_message_count` from `propagation_entries`. pub fn unhandled_message_count( &self, - handled_messages: &HashSet, + unhandled_messages: &HashSet, ) -> usize { - self.store - .entries() - .filter(|entry| { - self.eligible(&entry.transient_id) - && !handled_messages.contains(&entry.transient_id) - }) + unhandled_messages + .iter() + .filter(|id| self.contains(id)) .count() } @@ -1572,6 +1582,7 @@ impl PropagationNode { offer, generation: prepared.generation, terminal_handled_ids: prepared.terminal_handled_ids, + dropped_unhandled_ids: prepared.dropped_unhandled_ids, generation_exhausted: prepared.generation_exhausted, } } @@ -1595,13 +1606,18 @@ impl PropagationNode { InstallPreparedSyncOffer::Installed { offer, terminal_handled_ids, + dropped_unhandled_ids, .. } => { // Compatibility wrapper: production uses the staged task // path and exposes this delta to the daemon for off-loop // persistence. - if !terminal_handled_ids.is_empty() - && let Err(error) = self.persist_peer_handled(policy, &terminal_handled_ids) + if (!terminal_handled_ids.is_empty() || !dropped_unhandled_ids.is_empty()) + && let Err(error) = self.persist_peer_offer_dispositions( + policy, + &terminal_handled_ids, + &dropped_unhandled_ids, + ) { tracing::warn!(%error, "failed to persist terminal offer dispositions"); } @@ -1681,14 +1697,28 @@ impl PropagationNode { &self, policy: &OutboundOfferPolicy, transient_ids: &[PropagationTransientId], + ) -> std::io::Result<()> { + self.persist_peer_offer_dispositions(policy, transient_ids, &[]) + } + + /// Like [`Self::persist_peer_handled`], also dropping `dropped_ids` from + /// the peer's unhandled set without marking them handled. + pub fn persist_peer_offer_dispositions( + &self, + policy: &OutboundOfferPolicy, + handled_ids: &[PropagationTransientId], + dropped_ids: &[PropagationTransientId], ) -> std::io::Result<()> { let mut peer = self .load_peer(&policy.peer_hash) .unwrap_or_else(|| policy.to_peer()); policy.apply_to_peer(&mut peer); - for transient_id in transient_ids { + for transient_id in handled_ids { peer.add_handled_message(transient_id); } + for transient_id in dropped_ids { + peer.remove_unhandled_message(transient_id); + } self.save_peer(&peer) } @@ -1704,8 +1734,21 @@ impl PropagationNode { let filename = format!("{}.peer", hex_encode(peer_hash)); let path = dir.join(filename); let data = std::fs::read(&path).ok()?; - let mut peer = LxmPeer::from_bytes_with_handled(&data)?; + self.decode_peer(&data) + } + + fn decode_peer(&self, data: &[u8]) -> Option { + let (mut peer, legacy) = LxmPeer::decode_stored(data)?; self.prune_handled_against_store(&mut peer); + if legacy { + // Older records offered every unhandled entry; keep that queue. + peer.unhandled_messages = self + .store + .entries() + .map(|entry| entry.transient_id) + .filter(|id| self.eligible(id) && !peer.handled_messages.contains(id)) + .collect(); + } Some(peer) } @@ -1721,9 +1764,8 @@ impl PropagationNode { let path = entry.path(); if path.extension().map(|e| e == "peer").unwrap_or(false) && let Ok(data) = std::fs::read(&path) - && let Some(mut peer) = LxmPeer::from_bytes_with_handled(&data) + && let Some(peer) = self.decode_peer(&data) { - self.prune_handled_against_store(&mut peer); peers.push(peer); } } @@ -1738,6 +1780,7 @@ impl PropagationNode { /// Files converge lazily: the next `mark_peer_handled` saves the pruned set. fn prune_handled_against_store(&self, peer: &mut LxmPeer) { peer.handled_messages.retain(|id| self.contains(id)); + peer.unhandled_messages.retain(|id| self.contains(id)); } } @@ -2051,16 +2094,17 @@ pub(crate) mod tests { } #[test] - fn unhandled_count_is_derived_from_live_store_and_peer_handled_set() { + fn unhandled_count_covers_only_queued_ids_still_in_the_store() { let mut node = durable_test_node(PropagationNodeConfig::default(), [0xAA; 16]); let msg = make_signed_message([0xBB; 16], [0xCC; 16], "Test", "content"); let transient_id = msg.transient_id.or(msg.hash).unwrap(); assert!(node.accept_fixture(&msg)); - let mut handled = HashSet::new(); - assert_eq!(node.unhandled_message_count(&handled), 1); - handled.insert(transient_id); - assert_eq!(node.unhandled_message_count(&handled), 0); + let mut unhandled = HashSet::new(); + assert_eq!(node.unhandled_message_count(&unhandled), 0); + unhandled.insert(transient_id); + unhandled.insert(tid(0x77)); + assert_eq!(node.unhandled_message_count(&unhandled), 1); } #[test] @@ -2174,7 +2218,7 @@ pub(crate) mod tests { #[test] fn prepared_offer_distinguishes_terminal_filters_from_cumulative_deferral() { let mut node = durable_test_node(PropagationNodeConfig::default(), [0xAA; 16]); - insert_offer_entry(&mut node, tid(0x01), 10, 9.0); // terminal low stamp + insert_offer_entry(&mut node, tid(0x01), 10, 9.0); // low stamp: dropped, not handled insert_offer_entry(&mut node, tid(0x02), 100, 20.0); // selected insert_offer_entry(&mut node, tid(0x03), 100, 20.0); // cumulative deferred insert_offer_entry(&mut node, tid(0x04), 1000, 20.0); // terminal oversize @@ -2186,7 +2230,8 @@ pub(crate) mod tests { let prepared = prepare_sync_offer_snapshot(node.snapshot_sync_offer_preparation(&policy)); assert_eq!(prepared.selected_ids, vec![tid(0x02)]); - assert_eq!(prepared.terminal_handled_ids, vec![tid(0x01), tid(0x04)]); + assert_eq!(prepared.terminal_handled_ids, vec![tid(0x04)]); + assert_eq!(prepared.dropped_unhandled_ids, vec![tid(0x01)]); assert!( !prepared.generation_exhausted, "cumulative-only skips must stay pending for another batch" diff --git a/crates/lxmf-core/src/propagation_sync.rs b/crates/lxmf-core/src/propagation_sync.rs index 3d77815..9675f30 100644 --- a/crates/lxmf-core/src/propagation_sync.rs +++ b/crates/lxmf-core/src/propagation_sync.rs @@ -20,6 +20,7 @@ use std::time::{Duration, Instant}; use bytes::Bytes; use rns_crypto::ed25519::{Ed25519PrivateKey, Ed25519PublicKey}; use rns_link::link::{CloseReason, Link, LinkAction}; +use rns_link::stamp::{LinkRequestStamper, LinkStampPolicy}; use rns_protocol::resource::{ MAX_EFFICIENT_SIZE, MultiSegmentOutbound, OutboundTransfer, ResourceError, TransferAction, }; @@ -27,12 +28,12 @@ use rns_transport::link_messages::DestinationEvent; use rns_transport::messages::{ InterfaceId, LinkEndpointBindResult, LinkEndpointBinding, LinkEndpointLifecycleEvent, LinkEndpointRole, LinkEndpointSendResult, LinkEndpointUnbindResult, OutboundRequest, - TransportMessage, + TransportMessage, TransportQuery, TransportQueryResponse, }; use tokio::sync::mpsc::error::TrySendError; use tokio::sync::{mpsc, oneshot}; -use crate::constants::OFFER_REQUEST_PATH; +use crate::constants::{OFFER_REQUEST_PATH, PATH_REQUEST_GRACE}; use crate::peer::{LxmPeer, OutboundOfferPolicy}; use crate::propagation::hex_encode; use crate::propagation_node::{ @@ -45,17 +46,23 @@ use crate::types::PropagationTransientId; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SyncTaskState { Idle, + /// Checking for, or waiting on, a path to the peer before linking. + PathRequested, Establishing, Offering, AwaitingResponse, Transferring, Complete, + /// No path to the peer arrived within the path request grace. + NoPath, Failed, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum PeerSyncTerminalState { Complete, + /// The path request was not answered; no link was attempted. + NoPath, Failed, } @@ -166,9 +173,11 @@ pub struct PropagationSyncTask { offer_preparation_rx: Option>, ready_prepared_offer: Option, handled_updates: Vec, + dropped_unhandled_updates: Vec, runtime_handle: Option, identity_pub: Option<[u8; 64]>, identity_key: Option, + link_stamper: LinkRequestStamper, active_offer_generation: Option, generation_exhausted: bool, terminal_result: Option, @@ -180,6 +189,8 @@ pub struct PropagationSyncTask { transfer_wire_size: u64, transfer_started: Option, link_establishment_rate: Option, + path_query: Option>, + path_requested_at: Option, } impl PropagationSyncTask { @@ -220,9 +231,11 @@ impl PropagationSyncTask { offer_preparation_rx: None, ready_prepared_offer: None, handled_updates: Vec::new(), + dropped_unhandled_updates: Vec::new(), runtime_handle: tokio::runtime::Handle::try_current().ok(), identity_pub: None, identity_key: None, + link_stamper: LinkRequestStamper::without_recall(LinkStampPolicy::default()), active_offer_generation: None, generation_exhausted: false, terminal_result: None, @@ -234,6 +247,8 @@ impl PropagationSyncTask { transfer_wire_size: 0, transfer_started: None, link_establishment_rate: None, + path_query: None, + path_requested_at: None, } } @@ -282,9 +297,11 @@ impl PropagationSyncTask { offer_preparation_rx: None, ready_prepared_offer: None, handled_updates: Vec::new(), + dropped_unhandled_updates: Vec::new(), runtime_handle: tokio::runtime::Handle::try_current().ok(), identity_pub: None, identity_key: None, + link_stamper: LinkRequestStamper::without_recall(LinkStampPolicy::default()), active_offer_generation: None, generation_exhausted: false, terminal_result: None, @@ -296,6 +313,8 @@ impl PropagationSyncTask { transfer_wire_size: 0, transfer_started: None, link_establishment_rate: None, + path_query: None, + path_requested_at: None, }) } @@ -338,9 +357,11 @@ impl PropagationSyncTask { offer_preparation_rx: None, ready_prepared_offer: None, handled_updates: Vec::new(), + dropped_unhandled_updates: Vec::new(), runtime_handle: tokio::runtime::Handle::try_current().ok(), identity_pub: None, identity_key: None, + link_stamper: LinkRequestStamper::without_recall(LinkStampPolicy::default()), active_offer_generation: None, generation_exhausted: false, terminal_result: None, @@ -352,6 +373,8 @@ impl PropagationSyncTask { transfer_wire_size: 0, transfer_started: None, link_establishment_rate: None, + path_query: None, + path_requested_at: None, } } @@ -375,7 +398,7 @@ impl PropagationSyncTask { } self.node_dest_hash = Some(dest_hash); self.offer_policy = None; - if !self.start_sync(dest_hash) { + if !self.begin_attempt(dest_hash) { return false; } self.last_sync = Instant::now(); @@ -392,13 +415,19 @@ impl PropagationSyncTask { let dest_hash = policy.peer_hash; self.node_dest_hash = Some(dest_hash); self.offer_policy = Some(policy); - if !self.start_sync(dest_hash) { + if !self.begin_attempt(dest_hash) { return false; } self.last_sync = Instant::now(); true } + /// Stamp new link requests with this stamper's policy and announced costs. + /// The default stamps only when `always_stamp_lrs` is set. + pub fn set_link_request_stamper(&mut self, stamper: LinkRequestStamper) { + self.link_stamper = stamper; + } + /// Configure the local identity used for Link identification. Production /// peer sync must set this before requesting a sync; compatibility callers /// without identity material retain the historical unidentified behavior. @@ -414,6 +443,12 @@ impl PropagationSyncTask { std::mem::take(&mut self.handled_updates) } + /// Drain IDs that offer preparation dropped from the peer's unhandled set + /// for an insufficient stamp value. They are not handled by the peer. + pub fn take_dropped_unhandled_updates(&mut self) -> Vec { + std::mem::take(&mut self.dropped_unhandled_updates) + } + pub fn take_terminal_peer_result(&mut self) -> Option { self.terminal_result.take() } @@ -452,6 +487,7 @@ impl PropagationSyncTask { self.active_offer_generation = None; self.generation_exhausted = false; self.handled_updates.clear(); + self.dropped_unhandled_updates.clear(); self.terminal_result = None; self.reset_attempt_accounting(); self.state = SyncTaskState::Idle; @@ -629,8 +665,10 @@ impl PropagationSyncTask { self.state = SyncTaskState::Failed; return; } - let establishment_rate = - self.link.as_ref().and_then(|link| link.establishment_rate); + let establishment_rate = self + .link + .as_ref() + .and_then(|link| link.get_establishment_rate()); self.link_establishment_rate = establishment_rate; if let (Some(peer), Some(link_id)) = (self.peer.as_mut(), self.link_id) { peer.link_established(link_id, establishment_rate); @@ -1148,14 +1186,21 @@ impl PropagationSyncTask { } if !self.pending_transport.is_empty() - && !matches!(self.state, SyncTaskState::Complete | SyncTaskState::Failed) + && !matches!( + self.state, + SyncTaskState::Complete | SyncTaskState::NoPath | SyncTaskState::Failed + ) { return; } if !matches!( self.state, - SyncTaskState::Idle | SyncTaskState::Complete | SyncTaskState::Failed + SyncTaskState::Idle + | SyncTaskState::PathRequested + | SyncTaskState::Complete + | SyncTaskState::NoPath + | SyncTaskState::Failed ) { self.drive_link_watchdog(); } @@ -1168,12 +1213,13 @@ impl PropagationSyncTask { && let Some(node_hash) = self.node_dest_hash { if self.message_count() > 0 { - let _ = self.start_sync(node_hash); + let _ = self.begin_attempt(node_hash); } else { self.last_sync = Instant::now(); } } } + SyncTaskState::PathRequested => self.poll_path_wait(), SyncTaskState::Establishing | SyncTaskState::AwaitingResponse => {} SyncTaskState::Offering => { self.send_offer_request(); @@ -1181,17 +1227,17 @@ impl PropagationSyncTask { SyncTaskState::Transferring => { self.drive_transfers(); } - SyncTaskState::Complete | SyncTaskState::Failed => { + SyncTaskState::Complete | SyncTaskState::NoPath | SyncTaskState::Failed => { if self.terminal_result.is_none() && let Some(peer_hash) = self.node_dest_hash { let complete = self.state == SyncTaskState::Complete; self.terminal_result = Some(PeerSyncTerminalResult { peer_hash, - state: if complete { - PeerSyncTerminalState::Complete - } else { - PeerSyncTerminalState::Failed + state: match self.state { + SyncTaskState::Complete => PeerSyncTerminalState::Complete, + SyncTaskState::NoPath => PeerSyncTerminalState::NoPath, + _ => PeerSyncTerminalState::Failed, }, offer_generation: complete .then_some(self.active_offer_generation) @@ -1342,11 +1388,20 @@ impl PropagationSyncTask { offer, generation, terminal_handled_ids, + dropped_unhandled_ids, generation_exhausted, } => { self.active_offer_generation = Some(generation); self.generation_exhausted = generation_exhausted; self.record_handled_updates(&terminal_handled_ids); + for transient_id in dropped_unhandled_ids { + if !self.dropped_unhandled_updates.contains(&transient_id) { + self.dropped_unhandled_updates.push(transient_id); + } + if let Some(peer) = self.peer.as_mut() { + peer.remove_unhandled_message(&transient_id); + } + } if offer.transient_ids.is_empty() && let Ok(mut node) = self.propagation_node.lock() { @@ -1423,6 +1478,80 @@ impl PropagationSyncTask { } } + /// LXMPeer.sync: link only once a path is known. + fn begin_attempt(&mut self, node_hash: [u8; 16]) -> bool { + self.path_requested_at = None; + if !self.query_path(node_hash) { + self.state = SyncTaskState::Failed; + return false; + } + self.state = SyncTaskState::PathRequested; + true + } + + fn query_path(&mut self, node_hash: [u8; 16]) -> bool { + let (response_tx, response_rx) = oneshot::channel(); + if !self.queue_transport(TransportMessage::Rpc { + query: TransportQuery::HasPath { dest: node_hash }, + response_tx, + }) { + return false; + } + self.path_query = Some(response_rx); + true + } + + /// Without a path, request one, check again after `PATH_REQUEST_GRACE`, + /// and end in `NoPath` if it is still missing. + fn poll_path_wait(&mut self) { + let Some(node_hash) = self.node_dest_hash else { + self.state = SyncTaskState::Failed; + return; + }; + if let Some(receiver) = self.path_query.as_mut() { + let has_path = match receiver.try_recv() { + Ok(TransportQueryResponse::BoolResult(has_path)) => has_path, + Err(oneshot::error::TryRecvError::Empty) => return, + Ok(_) | Err(oneshot::error::TryRecvError::Closed) => { + self.path_query = None; + self.state = SyncTaskState::Failed; + return; + } + }; + self.path_query = None; + if has_path { + self.path_requested_at = None; + let _ = self.start_sync(node_hash); + return; + } + if self.path_requested_at.is_some() { + tracing::debug!( + peer = %hex_encode(&node_hash), + "path request was not answered, retrying sync with peer later" + ); + self.path_requested_at = None; + self.state = SyncTaskState::NoPath; + return; + } + tracing::debug!(peer = %hex_encode(&node_hash), "no path to peer exists, requesting"); + if !self.queue_transport(TransportMessage::RequestPath { + destination_hash: node_hash, + }) { + self.state = SyncTaskState::Failed; + return; + } + self.path_requested_at = Some(Instant::now()); + return; + } + if self + .path_requested_at + .is_some_and(|requested| requested.elapsed().as_secs_f64() >= PATH_REQUEST_GRACE) + && !self.query_path(node_hash) + { + self.state = SyncTaskState::Failed; + } + } + fn start_sync(&mut self, node_hash: [u8; 16]) -> bool { self.pending_transport.clear(); self.preserve_pending_on_cleanup = false; @@ -1437,7 +1566,11 @@ impl PropagationSyncTask { self.active_transfer_ids.clear(); self.active_offer_generation = None; self.generation_exhausted = false; - let (link, request_data) = Link::new_initiator(node_hash, 1); + let Ok((link, request_data)) = self.link_stamper.new_initiator(node_hash, 1) else { + tracing::warn!("propagation sync link request stamp generation failed"); + self.state = SyncTaskState::Failed; + return false; + }; let link_id = link.link_id; self.link = Some(link); @@ -1771,6 +1904,8 @@ impl PropagationSyncTask { /// Python LXMPeer.py:540-542. fn cleanup_sync(&mut self) { self.link_request_result = None; + self.path_query = None; + self.path_requested_at = None; self.pending_transport .retain(|message| !matches!(message, TransportMessage::SendLinkRequest { .. })); // No transfer packet should survive the attempt it belongs to. The @@ -2341,6 +2476,72 @@ mod tests { task.last_sync = Instant::now(); } + /// Answer queued path queries, then tick; returns whether a path was requested. + fn answer_sync_path( + task: &mut PropagationSyncTask, + rx: &mut mpsc::Receiver, + has_path: bool, + ) -> bool { + let mut requested_path = false; + while let Ok(message) = rx.try_recv() { + match message { + TransportMessage::Rpc { + query: TransportQuery::HasPath { .. }, + response_tx, + } => { + let _ = response_tx.send(TransportQueryResponse::BoolResult(has_path)); + } + TransportMessage::RequestPath { .. } => requested_path = true, + TransportMessage::SendLinkRequest { .. } => panic!("link request without a path"), + _ => {} + } + } + task.tick(); + requested_path + } + + #[test] + fn peer_sync_waits_for_a_peer_path_before_linking() { + let (tx, mut rx) = mpsc::channel(64); + let mut task = test_task(tx, [0xAA; 16]); + assert!(task.request_sync_now([0xB6; 16])); + assert_eq!(task.state, SyncTaskState::PathRequested); + assert!(!answer_sync_path(&mut task, &mut rx, false)); + assert!( + answer_sync_path(&mut task, &mut rx, false), + "missing path is requested" + ); + assert_eq!(task.state, SyncTaskState::PathRequested); + task.path_requested_at = Some(ago_or_skip!(Duration::from_secs_f64(PATH_REQUEST_GRACE))); + task.tick(); + assert!( + !answer_sync_path(&mut task, &mut rx, true), + "path is requested once" + ); + assert_eq!(task.state, SyncTaskState::Establishing); + assert!(matches!( + rx.try_recv().unwrap(), + TransportMessage::RegisterDestination { .. } + )); + + let (tx, mut rx) = mpsc::channel(64); + let mut task = test_task(tx, [0xAA; 16]); + assert!(task.request_sync_now([0xB7; 16])); + answer_sync_path(&mut task, &mut rx, false); + assert!(answer_sync_path(&mut task, &mut rx, false)); + task.path_requested_at = Some(ago_or_skip!(Duration::from_secs_f64(PATH_REQUEST_GRACE))); + task.tick(); + answer_sync_path(&mut task, &mut rx, false); + assert_eq!(task.state, SyncTaskState::NoPath); + task.tick(); + assert_eq!(task.state, SyncTaskState::Idle); + assert!(task.link_id.is_none()); + assert_eq!( + task.take_terminal_peer_result().unwrap().state, + PeerSyncTerminalState::NoPath + ); + } + #[test] fn test_sync_task_creation() { let (tx, _rx) = mpsc::channel(16); @@ -2405,6 +2606,7 @@ mod tests { assert_eq!(task.message_count(), 1); task.tick(); + answer_sync_path(&mut task, &mut rx, true); assert_eq!(task.state, SyncTaskState::Establishing); assert!(matches!( rx.try_recv().unwrap(), @@ -2449,6 +2651,7 @@ mod tests { task.accept_fixture(&msg); task.tick(); + answer_sync_path(&mut task, &mut rx, true); assert_eq!(task.state, SyncTaskState::Establishing); assert!(task.link_id.is_some()); @@ -2466,7 +2669,7 @@ mod tests { #[test] fn test_sync_timeout() { - let (tx, _rx) = mpsc::channel(64); + let (tx, mut rx) = mpsc::channel(64); let mut task = test_task(tx, [0xAA; 16]); task.set_node([0xBB; 16]); make_sync_due(&mut task); @@ -2483,6 +2686,7 @@ mod tests { task.accept_fixture(&msg); task.tick(); + answer_sync_path(&mut task, &mut rx, true); assert_eq!(task.state, SyncTaskState::Establishing); task.sync_timeout = Duration::ZERO; @@ -2571,10 +2775,11 @@ mod tests { let mut task = test_task(tx, [0xAA; 16]); assert!(task.request_sync_now([0xBB; 16])); - assert_eq!(task.pending_transport.len(), 2); + assert_eq!(task.pending_transport.len(), 1); let _blocker = rx.try_recv().unwrap(); task.tick(); + answer_sync_path(&mut task, &mut rx, true); assert!(matches!( rx.try_recv().unwrap(), TransportMessage::RegisterDestination { .. } @@ -2709,6 +2914,7 @@ mod tests { task.accept_fixture(&msg); task.tick(); + answer_sync_path(&mut task, &mut rx, true); while let Ok(message) = rx.try_recv() { if let TransportMessage::SendLinkRequest { result_tx, .. } = message { let _ = result_tx.send(Ok(())); @@ -2943,14 +3149,14 @@ mod tests { task.send_offer_request(); - let mut updates = task.take_handled_updates(); - updates.sort(); - let mut expected = vec![ - rns_crypto::sha::full_hash(&low), - rns_crypto::sha::full_hash(&oversized), - ]; - expected.sort(); - assert_eq!(updates, expected); + assert_eq!( + task.take_handled_updates(), + vec![rns_crypto::sha::full_hash(&oversized)] + ); + assert_eq!( + task.take_dropped_unhandled_updates(), + vec![rns_crypto::sha::full_hash(&low)] + ); assert_eq!(task.state, SyncTaskState::Complete); assert!(task.generation_exhausted); assert!(rx.try_recv().is_err()); @@ -3254,7 +3460,7 @@ mod tests { #[test] fn test_peer_created_on_sync_start() { - let (tx, _rx) = mpsc::channel(64); + let (tx, mut rx) = mpsc::channel(64); let mut task = test_task(tx, [0xAA; 16]); task.set_node([0xBB; 16]); make_sync_due(&mut task); @@ -3273,6 +3479,7 @@ mod tests { task.accept_fixture(&msg); task.tick(); + answer_sync_path(&mut task, &mut rx, true); assert_eq!(task.state, SyncTaskState::Establishing); let peer = task.peer().expect("peer should exist after sync start"); @@ -3282,10 +3489,11 @@ mod tests { #[test] fn request_sync_now_starts_without_waiting_for_interval() { - let (tx, _rx) = mpsc::channel(64); + let (tx, mut rx) = mpsc::channel(64); let mut task = test_task(tx, [0xAA; 16]); task.request_sync_now([0xBB; 16]); + answer_sync_path(&mut task, &mut rx, true); assert_eq!(task.node_dest_hash(), Some([0xBB; 16])); assert_eq!(task.state, SyncTaskState::Establishing); @@ -3439,6 +3647,11 @@ mod tests { }; result_tx.send(LinkEndpointBindResult::Bound).unwrap(); task.poll_endpoint_control(); + // Python stores Link.get_establishment_rate(), in bits per second. + let bits = task.link.as_ref().unwrap().get_establishment_rate(); + assert!(bits.is_some_and(|rate| rate > 0.0)); + assert_eq!(task.link_establishment_rate, bits); + assert_eq!(task.peer().unwrap().link_establishment_rate, bits.unwrap()); task.send_offer_request(); let mut contexts = Vec::new(); @@ -3477,6 +3690,7 @@ mod tests { task.accept_fixture(&msg); task.tick(); + answer_sync_path(&mut task, &mut rx, true); while rx.try_recv().is_ok() {} assert!(task.peer().is_some()); diff --git a/crates/lxmf-core/src/router.rs b/crates/lxmf-core/src/router.rs index 4d2710b..d1b242c 100644 --- a/crates/lxmf-core/src/router.rs +++ b/crates/lxmf-core/src/router.rs @@ -21,7 +21,7 @@ use crate::message::{ LxMessage, LxMessageDraft, MessageError, MessageMetadata, RecipientStamp, ResumableLxMessage, SignedLxMessage, VerifiedLxMessage, }; -use crate::peer::{LxmPeer, OutboundOfferPolicy}; +use crate::peer::LxmPeer; use crate::propagation::PropagationStore; use crate::propagation_client::PropagationTransferStatus; use crate::stamper; @@ -1429,55 +1429,52 @@ impl LxmRouter { self.state_snapshot().save_state(state_dir) } - /// Return peer destination hashes that are due for sync and mark each as - /// `LinkEstablishing` so concurrent calls don't double-schedule. - /// - /// Python's `LXMRouter.sync_peers()` drives network I/O directly; in Rust - /// network I/O lives outside the router, so callers (e.g. `lxmd`) feed this - /// list into whatever sync task manages link establishment. - pub fn sync_peers(&mut self) -> Vec<[u8; 16]> { - let mut due = Vec::new(); - for (hash, peer) in self.peers.iter_mut() { - if peer.alive - && peer.state == PeerState::Idle - && peer.unhandled_messages() > 0 - && peer.should_sync() - { - peer.begin_sync(); - due.push(*hash); - } + /// One peer-sync job pass of Python `LXMRouter.sync_peers()`: remove + /// non-static peers unreachable for [`MAX_UNREACHABLE`] and choose at most + /// one peer to sync. Peers that conclusively processed the current store + /// generation are skipped. The caller performs the sync attempt and + /// deletes persisted state for the culled peers. + pub fn sync_peers(&mut self, now: f64, offer_generation: u64) -> PeerSyncPass { + let culled: Vec<[u8; 16]> = self + .peers + .iter() + .filter(|(hash, peer)| { + peer.unreachable_too_long(now) && !self.static_peers.contains(hash) + }) + .map(|(hash, _)| *hash) + .collect(); + for hash in &culled { + self.peers.remove(hash); } - due - } - - /// Return authoritative policies for peers that have not processed the - /// current propagation-store generation. Prefers eligible alive peers; if - /// none are alive, returns eligible unresponsive peers. Snapshots clone peer - /// policy/handled-ID state and are sorted by peer hash. Exact message - /// eligibility is checked during offer preparation. - /// - /// The method does not mutate peer state, allowing a single shared sync - /// task to accept one policy before the daemon marks that peer started. - pub fn sync_peer_policies_for_store(&self, offer_generation: u64) -> Vec { - let eligible = self + let candidates: Vec<&LxmPeer> = self .peers .values() + // A long-unreachable static peer is kept but not synced. .filter(|peer| { - peer.state == PeerState::Idle - && peer.should_sync() - && peer.needs_offer_generation(offer_generation) + !peer.unreachable_too_long(now) && peer.needs_offer_generation(offer_generation) }) - .collect::>(); - let has_alive = eligible.iter().any(|peer| peer.alive); - let mut policies = eligible - .into_iter() - .filter(|peer| peer.alive == has_alive) - .map(OutboundOfferPolicy::from) - .collect::>(); - policies.sort_by_key(|policy| policy.peer_hash); - policies + .collect(); + let selected = crate::peer::select_sync_peer(&candidates, now) + .map(|index| candidates[index].destination_hash); + PeerSyncPass { culled, selected } } + /// Python `flush_peer_distribution_queue()`: queue each newly stored + /// message for every current peer except the one it came from. + pub fn flush_peer_distribution( + &mut self, + entries: &[(PropagationTransientId, Option<[u8; 16]>)], + ) { + for (peer_hash, peer) in self.peers.iter_mut() { + for (transient_id, from_peer) in entries { + if *from_peer != Some(*peer_hash) { + peer.add_unhandled_message(transient_id); + } + } + } + } + + /// Python `LXMRouter.peer()`: a new peer is refused once `max_peers` is reached. pub fn add_peer(&mut self, peer: LxmPeer) -> bool { if self.peers.len() >= self.config.max_peers { return false; @@ -1811,7 +1808,7 @@ impl LxmRouter { offered: peer.offered, outgoing: peer.outgoing, incoming: peer.incoming, - unhandled: peer.unhandled_messages(), + unhandled: peer.unhandled_message_count() as u32, }, ) }) @@ -1863,8 +1860,7 @@ impl LxmRouter { let rotation_headroom = (self.config.max_peers * ROTATION_HEADROOM_PCT / 100).max(1); let required_drops = self.peers.len() as isize - (self.config.max_peers as isize - rotation_headroom as isize); - - if required_drops <= 0 || self.peers.len() <= 1 { + if required_drops <= 0 || self.peers.len() as isize - required_drops <= 1 { return; } @@ -1878,21 +1874,32 @@ impl LxmRouter { return; } - let mut drop_candidates: Vec<([u8; 16], f64)> = self + let fully_synced = self .peers - .iter() - .filter(|(hash, peer)| { - !self.static_peers.contains(hash) - && peer.state == PeerState::Idle - && peer.offered > 0 - }) - .map(|(hash, peer)| (*hash, peer.acceptance_rate())) - .collect(); + .values() + .any(|peer| peer.unhandled_message_count() == 0); + let mut waiting = Vec::new(); + let mut unresponsive = Vec::new(); + for (hash, peer) in &self.peers { + if (fully_synced && peer.unhandled_message_count() != 0) + || self.static_peers.contains(hash) + || peer.state != PeerState::Idle + { + continue; + } + if !peer.alive { + unresponsive.push((*hash, peer.acceptance_rate())); + } else if peer.offered > 0 { + waiting.push((*hash, peer.acceptance_rate())); + } + } + // prioritise_rotating_unreachable_peers is off by default upstream. + let mut drop_pool = unresponsive; + drop_pool.extend(waiting); + drop_pool.sort_by(|a, b| a.1.total_cmp(&b.1)); - drop_candidates.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal)); - - let drop_count = (required_drops as usize).min(drop_candidates.len()); - for (hash, ar) in drop_candidates.into_iter().take(drop_count) { + let drop_count = (required_drops as usize).min(drop_pool.len()); + for (hash, ar) in drop_pool.into_iter().take(drop_count) { if ar < ROTATION_AR_MAX { self.unpeer(&hash); } @@ -2680,6 +2687,15 @@ pub struct RouterStats { pub stamp_costs_cached: usize, } +/// Outcome of one [`LxmRouter::sync_peers`] pass. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct PeerSyncPass { + /// Peers removed for excessive unreachability. + pub culled: Vec<[u8; 16]>, + /// The peer to attempt a sync with, if any. + pub selected: Option<[u8; 16]>, +} + /// Per-peer stats for control status. #[derive(Debug, Clone)] pub struct PeerStats { @@ -3641,100 +3657,44 @@ mod tests { } #[test] - fn test_sync_peers_picks_due_peers() { + fn sync_peers_skips_busy_and_empty_peers_and_culls_long_unreachable() { + let now = now_f64(); let mut router = LxmRouter::new(RouterConfig::default()); - let mut peer_due = LxmPeer::new([0x01; 16]); - peer_due.add_unhandled_message(); - router.add_peer(peer_due); + let mut due = LxmPeer::new([0x01; 16]); + due.alive = true; + due.last_heard = now; + due.add_unhandled_message(&[0x31; 32]); + router.add_peer(due); - let peer_idle_no_msgs = LxmPeer::new([0x02; 16]); - router.add_peer(peer_idle_no_msgs); + let mut idle_no_msgs = LxmPeer::new([0x02; 16]); + idle_no_msgs.alive = true; + idle_no_msgs.last_heard = now; + router.add_peer(idle_no_msgs); - let mut peer_in_flight = LxmPeer::new([0x03; 16]); - peer_in_flight.add_unhandled_message(); - peer_in_flight.begin_sync(); - router.add_peer(peer_in_flight); + let mut in_flight = LxmPeer::new([0x03; 16]); + in_flight.alive = true; + in_flight.last_heard = now; + in_flight.add_unhandled_message(&[0x31; 32]); + in_flight.begin_sync(); + router.add_peer(in_flight); - let due = router.sync_peers(); - assert_eq!(due, vec![[0x01; 16]]); + let mut gone = LxmPeer::new([0x04; 16]); + gone.last_heard = now - MAX_UNREACHABLE as f64 - 1.0; + router.add_peer(gone); - // Subsequent call returns empty — the due peer is now LinkEstablishing. - assert!(router.sync_peers().is_empty()); - } - - #[test] - fn store_generation_scheduler_skips_unchanged_and_reenables_on_store_or_policy_change() { - let peer_hash = [0x11; 16]; - let mut router = LxmRouter::new(RouterConfig::default()); - let mut peer = LxmPeer::from_announce( - peer_hash, - 10.0, - Some(1.0), - Some(2.0), - Some(16.0), - Some(3.0), - Some(18.0), - ); - peer.mark_offer_generation_processed(5); - router.add_peer(peer); - - assert!(router.sync_peer_policies_for_store(5).is_empty()); - let due = router.sync_peer_policies_for_store(6); - assert_eq!(due.len(), 1); - assert_eq!(due[0].peer_hash, peer_hash); - assert_eq!(router.peers[&peer_hash].state, PeerState::Idle); + let pass = router.sync_peers(now, 1); + assert_eq!(pass.selected, Some([0x01; 16])); + assert_eq!(pass.culled, vec![[0x04; 16]]); + assert!(!router.peers.contains_key(&[0x04; 16])); router .peers - .get_mut(&peer_hash) + .get_mut(&[0x01; 16]) .unwrap() - .mark_offer_generation_processed(6); - assert!(router.sync_peer_policies_for_store(6).is_empty()); - assert!(router.autopeer(AutopeerCandidate { - destination_hash: peer_hash, - timebase: 11.0, - transfer_limit: Some(1.0), - sync_limit: Some(2.0), - stamp_cost: Some(12.0), - stamp_flexibility: Some(3.0), - peering_cost: Some(18.0), - metadata: Some(std::collections::HashMap::new()), - hops: Some(1), - })); - assert_eq!(router.sync_peer_policies_for_store(6).len(), 1); - } - - #[test] - fn store_generation_scheduler_falls_back_to_backoff_expired_unresponsive_peers() { - let alive_hash = [0x21; 16]; - let fallback_hash = [0x22; 16]; - let mut router = LxmRouter::new(RouterConfig::default()); - let alive = LxmPeer::new(alive_hash); - let mut fallback = LxmPeer::new(fallback_hash); - fallback.alive = false; - fallback.next_sync_attempt = 0.0; - assert!(router.add_peer(alive)); - assert!(router.add_peer(fallback)); - - let policies = router.sync_peer_policies_for_store(1); - assert_eq!( - policies - .iter() - .map(|policy| policy.peer_hash) - .collect::>(), - vec![alive_hash] - ); - - router.peers.get_mut(&alive_hash).unwrap().begin_sync(); - let policies = router.sync_peer_policies_for_store(1); - assert_eq!( - policies - .iter() - .map(|policy| policy.peer_hash) - .collect::>(), - vec![fallback_hash] - ); + .mark_offer_generation_processed(1); + assert_eq!(router.sync_peers(now, 1).selected, None); + assert_eq!(router.sync_peers(now, 2).selected, Some([0x01; 16])); } #[test] diff --git a/crates/lxmf-core/tests/durable_delivery.rs b/crates/lxmf-core/tests/durable_delivery.rs index 4b5bf7f..9e38822 100644 --- a/crates/lxmf-core/tests/durable_delivery.rs +++ b/crates/lxmf-core/tests/durable_delivery.rs @@ -357,6 +357,23 @@ fn adapter_processing_memory_shares_peak_budget_without_second_worker() { assert!(ProcessingLease::try_acquire(1).is_ok()); } +fn answer_node_path( + receiver: &mut tokio::sync::mpsc::Receiver, +) { + use rns_transport::messages::{TransportMessage, TransportQuery, TransportQueryResponse}; + while let Ok(message) = receiver.try_recv() { + if let TransportMessage::Rpc { + query: TransportQuery::HasPath { .. }, + response_tx, + } = message + { + response_tx + .send(TransportQueryResponse::BoolResult(true)) + .unwrap(); + } + } +} + fn reject_link_request( receiver: &mut tokio::sync::mpsc::Receiver, ) { @@ -395,6 +412,8 @@ fn link_capacity_failure_reaches_all_three_initiators_before_establishment_timeo let mut client = PropagationClient::new(tx, None, None); client.set_propagation_node([3; 16]); assert!(client.start_download()); + answer_node_path(&mut rx); + client.tick(); reject_link_request(&mut rx); client.tick(); assert_eq!( @@ -404,6 +423,8 @@ fn link_capacity_failure_reaches_all_three_initiators_before_establishment_timeo let (tx, mut rx) = tokio::sync::mpsc::channel(32); let mut sync = PropagationSyncTask::new(tx, [8; 16]); assert!(sync.request_sync_now([3; 16])); + answer_node_path(&mut rx); + sync.tick(); reject_link_request(&mut rx); sync.tick(); assert_eq!( @@ -417,6 +438,8 @@ fn canceled_download_closes_exact_request_admission_reply() { let mut client = lxmf_core::propagation_client::PropagationClient::new(tx, None, None); client.set_propagation_node([3; 16]); assert!(client.start_download()); + answer_node_path(&mut rx); + client.tick(); client.cancel_download(); let mut found = false; while let Ok(message) = rx.try_recv() { diff --git a/crates/lxmf-tools/src/commands/lxmd.rs b/crates/lxmf-tools/src/commands/lxmd.rs index 7adb905..824d010 100644 --- a/crates/lxmf-tools/src/commands/lxmd.rs +++ b/crates/lxmf-tools/src/commands/lxmd.rs @@ -160,19 +160,6 @@ fn observe_lossless_queue_depth(queue: &'static str, depth: usize, high_water: & } } -fn round_robin_peer_order( - mut peers: Vec<[u8; 16]>, - last_selected: Option<[u8; 16]>, -) -> Vec<[u8; 16]> { - peers.sort_unstable(); - if let (Some(last_selected), false) = (last_selected, peers.is_empty()) { - let next = peers.partition_point(|peer| *peer <= last_selected); - let peer_count = peers.len(); - peers.rotate_left(next % peer_count); - } - peers -} - #[derive(Debug)] struct ValidatedPnEntry { lxmf_data: Vec, @@ -195,6 +182,7 @@ struct PnPacketValidationWorkerResult { payload_owner: Bytes, malformed: bool, stored: bool, + accounted: Vec<([u8; 32], u64)>, committed: Vec<([u8; 32], u64)>, link_id: [u8; 16], #[cfg(test)] @@ -296,12 +284,16 @@ enum PropagationStoreWriteOrigin { #[derive(Debug)] struct PropagationStoreCommitResult { origin: PropagationStoreWriteOrigin, + /// Every stamp-validated entry and its message size, duplicates included. + accounted: Vec<([u8; 32], u64)>, + /// Entries newly stored by this write. committed: Vec<([u8; 32], u64)>, } fn spawn_propagation_store_writes( node: Arc>, plans: Vec<(PropagationStoreWritePlan, u64)>, + accounted: Vec<([u8; 32], u64)>, origin: PropagationStoreWriteOrigin, commit_tx: mpsc::UnboundedSender, operation: &'static str, @@ -343,7 +335,11 @@ fn spawn_propagation_store_writes( "propagation store writes committed" ); if commit_tx - .send(PropagationStoreCommitResult { origin, committed }) + .send(PropagationStoreCommitResult { + origin, + accounted, + committed, + }) .is_err() { tracing::debug!(operation, "propagation store commit receiver closed"); @@ -351,17 +347,33 @@ fn spawn_propagation_store_writes( })) } +/// Python counts every validated entry before deduplication +/// (`propagation_resource_concluded`, `propagation_packet`) and distributes +/// only newly stored ones (`lxmf_propagation`). fn apply_propagation_store_commit( router: &mut LxmRouter, node: Option<&Arc>>, + distribution: &mut Vec<([u8; 32], Option<[u8; 16]>)>, result: PropagationStoreCommitResult, ) { - if result.committed.is_empty() { + let from_peer = match result.origin { + PropagationStoreWriteOrigin::Peer(peer_hash) if router.peers.contains_key(&peer_hash) => { + Some(peer_hash) + } + _ => None, + }; + distribution.extend( + result + .committed + .iter() + .map(|(transient_id, _)| (*transient_id, from_peer)), + ); + if result.accounted.is_empty() { return; } - let committed_count = result.committed.len() as u64; + let committed_count = result.accounted.len() as u64; let committed_bytes = result - .committed + .accounted .iter() .map(|(_, bytes)| *bytes) .sum::(); @@ -372,7 +384,7 @@ fn apply_propagation_store_commit( peer.incoming = peer.incoming.saturating_add(committed_count); peer.rx_bytes = peer.rx_bytes.saturating_add(committed_bytes); peer.heard(); - for (transient_id, _) in result.committed { + for (transient_id, _) in result.accounted { peer.add_handled_message(&transient_id); } if let Some(node) = node @@ -620,6 +632,7 @@ fn validate_pn_packet_job( payload_owner: data.clone(), malformed: false, stored: false, + accounted: Vec::new(), committed: Vec::new(), entries: Vec::new(), timing: None, @@ -673,6 +686,7 @@ fn execute_pn_packet_job(job: PnPacketValidationJob) -> PnPacketExecution { payload_owner: job.data.clone(), malformed: false, stored: false, + accounted: Vec::new(), committed: Vec::new(), #[cfg(test)] entries: Vec::new(), @@ -704,6 +718,13 @@ fn execute_pn_packet_job(job: PnPacketValidationJob) -> PnPacketExecution { #[cfg(test)] let store_started = Instant::now(); result.stored = true; + result.accounted = validated + .iter() + .map(|blob| { + let size = blob.len().saturating_sub(32) as u64; + (blob.transient_id(), size) + }) + .collect(); for blob in validated { let tid = blob.transient_id(); let admission = job @@ -1271,6 +1292,18 @@ const ROUTE_HOPS_REFRESH_SECS: f64 = 300.0; /// Python lxmd `DEFFERED_JOBS_DELAY` and `JOBS_INTERVAL`, in seconds. const DEFERRED_JOBS_DELAY: u64 = 10; +/// Python `LXMRouter.JOB_STAMPCOST_INTERVAL`, in router job passes. +const JOB_STAMPCOST_INTERVAL: u64 = 120; +/// `RNS.Transport.await_path` timeouts Python `enable_propagation()` gives a +/// loaded peer: 2.5 s, plus 5 s first for a static peer never heard. +const PEER_LOAD_PATH_WAIT: f64 = 2.5; +const PEER_LOAD_STATIC_PATH_WAIT: f64 = 7.5; + +#[derive(Debug)] +struct PeerPathCheck { + response: Option>, + grace_until: Option, +} const JOBS_INTERVAL: u64 = 5; /// Resolve a destination hash to its identity hash via the learned identity @@ -1597,7 +1630,21 @@ struct LxmdRunner { pending_backchannel_resource_cancellations: VecDeque, last_delivery_failure: Option, - propagation_sync: Option, + /// Outbound peer syncs in progress, one per peer, as Python runs one + /// `LXMPeer` link per peer. + peer_syncs: HashMap<[u8; 16], lxmf_core::propagation_sync::PropagationSyncTask>, + /// Peers whose sync waits on a path check (Python `LXMPeer.sync()` path gate). + peer_path_checks: HashMap<[u8; 16], PeerPathCheck>, + /// Loaded peers whose identity must resolve within a path wait (seconds), + /// and the deadline once the wait has started. + peer_identity_deadlines: HashMap<[u8; 16], (f64, Option)>, + /// Unpeered remotes whose announce data is recalled for autopeering. + sync_autopeer_recalls: HashMap<[u8; 16], oneshot::Receiver>, + peer_state_dirty: bool, + /// Python `peer_distribution_queue`: stored IDs and the peer they came from. + peer_distribution_queue: Vec<([u8; 32], Option<[u8; 16]>)>, + peer_jobs_count: u64, + last_peer_jobs: f64, propagation_client: Option, propagation_node: Option>>, propagation_admission: Option>>, @@ -1647,8 +1694,6 @@ struct LxmdRunner { peering_key_result_rx: mpsc::Receiver, peering_key_result_tx: mpsc::Sender, peering_key_jobs: HashSet<[u8; 16]>, - pending_peer_syncs: HashSet<[u8; 16]>, - peer_sync_cursor: Option<[u8; 16]>, /// Non-link inbound packets; still encrypted, need destination-level decrypt. inbound_raw_rx: mpsc::Receiver>, announce_subscriptions: Vec, @@ -2122,9 +2167,10 @@ impl LxmdRunner { prop_storage_path, )?)); if let Ok(node) = pn.lock() { + // Python rebuilds every stored peer, without the max_peers cap. for mut peer in node.load_peers() { peer.is_static = static_peer_hashes.contains(&peer.destination_hash); - let _ = router.add_peer(peer); + router.peers.insert(peer.destination_hash, peer); } } @@ -2506,7 +2552,14 @@ impl LxmdRunner { backchannel_bridge_slots: Arc::new(tokio::sync::Semaphore::new(256)), pending_backchannel_resource_cancellations: VecDeque::new(), last_delivery_failure: None, - propagation_sync: None, + peer_syncs: HashMap::new(), + peer_path_checks: HashMap::new(), + peer_identity_deadlines: HashMap::new(), + sync_autopeer_recalls: HashMap::new(), + peer_state_dirty: false, + peer_distribution_queue: Vec::new(), + peer_jobs_count: 0, + last_peer_jobs: 0.0, propagation_client: None, propagation_node: None, propagation_admission, @@ -2540,8 +2593,6 @@ impl LxmdRunner { peering_key_result_rx, peering_key_result_tx, peering_key_jobs: HashSet::new(), - pending_peer_syncs: HashSet::new(), - peer_sync_cursor: None, inbound_raw_rx, announce_subscriptions: Vec::new(), last_peer_announce: 0.0, @@ -2560,19 +2611,22 @@ impl LxmdRunner { }; if runner.config.propagation_enabled { - if let Some(ref pn) = propagation_node { - let mut sync = lxmf_core::propagation_sync::PropagationSyncTask::with_shared_node( - transport_tx.clone(), - pn.clone(), + if runner.identity.get_signing_key().is_none() { + tracing::error!( + "local identity has no signing key; outbound peer sync cannot identify" ); - if let Some(signing_key) = runner.identity.get_signing_key() { - sync.set_identity(runner.identity.get_public_key(), signing_key); - } else { - tracing::error!( - "local identity has no signing key; outbound peer sync cannot identify" - ); + } + // Python enable_propagation(): a loaded peer whose identity cannot be + // recalled after a short path wait is dropped. + for (hash, peer) in &runner.router.peers { + if !runner.known_identities.contains_key(&hex::encode(hash)) { + let wait = if peer.is_static && peer.last_heard == 0.0 { + PEER_LOAD_STATIC_PATH_WAIT + } else { + PEER_LOAD_PATH_WAIT + }; + runner.peer_identity_deadlines.insert(*hash, (wait, None)); } - runner.propagation_sync = Some(sync); } runner.propagation_node = propagation_node; @@ -2586,6 +2640,9 @@ impl LxmdRunner { runner.identity.get_signing_key(), ); client.set_delivery_limit(runner.config.delivery_transfer_max_accepted_size); + client.set_link_request_stamper(rns_runtime::link_stamp::blocking_stamper( + transport_tx.clone(), + )); if let Some(ref node_hex) = runner.config.outbound_propagation_node { match hex::decode(node_hex) { Ok(bytes) if bytes.len() == 16 => { @@ -2674,6 +2731,10 @@ impl LxmdRunner { .entry(hash) .or_insert_with(|| lxmf_core::peer::LxmPeer::new(hash)); peer.is_static = true; + // Python enable_propagation() asks for a never-heard static peer's path. + if peer.last_heard == 0.0 && self.config.propagation_enabled { + queue_path_request(&self.transport_tx, hash, false, "static peer"); + } } Err(e) => { tracing::warn!(hash = %configured, "ignoring invalid static peer hash: {e}") @@ -2950,18 +3011,11 @@ impl LxmdRunner { if !self.router.peers.contains_key(&peer_hash) { continue; } - self.pending_peer_syncs.insert(peer_hash); - if let Some(peer) = self.router.peers.get_mut(&peer_hash) { - peer.next_sync_attempt = 0.0; - peer.alive = true; - } tracing::info!(peer = %hex::encode(peer_hash), "control: queued peer sync"); + self.attempt_peer_sync(peer_hash, now_f64()); } ControlCommand::Unpeer(peer_hash) => { - self.pending_peer_syncs.remove(&peer_hash); - if let Some(sync) = self.propagation_sync.as_mut() { - sync.cancel_peer_sync(&peer_hash); - } + self.cancel_peer_sync(&peer_hash); // Upstream control unpeer breaks the live peering without // mutating the operator's configured static-peer set. self.router.remove_peer(&peer_hash); @@ -3019,7 +3073,6 @@ impl LxmdRunner { // A bounded key search can fail for an excessive advertised // cost. Put this policy generation into the normal peer // backoff instead of spinning a fresh CPU job every tick. - self.pending_peer_syncs.remove(&result.peer_hash); if let Some(peer) = self.router.peers.get_mut(&result.peer_hash) { peer.next_sync_attempt = now_f64() + lxmf_core::constants::SYNC_BACKOFF_STEP as f64; @@ -3031,124 +3084,409 @@ impl LxmdRunner { ); } // A result for a different cost that no longer satisfies policy - // is ignored. The pending sync remains queued and dispatches a - // new job for the current target. + // is ignored; a later sync attempt dispatches a new job. } } - fn queue_due_peer_syncs(&mut self) { - if self.propagation_sync.is_none() { + /// The peer half of Python `LXMRouter.jobs()`, counted in 4 s passes. + fn run_peer_jobs(&mut self, now: f64) { + use lxmf_core::constants::{ + JOB_PEERINGEST_INTERVAL, JOB_PEERSYNC_INTERVAL, PROCESSING_INTERVAL, + }; + if now - self.last_peer_jobs < PROCESSING_INTERVAL as f64 * 0.9 { return; } - let Some(offer_generation) = self - .propagation_node - .as_ref() - .and_then(|node| node.lock().ok().map(|node| node.offer_generation())) - else { + self.last_peer_jobs = now; + self.peer_jobs_count += 1; + let propagation = self.propagation_node.is_some(); + if propagation && self.peer_jobs_count.is_multiple_of(JOB_PEERINGEST_INTERVAL) { + self.flush_peer_distribution_queue(); + } + if propagation && self.peer_jobs_count.is_multiple_of(JOB_PEERSYNC_INTERVAL) { + self.run_peer_sync_pass(now); + } + if self.peer_jobs_count.is_multiple_of(JOB_STAMPCOST_INTERVAL) { + self.router.cull_stamp_costs(); + } + } + + fn flush_peer_distribution_queue(&mut self) { + if self.peer_distribution_queue.is_empty() || self.router.peers.is_empty() { + return; + } + let entries = std::mem::take(&mut self.peer_distribution_queue); + self.router.flush_peer_distribution(&entries); + self.peer_state_dirty = true; + } + + /// Python `LXMRouter.sync_peers()`, run every `JOB_PEERSYNC_INTERVAL` jobs. + fn run_peer_sync_pass(&mut self, now: f64) { + let Some(offer_generation) = self.propagation_node.as_ref().and_then(|node| { + node.lock().ok().map(|node| { + // Python derives each peer's unhandled set from the live store. + for peer in self.router.peers.values_mut() { + peer.unhandled_messages.retain(|id| node.contains(id)); + } + node.offer_generation() + }) + }) else { return; }; - - for policy in self.router.sync_peer_policies_for_store(offer_generation) { - self.pending_peer_syncs.insert(policy.peer_hash); + let pass = self.router.sync_peers(now, offer_generation); + if let Some(peer_hash) = pass.selected { + self.attempt_peer_sync(peer_hash, now); + } + for peer_hash in pass.culled { + tracing::warn!( + peer = %hex::encode(peer_hash), + "removing peer due to excessive unreachability" + ); + self.forget_peer(&peer_hash); + } + if std::mem::take(&mut self.peer_state_dirty) { + self.save_all_peers(); } } - fn drive_pending_peer_syncs(&mut self) { - if self - .propagation_sync - .as_ref() - .is_none_or(|sync| sync.state != lxmf_core::propagation_sync::SyncTaskState::Idle) + fn save_all_peers(&self) { + let Some(node) = self.propagation_node.as_ref() else { + return; + }; + let Ok(node) = node.lock() else { + return; + }; + for peer in self.router.peers.values() { + if let Err(error) = node.save_peer(peer) { + tracing::warn!( + peer = %hex::encode(peer.destination_hash), + "failed to persist peer state: {error}" + ); + } + } + } + + /// Cancel sync work for a peer the router no longer holds and delete its + /// persisted state. + fn forget_peer(&mut self, peer_hash: &[u8; 16]) { + self.cancel_peer_sync(peer_hash); + if let Some(node) = self.propagation_node.as_ref() + && let Ok(mut node) = node.lock() + && let Err(error) = node.delete_peer(peer_hash) + { + tracing::warn!( + peer = %hex::encode(peer_hash), + "failed to remove persisted propagation peer: {error}" + ); + } + } + + fn cancel_peer_sync(&mut self, peer_hash: &[u8; 16]) -> bool { + self.peer_path_checks.remove(peer_hash); + match self.peer_syncs.remove(peer_hash) { + Some(mut sync) => { + sync.cancel_peer_sync(peer_hash); + true + } + None => false, + } + } + + /// Python `LXMPeer.sync()` up to its path check: postpone during backoff, + /// until stamp costs are known and until a peering key exists. + fn attempt_peer_sync(&mut self, peer_hash: [u8; 16], now: f64) { + if self.peer_syncs.contains_key(&peer_hash) + || self.peer_path_checks.contains_key(&peer_hash) { return; } - - let mut pending = self.pending_peer_syncs.iter().copied().collect::>(); - // Match Python's preference for responsive peers. Peers that have - // exhausted their backoff stay queued as a fallback when no live peer - // is available. - if pending.iter().any(|peer_hash| { - self.router - .peers - .get(peer_hash) - .is_some_and(|peer| peer.alive) - }) { - pending.retain(|peer_hash| { - self.router - .peers - .get(peer_hash) - .is_some_and(|peer| peer.alive) - }); + let Some(peer) = self.router.peers.get_mut(&peer_hash) else { + return; + }; + if peer.state != lxmf_core::constants::PeerState::Idle { + return; } - let pending = round_robin_peer_order(pending, self.peer_sync_cursor); - for peer_hash in pending { - let Some(peer_identity_hash) = recall_identity_hash(&self.known_identities, &peer_hash) - else { - self.recall_identity(peer_hash); - tracing::debug!( - peer = %hex::encode(peer_hash), - "peer sync postponed until its identity is known" - ); - continue; - }; - let policy = self.router.peers.get(&peer_hash).and_then(|peer| { - (peer.stamp_costs_known() && (peer.peering_cost == 0.0 || peer.peering_key_ready())) - .then(|| OutboundOfferPolicy::from(peer)) - }); - if let Some(policy) = policy { - if let Some(sync) = self.propagation_sync.as_mut() - && sync.request_sync_now_with_policy(policy) - { - if let Some(peer) = self.router.peers.get_mut(&peer_hash) { - peer.begin_sync(); - } - self.pending_peer_syncs.remove(&peer_hash); - self.peer_sync_cursor = Some(peer_hash); - } - return; - } + self.peer_state_dirty = true; + if !peer.sync_attempt(now) { + tracing::debug!( + peer = %hex::encode(peer_hash), + "postponing peer sync due to previous failures" + ); + return; + } + if !peer.stamp_costs_known() { + tracing::debug!( + peer = %hex::encode(peer_hash), + "postponing peer sync since its required stamp costs are not yet known" + ); + return; + } + if peer.peering_cost != 0.0 && !peer.peering_key_ready() { + tracing::debug!( + peer = %hex::encode(peer_hash), + "postponing peer sync since a peering key has not been generated yet" + ); + self.spawn_peering_key_job(peer_hash); + return; + } + let (response_tx, response_rx) = oneshot::channel(); + if self + .transport_tx + .try_send(TransportMessage::Rpc { + query: TransportQuery::HasPath { dest: peer_hash }, + response_tx, + }) + .is_ok() + { + self.peer_path_checks.insert( + peer_hash, + PeerPathCheck { + response: Some(response_rx), + grace_until: None, + }, + ); + } + } - if self - .router - .peers - .get(&peer_hash) - .is_some_and(|peer| !peer.stamp_costs_known()) - { - tracing::debug!( - peer = %hex::encode(peer_hash), - "peer sync postponed until its stamp policy is known" - ); - continue; - } - - if self.peering_key_jobs.contains(&peer_hash) { - continue; - } - let Some(peer) = self.router.peers.get(&peer_hash) else { - self.pending_peer_syncs.remove(&peer_hash); - continue; - }; - - let peering_cost = peer.peering_cost; - let local_identity_hash = self.identity.hash; - let result_tx = self.peering_key_result_tx.clone(); - self.peering_key_jobs.insert(peer_hash); - tokio::spawn(async move { - let result = tokio::task::spawn_blocking(move || { - generate_peering_key_job( - peer_hash, - peering_cost, - peer_identity_hash, - local_identity_hash, - ) - }) - .await - .unwrap_or(PeeringKeyWorkerResult { + fn spawn_peering_key_job(&mut self, peer_hash: [u8; 16]) { + if self.peering_key_jobs.contains(&peer_hash) { + return; + } + let Some(peer_identity_hash) = recall_identity_hash(&self.known_identities, &peer_hash) + else { + self.recall_identity(peer_hash); + return; + }; + let Some(peer) = self.router.peers.get(&peer_hash) else { + return; + }; + let peering_cost = peer.peering_cost; + let local_identity_hash = self.identity.hash; + let result_tx = self.peering_key_result_tx.clone(); + self.peering_key_jobs.insert(peer_hash); + tokio::spawn(async move { + let result = tokio::task::spawn_blocking(move || { + generate_peering_key_job( peer_hash, peering_cost, - peering_key: None, - }); - let _ = result_tx.send(result).await; + peer_identity_hash, + local_identity_hash, + ) + }) + .await + .unwrap_or(PeeringKeyWorkerResult { + peer_hash, + peering_cost, + peering_key: None, }); + let _ = result_tx.send(result).await; + }); + } + + /// Without a path, request one and wait `PATH_REQUEST_GRACE` before + /// checking again; a path still missing defers the sync (`LXMPeer.sync()`). + fn drive_peer_path_checks(&mut self, now: f64) { + let mut ready = Vec::new(); + let mut failed = Vec::new(); + for (peer_hash, check) in &mut self.peer_path_checks { + if let Some(response) = check.response.as_mut() { + let has_path = match response.try_recv() { + Err(oneshot::error::TryRecvError::Empty) => continue, + Ok(TransportQueryResponse::BoolResult(has_path)) => has_path, + _ => false, + }; + check.response = None; + if has_path { + ready.push(*peer_hash); + } else if check.grace_until.is_some() { + failed.push(*peer_hash); + } else { + tracing::debug!( + peer = %hex::encode(peer_hash), + "no path to peer exists, requesting" + ); + queue_path_request(&self.transport_tx, *peer_hash, false, "peer sync"); + check.grace_until = Some(now + lxmf_core::constants::PATH_REQUEST_GRACE); + } + } else if check.grace_until.is_some_and(|until| now >= until) { + let (response_tx, response_rx) = oneshot::channel(); + if self + .transport_tx + .try_send(TransportMessage::Rpc { + query: TransportQuery::HasPath { dest: *peer_hash }, + response_tx, + }) + .is_ok() + { + check.response = Some(response_rx); + } else { + failed.push(*peer_hash); + } + } + } + for peer_hash in failed { + self.peer_path_checks.remove(&peer_hash); + if let Some(peer) = self.router.peers.get_mut(&peer_hash) { + peer.path_request_failed(now); + self.peer_state_dirty = true; + tracing::debug!( + peer = %hex::encode(peer_hash), + "path request was not answered, retrying peer sync later" + ); + } + } + for peer_hash in ready { + self.peer_path_checks.remove(&peer_hash); + self.start_peer_sync(peer_hash); + } + } + + /// The link half of Python `LXMPeer.sync()`, once a path exists. + fn start_peer_sync(&mut self, peer_hash: [u8; 16]) { + let Some(node) = self.propagation_node.clone() else { + return; + }; + if recall_identity_hash(&self.known_identities, &peer_hash).is_none() { + self.recall_identity(peer_hash); + tracing::error!( + peer = %hex::encode(peer_hash), + "could not request sync to peer since its identity could not be recalled" + ); + return; + } + let Some(peer) = self.router.peers.get_mut(&peer_hash) else { + return; + }; + if peer.unhandled_message_count() == 0 { + tracing::debug!( + peer = %hex::encode(peer_hash), + "sync requested, but no unhandled messages exist for peer" + ); + return; + } + let mut sync = lxmf_core::propagation_sync::PropagationSyncTask::with_shared_node( + self.transport_tx.clone(), + node, + ); + sync.set_link_request_stamper(rns_runtime::link_stamp::blocking_stamper( + self.transport_tx.clone(), + )); + if let Some(signing_key) = self.identity.get_signing_key() { + sync.set_identity(self.identity.get_public_key(), signing_key); + } + if sync.request_sync_now_with_policy(OutboundOfferPolicy::from(&*peer)) { + peer.begin_sync(); + self.peer_syncs.insert(peer_hash, sync); + } + } + + /// Python `propagation_resource_concluded()` autopeers an identified, + /// unpeered remote from its recalled propagation node announce. + fn recall_sync_autopeer(&mut self, peer_hash: [u8; 16]) { + if !self.config.autopeer + || self.router.peers.contains_key(&peer_hash) + || self.sync_autopeer_recalls.contains_key(&peer_hash) + { + return; + } + let (response_tx, response_rx) = oneshot::channel(); + if self + .transport_tx + .try_send(TransportMessage::Rpc { + query: TransportQuery::RecallDestination { dest: peer_hash }, + response_tx, + }) + .is_ok() + { + self.sync_autopeer_recalls.insert(peer_hash, response_rx); + } + } + + fn drain_sync_autopeer_recalls(&mut self) { + let mut answered = Vec::new(); + for (peer_hash, response) in &mut self.sync_autopeer_recalls { + match response.try_recv() { + Err(oneshot::error::TryRecvError::Empty) => {} + Ok(TransportQueryResponse::RecalledDestination(Some(recalled))) => { + answered.push((*peer_hash, Some(recalled))); + } + _ => answered.push((*peer_hash, None)), + } + } + for (peer_hash, recalled) in answered { + self.sync_autopeer_recalls.remove(&peer_hash); + let Some(recalled) = recalled else { + continue; + }; + let Some(pn) = recalled + .app_data + .as_deref() + .and_then(lxmf_core::handlers::parse_pn_announce_data) + else { + continue; + }; + if !pn.node_state || !self.config.autopeer { + continue; + } + self.learn_identity(&peer_hash, recalled.public_key, recalled.ratchet, None); + tracing::debug!( + peer = %hex::encode(peer_hash), + "auto-peering with propagation node discovered via incoming sync" + ); + if self.router.autopeer(AutopeerCandidate { + destination_hash: peer_hash, + timebase: pn.timebase as f64, + transfer_limit: Some(pn.transfer_limit as f64), + sync_limit: Some(pn.sync_limit as f64), + stamp_cost: Some(pn.stamp_cost), + stamp_flexibility: Some(pn.stamp_flex), + peering_cost: Some(pn.peering_cost), + hops: Some( + self.route_hops + .get(&peer_hash) + .copied() + .unwrap_or(recalled.hops), + ), + metadata: Some(pn.metadata.clone()), + }) { + self.peer_state_dirty = true; + } + } + } + + /// Drop loaded peers whose identity did not resolve in time + /// (Python `enable_propagation()`); static peers start over. + fn drive_peer_identity_resolution(&mut self, now: f64) { + if self.peer_identity_deadlines.is_empty() { + return; + } + let pending = self.peer_identity_deadlines.clone(); + for (peer_hash, (wait, deadline)) in pending { + if self.known_identities.contains_key(&hex::encode(peer_hash)) + || !self.router.peers.contains_key(&peer_hash) + { + self.peer_identity_deadlines.remove(&peer_hash); + } else if deadline.is_none() { + self.peer_identity_deadlines + .insert(peer_hash, (wait, Some(now + wait))); + queue_path_request(&self.transport_tx, peer_hash, false, "loaded peer"); + self.recall_identity(peer_hash); + } else if deadline.is_some_and(|deadline| now >= deadline) { + self.peer_identity_deadlines.remove(&peer_hash); + tracing::debug!( + peer = %hex::encode(peer_hash), + "peer could not be loaded, because its identity could not be recalled" + ); + self.router.peers.remove(&peer_hash); + self.forget_peer(&peer_hash); + if self.router.static_peers.contains(&peer_hash) { + let mut peer = LxmPeer::new(peer_hash); + peer.is_static = true; + self.router.peers.insert(peer_hash, peer); + queue_path_request(&self.transport_tx, peer_hash, false, "static peer"); + } + } else if !self.identity_recalls.contains_key(&peer_hash) { + self.recall_identity(peer_hash); + } } } @@ -3452,35 +3790,39 @@ impl LxmdRunner { /// from the four-second router maintenance job loop. fn drive_propagation_sync(&mut self) { self.poll_download_commits(); - let mut peer_handled_updates = None; - let mut peer_terminal_result = None; - if let Some(ref mut sync) = self.propagation_sync { + let now = now_f64(); + self.drive_peer_path_checks(now); + let mut peers_to_persist = HashSet::new(); + let mut finished = Vec::new(); + let mut resync = Vec::new(); + for (peer_hash, sync) in &mut self.peer_syncs { sync.drain_events(&self.known_identities); sync.tick(); - let updates = sync.take_handled_updates(); - if !updates.is_empty() - && let Some(peer_hash) = sync.node_dest_hash() - { - peer_handled_updates = Some((peer_hash, updates)); + let handled = sync.take_handled_updates(); + let dropped = sync.take_dropped_unhandled_updates(); + let terminal = sync.take_terminal_peer_result(); + let Some(peer) = self.router.peers.get_mut(peer_hash) else { + finished.push(*peer_hash); + continue; + }; + if !handled.is_empty() || !dropped.is_empty() { + for transient_id in &handled { + peer.add_handled_message(transient_id); + } + for transient_id in &dropped { + peer.remove_unhandled_message(transient_id); + } + peers_to_persist.insert(*peer_hash); } - peer_terminal_result = sync.take_terminal_peer_result(); - } - - let mut peers_to_persist = HashSet::new(); - if let Some((peer_hash, updates)) = peer_handled_updates - && let Some(peer) = self.router.peers.get_mut(&peer_hash) - { - for transient_id in updates { - peer.add_handled_message(&transient_id); - } - peers_to_persist.insert(peer_hash); - } - if let Some(result) = peer_terminal_result - && let Some(peer) = self.router.peers.get_mut(&result.peer_hash) - { + let Some(result) = terminal else { + continue; + }; + finished.push(*peer_hash); if let Some(rate) = result.link_establishment_rate { + // Python link_established() and the LINK_READY branch of sync(). peer.link_establishment_rate = rate; peer.heard(); + peer.next_sync_attempt = 0.0; } match result.state { lxmf_core::propagation_sync::PeerSyncTerminalState::Complete => { @@ -3490,6 +3832,14 @@ impl LxmdRunner { if let Some(rate) = result.sync_transfer_rate { peer.sync_transfer_rate = rate; } + if result.outgoing > 0 { + peer.heard(); + if peer.sync_strategy == lxmf_core::constants::SyncStrategy::Persistent + && peer.unhandled_message_count() > 0 + { + resync.push(result.peer_hash); + } + } peer.sync_complete(); if result.generation_exhausted && let Some(generation) = result.offer_generation @@ -3497,12 +3847,24 @@ impl LxmdRunner { peer.mark_offer_generation_processed(generation); } } + lxmf_core::propagation_sync::PeerSyncTerminalState::NoPath => { + // LXMPeer.sync: no link was made; begin_sync already applied the backoff step. + peer.state = lxmf_core::constants::PeerState::Idle; + peer.alive = false; + } lxmf_core::propagation_sync::PeerSyncTerminalState::Failed => { peer.sync_failed(); } } peers_to_persist.insert(result.peer_hash); } + for peer_hash in finished { + self.peer_syncs.remove(&peer_hash); + } + // Python resource_concluded(): a persistent peer with messages left syncs again. + for peer_hash in resync { + self.attempt_peer_sync(peer_hash, now); + } for peer_hash in peers_to_persist { if let (Some(node), Some(peer)) = ( self.propagation_node.as_ref(), @@ -3748,8 +4110,9 @@ impl LxmdRunner { self.drain_control_commands(); self.drain_identity_recalls(); self.drain_peering_key_results(); - self.queue_due_peer_syncs(); - self.drive_pending_peer_syncs(); + self.drain_sync_autopeer_recalls(); + self.drive_peer_identity_resolution(now); + self.run_peer_jobs(now); self.drain_backchannel_events(); self.router.process_deferred_stamps(); @@ -3757,7 +4120,13 @@ impl LxmdRunner { // Advance the router jobloop counters (transient-cache cleaning, store // cull, peer rotation at Python cadences). `process_outbound_with_direct` // does not drive these. + let peers_before = self.router.peers.keys().copied().collect::>(); self.router.run_jobs_tick(); + for peer_hash in peers_before { + if !self.router.peers.contains_key(&peer_hash) { + self.forget_peer(&peer_hash); + } + } if let Some(ref mut ld) = self.link_delivery { ld.drain_events(&self.known_identities); @@ -3829,6 +4198,7 @@ impl LxmdRunner { status.state, lxmf_core::propagation_client::PropagationClientState::Complete | lxmf_core::propagation_client::PropagationClientState::Partial + | lxmf_core::propagation_client::PropagationClientState::NoPath | lxmf_core::propagation_client::PropagationClientState::Failed ); propagation_status = Some(status); @@ -3866,7 +4236,6 @@ impl LxmdRunner { } } if self.prop_maintenance_task.is_none() && now - self.last_cull > 300.0 { - self.router.cull_stamp_costs(); // Reserve only metadata under the lock. Native durable deletion // barriers run on one joined worker, away from receipt dispatch. if let Some(ref pn) = self.propagation_node @@ -4064,19 +4433,7 @@ impl LxmdRunner { } if peer_removed { - self.pending_peer_syncs.remove(&event.destination_hash); - if let Some(sync) = self.propagation_sync.as_mut() { - sync.cancel_peer_sync(&event.destination_hash); - } - if let Some(node) = self.propagation_node.as_ref() - && let Ok(mut node) = node.lock() - && let Err(error) = node.delete_peer(&event.destination_hash) - { - tracing::warn!( - peer = %dest_hex, - "failed to remove retired propagation peer: {error}" - ); - } + self.forget_peer(&event.destination_hash); } else if peer_changed { let offer_constraints_changed = previous_offer_constraints.is_some_and(|previous| { @@ -4087,15 +4444,10 @@ impl LxmdRunner { != Some(previous) }); if offer_constraints_changed - && self - .propagation_sync - .as_mut() - .is_some_and(|sync| sync.cancel_peer_sync(&event.destination_hash)) + && self.cancel_peer_sync(&event.destination_hash) + && let Some(peer) = self.router.peers.get_mut(&event.destination_hash) { - if let Some(peer) = self.router.peers.get_mut(&event.destination_hash) { - peer.link_closed(); - } - self.pending_peer_syncs.insert(event.destination_hash); + peer.link_closed(); } if let (Some(node), Some(peer)) = ( self.propagation_node.as_ref(), @@ -4187,6 +4539,7 @@ impl LxmdRunner { apply_propagation_store_commit( &mut self.router, self.propagation_node.as_ref(), + &mut self.peer_distribution_queue, result, ); } @@ -4438,11 +4791,36 @@ impl LxmdRunner { } } } + let accounted = result + .entries + .iter() + .map(|entry| { + ( + rns_crypto::sha::full_hash(&entry.lxmf_data), + entry.lxmf_data.len() as u64, + ) + }) + .collect::>(); + if let PropagationStoreWriteOrigin::Peer(peer_hash) = write_origin { + self.recall_sync_autopeer(peer_hash); + } let reserved = write_plans.len(); - if let Some(node) = self.propagation_node.clone() + if write_plans.is_empty() { + apply_propagation_store_commit( + &mut self.router, + self.propagation_node.as_ref(), + &mut self.peer_distribution_queue, + PropagationStoreCommitResult { + origin: write_origin, + accounted, + committed: Vec::new(), + }, + ); + } else if let Some(node) = self.propagation_node.clone() && let Some(task) = spawn_propagation_store_writes( node, write_plans, + accounted, write_origin, self.prop_store_commit_tx.clone(), "propagation Resource ingress", @@ -4516,8 +4894,10 @@ impl LxmdRunner { apply_propagation_store_commit( &mut self.router, self.propagation_node.as_ref(), + &mut self.peer_distribution_queue, PropagationStoreCommitResult { origin: PropagationStoreWriteOrigin::Client, + accounted: std::mem::take(&mut result.accounted), committed: std::mem::take(&mut result.committed), }, ); @@ -5380,6 +5760,9 @@ impl LxmdRunner { if let Some(handle) = &self.endpoint_dispatch { delivery.set_link_endpoint_dispatch_handle(handle.clone()); } + delivery.set_link_request_stamper(rns_runtime::link_stamp::blocking_stamper( + self.transport_tx.clone(), + )); self.link_delivery = Some(delivery); } self.ensure_backchannel_sender(); @@ -6401,6 +6784,7 @@ pub(crate) async fn main() { apply_propagation_store_commit( &mut runner.router, runner.propagation_node.as_ref(), + &mut runner.peer_distribution_queue, result, ); runner.drain_link_packets(); @@ -6465,6 +6849,7 @@ pub(crate) async fn main() { apply_propagation_store_commit( &mut runner.router, runner.propagation_node.as_ref(), + &mut runner.peer_distribution_queue, result, ); } @@ -6491,6 +6876,9 @@ pub(crate) async fn main() { one_shot_status = Some(1); } } + // Python exit_handler() saves every peer's synchronisation state. + runner.flush_peer_distribution_queue(); + runner.save_all_peers(); if let Err(e) = runner.router.save_state(&runner.data_dir) { tracing::warn!("Failed to save router state on shutdown: {e}"); if one_shot_status.is_some() { @@ -6680,6 +7068,100 @@ mod tests { ); } + /// Python `LXMPeer.sync()`: with no path a sync requests one and waits + /// `PATH_REQUEST_GRACE`; a path still missing defers the sync without a link. + #[tokio::test] + async fn peer_sync_without_a_path_requests_one_and_backs_off_without_a_link() { + let temp = tempfile::tempdir().unwrap(); + initialize_storage_namespace(temp.path()).unwrap(); + let (tx, mut rx) = mpsc::channel(1024); + let mut runner = LxmdRunner::new(DaemonConfig::default(), temp.path(), tx, None).unwrap(); + while rx.try_recv().is_ok() {} + let peer_hash = [0x77; 16]; + let mut peer = LxmPeer::new(peer_hash); + peer.alive = true; + peer.last_heard = now_f64(); + peer.stamp_cost = Some(0.0); + peer.stamp_cost_flexibility = Some(0.0); + peer.peering_cost = 0.0; + peer.add_unhandled_message(&[0x31; 32]); + runner.router.peers.insert(peer_hash, peer); + + let answer_no_path = |rx: &mut mpsc::Receiver| { + let mut requested_path = false; + while let Ok(message) = rx.try_recv() { + match message { + TransportMessage::Rpc { + query: TransportQuery::HasPath { dest }, + response_tx, + } if dest == peer_hash => { + let _ = response_tx.send(TransportQueryResponse::BoolResult(false)); + } + TransportMessage::RequestPath { destination_hash } => { + assert_eq!(destination_hash, peer_hash); + requested_path = true; + } + TransportMessage::SendLinkRequest { .. } => { + panic!("link opened without a path") + } + _ => {} + } + } + requested_path + }; + + let now = now_f64(); + runner.attempt_peer_sync(peer_hash, now); + assert!(!answer_no_path(&mut rx)); + runner.drive_peer_path_checks(now); + assert!(answer_no_path(&mut rx), "a path request is sent"); + assert!(runner.peer_syncs.is_empty()); + + runner.drive_peer_path_checks(now + 1.0); + assert!( + runner.peer_path_checks.contains_key(&peer_hash), + "still within the grace" + ); + let after_grace = now + lxmf_core::constants::PATH_REQUEST_GRACE; + runner.drive_peer_path_checks(after_grace); + answer_no_path(&mut rx); + runner.drive_peer_path_checks(after_grace); + assert!(runner.peer_syncs.is_empty()); + let peer = &runner.router.peers[&peer_hash]; + assert!(!peer.alive); + assert_eq!( + peer.sync_backoff, + lxmf_core::constants::SYNC_BACKOFF_STEP as f64 + ); + assert!(!answer_no_path(&mut rx)); + } + + /// Python `propagation_resource_concluded()` peers with an unpeered sender + /// whose recalled announce shows an enabled propagation node. + #[tokio::test] + async fn sync_from_unpeered_propagation_node_autopeers_from_recalled_announce() { + let node = Identity::new(); + let app_data = + propagation_announce_app_data(&lxmf_core::handlers::PropagationNodeAnnounceData::new( + true, 256, 10240, 16.0, 3.0, 18.0, + )); + let (announce, node_hex) = lxmf_announce(&node, "lxmf.propagation", Some(&app_data)); + let (tx, _driver) = transport_that_heard(&announce).await; + let temp = tempfile::tempdir().unwrap(); + initialize_storage_namespace(temp.path()).unwrap(); + let mut runner = LxmdRunner::new(DaemonConfig::default(), temp.path(), tx, None).unwrap(); + let node_hash: [u8; 16] = hex::decode(&node_hex).unwrap().try_into().unwrap(); + + runner.recall_sync_autopeer(node_hash); + let deadline = Instant::now() + Duration::from_secs(5); + while !runner.router.peers.contains_key(&node_hash) { + assert!(Instant::now() < deadline, "the sending node is peered"); + runner.drain_sync_autopeer_recalls(); + tokio::time::sleep(Duration::from_millis(10)).await; + } + assert!(runner.router.peers[&node_hash].autopeered); + } + /// A propagation node the daemon never heard announced is recalled from /// Transport before the download, as Python's LXMF does /// (LXMRouter.request_messages_from_propagation_node, Identity.recall). @@ -7099,31 +7581,22 @@ mod tests { } #[test] - fn propagation_accounting_advances_only_for_durable_commits() { + fn propagation_accounting_counts_duplicates_and_distributes_only_new_entries() { let peer_hash = [0x21; 16]; let first_id = [0x31; 32]; let second_id = [0x32; 32]; let mut router = LxmRouter::new(Default::default()); router.peers.insert(peer_hash, LxmPeer::new(peer_hash)); + let mut distribution = Vec::new(); apply_propagation_store_commit( &mut router, None, + &mut distribution, PropagationStoreCommitResult { origin: PropagationStoreWriteOrigin::Peer(peer_hash), - committed: Vec::new(), - }, - ); - let peer = router.peers.get(&peer_hash).unwrap(); - assert_eq!(peer.incoming, 0); - assert_eq!(peer.rx_bytes, 0); - - apply_propagation_store_commit( - &mut router, - None, - PropagationStoreCommitResult { - origin: PropagationStoreWriteOrigin::Peer(peer_hash), - committed: vec![(first_id, 120), (second_id, 180)], + accounted: vec![(first_id, 120), (second_id, 180)], + committed: vec![(first_id, 120)], }, ); let peer = router.peers.get(&peer_hash).unwrap(); @@ -7131,16 +7604,20 @@ mod tests { assert_eq!(peer.rx_bytes, 300); assert!(peer.handled_messages.contains(&first_id)); assert!(peer.handled_messages.contains(&second_id)); + assert_eq!(distribution, vec![(first_id, Some(peer_hash))]); apply_propagation_store_commit( &mut router, None, + &mut distribution, PropagationStoreCommitResult { origin: PropagationStoreWriteOrigin::Client, + accounted: vec![([0x41; 32], 64), ([0x41; 32], 64)], committed: vec![([0x41; 32], 64)], }, ); - assert_eq!(router.client_propagation_messages_received, 1); + assert_eq!(router.client_propagation_messages_received, 2); + assert_eq!(distribution.last(), Some(&([0x41; 32], None))); } #[test] @@ -7261,24 +7738,6 @@ mod tests { assert!(queue_control_command(&tx, ControlCommand::Sync([0x24; 16])).is_none()); } - #[test] - fn peer_sync_round_robin_does_not_starve_large_peer_sets() { - let peers = (0u8..128).map(|byte| [byte; 16]).collect::>(); - let mut cursor = None; - let mut selected = HashSet::new(); - - for _ in 0..peers.len() { - let next = round_robin_peer_order(peers.clone(), cursor)[0]; - assert!( - selected.insert(next), - "selected a peer twice before a full pass" - ); - cursor = Some(next); - } - - assert_eq!(selected.len(), 128); - } - #[tokio::test] async fn inbound_resource_cancel_adapter_preserves_exact_owner_and_direction() { let (cancel_tx, cancel_rx) = mpsc::channel(2); diff --git a/crates/lxmf-tools/src/lxmd_control.rs b/crates/lxmf-tools/src/lxmd_control.rs index c081bce..3b7c22c 100644 --- a/crates/lxmf-tools/src/lxmd_control.rs +++ b/crates/lxmf-tools/src/lxmd_control.rs @@ -193,8 +193,8 @@ pub fn encode_router_control_stats( .map(|(_, value)| Value::from(*value as u64)) .unwrap_or(Value::Nil); let unhandled = node - .map(|node| node.unhandled_message_count(&peer.handled_messages)) - .unwrap_or_else(|| peer.unhandled_messages() as usize); + .map(|node| node.unhandled_message_count(&peer.unhandled_messages)) + .unwrap_or_else(|| peer.unhandled_message_count()); let peer_map = Value::Map(vec![ (Value::String("type".into()), Value::from(peer_type)), @@ -1120,7 +1120,7 @@ mod tests { let mut peer = LxmPeer::new(peer_hash); peer.offered = 4; peer.outgoing = 2; - peer.set_unhandled_count(1); + peer.add_unhandled_message(&[0x31; 32]); router.peers.insert(peer_hash, peer); router.static_peers.push(peer_hash);