lxmf: stamp link requests, wait for paths, and pick peers like upstream

This commit is contained in:
DeFiDude committed 2026-11-10 13:37:20 -07:00
1 parent 052128bf4e
commit 1a9830008c
11 files changed
+1569 -524

No files matched your search

+7
View File
@@ -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"
+1 -1
View File
@@ -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));
+18 -1
View File
@@ -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<TransportReady>,
delivery_events: VecDeque<LxmfDeliveryEvent>,
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()
+175 -87
View File
@@ -73,6 +73,24 @@ struct StoredPeerV2 {
metadata: Option<HashMap<u8, Vec<u8>>>,
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<Vec<Vec<u8>>>,
}
/// Immutable inputs for one outbound propagation offer.
@@ -96,6 +114,8 @@ pub struct OutboundOfferPolicy {
pub autopeered: bool,
pub is_static: bool,
pub metadata: Option<HashMap<u8, Vec<u8>>>,
/// Messages queued for this peer; `None` offers every live store entry.
pub unhandled_messages: Option<HashSet<PropagationTransientId>>,
}
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<f64>,
@@ -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<PropagationTransientId>,
/// Messages distributed to this peer and not yet handled by it.
pub unhandled_messages: HashSet<PropagationTransientId>,
}
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<u8> {
let mut handled: Vec<Vec<u8>> = self.handled_messages.iter().map(|h| h.to_vec()).collect();
handled.sort();
let mut unhandled: Vec<Vec<u8>> =
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> {
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::<StoredPeerV2>(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<Self> {
@@ -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<usize> {
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<usize> {
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<usize> = (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<usize> = if !waiting.is_empty() {
let unknown_speed: Vec<usize> = 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<usize> = 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]
+242 -10
View File
@@ -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<PropagationClientState>,
identity_pub: Option<[u8; 64]>,
identity_key: Option<Ed25519PrivateKey>,
link_stamper: LinkRequestStamper,
/// Phase 1 response: transient IDs the server has.
available_messages: Vec<Vec<u8>>,
/// Messages we already have locally.
@@ -269,8 +275,17 @@ pub struct PropagationClient {
started_at: Option<Instant>,
timeout: Duration,
identified: bool,
path_query: Option<oneshot::Receiver<TransportQueryResponse>>,
bitrate_query: Option<oneshot::Receiver<TransportQueryResponse>>,
path_requested_at: Option<Instant>,
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<TransportMessage>,
@@ -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<TransportMessage>) {
assert!(client.start_download());
answer_path_query(rx, true);
client.tick();
}
fn answer_path_query(rx: &mut mpsc::Receiver<TransportMessage>, 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;
+70 -25
View File
@@ -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<PropagationTransientId>,
pub terminal_handled_ids: Vec<PropagationTransientId>,
/// Below the peer's stamp requirement: dropped from its unhandled set only.
pub dropped_unhandled_ids: Vec<PropagationTransientId>,
pub generation_exhausted: bool,
}
@@ -560,6 +569,7 @@ pub(crate) enum InstallPreparedSyncOffer {
offer: SyncOffer,
generation: u64,
terminal_handled_ids: Vec<PropagationTransientId>,
dropped_unhandled_ids: Vec<PropagationTransientId>,
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<PropagationTransientId>,
unhandled_messages: &HashSet<PropagationTransientId>,
) -> 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<LxmPeer> {
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"
+241 -27
View File
@@ -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<oneshot::Receiver<PreparedSyncOffer>>,
ready_prepared_offer: Option<PreparedSyncOffer>,
handled_updates: Vec<PropagationTransientId>,
dropped_unhandled_updates: Vec<PropagationTransientId>,
runtime_handle: Option<tokio::runtime::Handle>,
identity_pub: Option<[u8; 64]>,
identity_key: Option<Ed25519PrivateKey>,
link_stamper: LinkRequestStamper,
active_offer_generation: Option<u64>,
generation_exhausted: bool,
terminal_result: Option<PeerSyncTerminalResult>,
@@ -180,6 +189,8 @@ pub struct PropagationSyncTask {
transfer_wire_size: u64,
transfer_started: Option<Instant>,
link_establishment_rate: Option<f64>,
path_query: Option<oneshot::Receiver<TransportQueryResponse>>,
path_requested_at: Option<Instant>,
}
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<PropagationTransientId> {
std::mem::take(&mut self.dropped_unhandled_updates)
}
pub fn take_terminal_peer_result(&mut self) -> Option<PeerSyncTerminalResult> {
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<TransportMessage>,
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());
+103 -143
View File
@@ -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<OutboundOfferPolicy> {
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::<Vec<_>>();
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::<Vec<_>>();
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<_>>(),
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<_>>(),
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]
@@ -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<rns_transport::messages::TransportMessage>,
) {
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<rns_transport::messages::TransportMessage>,
) {
@@ -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() {
File diff suppressed because it is too large. Load diff
+3 -3
View File
@@ -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);