mirror of
https://github.com/ratspeak/rsLXMF
synced 2026-11-22 23:10:35 +00:00
router: rework outbound delivery to follow upstream's process_outbound
This commit is contained in:
1 parent
f855bcfbe5
commit
ea5c61aa6f
7 files changed
+1621
-2241
No files matched your search
@@ -146,7 +146,7 @@ impl LinkDeliveryStartOptions {
|
||||
timing,
|
||||
packed_override: Some(packed_payload),
|
||||
auto_compress,
|
||||
reusable: false,
|
||||
reusable: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -389,9 +389,10 @@ pub struct PendingDelivery {
|
||||
packet_awaiting_dispatch: bool,
|
||||
pretransfer_identify_staged: bool,
|
||||
endpoint_release_queued: bool,
|
||||
/// Keep successful Direct links open for additional messages. Propagation
|
||||
/// deposits currently keep the old one-shot behavior.
|
||||
/// Keep successful links open for additional messages.
|
||||
pub reusable: bool,
|
||||
/// Upload link to a propagation node; never identified (LXMRouter.py:3283-3287).
|
||||
propagation_upload: bool,
|
||||
/// Whether local Link identification was staged after a successful Direct
|
||||
/// delivery. Requires configured identity keys; it is not a peer acknowledgement.
|
||||
pub backchannel_identified: bool,
|
||||
@@ -801,6 +802,18 @@ pub struct DirectLinkSnapshot {
|
||||
pub idle_expired: bool,
|
||||
pub queued_deliveries: usize,
|
||||
pub in_flight_deliveries: usize,
|
||||
/// Whether the Link ever became active.
|
||||
pub link_activated: bool,
|
||||
}
|
||||
|
||||
impl DirectLinkSnapshot {
|
||||
pub fn link_active(&self) -> bool {
|
||||
self.link_state == LinkState::Active
|
||||
}
|
||||
|
||||
pub fn link_closed(&self) -> bool {
|
||||
self.link_state == LinkState::Closed || self.delivery_state == DeliveryState::Failed
|
||||
}
|
||||
}
|
||||
|
||||
/// Snapshot of a message currently owned by link delivery.
|
||||
@@ -884,6 +897,8 @@ pub struct LinkDeliveryManager {
|
||||
direct_links: HashMap<[u8; 16], [u8; 16]>,
|
||||
/// Reusable upstream-style inbound backchannels keyed by remote LXMF delivery destination hash.
|
||||
backchannel_links: HashMap<[u8; 16], [u8; 16]>,
|
||||
/// Reusable propagation upload links keyed by propagation node hash.
|
||||
propagation_links: HashMap<[u8; 16], [u8; 16]>,
|
||||
pending: HashMap<[u8; 16], PendingDelivery>,
|
||||
backchannel_tx: Option<mpsc::Sender<BackchannelSendCommand>>,
|
||||
backchannel_cancellation_aware: bool,
|
||||
@@ -942,6 +957,7 @@ impl LinkDeliveryManager {
|
||||
endpoint_lifecycle_rx,
|
||||
direct_links: HashMap::new(),
|
||||
backchannel_links: HashMap::new(),
|
||||
propagation_links: HashMap::new(),
|
||||
pending: HashMap::new(),
|
||||
backchannel_tx: None,
|
||||
backchannel_cancellation_aware: false,
|
||||
@@ -1039,11 +1055,9 @@ impl LinkDeliveryManager {
|
||||
/// segments remain immutable. This never enables compression or changes the
|
||||
/// propagation-node envelope. New submissions still carry their own policy.
|
||||
pub fn disable_pending_direct_compression(&mut self, destination: [u8; 16]) {
|
||||
for delivery in self
|
||||
.pending
|
||||
.values_mut()
|
||||
.filter(|delivery| delivery.reusable && delivery.dest_hash == destination)
|
||||
{
|
||||
for delivery in self.pending.values_mut().filter(|delivery| {
|
||||
delivery.reusable && !delivery.propagation_upload && delivery.dest_hash == destination
|
||||
}) {
|
||||
if delivery.transfer.is_none() && delivery.remaining_segments.is_none() {
|
||||
delivery.message.auto_compress = false;
|
||||
delivery.auto_compress = false;
|
||||
@@ -1226,6 +1240,7 @@ impl LinkDeliveryManager {
|
||||
dest_hash: delivery.dest_hash,
|
||||
message: delivery.message,
|
||||
reason: reason.to_string(),
|
||||
link_activated: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1344,6 +1359,20 @@ impl LinkDeliveryManager {
|
||||
auto_compress: bool,
|
||||
timing: LinkEstablishmentTiming,
|
||||
) -> Result<[u8; 16], LinkDeliveryStartFailure> {
|
||||
if let Some(link_id) = self.propagation_links.get(&dest_hash).copied() {
|
||||
if let Some(delivery) = self
|
||||
.pending
|
||||
.get_mut(&link_id)
|
||||
.filter(|delivery| delivery.link.state != LinkState::Closed)
|
||||
{
|
||||
delivery.queue_delivery(message, Some(packed_payload), auto_compress);
|
||||
if delivery.state == DeliveryState::Idle && delivery.link.is_active() {
|
||||
let _ = delivery.start_queued_delivery();
|
||||
}
|
||||
return Ok(link_id);
|
||||
}
|
||||
self.propagation_links.remove(&dest_hash);
|
||||
}
|
||||
self.start_delivery_inner(
|
||||
message,
|
||||
dest_hash,
|
||||
@@ -1642,6 +1671,7 @@ impl LinkDeliveryManager {
|
||||
reusable,
|
||||
} = 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);
|
||||
if link
|
||||
.try_extend_establishment_timeout(timing.first_hop_timeout().as_secs_f64())
|
||||
@@ -1756,6 +1786,7 @@ impl LinkDeliveryManager {
|
||||
pretransfer_identify_staged: false,
|
||||
endpoint_release_queued: false,
|
||||
reusable,
|
||||
propagation_upload: packed_override_kind,
|
||||
backchannel_identified: false,
|
||||
queued: VecDeque::new(),
|
||||
inbound_resources: HashMap::new(),
|
||||
@@ -1764,7 +1795,9 @@ impl LinkDeliveryManager {
|
||||
inbound_resource_lifecycles: HashMap::new(),
|
||||
},
|
||||
);
|
||||
if reusable {
|
||||
if packed_override_kind {
|
||||
self.propagation_links.insert(dest_hash, link_id);
|
||||
} else if reusable {
|
||||
self.direct_links.insert(dest_hash, link_id);
|
||||
}
|
||||
|
||||
@@ -2417,7 +2450,7 @@ impl LinkDeliveryManager {
|
||||
};
|
||||
delivery.link.record_inbound();
|
||||
delivery.link.record_rx(encrypted_data.len());
|
||||
if !delivery.reusable {
|
||||
if delivery.propagation_upload {
|
||||
let mut input = plaintext.as_slice();
|
||||
let rejection = rmpv::decode::read_value(&mut input).ok();
|
||||
if input.is_empty()
|
||||
@@ -2479,7 +2512,7 @@ impl LinkDeliveryManager {
|
||||
let Some(delivery) = self.pending.get_mut(link_id) else {
|
||||
return false;
|
||||
};
|
||||
if !delivery.reusable || !delivery.link.is_active() {
|
||||
if !delivery.reusable || delivery.propagation_upload || !delivery.link.is_active() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -2670,7 +2703,7 @@ impl LinkDeliveryManager {
|
||||
let Some(delivery) = self.pending.get_mut(link_id) else {
|
||||
return false;
|
||||
};
|
||||
if !delivery.reusable || !delivery.link.is_active() {
|
||||
if !delivery.reusable || delivery.propagation_upload || !delivery.link.is_active() {
|
||||
return false;
|
||||
}
|
||||
delivery.link.record_inbound();
|
||||
@@ -3046,8 +3079,6 @@ impl LinkDeliveryManager {
|
||||
}
|
||||
// Reusable Direct links follow upstream LXMF and identify
|
||||
// after a successful delivery, not before the transfer.
|
||||
// One-shot propagation links keep the previous pre-transfer
|
||||
// identify behavior for compatibility with existing callers.
|
||||
delivery.state = DeliveryState::Transferring;
|
||||
if delivery.message.progress < 0.05 {
|
||||
delivery.message.progress = 0.05;
|
||||
@@ -3395,7 +3426,9 @@ impl LinkDeliveryManager {
|
||||
resource_id,
|
||||
);
|
||||
}
|
||||
if delivery.reusable {
|
||||
if delivery.propagation_upload {
|
||||
self.propagation_links.remove(&delivery.dest_hash);
|
||||
} else if delivery.reusable {
|
||||
self.direct_links.remove(&delivery.dest_hash);
|
||||
}
|
||||
let graceful_release = delivery.endpoint_release_queued
|
||||
@@ -3662,6 +3695,7 @@ impl LinkDeliveryManager {
|
||||
dest_hash: delivery.dest_hash,
|
||||
message: delivery.message,
|
||||
reason,
|
||||
link_activated: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -4151,6 +4185,7 @@ impl LinkDeliveryManager {
|
||||
dest_hash: delivery.dest_hash,
|
||||
message: delivery.message,
|
||||
reason,
|
||||
link_activated: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -4376,6 +4411,7 @@ impl LinkDeliveryManager {
|
||||
dest_hash: delivery.dest_hash,
|
||||
message: queued.message,
|
||||
reason: reason.to_string(),
|
||||
link_activated: delivery.link.activated_at.is_some(),
|
||||
});
|
||||
}
|
||||
break;
|
||||
@@ -4405,6 +4441,9 @@ impl LinkDeliveryManager {
|
||||
if self.direct_links.get(&dest_hash) == Some(&link_id) {
|
||||
self.direct_links.remove(&dest_hash);
|
||||
}
|
||||
if self.propagation_links.get(&dest_hash) == Some(&link_id) {
|
||||
self.propagation_links.remove(&dest_hash);
|
||||
}
|
||||
}
|
||||
|
||||
if !results.is_empty() {
|
||||
@@ -4460,6 +4499,7 @@ impl LinkDeliveryManager {
|
||||
dest_hash: delivery.dest_hash,
|
||||
message: delivery.message,
|
||||
reason: reason.to_string(),
|
||||
link_activated: true,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -4533,6 +4573,9 @@ impl LinkDeliveryManager {
|
||||
if self.direct_links.get(&dest_hash) == Some(&link_id) {
|
||||
self.direct_links.remove(&dest_hash);
|
||||
}
|
||||
if self.propagation_links.get(&dest_hash) == Some(&link_id) {
|
||||
self.propagation_links.remove(&dest_hash);
|
||||
}
|
||||
}
|
||||
|
||||
if cancelled {
|
||||
@@ -4859,6 +4902,23 @@ impl LinkDeliveryManager {
|
||||
idle_expired: direct_link_idle_expired(delivery),
|
||||
queued_deliveries: delivery.queued.len(),
|
||||
in_flight_deliveries: usize::from(delivery.state != DeliveryState::Idle),
|
||||
link_activated: delivery.link.activated_at.is_some(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Snapshot of the reusable upload Link to a propagation node.
|
||||
pub fn propagation_link_snapshot(&self, node: [u8; 16]) -> Option<DirectLinkSnapshot> {
|
||||
let link_id = *self.propagation_links.get(&node)?;
|
||||
let delivery = self.pending.get(&link_id)?;
|
||||
Some(DirectLinkSnapshot {
|
||||
link_id,
|
||||
dest_hash: node,
|
||||
link_state: delivery.link.state,
|
||||
delivery_state: delivery.state,
|
||||
idle_expired: direct_link_idle_expired(delivery),
|
||||
queued_deliveries: delivery.queued.len(),
|
||||
in_flight_deliveries: usize::from(delivery.state != DeliveryState::Idle),
|
||||
link_activated: delivery.link.activated_at.is_some(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -4897,7 +4957,11 @@ impl LinkDeliveryManager {
|
||||
pub fn stats(&self) -> LinkDeliveryStats {
|
||||
let mut stats = LinkDeliveryStats {
|
||||
sessions: self.pending.len(),
|
||||
direct_sessions: self.pending.values().filter(|d| d.reusable).count(),
|
||||
direct_sessions: self
|
||||
.pending
|
||||
.values()
|
||||
.filter(|d| d.reusable && !d.propagation_upload)
|
||||
.count(),
|
||||
one_shot_sessions: self.pending.values().filter(|d| !d.reusable).count(),
|
||||
backchannel_sessions: self.backchannel_links.len(),
|
||||
pending_backchannel_starts: self
|
||||
@@ -4944,7 +5008,7 @@ fn delivery_event(
|
||||
) -> LxmfDeliveryEvent {
|
||||
LxmfDeliveryEvent {
|
||||
kind,
|
||||
method: if delivery.reusable {
|
||||
method: if !delivery.propagation_upload {
|
||||
LxmfDeliveryEventMethod::Direct
|
||||
} else {
|
||||
LxmfDeliveryEventMethod::PropagationDeposit
|
||||
@@ -5073,6 +5137,7 @@ fn fail_backchannel_start_in_place(
|
||||
dest_hash: start.dest_hash,
|
||||
message,
|
||||
reason,
|
||||
link_activated: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5138,6 +5203,7 @@ fn finish_reusable_delivery(
|
||||
delivery: &mut PendingDelivery,
|
||||
) {
|
||||
if !delivery.backchannel_identified
|
||||
&& !delivery.propagation_upload
|
||||
&& let (Some(pub_key), Some(sign_key)) = (identity_pub, identity_key)
|
||||
{
|
||||
delivery.backchannel_identified = send_link_identify(
|
||||
@@ -5227,6 +5293,7 @@ fn push_failed_delivery_and_queue(
|
||||
dest_hash: delivery.dest_hash,
|
||||
message,
|
||||
reason: reason.to_string(),
|
||||
link_activated: delivery.link.activated_at.is_some(),
|
||||
});
|
||||
fail_queued_deliveries(results, events, link_id, delivery, reason);
|
||||
}
|
||||
@@ -5259,6 +5326,7 @@ fn fail_queued_deliveries(
|
||||
dest_hash: delivery.dest_hash,
|
||||
message: queued.message,
|
||||
reason: reason.to_string(),
|
||||
link_activated: delivery.link.activated_at.is_some(),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -5487,6 +5555,8 @@ pub enum DeliveryResult {
|
||||
dest_hash: [u8; 16],
|
||||
message: LxMessage,
|
||||
reason: String,
|
||||
/// Whether the Link carrying the message had become active.
|
||||
link_activated: bool,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -6519,7 +6589,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn exact_packed_packet_preserves_rtt_identify_and_payload_order() {
|
||||
async fn exact_packed_packet_sends_rtt_then_payload_without_identify() {
|
||||
exact_packet_driver_fixture(false, true).await;
|
||||
}
|
||||
|
||||
@@ -6802,34 +6872,6 @@ mod tests {
|
||||
mgr.tick().is_empty(),
|
||||
"5ms proof floor must not run before driver admission"
|
||||
);
|
||||
if packed {
|
||||
assert_eq!(mgr.pending[&link_id].state, DeliveryState::Identifying);
|
||||
let rtt = driver_rx.recv().await.unwrap();
|
||||
let (header, offset) = rns_wire::header::PacketHeader::unpack(&rtt).unwrap();
|
||||
assert_eq!(header.context, rns_wire::context::PacketContext::Lrrtt);
|
||||
responder.receive_rtt_packet(&rtt[offset..]).unwrap();
|
||||
tx.send(TransportMessage::Tick(TimerTick {
|
||||
timestamp: std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs_f64(),
|
||||
}))
|
||||
.await
|
||||
.unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(2), async {
|
||||
loop {
|
||||
assert!(mgr.tick().is_empty());
|
||||
if mgr.pending[&link_id].state == DeliveryState::AwaitingProof {
|
||||
break;
|
||||
}
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
tokio::time::sleep(Duration::from_millis(30)).await;
|
||||
assert!(mgr.tick().is_empty());
|
||||
}
|
||||
assert!(mgr.pending[&link_id].packet_awaiting_dispatch);
|
||||
assert_eq!(
|
||||
mgr.message_timeout_window(message_hash).unwrap().1,
|
||||
@@ -6841,19 +6883,9 @@ mod tests {
|
||||
}
|
||||
let rtt = driver_rx.recv().await.unwrap();
|
||||
let (header, offset) = rns_wire::header::PacketHeader::unpack(&rtt).unwrap();
|
||||
if packed {
|
||||
assert_eq!(
|
||||
header.context,
|
||||
rns_wire::context::PacketContext::LinkIdentify
|
||||
);
|
||||
assert_eq!(
|
||||
responder.handle_identification(&rtt[offset..]).unwrap(),
|
||||
identity_pub
|
||||
);
|
||||
} else {
|
||||
assert_eq!(header.context, rns_wire::context::PacketContext::Lrrtt);
|
||||
responder.receive_rtt_packet(&rtt[offset..]).unwrap();
|
||||
}
|
||||
// Propagation uploads are never identified, even with identity keys.
|
||||
assert_eq!(header.context, rns_wire::context::PacketContext::Lrrtt);
|
||||
responder.receive_rtt_packet(&rtt[offset..]).unwrap();
|
||||
tx.send(TransportMessage::Tick(TimerTick {
|
||||
timestamp: std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
@@ -9112,29 +9144,34 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_packed_delivery_is_one_shot_not_direct_session() {
|
||||
fn packed_deliveries_share_one_propagation_link() {
|
||||
let (tx, _rx) = mpsc::channel(64);
|
||||
let mut mgr = LinkDeliveryManager::new(tx, None, None);
|
||||
let dest_hash = [0xC1; 16];
|
||||
let msg = crate::message::test_message(
|
||||
[0xAA; 16],
|
||||
[0xBB; 16],
|
||||
"Propagation",
|
||||
"deposit",
|
||||
crate::constants::DeliveryMethod::Propagated,
|
||||
);
|
||||
let node = [0xC1; 16];
|
||||
let message = |content: &str| {
|
||||
crate::message::test_message(
|
||||
[0xAA; 16],
|
||||
[0xBB; 16],
|
||||
"Propagation",
|
||||
content,
|
||||
crate::constants::DeliveryMethod::Propagated,
|
||||
)
|
||||
};
|
||||
|
||||
let link_id = mgr
|
||||
.start_packed_delivery(msg, dest_hash, 1, b"packed propagation".to_vec(), false)
|
||||
let first = mgr
|
||||
.start_packed_delivery(message("one"), node, 1, b"one".to_vec(), false)
|
||||
.unwrap();
|
||||
let second = mgr
|
||||
.start_packed_delivery(message("two"), node, 1, b"two".to_vec(), false)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(mgr.pending_count(), 1);
|
||||
assert_eq!(first, second, "a second upload reuses the pending link");
|
||||
assert_eq!(mgr.session_count(), 1);
|
||||
assert_eq!(mgr.pending_count(), 2);
|
||||
assert_eq!(mgr.stats().direct_sessions, 0);
|
||||
assert_eq!(mgr.stats().one_shot_sessions, 1);
|
||||
assert!(!mgr.delivery_link_available(&dest_hash));
|
||||
assert!(mgr.direct_link_snapshot(dest_hash).is_none());
|
||||
assert!(!mgr.pending.get(&link_id).unwrap().reusable);
|
||||
assert!(mgr.direct_link_snapshot(node).is_none());
|
||||
let snapshot = mgr.propagation_link_snapshot(node).unwrap();
|
||||
assert_eq!(snapshot.queued_deliveries, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -48,6 +48,11 @@ fn bounded_lossy_text(bytes: &[u8]) -> Cow<'_, str> {
|
||||
}
|
||||
|
||||
pub type MessageCallback = Arc<dyn Fn(&LxMessage) + Send + Sync>;
|
||||
fn run_isolated_callback(callback: &MessageCallback, message: &LxMessage, kind: &str) {
|
||||
if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| callback(message))).is_err() {
|
||||
tracing::error!(callback = kind, "an external message callback panicked");
|
||||
}
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct AudioField<'a> {
|
||||
pub mode: u8,
|
||||
@@ -84,6 +89,13 @@ pub struct MessageMetadata {
|
||||
pub progress: f64,
|
||||
pub auto_compress: bool,
|
||||
pub callbacks: MessageCallbacks,
|
||||
/// Retry state owned by the outbound router; never persisted.
|
||||
pub awaiting_path: bool,
|
||||
pub sent_on_path: bool,
|
||||
pub sent_on_slow_path: bool,
|
||||
pub path_request_retried: bool,
|
||||
pub max_delivery_attempts: Option<u32>,
|
||||
pub receipt_timeout: Option<f64>,
|
||||
}
|
||||
impl Default for MessageMetadata {
|
||||
fn default() -> Self {
|
||||
@@ -103,6 +115,12 @@ impl Default for MessageMetadata {
|
||||
progress: 0.,
|
||||
auto_compress: true,
|
||||
callbacks: MessageCallbacks::default(),
|
||||
awaiting_path: false,
|
||||
sent_on_path: false,
|
||||
sent_on_slow_path: false,
|
||||
path_request_retried: false,
|
||||
max_delivery_attempts: None,
|
||||
receipt_timeout: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -479,18 +497,20 @@ impl LxMessage {
|
||||
}
|
||||
|
||||
/// Invoke the delivery callback, if registered. Every call invokes it again;
|
||||
/// the caller must prevent duplicate notifications when required.
|
||||
/// the caller must prevent duplicate notifications when required. A
|
||||
/// panicking callback is logged and contained.
|
||||
pub fn notify_delivered(&self) {
|
||||
if let Some(ref cb) = self.callbacks.on_delivered {
|
||||
cb(self);
|
||||
run_isolated_callback(cb, self, "delivery");
|
||||
}
|
||||
}
|
||||
|
||||
/// Invoke the failure callback, if registered. Every call invokes it again;
|
||||
/// the caller must prevent duplicate notifications when required.
|
||||
/// the caller must prevent duplicate notifications when required. A
|
||||
/// panicking callback is logged and contained.
|
||||
pub fn notify_failed(&self) {
|
||||
if let Some(ref cb) = self.callbacks.on_failed {
|
||||
cb(self);
|
||||
run_isolated_callback(cb, self, "failed");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -654,7 +674,11 @@ impl LxMessage {
|
||||
self.state = MessageState::Rejected;
|
||||
}
|
||||
|
||||
/// Mark the message delivered; repeated calls notify only once.
|
||||
pub fn mark_delivered(&mut self) {
|
||||
if self.state == MessageState::Delivered {
|
||||
return;
|
||||
}
|
||||
self.state = MessageState::Delivered;
|
||||
self.notify_delivered();
|
||||
}
|
||||
|
||||
+735
-1271
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,146 @@
|
||||
//! Medium-aware outbound timing: Python `LXMRouter` path and retry model.
|
||||
//!
|
||||
//! The embedder supplies a [`MediumSnapshot`] of Reticulum's view (lowest
|
||||
//! online bitrate, medium path timeout and per-destination routes); the router
|
||||
//! derives retry waits, attempt limits and receipt timeouts from it.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::time::Duration;
|
||||
|
||||
use rand::Rng;
|
||||
|
||||
use crate::constants::{
|
||||
DELIVERY_RETRY_WAIT, MAX_DELIVERY_ATTEMPTS, PATH_REQUEST_WAIT, PROCESSING_INTERVAL,
|
||||
};
|
||||
use crate::message::LxMessage;
|
||||
|
||||
pub const PATH_REQUEST_DEBOUNCE: f64 = 60.0;
|
||||
pub const SLOW_INTERFACE_BITRATE: u64 = 2000;
|
||||
pub const AIRTIME_AWARE_MTU_TIME: f64 = 0.5;
|
||||
const PER_HOP_TIMEOUT: f64 = rns_wire::constants::DEFAULT_PER_HOP_TIMEOUT;
|
||||
|
||||
/// Reticulum's current route to a destination.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct RouteInfo {
|
||||
pub hops: u8,
|
||||
/// `Reticulum.get_first_hop_timeout` for the destination, in seconds.
|
||||
pub first_hop_timeout: f64,
|
||||
}
|
||||
|
||||
/// Reticulum inputs to outbound planning. A destination without an entry in
|
||||
/// `routes` has no known path.
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub struct MediumSnapshot {
|
||||
/// `Reticulum.get_lowest_interface_bitrate`.
|
||||
pub lowest_interface_bitrate: Option<u64>,
|
||||
/// `Reticulum.get_medium_path_timeout`; 0 when no bitrate is known.
|
||||
pub medium_path_timeout: f64,
|
||||
pub routes: HashMap<[u8; 16], RouteInfo>,
|
||||
}
|
||||
|
||||
impl MediumSnapshot {
|
||||
pub fn has_path(&self, destination: &[u8; 16]) -> bool {
|
||||
self.routes.contains_key(destination)
|
||||
}
|
||||
|
||||
pub fn route(&self, destination: &[u8; 16]) -> Option<RouteInfo> {
|
||||
self.routes.get(destination).copied()
|
||||
}
|
||||
|
||||
/// Python `LXMRouter.destination_round_trip`.
|
||||
pub fn destination_round_trip(&self, destination: &[u8; 16]) -> f64 {
|
||||
match self.routes.get(destination) {
|
||||
None => self.medium_path_timeout,
|
||||
Some(route) => {
|
||||
2.0 * (route.first_hop_timeout - PER_HOP_TIMEOUT).max(0.0) + PER_HOP_TIMEOUT
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Python `LXMRouter.path_request_wait`.
|
||||
pub fn path_request_wait(&self) -> f64 {
|
||||
(PATH_REQUEST_WAIT as f64).max(self.medium_path_timeout)
|
||||
}
|
||||
|
||||
/// Python `LXMRouter.slow_interface_online`.
|
||||
pub fn slow_interface_online(&self) -> bool {
|
||||
self.lowest_interface_bitrate
|
||||
.is_some_and(|bitrate| bitrate < SLOW_INTERFACE_BITRATE)
|
||||
}
|
||||
|
||||
/// Window within which a repeated path request for one destination is skipped.
|
||||
pub fn path_request_debounce(&self) -> f64 {
|
||||
if self.slow_interface_online() {
|
||||
PATH_REQUEST_DEBOUNCE
|
||||
} else {
|
||||
self.path_request_wait()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Python `LXMRouter.attempt_limit`.
|
||||
pub fn attempt_limit(message: &LxMessage) -> u32 {
|
||||
message
|
||||
.max_delivery_attempts
|
||||
.unwrap_or(MAX_DELIVERY_ATTEMPTS)
|
||||
}
|
||||
|
||||
/// Python `LXMRouter.attempt_due`.
|
||||
pub fn attempt_due(message: &LxMessage, has_path: bool, now: f64) -> bool {
|
||||
now > message.next_delivery_attempt || (message.awaiting_path && has_path)
|
||||
}
|
||||
|
||||
/// Python `LXMRouter.schedule_attempt`, given the round trip it would use:
|
||||
/// the medium path timeout for a path request, else the destination round trip.
|
||||
pub fn schedule_attempt(message: &mut LxMessage, round_trip: f64, path_request: bool, now: f64) {
|
||||
let wait = if path_request {
|
||||
message.awaiting_path = true;
|
||||
(PATH_REQUEST_WAIT as f64).max(round_trip)
|
||||
} else {
|
||||
(DELIVERY_RETRY_WAIT as f64).max(round_trip)
|
||||
};
|
||||
message.next_delivery_attempt = now + wait;
|
||||
|
||||
let limit = if round_trip > DELIVERY_RETRY_WAIT as f64 {
|
||||
// Python's round() rounds half to even.
|
||||
let scaled = (MAX_DELIVERY_ATTEMPTS as f64 * DELIVERY_RETRY_WAIT as f64 / round_trip)
|
||||
.round_ties_even() as u32;
|
||||
scaled.max(3)
|
||||
} else {
|
||||
MAX_DELIVERY_ATTEMPTS
|
||||
};
|
||||
message.max_delivery_attempts = Some(limit);
|
||||
|
||||
let mtu_time = (round_trip - PER_HOP_TIMEOUT).max(0.0) / 2.0;
|
||||
if mtu_time > AIRTIME_AWARE_MTU_TIME {
|
||||
message.next_delivery_attempt += rand::thread_rng().gen_range(0.0..=mtu_time);
|
||||
let retry_wait = (DELIVERY_RETRY_WAIT as f64).max(round_trip) + mtu_time;
|
||||
let remaining = (i64::from(limit) - i64::from(message.delivery_attempts) + 1).max(1);
|
||||
message.receipt_timeout = Some(retry_wait * remaining as f64 + PROCESSING_INTERVAL as f64);
|
||||
} else {
|
||||
message.receipt_timeout = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Timeout for an opportunistic delivery receipt: the RNS packet receipt
|
||||
/// timeout (Packet.py:429-433), raised to the message's airtime-aware
|
||||
/// `receipt_timeout` (LXMessage.py:482). Without a route Reticulum counts
|
||||
/// `PATHFINDER_M` hops.
|
||||
pub fn opportunistic_receipt_timeout(
|
||||
route: Option<RouteInfo>,
|
||||
receipt_timeout: Option<f64>,
|
||||
) -> Duration {
|
||||
let (first_hop, hops) = route
|
||||
.map(|route| (route.first_hop_timeout, route.hops))
|
||||
.unwrap_or((PER_HOP_TIMEOUT, rns_transport::constants::PATHFINDER_M));
|
||||
let base = rns_wire::receipt::receipt_timeout_for_route(
|
||||
Duration::from_secs_f64(first_hop.max(0.0)),
|
||||
hops,
|
||||
);
|
||||
match receipt_timeout {
|
||||
Some(timeout) if timeout.is_finite() && timeout > base.as_secs_f64() => {
|
||||
Duration::from_secs_f64(timeout)
|
||||
}
|
||||
_ => base,
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -112,8 +112,9 @@ pub struct Args {
|
||||
#[arg(long, value_name = "PATH")]
|
||||
pub identity: Option<PathBuf>,
|
||||
|
||||
/// Send a single message and exit: `--send <dest_hash> <content>`.
|
||||
#[arg(long, num_args = 1..=2, value_names = ["DEST_HASH", "CONTENT"])]
|
||||
/// Send messages and exit: `--send <dest_hash> <content>...`, one message
|
||||
/// per content, queued together.
|
||||
#[arg(long, num_args = 1.., value_names = ["DEST_HASH", "CONTENT"])]
|
||||
pub send: Option<Vec<String>>,
|
||||
|
||||
/// Read outgoing `--send` content from a UTF-8 file instead of argv.
|
||||
|
||||
@@ -280,7 +280,7 @@ fn clap_requires_send_argument() {
|
||||
"expected Clap usage failure, got:\n{}",
|
||||
combined_output(&output)
|
||||
);
|
||||
assert!(stderr(&output).contains("a value is required for '--send <DEST_HASH> <CONTENT>'"));
|
||||
assert!(stderr(&output).contains("a value is required for '--send <DEST_HASH> <CONTENT>...'"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Reference in new issue
Block a user