From 455e0b14761a4fae529c2c77644dbaed800f5004 Mon Sep 17 00:00:00 2001 From: DeFiDude <59237470+DeFiDude@users.noreply.github.com> Date: Wed, 11 Nov 2026 00:52:26 -0700 Subject: [PATCH] propagation: match upstream in the client's requests, purges, and errors --- crates/lxmf-core/src/propagation_client.rs | 307 +++++++++++++----- .../lxmf-core/src/propagation_client_tests.rs | 150 ++++++--- crates/lxmf-core/src/router.rs | 30 ++ crates/lxmf-tools/src/commands/lxmd.rs | 31 +- 4 files changed, 376 insertions(+), 142 deletions(-) diff --git a/crates/lxmf-core/src/propagation_client.rs b/crates/lxmf-core/src/propagation_client.rs index 83ed6bc..2b1f483 100644 --- a/crates/lxmf-core/src/propagation_client.rs +++ b/crates/lxmf-core/src/propagation_client.rs @@ -76,9 +76,37 @@ pub enum PropagationClientState { Complete, /// No path to the node arrived within the path timeout. NoPath, + /// The Link closed before it was established. + LinkFailed, + /// The Link closed while a request was outstanding. + TransferFailed, + /// The node answered `ERROR_NO_IDENTITY`. + NoIdentityReceived, + /// The node answered `ERROR_NO_ACCESS`. + NoAccess, Failed, } +impl PropagationClientState { + /// Terminal failure states; the Link is released and a new download may start. + pub const fn is_failure(self) -> bool { + matches!( + self, + Self::NoPath + | Self::LinkFailed + | Self::TransferFailed + | Self::NoIdentityReceived + | Self::NoAccess + | Self::Failed + ) + } + + /// `Complete`, `Partial` or a failure state. + pub const fn is_terminal(self) -> bool { + matches!(self, Self::Complete | Self::Partial) || self.is_failure() + } +} + /// Local admission/backoff status; none of these records authorize purge. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub struct PropagationAdmissionStatus { @@ -110,7 +138,7 @@ pub struct PropagationTransferStatus { pub state: PropagationClientState, pub progress: f64, pub data_size: Option, - /// Number of durably accepted decisions, including duplicates/discards. + /// Messages in the last `/get` response, as Python's `propagation_transfer_last_result`. pub result: Option, pub admission: PropagationAdmissionCounts, } @@ -136,7 +164,8 @@ struct SegmentRoute { enum RequestKind { List, Haves(usize), - Get(usize), + /// Wanted IDs and haves carried in the single `[wants, haves, limit]` request. + Get(usize, usize), Purge(usize), } @@ -144,7 +173,7 @@ impl RequestKind { fn state(self) -> PropagationClientState { match self { Self::List => PropagationClientState::ListRequested, - Self::Get(_) => PropagationClientState::GetRequested, + Self::Get(..) => PropagationClientState::GetRequested, Self::Haves(_) | Self::Purge(_) => PropagationClientState::PurgeRequested, } } @@ -258,6 +287,8 @@ pub struct PropagationClient { suppression_revision: u64, /// IDs of messages successfully received (drives the Phase 3 purge). received_ids: Vec>, + /// Downloaded IDs that were not accepted locally; purged like Python, never haves. + rejected_ids: Vec>, pending_haves: VecDeque>, pending_wants: VecDeque>, request: Option, @@ -337,6 +368,7 @@ impl PropagationClient { suppression_dirty: false, suppression_revision: 0, received_ids: Vec::new(), + rejected_ids: Vec::new(), pending_haves: VecDeque::new(), pending_wants: VecDeque::new(), request: None, @@ -372,8 +404,21 @@ impl PropagationClient { self.prepared_link_keys = Some((node, keys)); } + /// Select the node to download from. Changing it tears down a Link to the + /// previous node, as `LXMRouter.set_outbound_propagation_node` does. pub fn set_propagation_node(&mut self, dest_hash: [u8; 16]) { + if self.outbound_propagation_node == Some(dest_hash) { + return; + } self.outbound_propagation_node = Some(dest_hash); + if self + .link + .as_ref() + .is_some_and(|link| link.destination_hash != dest_hash) + { + self.link_lost(); + self.cleanup(); + } } /// Set the requested server response budget in decimal kB (1000 bytes). @@ -579,16 +624,15 @@ impl PropagationClient { /// Clear a terminal presentation snapshot after the caller has consumed /// its result. Active transfers are never reset by acknowledgement. pub fn acknowledge_transfer(&mut self) -> bool { - if !matches!( - self.status.state, - PropagationClientState::Complete - | PropagationClientState::Partial - | PropagationClientState::NoPath - | PropagationClientState::Failed - ) { + if !self.status.state.is_terminal() { return false; } - self.cleanup(); + // LXMRouter.acknowledge_sync_completion keeps an established Link for reuse. + if self.status.state.is_failure() { + self.cleanup(); + } else { + self.revoke_admissions(); + } self.status = PropagationTransferStatus::default(); true } @@ -616,29 +660,32 @@ impl PropagationClient { Some(h) => h, None => return false, }; - if !matches!( - self.status.state, - PropagationClientState::Idle - | PropagationClientState::Complete - | PropagationClientState::Partial - | PropagationClientState::NoPath - | PropagationClientState::Failed - ) { + if self.status.state != PropagationClientState::Idle && !self.status.state.is_terminal() { return false; } - if matches!( - self.status.state, - PropagationClientState::Complete - | PropagationClientState::Partial - | PropagationClientState::NoPath - | PropagationClientState::Failed - ) { + if self.status.state.is_failure() { self.cleanup(); } self.flush_pending_transport(); if !self.pending_transport.is_empty() { return false; } + // An active Link to the node is reused: identify, then list again. + if self.link.as_ref().is_some_and(|link| { + link.state == LinkState::Active && link.destination_hash == node_hash + }) && self.request.is_none() + { + self.reset_cycle(); + self.status = PropagationTransferStatus { + state: PropagationClientState::LinkEstablished, + ..PropagationTransferStatus::default() + }; + self.max_messages = max_messages.filter(|limit| *limit > 0); + return true; + } + if self.link.is_some() { + self.cleanup(); + } // LXMRouter.request_messages_from_propagation_node: link only once a path is known. if !self.query_path(node_hash) { return false; @@ -822,6 +869,11 @@ impl PropagationClient { self.endpoint_release_queued = false; self.pending_endpoint_bind = None; self.started_at = Some(Instant::now()); + self.reset_cycle(); + true + } + + fn reset_cycle(&mut self) { self.identified = false; self.available_messages.clear(); self.received_messages.clear(); @@ -833,13 +885,13 @@ impl PropagationClient { self.admission_started = None; self.admission_progress = None; self.received_ids.clear(); + self.rejected_ids.clear(); self.pending_haves.clear(); self.pending_wants.clear(); self.unread_bytes = 0; self.inbound_resources.clear(); self.inbound_split_resources.clear(); self.segment_routing.clear(); - true } /// Revoke current admissions, drop client-owned downloads and return to idle. @@ -997,7 +1049,7 @@ impl PropagationClient { }); match pending.result_rx.try_recv() { Ok(LinkEndpointSendResult::Sent | LinkEndpointSendResult::Queued { .. }) => { - if current && self.status.state != PropagationClientState::Failed { + if current && !self.status.state.is_failure() { match pending.success { EndpointSendSuccess::None => {} EndpointSendSuccess::RequestPacket => { @@ -1137,7 +1189,7 @@ impl PropagationClient { } for event in events { - if self.status.state == PropagationClientState::Failed { + if self.status.state.is_failure() { break; } match event { @@ -1275,7 +1327,7 @@ impl PropagationClient { self.inbound_resources.clear(); self.inbound_split_resources.clear(); self.segment_routing.clear(); - self.fail(); + self.link_lost(); } verified @@ -1900,6 +1952,9 @@ impl PropagationClient { /// Phase 1: parse available transient IDs from the server. fn handle_list_response(&mut self, response_data: &[u8]) { + if self.handle_peer_error(response_data) { + return; + } let ids = match Self::parse_available_message_ids(response_data) { Ok(ids) => ids, Err(_) => { @@ -1968,13 +2023,16 @@ impl PropagationClient { /// Validate type/count, exact requested TID membership, duplicates and full /// byte budget before publishing any item. Payload ranges borrow one owner. fn handle_get_response_owned(&mut self, response_data: Bytes) { - let count = match self.request.as_ref().map(|request| request.kind) { - Some(RequestKind::Get(count)) => count, + let (count, haves) = match self.request.as_ref().map(|request| request.kind) { + Some(RequestKind::Get(count, haves)) => (count, haves), _ => { self.fail(); return; } }; + if self.handle_peer_error(&response_data) { + return; + } let parsed = (|| { let mut cursor = std::io::Cursor::new(response_data.as_ref()); let n = rmp::decode::read_array_len(&mut cursor).map_err(|_| ())? as usize; @@ -2017,7 +2075,10 @@ impl PropagationClient { return; }; self.finish_request(&[]); - self.pending_wants.drain(..count); + // LXMRouter.message_get_response: one response ends the sync. + self.pending_wants.clear(); + self.pending_haves.drain(..haves); + self.status.result = Some(ranges.len()); self.admission_generation = self.admission_generation.wrapping_add(1); self.current_admission_generation .store(self.admission_generation, Ordering::Release); @@ -2087,7 +2148,6 @@ impl PropagationClient { receipt.record(), )); self.received_ids.push(result.scope.transient_id.to_vec()); - self.status.result = Some(self.status.result.unwrap_or(0).saturating_add(1)); if self.suppression.get(&receipt.record().scope).is_some() { self.suppression.remove(&receipt.record().scope); self.suppression_dirty = true; @@ -2095,6 +2155,12 @@ impl PropagationClient { } } DownloadAdmissionOutcome::Rejected(reason) => { + // Python purges every downloaded message, whatever lxmf_propagation + // did (LXMRouter.py:1838-1853). A message that failed for a passing + // local reason stays on the node so the next sync can fetch it again. + if !reason.is_transient() { + self.rejected_ids.push(result.scope.transient_id.to_vec()); + } self.admission_failures += 1; self.status.admission.rejected += 1; self.status.admission.retryable += usize::from(reason.is_transient()); @@ -2164,7 +2230,9 @@ impl PropagationClient { self.pending_haves.drain(..count); } Some(RequestKind::Purge(count)) => { - self.received_ids.drain(..count); + let accepted = count.min(self.received_ids.len()); + self.received_ids.drain(..accepted); + self.rejected_ids.drain(..count - accepted); } _ => {} } @@ -2176,7 +2244,7 @@ impl PropagationClient { self.poll_link_request(); self.flush_pending_transport(); self.poll_endpoint_control(); - if self.status.state == PropagationClientState::Failed { + if self.status.state.is_failure() { self.cleanup(); return; } @@ -2187,8 +2255,8 @@ impl PropagationClient { && started.elapsed() > self.timeout && self.status.state == PropagationClientState::LinkEstablishing { + self.link_lost(); self.cleanup(); - self.fail(); return; } @@ -2201,7 +2269,8 @@ impl PropagationClient { && response.waiting_since.elapsed() > request.timeout }) }) { - self.fail(); + // message_get_failed tears the Link down; clean_links then reports it. + self.link_lost(); self.cleanup(); return; } @@ -2221,13 +2290,13 @@ impl PropagationClient { rns_wire::flags::PacketType::Data, &payload, ); - self.fail(); + self.link_lost(); } - Some(LinkAction::Closed(_)) => self.fail(), + Some(LinkAction::Closed(_)) => self.link_lost(), Some(LinkAction::None) | None => {} } - if self.status.state != PropagationClientState::Failed { + if !self.status.state.is_failure() { self.drive_outbound_request(); } @@ -2280,7 +2349,7 @@ impl PropagationClient { PropagationClientState::LinkEstablished => { if !self.identified { self.send_identify(); - if self.status.state == PropagationClientState::Failed { + if self.status.state.is_failure() { return; } self.identified = true; @@ -2292,12 +2361,8 @@ impl PropagationClient { | PropagationClientState::Receiving | PropagationClientState::PurgeRequested | PropagationClientState::AwaitingAdmission => {} - PropagationClientState::Complete - | PropagationClientState::Partial - | PropagationClientState::NoPath - | PropagationClientState::Failed => { - self.cleanup(); - } + state if state.is_failure() => self.cleanup(), + _ => {} } } @@ -2386,24 +2451,24 @@ impl PropagationClient { self.send_next_chunk(); } - fn chunk_body(&self, ids: &[Vec], get: bool) -> Vec { + /// `[wants, haves, limit]` when `wants` is given, else the purge body `[None, haves]`. + fn chunk_body(&self, wants: Option<&[Vec]>, haves: &[Vec]) -> Vec { use rmpv::Value; - let ids = Value::Array(ids.iter().cloned().map(Value::Binary).collect()); - let mut fields = if get { - vec![ids, Value::Array(Vec::new())] - } else { - vec![Value::Nil, ids] - }; - if get && let Some(limit) = self.delivery_limit { + let list = |ids: &[Vec]| Value::Array(ids.iter().cloned().map(Value::Binary).collect()); + let mut fields = vec![wants.map_or(Value::Nil, list), list(haves)]; + if wants.is_some() + && let Some(limit) = self.delivery_limit + { fields.push(Value::F64(limit)); } crate::encode_value(&Value::Array(fields)) } - /// Fit the complete canonical request, not an assumed ID count. The - /// timestamp/path portion is encoded with the same Value types as Link's - /// prepare_request; its timestamp value does not change its wire length. - fn bounded_chunk(&self, ids: &[Vec], get: bool) -> (usize, Vec) { + /// Largest prefix of `ids` whose complete canonical request fits one + /// Resource segment. The timestamp/path portion is encoded with the same + /// Value types as Link's prepare_request; its timestamp value does not + /// change its wire length. + fn bounded_count(&self, ids: &[Vec], body: impl Fn(&[Vec]) -> Vec) -> usize { use rmpv::Value; let overhead = crate::encode_value(&Value::Array(vec![ Value::F64(0.0), @@ -2420,47 +2485,58 @@ impl PropagationClient { .min(MAX_EFFICIENT_SIZE / 32); while low < high { let count = low + (high - low).div_ceil(2); - if self.chunk_body(&ids[..count], get).len() <= MAX_EFFICIENT_SIZE - overhead { + if body(&ids[..count]).len() <= MAX_EFFICIENT_SIZE - overhead { low = count; } else { high = count - 1; } } - (low, self.chunk_body(&ids[..low], get)) + low } fn send_next_chunk(&mut self) { if self.request.is_some() || !self.pending_admissions.is_empty() - || self.status.state == PropagationClientState::Failed + || self.status.state.is_failure() { return; } self.prune_expired_haves(crate::now_f64() as u64); - if !self.received_ids.is_empty() { + let haves: Vec<_> = self + .pending_haves + .iter() + .take(MAX_EFFICIENT_SIZE / 32) + .cloned() + .collect(); + if !self.received_ids.is_empty() || !self.rejected_ids.is_empty() { self.send_purge_request(); - } else if !self.pending_haves.is_empty() { - let ids: Vec<_> = self - .pending_haves - .iter() - .take(MAX_EFFICIENT_SIZE / 32) - .cloned() - .collect(); - let (count, data) = self.bounded_chunk(&ids, false); - self.send_get_path_request(&data, RequestKind::Haves(count)); } else if self.suppression_dirty || self.suppression_persist_failed { self.status.state = PropagationClientState::AwaitingAdmission; } else if !self.pending_wants.is_empty() { - let ids: Vec<_> = self + // LXMRouter.message_list_response sends one `[wants, haves, limit]`. + // Haves that cannot share its single segment are purged first. + let wants: Vec<_> = self .pending_wants .iter() .take(MAX_EFFICIENT_SIZE / 32) .cloned() .collect(); - let (count, data) = self.bounded_chunk(&ids, true); + let count = self.bounded_count(&wants, |ids| self.chunk_body(Some(ids), &[])); + let fit = self.bounded_count(&haves, |ids| self.chunk_body(Some(&wants[..count]), ids)); + if fit < self.pending_haves.len() { + let count = self.bounded_count(&haves, |ids| self.chunk_body(None, ids)); + let data = self.chunk_body(None, &haves[..count]); + self.send_get_path_request(&data, RequestKind::Haves(count)); + return; + } + let data = self.chunk_body(Some(&wants[..count]), &haves[..fit]); self.status.progress = 0.0; self.status.data_size = None; - self.send_get_path_request(&data, RequestKind::Get(count)); + self.send_get_path_request(&data, RequestKind::Get(count, fit)); + } else if !self.pending_haves.is_empty() { + let count = self.bounded_count(&haves, |ids| self.chunk_body(None, ids)); + let data = self.chunk_body(None, &haves[..count]); + self.send_get_path_request(&data, RequestKind::Haves(count)); } else { self.status.state = if self.admission_failures == 0 { PropagationClientState::Complete @@ -2473,7 +2549,15 @@ impl PropagationClient { } fn send_purge_request(&mut self) { - let (count, data) = self.bounded_chunk(&self.received_ids, false); + let ids: Vec<_> = self + .received_ids + .iter() + .chain(&self.rejected_ids) + .take(MAX_EFFICIENT_SIZE / 32) + .cloned() + .collect(); + let count = self.bounded_count(&ids, |ids| self.chunk_body(None, ids)); + let data = self.chunk_body(None, &ids[..count]); self.send_get_path_request(&data, RequestKind::Purge(count)); } @@ -2577,7 +2661,7 @@ impl PropagationClient { } else { self.drive_outbound_request(); } - self.status.state != PropagationClientState::Failed + !self.status.state.is_failure() } fn drive_outbound_request(&mut self) { @@ -2656,7 +2740,7 @@ impl PropagationClient { TransferAction::Failed(_) => self.fail(), _ => {} } - if self.status.state == PropagationClientState::Failed { + if self.status.state.is_failure() { break; } } @@ -2748,7 +2832,7 @@ impl PropagationClient { let payload = data.slice(start + 16..); if matches!( self.request.as_ref().map(|r| r.kind), - Some(RequestKind::Get(_)) + Some(RequestKind::Get(..)) ) { self.handle_get_response_owned(payload); } else { @@ -2774,6 +2858,51 @@ impl PropagationClient { self.status.state = PropagationClientState::Failed; } + /// `LXMRouter.clean_links`: a closed Link before establishment is + /// `PR_LINK_FAILED`, during a transfer `PR_TRANSFER_FAILED`. + fn link_lost(&mut self) { + let state = match self.status.state { + PropagationClientState::PathRequested | PropagationClientState::LinkEstablishing => { + PropagationClientState::LinkFailed + } + PropagationClientState::LinkEstablished + | PropagationClientState::ListRequested + | PropagationClientState::GetRequested + | PropagationClientState::Receiving + | PropagationClientState::PurgeRequested + | PropagationClientState::AwaitingAdmission => PropagationClientState::TransferFailed, + state if state.is_failure() => state, + state => { + // A kept Link closed between syncs: release it without a failure. + self.revoke_admissions(); + self.cleanup(); + self.status.state = state; + return; + } + }; + self.revoke_admissions(); + self.status.state = state; + } + + /// `ERROR_NO_IDENTITY` and `ERROR_NO_ACCESS` answers to list and get + /// requests end the sync in their own states and tear the Link down. + fn handle_peer_error(&mut self, response_data: &[u8]) -> bool { + let mut input = response_data; + let state = match rmp::decode::read_int::(&mut input) { + Ok(code) if input.is_empty() && code == PeerError::NoIdentity as u64 => { + PropagationClientState::NoIdentityReceived + } + Ok(code) if input.is_empty() && code == PeerError::NoAccess as u64 => { + PropagationClientState::NoAccess + } + _ => return false, + }; + self.finish_request(response_data); + self.cleanup(); + self.status.state = state; + true + } + fn cleanup(&mut self) { self.link_request_result = None; self.path_query = None; @@ -2874,7 +3003,7 @@ mod tests { link_id: [1; 16], generation: 1, id: [2; 16], - kind: RequestKind::Get(messages.len()), + kind: RequestKind::Get(messages.len(), 0), sender_active: false, outbound: None, response: None, @@ -3451,7 +3580,7 @@ mod tests { rns_crypto::sha::full_hash(&msg1) ); assert_eq!(client.state(), PropagationClientState::AwaitingAdmission); - assert_eq!(client.transfer_status().result, None); + assert_eq!(client.transfer_status().result, Some(2)); } #[test] @@ -3501,7 +3630,7 @@ mod tests { link_id: client.link_id.unwrap(), generation: 1, id: [0x44; 16], - kind: RequestKind::Get(0), + kind: RequestKind::Get(0, 0), sender_active: false, outbound: None, response: None, @@ -3566,7 +3695,7 @@ mod tests { link_id: client.link_id.unwrap(), generation: 1, id: [0x44; 16], - kind: RequestKind::Get(0), + kind: RequestKind::Get(0, 0), sender_active: false, outbound: None, response: None, @@ -3623,7 +3752,7 @@ mod tests { link_id: client.link_id.unwrap(), generation: 1, id: [0x44; 16], - kind: RequestKind::Get(0), + kind: RequestKind::Get(0, 0), sender_active: false, outbound: None, response: None, @@ -3699,10 +3828,10 @@ mod tests { client.timeout = Duration::ZERO; client.tick(); - assert_eq!(client.status.state, PropagationClientState::Failed); + assert_eq!(client.status.state, PropagationClientState::LinkFailed); client.tick(); - assert_eq!(client.status.state, PropagationClientState::Failed); + assert_eq!(client.status.state, PropagationClientState::LinkFailed); assert!(client.acknowledge_transfer()); assert_eq!(client.status.state, PropagationClientState::Idle); } @@ -3810,10 +3939,10 @@ mod tests { .unwrap(); client.drain_events(&std::collections::HashMap::new()); - assert_eq!(client.status.state, PropagationClientState::Failed); + assert_eq!(client.status.state, PropagationClientState::TransferFailed); client.tick(); - assert_eq!(client.status.state, PropagationClientState::Failed); + assert_eq!(client.status.state, PropagationClientState::TransferFailed); assert!(client.link.is_none()); let saw_deregister = complete_client_cleanup(&mut client, &mut rx); assert!(saw_deregister); diff --git a/crates/lxmf-core/src/propagation_client_tests.rs b/crates/lxmf-core/src/propagation_client_tests.rs index 4d24ff7..76d386e 100644 --- a/crates/lxmf-core/src/propagation_client_tests.rs +++ b/crates/lxmf-core/src/propagation_client_tests.rs @@ -543,11 +543,11 @@ fn request_resource_progress_is_not_a_fixed_120_second_operation() { let request = peer.client.request.as_mut().unwrap(); request.waiting_since = Some(ago_or_skip!(request.timeout + Duration::from_secs(1))); peer.client.tick(); - assert_eq!(peer.client.state(), PropagationClientState::Failed); + assert_eq!(peer.client.state(), PropagationClientState::TransferFailed); assert!(peer.client.request.is_none()); // No late response can resurrect a cleaned-up request. peer.response(id, empty(), false); - assert_eq!(peer.client.state(), PropagationClientState::Failed); + assert_eq!(peer.client.state(), PropagationClientState::TransferFailed); } #[test] @@ -580,42 +580,37 @@ fn lost_advertisement_retries_same_resource_and_eventually_fails() { } #[test] -fn oversized_logical_sets_advance_after_empty_and_partial_chunks() { +fn one_get_request_ends_the_sync_even_when_wants_exceed_one_segment() { let mut peer = Peer::new(); let selected = ids(30_845); peer.client.max_messages = Some(30_840); peer.client.available_messages = selected.clone(); peer.client.available_messages.push(selected[0].clone()); peer.client.send_get_request(); - let mut consumed = 0; - loop { - let request = peer.client.request.as_ref().unwrap(); - let RequestKind::Get(count) = request.kind else { - panic!("get chunk expected") - }; - assert!(count <= crate::admission::MAX_DOWNLOAD_ITEMS); - assert!(count > 0); - if let Some(transfer) = &request.outbound { - assert!(transfer.resource.advertisement_data_size <= MAX_EFFICIENT_SIZE); - } - let id = request.id; - if consumed + count < 30_840 { - peer.response(id, empty(), false); - consumed += count; - continue; - } - assert_eq!(consumed + count, 30_840); - peer.response(id, binary_list(&[blob(consumed)]), false); - break; + let request = peer.client.request.as_ref().unwrap(); + let RequestKind::Get(count, 0) = request.kind else { + panic!("one get request expected") + }; + assert!(count > 0 && count <= crate::admission::MAX_DOWNLOAD_ITEMS); + if let Some(transfer) = &request.outbound { + assert!(transfer.resource.advertisement_data_size <= MAX_EFFICIENT_SIZE); } - assert!(peer.client.pending_wants.is_empty()); - assert!(peer.client.received_ids.is_empty()); + let (id, data, _) = peer.request(true); + assert_eq!(data.as_array().unwrap()[0], binary_list(&selected[..count])); + peer.response(id, binary_list(&[blob(0)]), false); + assert!( + peer.client.pending_wants.is_empty(), + "unserved wants wait for the next list" + ); assert_eq!( peer.client.state(), PropagationClientState::AwaitingAdmission ); peer.accept_downloads(); - assert_eq!(peer.client.received_ids.len(), 1); + assert!(matches!( + peer.client.request.as_ref().unwrap().kind, + RequestKind::Purge(1) + )); let id = peer.client.request.as_ref().unwrap().id; peer.response(id, empty(), false); assert_eq!(peer.client.state(), PropagationClientState::Complete); @@ -719,22 +714,23 @@ fn every_id_branch_switches_at_real_packet_boundary() { peer.client.send_purge_request(); } } - assert_eq!( - peer.client.request.as_ref().unwrap().outbound.is_some(), - count > 11 - ); + if branch != 2 { + assert_eq!( + peer.client.request.as_ref().unwrap().outbound.is_some(), + count > 11 + ); + } let (id, body, _) = peer.request(true); let fields = body.as_array().unwrap(); assert_eq!( fields[if branch == 0 { 0 } else { 1 }], binary_list(&selected) ); - peer.response(id, empty(), false); if branch == 2 { - let (id, body, _) = peer.request(true); - assert_eq!(body.as_array().unwrap()[0], binary_list(&[vec![0xee; 32]])); - peer.response(id, empty(), false); + // One `[wants, haves, limit]` request carries both lists. + assert_eq!(fields[0], binary_list(&[vec![0xee; 32]])); } + peer.response(id, empty(), false); assert_eq!(peer.client.state(), PropagationClientState::Complete); } } @@ -1091,18 +1087,16 @@ fn expired_durable_haves_are_downloaded_instead_of_purged() { ]); peer.client.available_messages = vec![expired.to_vec(), visible.to_vec()]; peer.client.send_get_request(); - let (id, request, _) = peer.request(true); - assert_eq!( - request, - Value::Array(vec![Value::Nil, binary_list(&[visible.to_vec()])]) - ); - assert!(!peer.client.local_messages.contains(expired.as_slice())); - peer.response(id, empty(), false); let (_, request, _) = peer.request(true); assert_eq!( - request.as_array().unwrap()[0], - binary_list(&[expired.to_vec()]) + request, + Value::Array(vec![ + binary_list(&[expired.to_vec()]), + binary_list(&[visible.to_vec()]), + Value::F64(1000.0), + ]) ); + assert!(!peer.client.local_messages.contains(expired.as_slice())); } #[test] @@ -1244,7 +1238,7 @@ fn stale_suppression_checkpoint_cannot_acknowledge_newer_pruning_or_epochs() { } #[test] -fn rejected_and_retryable_download_counts_never_become_purge_authority() { +fn rejected_downloads_never_become_local_haves_and_only_definitive_ones_are_purged() { use crate::admission::{DownloadAdmissionOutcome, SuppressionReason}; let mut peer = Peer::new(); let messages = blobs(2); @@ -1272,5 +1266,71 @@ fn rejected_and_retryable_download_counts_never_become_purge_authority() { ); assert!(peer.client.local_messages.is_empty()); assert!(peer.client.received_ids.is_empty()); - assert!(peer.rx.is_empty(), "no durable acceptance means no purge"); + // LXMRouter.message_get_response purges every downloaded message; the one + // refused for a passing local reason (a missing key) stays on the node. + let (id, body, _) = peer.request(true); + assert_eq!( + body, + Value::Array(vec![Value::Nil, binary_list(&ids(2)[..1])]) + ); + peer.response(id, empty(), false); + let revision = peer.client.suppression_revision(); + assert!(peer.client.acknowledge_suppression_persistence(revision)); + peer.client.poll_admissions(); + assert_eq!(peer.client.state(), PropagationClientState::Partial); + assert_eq!(peer.client.transfer_status().result, Some(2)); +} + +#[test] +fn node_error_codes_end_list_and_get_in_their_own_states() { + for (code, state) in [ + (0xf0, PropagationClientState::NoIdentityReceived), + (0xf1, PropagationClientState::NoAccess), + ] { + for get in [false, true] { + let mut peer = Peer::new(); + if get { + peer.client.available_messages = ids(1); + peer.client.send_get_request(); + } else { + peer.client.send_list_request(); + } + let (id, _, _) = peer.request(true); + peer.response(id, Value::from(code), false); + assert_eq!(peer.client.state(), state); + assert!(peer.client.link.is_none(), "the Link is torn down"); + assert!(peer.client.take_downloaded_messages().is_empty()); + assert!(peer.client.acknowledge_transfer()); + } + } +} + +#[test] +fn changing_the_node_tears_down_the_link_to_the_previous_one() { + let mut peer = Peer::new(); + peer.client.set_propagation_node([0xe8; 16]); + assert!(peer.client.link.is_some(), "same node keeps the Link"); + peer.client.send_list_request(); + let _ = peer.request(true); + peer.client.set_propagation_node([0xe9; 16]); + assert!(peer.client.link.is_none()); + assert_eq!(peer.client.state(), PropagationClientState::TransferFailed); + assert!(peer.client.acknowledge_transfer()); +} + +#[test] +fn completed_sync_keeps_the_link_and_the_next_sync_reuses_it() { + let mut peer = Peer::new(); + peer.client.link.as_mut().unwrap().state = LinkState::Active; + peer.client.send_list_request(); + let (id, _, _) = peer.request(true); + peer.response(id, empty(), false); + assert_eq!(peer.client.state(), PropagationClientState::Complete); + assert!(peer.client.acknowledge_transfer()); + assert!(peer.client.link.is_some(), "acknowledgement keeps the Link"); + assert!(peer.client.start_download()); + assert_eq!(peer.client.state(), PropagationClientState::LinkEstablished); + peer.client.tick(); + let (_, body, _) = peer.request(true); + assert_eq!(body, Value::Array(vec![Value::Nil, Value::Nil])); } diff --git a/crates/lxmf-core/src/router.rs b/crates/lxmf-core/src/router.rs index cf2c416..becb12d 100644 --- a/crates/lxmf-core/src/router.rs +++ b/crates/lxmf-core/src/router.rs @@ -333,6 +333,7 @@ pub struct LxmRouter { path_request_times: HashMap<[u8; 16], f64>, /// A slow-path message concluded; outbound processing should run again. outbound_kick: bool, + propagation_announce_due: bool, /// Directory given to [`Self::load_state`]; delivered and processed IDs are /// claimed there durably before delivery callbacks run. claims_dir: Option, @@ -443,6 +444,7 @@ impl LxmRouter { destination_retains: VecDeque::new(), path_request_times: HashMap::new(), outbound_kick: false, + propagation_announce_due: false, claims_dir: None, } } @@ -1681,6 +1683,19 @@ impl LxmRouter { self.config.propagation_enabled = enabled; } + /// `LXMRouter.disable_propagation`: stop propagating and re-announce the + /// node with `node_state` false. The embedder sends the announce after + /// [`Self::take_propagation_announce`], `NODE_ANNOUNCE_DELAY` later. + pub fn disable_propagation(&mut self) { + self.config.propagation_enabled = false; + self.propagation_announce_due = true; + } + + /// Whether a propagation node announce was requested since the last call. + pub fn take_propagation_announce(&mut self) -> bool { + std::mem::take(&mut self.propagation_announce_due) + } + /// Set the singular outbound propagation node used for `PROPAGATED` /// message delivery. pub fn set_outbound_propagation_node(&mut self, destination_hash: Option<[u8; 16]>) { @@ -4426,6 +4441,21 @@ mod tests { assert!(peer.currently_transferring_messages.is_none()); } + #[test] + fn disable_propagation_requests_an_announce_with_node_state_false() { + let mut router = LxmRouter::new(RouterConfig { + propagation_enabled: true, + ..Default::default() + }); + assert!(!router.take_propagation_announce()); + router.disable_propagation(); + assert!(router.take_propagation_announce()); + assert!(!router.take_propagation_announce()); + let data = crate::handlers::parse_pn_announce_data(&router.get_propagation_node_app_data()) + .unwrap(); + assert!(!data.node_state); + } + #[test] fn test_control_status() { let config = RouterConfig { diff --git a/crates/lxmf-tools/src/commands/lxmd.rs b/crates/lxmf-tools/src/commands/lxmd.rs index 8962dcc..a683776 100644 --- a/crates/lxmf-tools/src/commands/lxmd.rs +++ b/crates/lxmf-tools/src/commands/lxmd.rs @@ -1749,6 +1749,9 @@ struct LxmdRunner { node_announces_due: VecDeque, startup_node_announce_pending: bool, last_propagation_check: f64, + /// `wants_download_on_path_available_timeout`: start the download as soon + /// as the node becomes known, until this time. + download_on_path_until: Option, last_crypto_save: f64, checkpoint_task: Option, last_cull: f64, @@ -2658,6 +2661,7 @@ impl LxmdRunner { node_announces_due: VecDeque::new(), startup_node_announce_pending: false, last_propagation_check: 0.0, + download_on_path_until: None, last_crypto_save: now, checkpoint_task: None, last_cull: now, @@ -4222,6 +4226,9 @@ impl LxmdRunner { if self.router.take_outbound_kick() { self.run_outbound(); } + if self.router.take_propagation_announce() { + self.schedule_node_announce(now_f64()); + } self.drive_propagation_sync(); @@ -4245,6 +4252,10 @@ impl LxmdRunner { let retain_synced_on_node = self.router.retain_node_lxms(); let mut unknown_propagation_node = None; if let Some(ref mut client) = self.propagation_client { + // One outbound node serves uploads and downloads, as in LXMRouter. + if let Some(node) = self.router.outbound_propagation_node { + client.set_propagation_node(node); + } client.replace_durable_haves(locally_delivered_ids); client.set_retain_synced_on_node(retain_synced_on_node); client.drain_events(&self.known_identities); @@ -4254,12 +4265,16 @@ impl LxmdRunner { let _ = client.take_suppression_updates(); // Auto-download every 90s - if now - self.last_propagation_check > 90.0 + let path_awaited = self + .download_on_path_until + .is_some_and(|until| now < until && propagation_node_ready); + if (now - self.last_propagation_check > 90.0 || path_awaited) && client.state() == lxmf_core::propagation_client::PropagationClientState::Idle { if propagation_node_ready && self.admission_store.is_some() { client.start_download(); self.last_propagation_check = now; + self.download_on_path_until = None; tracing::debug!("auto-triggered propagation download"); } else if let Some(node) = self.router.outbound_propagation_node && queue_unknown_propagation_node_path_request( @@ -4269,6 +4284,12 @@ impl LxmdRunner { now, ) { + // LXMRouter.request_messages_from_propagation_node path wait. + self.download_on_path_until = Some( + now + lxmf_core::propagation_client::PR_PATH_TIMEOUT + .max(lxmf_core::constants::PATH_REQUEST_WAIT) + as f64, + ); unknown_propagation_node = Some(node); tracing::debug!( node = %hex::encode(node), @@ -4277,13 +4298,7 @@ impl LxmdRunner { } } let status = client.transfer_status(); - acknowledge_propagation = matches!( - 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 - ); + acknowledge_propagation = status.state.is_terminal(); propagation_status = Some(status); } if let Some(node) = unknown_propagation_node {