link: a closed channel is an error; rnsh floors scale with the link RTT

This commit is contained in:
DeFiDude committed 2026-11-11 09:21:10 -07:00
1 parent fc62f7e94a
commit 3eec4e0995
3 files changed
+178 -23

No files matched your search

+53 -4
View File
@@ -533,8 +533,10 @@ pub enum ChannelSendError {
NoSessionKeys,
#[error("channel error: {0}")]
Channel(#[from] ChannelError),
#[error("transport channel is full or closed")]
#[error("transport channel is full")]
TransportUnavailable,
#[error("transport channel is closed")]
TransportClosed,
}
#[derive(Debug, thiserror::Error)]
@@ -582,6 +584,11 @@ pub enum LinkManagerCommand {
link_id: [u8; 16],
result_tx: oneshot::Sender<Option<usize>>,
},
/// The Link's measured RTT in seconds (`link.rtt`), `None` for an unknown Link.
LinkRtt {
link_id: [u8; 16],
result_tx: oneshot::Sender<Option<f64>>,
},
/// Channel readiness and the Python Buffer close wait, `link.rtt * len(tx_ring)`.
ChannelCloseWait {
link_id: [u8; 16],
@@ -2425,6 +2432,14 @@ impl LinkManager {
let _ = result_tx.send(mdu);
true
}
LinkManagerCommand::LinkRtt { link_id, result_tx } => {
let rtt = self
.active_links
.get(&link_id)
.map(|active| active.link.rtt_secs());
let _ = result_tx.send(rtt);
true
}
LinkManagerCommand::ChannelCloseWait { link_id, result_tx } => {
let status = self.active_links.get(&link_id).and_then(|active| {
let channel = active.channel.as_ref()?;
@@ -7566,9 +7581,10 @@ impl LinkManager {
}
let transport_tx = self.transport_tx.clone();
let permit = transport_tx
.try_reserve()
.map_err(|_| ChannelSendError::TransportUnavailable)?;
let permit = transport_tx.try_reserve().map_err(|error| match error {
mpsc::error::TrySendError::Full(()) => ChannelSendError::TransportUnavailable,
mpsc::error::TrySendError::Closed(()) => ChannelSendError::TransportClosed,
})?;
let active = self
.active_links
@@ -12278,6 +12294,39 @@ mod tests {
assert!(channel_rx.try_recv().is_err());
}
#[test]
fn channel_send_on_a_closed_transport_is_an_error_not_backpressure() {
let (initiator, _responder, _identity_key) = handshaken_link_pair_with_identity();
let link_id = initiator.link_id;
let (tx, rx) = mpsc::channel(16);
drop(rx);
let (_event_tx, event_rx) = mpsc::channel(16);
let mut lm = LinkManager::new(tx, event_rx, [0xA2; 16], None);
lm.active_links.insert(
link_id,
ActiveLink {
link: initiator,
_interface_id: 1,
interface_owner: None,
endpoint_authority: None,
channel: None,
inbound_resources: HashMap::new(),
outbound_resources: HashMap::new(),
outbound_split_queues: HashMap::new(),
inbound_split_resources: HashMap::new(),
segment_routing: HashMap::new(),
},
);
lm.get_channel(&link_id)
.unwrap()
.register_message_type(TEST_CHANNEL_MSG_TYPE)
.unwrap();
assert!(matches!(
lm.send_channel_message(&link_id, &TestChannelNoop),
Err(ChannelSendError::TransportClosed)
));
}
/// 1.3.8 stats parity (Packet.py:291): tx counts the link payload after
/// the context byte — the same unit rx counts (Link.py:929) — so a channel
/// echo round-trip yields matching data counters on both peers.
+60 -17
View File
@@ -6,8 +6,11 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, OnceLock};
use std::time::Duration;
use rns_link::handshake::EphemeralKeys;
use rns_link::link::Link;
use rns_link::stamp::{LinkRequestStamper, LinkStampError, LinkStampPolicy};
use rns_link::stamp::{
LinkRequestStamper, LinkStampError, LinkStampPolicy, generate_stamped_ephemeral_keys,
};
use rns_transport::messages::{TransportMessage, TransportQuery, TransportQueryResponse};
use tokio::sync::{Semaphore, mpsc, oneshot};
@@ -112,14 +115,14 @@ pub async fn signalled_link_mtu(
.unwrap_or(base)
}
/// Create an initiator Link whose request carries the stamp upstream would
/// send to `destination_hash` and the MTU it would signal. Dropping the future
/// cancels the grind.
pub async fn new_initiator(
/// The request keys upstream would use for a link to `destination_hash`:
/// stamped at the destination's announced cost (Link.py:310-316@1.6.0), with
/// the grind on the blocking pool. Synchronous owners hand the result to
/// their `provide_link_request_keys`. Dropping the future cancels the grind.
pub async fn link_request_keys(
transport_tx: &mpsc::Sender<TransportMessage>,
destination_hash: [u8; 16],
hops: u8,
) -> Result<(Link, Vec<u8>), LinkStampError> {
) -> Result<EphemeralKeys, LinkStampError> {
let policy = link_stamp_policy();
let recalled = if policy.stamp_lrs {
recall_link_cost(transport_tx, destination_hash).await
@@ -127,21 +130,14 @@ pub async fn new_initiator(
None
};
let Some(cost) = policy.request_cost(recalled) else {
let mtu = signalled_link_mtu(transport_tx, destination_hash).await;
return Ok(Link::new_initiator_with_keys(
destination_hash,
hops,
rns_link::handshake::EphemeralKeys::generate(),
mtu,
));
return Ok(EphemeralKeys::generate());
};
let mtu = signalled_link_mtu(transport_tx, destination_hash).await;
let _permit = grind_permits().acquire_owned().await.ok();
let ctl = policy.control(cost);
let _cancel = CancelOnDrop(ctl.cancel.clone());
let started = std::time::Instant::now();
let result = tokio::task::spawn_blocking(move || {
Link::new_stamped_initiator(destination_hash, hops, Some(cost), &ctl, mtu)
generate_stamped_ephemeral_keys(&destination_hash, cost, &ctl)
})
.await
.map_err(|_| LinkStampError::Stopped)?;
@@ -162,10 +158,29 @@ pub async fn new_initiator(
result
}
/// Create an initiator Link whose request carries the stamp upstream would
/// send to `destination_hash` and the MTU it would signal. Dropping the future
/// cancels the grind.
pub async fn new_initiator(
transport_tx: &mpsc::Sender<TransportMessage>,
destination_hash: [u8; 16],
hops: u8,
) -> Result<(Link, Vec<u8>), LinkStampError> {
let keys = link_request_keys(transport_tx, destination_hash).await?;
let mtu = signalled_link_mtu(transport_tx, destination_hash).await;
Ok(Link::new_initiator_with_keys(
destination_hash,
hops,
keys,
mtu,
))
}
/// A stamper for synchronous Link owners on a multi-threaded runtime: link
/// costs are recalled from Transport by blocking in place, and MTU discovery
/// follows the running instance. Elsewhere no cost is recalled and requests
/// are stamped only under `always_stamp_lrs`.
/// are stamped only under `always_stamp_lrs`; such owners take keys from
/// [`link_request_keys`] instead.
pub fn blocking_stamper(transport_tx: mpsc::Sender<TransportMessage>) -> LinkRequestStamper {
let mut stamper = LinkRequestStamper::new(
link_stamp_policy(),
@@ -183,3 +198,31 @@ pub fn blocking_stamper(transport_tx: mpsc::Sender<TransportMessage>) -> LinkReq
stamper.link_mtu_discovery = link_mtu_discovery();
stamper
}
#[cfg(test)]
mod tests {
use super::*;
use rns_link::handshake::LinkRequestData;
use rns_link::mtu_discovery::SignallingData;
use rns_link::stamp::link_request_stamp_valid;
#[tokio::test(flavor = "current_thread")]
async fn request_keys_meet_the_announced_cost_on_a_current_thread_runtime() {
let (tx, mut rx) = mpsc::channel(4);
let dest = [0x3C; 16];
let keys = tokio::spawn(async move { link_request_keys(&tx, dest).await });
match rx.recv().await.unwrap() {
TransportMessage::Rpc {
query: TransportQuery::RecallLinkCost { dest: asked },
response_tx,
} => {
assert_eq!(asked, dest);
let _ = response_tx.send(TransportQueryResponse::FloatResult(Some(6.0)));
}
other => panic!("expected link cost recall, got {other:?}"),
}
let keys = keys.await.unwrap().unwrap();
let request = LinkRequestData::pack(&keys, SignallingData::new(1, 500));
assert!(link_request_stamp_valid(&dest, &request, 6.0));
}
}
+65 -2
View File
@@ -54,8 +54,10 @@ const STREAM_HEADER_LEN: usize = 2;
const PROCESS_READ_LEN: usize = 4096;
/// Session prune delay floor: `max(rtt*3, PROCESS_PIPE_TIME+5)` in rnsh/session.py.
const LISTENER_PRUNE_DELAY: Duration = Duration::from_secs(6);
const LISTENER_PRUNE_RTT_FACTOR: f64 = 3.0;
/// Post-CommandExited check floor: `max(rtt*5, 10)` in rnsh/session.py.
const COMMAND_EXITED_TIMEOUT: Duration = Duration::from_secs(10);
const COMMAND_EXITED_RTT_FACTOR: f64 = 5.0;
/// Grace between "Shutting down" and link teardown in rnsh/listener.py.
const LISTENER_SHUTDOWN_GRACE: Duration = Duration::from_secs(1);
/// Version reply floor: `max(rtt*20, 5)` in rnsh/initiator.py.
@@ -425,7 +427,37 @@ async fn terminate_session(
.await;
}
session.close();
close_link_after(command_tx.clone(), link_id, LISTENER_PRUNE_DELAY);
let delay = rtt_scaled(
command_tx,
link_id,
LISTENER_PRUNE_RTT_FACTOR,
LISTENER_PRUNE_DELAY,
)
.await;
close_link_after(command_tx.clone(), link_id, delay);
}
/// `max(link.rtt * factor, floor)`, the rnsh/session.py timer form.
async fn rtt_scaled(
command_tx: &mpsc::Sender<LinkManagerCommand>,
link_id: [u8; 16],
factor: f64,
floor: Duration,
) -> Duration {
let (result_tx, result_rx) = oneshot::channel();
if command_tx
.send(LinkManagerCommand::LinkRtt { link_id, result_tx })
.await
.is_err()
{
return floor;
}
result_rx
.await
.ok()
.flatten()
.and_then(|rtt| Duration::try_from_secs_f64(rtt * factor).ok())
.map_or(floor, |scaled| scaled.max(floor))
}
/// Open a Link, negotiate rnsh and execute one remote command session. Return
@@ -1743,9 +1775,16 @@ async fn pump_listener_process(
{
let _ =
send_manager_message(&command_tx, link_id, CommandExitedMessage::new(code)).await;
let exited_timeout = rtt_scaled(
&command_tx,
link_id,
COMMAND_EXITED_RTT_FACTOR,
COMMAND_EXITED_TIMEOUT,
)
.await;
tokio::select! {
_ = &mut stop_rx => {}
_ = tokio::time::sleep(COMMAND_EXITED_TIMEOUT) => {
_ = tokio::time::sleep(exited_timeout) => {
let _ = exited_tx.send(link_id);
}
}
@@ -2480,6 +2519,24 @@ mod tests {
use super::*;
use std::sync::{Arc, Mutex};
#[tokio::test]
async fn session_timers_scale_with_link_rtt_above_their_floors() {
let (command_tx, mut command_rx) = mpsc::channel(4);
let floor = Duration::from_secs(6);
for (rtt, expected) in [(4.0, Duration::from_secs(12)), (0.5, floor)] {
let answer = async {
match command_rx.recv().await {
Some(LinkManagerCommand::LinkRtt { result_tx, .. }) => {
let _ = result_tx.send(Some(rtt));
}
_ => panic!("expected a link RTT query"),
}
};
let (scaled, ()) = tokio::join!(rtt_scaled(&command_tx, [1; 16], 3.0, floor), answer);
assert_eq!(scaled, expected);
}
}
#[test]
fn rnsh_channel_registration_accepts_every_protocol_type() {
let mut channel = LinkChannel::new([0xA2; 16], 0.1);
@@ -3074,6 +3131,12 @@ mod tests {
sequence: 0,
packet_hash: [0; 32],
}));
match command_rx.recv().await {
Some(LinkManagerCommand::LinkRtt { result_tx, .. }) => {
let _ = result_tx.send(Some(0.1));
}
_ => panic!("expected a link RTT query"),
}
decoded
}
_ => panic!("expected an ErrorMessage"),