runtime: retain ordered Link cleanup ownership

This commit is contained in:
DeFiDude committed 2026-08-16 16:07:10 -06:00
1 parent 0049231139
commit 1d38688b8f
6 files changed
+875 -316

No files matched your search

+7 -40
View File
@@ -48,38 +48,12 @@ pub struct LinkClient {
identity: Arc<Identity>,
}
struct QueryLinkGuard {
transport_tx: mpsc::Sender<TransportMessage>,
link_id: [u8; 16],
endpoint_bound: bool,
cleanup_required: bool,
}
struct LinkClientEndpoint<'a> {
delivery_rx: &'a mut mpsc::Receiver<DestinationEvent>,
lifecycle_rx: &'a mut mpsc::UnboundedReceiver<LinkEndpointLifecycleEvent>,
attached_interface: InterfaceId,
}
impl Drop for QueryLinkGuard {
fn drop(&mut self) {
if !self.cleanup_required {
return;
}
if self.endpoint_bound {
let _ = self
.transport_tx
.try_send(crate::link_endpoint::unbind_message(
self.link_id,
LinkEndpointRole::Initiator,
));
}
let _ = self
.transport_tx
.try_send(TransportMessage::DeregisterDestination { hash: self.link_id });
}
}
impl LinkClient {
pub fn new(transport_tx: mpsc::Sender<TransportMessage>, identity: Identity) -> Self {
Self {
@@ -148,12 +122,11 @@ impl LinkClient {
delivery_tx: Some(dest_tx),
})
.await?;
let mut registration = QueryLinkGuard {
transport_tx: self.transport_tx.clone(),
let mut registration = crate::link_endpoint::LinkEndpointCleanupGuard::new(
self.transport_tx.clone(),
link_id,
endpoint_bound: false,
cleanup_required: true,
};
LinkEndpointRole::Initiator,
);
let req_pkt = build_link_request_packet(dest_hash, &request_data);
self.send_msg(TransportMessage::Outbound(OutboundRequest {
@@ -197,7 +170,7 @@ impl LinkClient {
)
.await
.map_err(|_| LinkClientError::TransportUnavailable)?;
registration.endpoint_bound = true;
registration.endpoint_bound();
let mut endpoint = LinkClientEndpoint {
delivery_rx: &mut dest_rx,
lifecycle_rx: &mut endpoint_lifecycle_rx,
@@ -252,15 +225,9 @@ impl LinkClient {
// Tear down even on failure so the remote doesn't keep link state.
let endpoint_closing = self.send_close(&mut link).await.unwrap_or(false);
if !endpoint_closing {
let _ = crate::link_endpoint::unbind(
&self.transport_tx,
link_id,
LinkEndpointRole::Initiator,
)
.await;
registration.endpoint_bound = false;
let _ = registration.cleanup().await;
} else {
registration.cleanup_required = false;
registration.disarm();
}
response
+282 -11
View File
@@ -18,6 +18,99 @@ pub(crate) enum LinkEndpointError {
Bind(LinkEndpointBindResult),
#[error("Link endpoint rejected outbound packet: {0:?}")]
Send(LinkEndpointSendResult),
#[error("Link endpoint cleanup was rejected: {0:?}")]
Unbind(LinkEndpointUnbindResult),
}
pub(crate) struct PendingLinkEndpointCleanup {
pub(crate) link_id: [u8; 16],
pub(crate) role: LinkEndpointRole,
pub(crate) deregister_on_success: bool,
pub(crate) result_rx: oneshot::Receiver<LinkEndpointUnbindResult>,
}
/// Owns cleanup for a temporary initiator Link destination until ownership is
/// transferred to a long-lived actor or an atomic final send succeeds.
///
/// Cancellation cannot use `try_send`: a full transport ingress queue is a
/// normal transient condition. Drop therefore transfers cleanup to a retained
/// task which waits for admission, verifies typed endpoint ownership, and only
/// then deregisters the temporary destination.
pub(crate) struct LinkEndpointCleanupGuard {
transport_tx: mpsc::Sender<TransportMessage>,
link_id: [u8; 16],
role: LinkEndpointRole,
endpoint_bound: bool,
armed: bool,
}
impl LinkEndpointCleanupGuard {
pub(crate) fn new(
transport_tx: mpsc::Sender<TransportMessage>,
link_id: [u8; 16],
role: LinkEndpointRole,
) -> Self {
Self {
transport_tx,
link_id,
role,
endpoint_bound: false,
armed: true,
}
}
pub(crate) fn endpoint_bound(&mut self) {
self.endpoint_bound = true;
}
pub(crate) fn disarm(&mut self) {
self.armed = false;
}
pub(crate) async fn cleanup(&mut self) -> Result<(), LinkEndpointError> {
cleanup_registered_link(
&self.transport_tx,
self.link_id,
self.role,
self.endpoint_bound,
)
.await?;
self.endpoint_bound = false;
self.armed = false;
Ok(())
}
}
impl Drop for LinkEndpointCleanupGuard {
fn drop(&mut self) {
if !self.armed {
return;
}
let transport_tx = self.transport_tx.clone();
let link_id = self.link_id;
let role = self.role;
let endpoint_bound = self.endpoint_bound;
let Ok(runtime) = tokio::runtime::Handle::try_current() else {
tracing::error!(
link_id = %hex::encode(link_id),
role = ?role,
"cannot retain Link endpoint cleanup without a Tokio runtime"
);
return;
};
runtime.spawn(async move {
if let Err(error) =
cleanup_registered_link(&transport_tx, link_id, role, endpoint_bound).await
{
tracing::error!(
link_id = %hex::encode(link_id),
role = ?role,
error = %error,
"retained Link endpoint cleanup failed"
);
}
});
}
}
pub(crate) struct PendingLinkEndpointSend {
@@ -27,6 +120,52 @@ pub(crate) struct PendingLinkEndpointSend {
pub(crate) result_rx: oneshot::Receiver<LinkEndpointSendResult>,
}
struct AtomicFinalSendGuard {
transport_tx: mpsc::Sender<TransportMessage>,
link_id: [u8; 16],
role: LinkEndpointRole,
result_rx: Option<oneshot::Receiver<LinkEndpointSendResult>>,
}
impl AtomicFinalSendGuard {
async fn result(&mut self) -> Result<LinkEndpointSendResult, LinkEndpointError> {
let result = self
.result_rx
.as_mut()
.expect("atomic final-send result receiver")
.await;
self.result_rx = None;
result.map_err(|_| LinkEndpointError::TransportUnavailable)
}
}
impl Drop for AtomicFinalSendGuard {
fn drop(&mut self) {
let Some(result_rx) = self.result_rx.take() else {
return;
};
let transport_tx = self.transport_tx.clone();
let link_id = self.link_id;
let role = self.role;
let Ok(runtime) = tokio::runtime::Handle::try_current() else {
tracing::error!(
link_id = %hex::encode(link_id),
role = ?role,
"cannot retain atomic Link close result without a Tokio runtime"
);
return;
};
runtime.spawn(async move {
match result_rx.await {
Ok(LinkEndpointSendResult::Sent | LinkEndpointSendResult::Queued { .. }) => {}
Ok(_) | Err(_) => {
let _ = cleanup_registered_link(&transport_tx, link_id, role, true).await;
}
}
});
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum LinkProofWaitError {
LinkClosed,
@@ -172,10 +311,16 @@ pub(crate) async fn send_and_unbind(
})
.await
.map_err(|_| LinkEndpointError::TransportUnavailable)?;
match result_rx
.await
.map_err(|_| LinkEndpointError::TransportUnavailable)?
{
// Once admitted, retain ownership of the typed result across caller
// cancellation. A successful atomic operation owns the final FIFO drain;
// a rejected one falls back to ordered explicit cleanup.
let mut final_send = AtomicFinalSendGuard {
transport_tx: transport_tx.clone(),
link_id,
role,
result_rx: Some(result_rx),
};
match final_send.result().await? {
LinkEndpointSendResult::Sent | LinkEndpointSendResult::Queued { .. } => Ok(()),
result => Err(LinkEndpointError::Send(result)),
}
@@ -228,6 +373,26 @@ pub(crate) async fn unbind(
.map_err(|_| LinkEndpointError::TransportUnavailable)
}
async fn cleanup_registered_link(
transport_tx: &mpsc::Sender<TransportMessage>,
link_id: [u8; 16],
role: LinkEndpointRole,
endpoint_bound: bool,
) -> Result<(), LinkEndpointError> {
if endpoint_bound {
match unbind(transport_tx, link_id, role).await? {
LinkEndpointUnbindResult::Unbound | LinkEndpointUnbindResult::NotBound => {}
result @ LinkEndpointUnbindResult::RoleMismatch => {
return Err(LinkEndpointError::Unbind(result));
}
}
}
transport_tx
.send(TransportMessage::DeregisterDestination { hash: link_id })
.await
.map_err(|_| LinkEndpointError::TransportUnavailable)
}
pub(crate) fn send_message(
link_id: [u8; 16],
role: LinkEndpointRole,
@@ -278,13 +443,25 @@ pub(crate) fn send_and_unbind_message(
)
}
pub(crate) fn unbind_message(link_id: [u8; 16], role: LinkEndpointRole) -> TransportMessage {
let (result_tx, _result_rx) = oneshot::channel();
TransportMessage::UnbindLinkEndpoint {
link_id,
role,
result_tx,
}
pub(crate) fn cleanup_message(
link_id: [u8; 16],
role: LinkEndpointRole,
deregister_on_success: bool,
) -> (TransportMessage, PendingLinkEndpointCleanup) {
let (result_tx, result_rx) = oneshot::channel();
(
TransportMessage::UnbindLinkEndpoint {
link_id,
role,
result_tx,
},
PendingLinkEndpointCleanup {
link_id,
role,
deregister_on_success,
result_rx,
},
)
}
#[cfg(test)]
@@ -403,4 +580,98 @@ mod tests {
assert_eq!(initiator.state, LinkState::Pending);
drop(event_tx);
}
#[tokio::test]
async fn dropped_cleanup_guard_survives_transport_ingress_backpressure() {
let link_id = [0xC1; 16];
let (transport_tx, mut transport_rx) = mpsc::channel(1);
transport_tx.send(TransportMessage::Shutdown).await.unwrap();
let mut guard =
LinkEndpointCleanupGuard::new(transport_tx, link_id, LinkEndpointRole::Initiator);
guard.endpoint_bound();
drop(guard);
assert!(matches!(
transport_rx.recv().await,
Some(TransportMessage::Shutdown)
));
let Some(TransportMessage::UnbindLinkEndpoint {
link_id: unbound,
role,
result_tx,
}) = transport_rx.recv().await
else {
panic!("retained cleanup must enqueue typed unbind after capacity returns");
};
assert_eq!(unbound, link_id);
assert_eq!(role, LinkEndpointRole::Initiator);
assert!(
tokio::time::timeout(Duration::from_millis(10), transport_rx.recv())
.await
.is_err(),
"destination deregistration must wait for the typed unbind result"
);
let _ = result_tx.send(LinkEndpointUnbindResult::Unbound);
assert!(matches!(
transport_rx.recv().await,
Some(TransportMessage::DeregisterDestination { hash }) if hash == link_id
));
}
#[tokio::test]
async fn role_mismatch_never_deregisters_another_endpoint_owner() {
let link_id = [0xC2; 16];
let (transport_tx, mut transport_rx) = mpsc::channel(2);
let cleanup = tokio::spawn(async move {
cleanup_registered_link(&transport_tx, link_id, LinkEndpointRole::Initiator, true).await
});
let Some(TransportMessage::UnbindLinkEndpoint { result_tx, .. }) =
transport_rx.recv().await
else {
panic!("expected typed unbind");
};
let _ = result_tx.send(LinkEndpointUnbindResult::RoleMismatch);
assert!(matches!(
cleanup.await.unwrap(),
Err(LinkEndpointError::Unbind(
LinkEndpointUnbindResult::RoleMismatch
))
));
assert!(
transport_rx.try_recv().is_err(),
"role mismatch must not deregister the foreign Link destination"
);
}
#[tokio::test]
async fn cancelled_atomic_close_retains_queued_fifo_ownership() {
let link_id = [0xC3; 16];
let (transport_tx, mut transport_rx) = mpsc::channel(2);
let call_tx = transport_tx.clone();
let close = tokio::spawn(async move {
send_and_unbind(
&call_tx,
link_id,
LinkEndpointRole::Initiator,
proof_packet(link_id, b"final"),
)
.await
});
let Some(TransportMessage::SendLinkEndpointAndUnbind { result_tx, .. }) =
transport_rx.recv().await
else {
panic!("expected atomic final send");
};
close.abort();
let _ = close.await;
let _ = result_tx.send(LinkEndpointSendResult::Queued { depth: 1 });
tokio::task::yield_now().await;
tokio::task::yield_now().await;
assert!(
transport_rx.try_recv().is_err(),
"accepted atomic close owns FIFO drain; cancellation must not preempt it"
);
drop(transport_tx);
}
}
+548 -98
View File
@@ -26,7 +26,8 @@ use rns_protocol::resource_adv::ResourceAdvertisement;
use rns_transport::link_messages::{AnnounceRequest, DestinationEvent};
use rns_transport::messages::{
InterfaceId, LinkEndpointBindResult, LinkEndpointBinding, LinkEndpointLifecycleEvent,
LinkEndpointRole, LinkEndpointSendResult, OutboundRequest, TransportMessage,
LinkEndpointRole, LinkEndpointSendResult, LinkEndpointUnbindResult, OutboundRequest,
TransportMessage,
};
const MAX_PENDING_DESTINATION_ANNOUNCES: usize = 256;
@@ -60,6 +61,12 @@ struct ActiveLink {
segment_routing: HashMap<[u8; 32], SegmentRoute>,
}
struct PendingResponderEndpointBind {
result_rx: oneshot::Receiver<LinkEndpointBindResult>,
register_link: TransportMessage,
proof: TransportMessage,
}
#[derive(Debug, Clone, Copy)]
struct SegmentRoute {
original_hash: [u8; 32],
@@ -427,9 +434,11 @@ pub struct LinkManager {
pending_destination_announces: VecDeque<TransportMessage>,
pending_link_control: VecDeque<TransportMessage>,
pending_endpoint_sends: Vec<crate::link_endpoint::PendingLinkEndpointSend>,
pending_endpoint_cleanups: Vec<crate::link_endpoint::PendingLinkEndpointCleanup>,
endpoint_lifecycle_tx: mpsc::UnboundedSender<LinkEndpointLifecycleEvent>,
endpoint_lifecycle_rx: mpsc::UnboundedReceiver<LinkEndpointLifecycleEvent>,
pending_endpoint_binds: HashMap<[u8; 16], oneshot::Receiver<LinkEndpointBindResult>>,
pending_endpoint_binds: HashMap<[u8; 16], PendingResponderEndpointBind>,
owned_endpoint_bindings: HashSet<[u8; 16]>,
active_links: HashMap<[u8; 16], ActiveLink>,
/// Raw software signing key, when available. Hardware-backed identities sign
/// through `identity` instead.
@@ -521,9 +530,11 @@ impl LinkManager {
pending_destination_announces: VecDeque::new(),
pending_link_control: VecDeque::new(),
pending_endpoint_sends: Vec::new(),
pending_endpoint_cleanups: Vec::new(),
endpoint_lifecycle_tx,
endpoint_lifecycle_rx,
pending_endpoint_binds: HashMap::new(),
owned_endpoint_bindings: HashSet::new(),
active_links: HashMap::new(),
identity_key,
destination_hash,
@@ -590,9 +601,11 @@ impl LinkManager {
pending_destination_announces: VecDeque::new(),
pending_link_control: VecDeque::new(),
pending_endpoint_sends: Vec::new(),
pending_endpoint_cleanups: Vec::new(),
endpoint_lifecycle_tx,
endpoint_lifecycle_rx,
pending_endpoint_binds: HashMap::new(),
owned_endpoint_bindings: HashSet::new(),
active_links: HashMap::new(),
identity_key,
destination_hash,
@@ -750,7 +763,7 @@ impl LinkManager {
}
}
}
self.close_all_active_links(CloseReason::DestinationClosed);
self.drain_shutdown_link_ownership().await;
}
pub async fn run_with_commands(mut self, mut command_rx: mpsc::Receiver<LinkManagerCommand>) {
@@ -786,43 +799,80 @@ impl LinkManager {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
self.close_all_active_links(CloseReason::DestinationClosed);
self.drain_shutdown_link_ownership().await;
}
fn poll_link_endpoints(&mut self) -> bool {
let mut progressed = false;
let mut failed = Vec::new();
let mut completed_binds = Vec::new();
let link_ids: Vec<_> = self.pending_endpoint_binds.keys().copied().collect();
for link_id in link_ids {
let Some(receiver) = self.pending_endpoint_binds.get_mut(&link_id) else {
let Some(pending) = self.pending_endpoint_binds.get_mut(&link_id) else {
continue;
};
match receiver.try_recv() {
Ok(LinkEndpointBindResult::Bound) => {
self.pending_endpoint_binds.remove(&link_id);
progressed = true;
match pending.result_rx.try_recv() {
Ok(result) => completed_binds.push((link_id, Some(result))),
Err(oneshot::error::TryRecvError::Closed) => {
completed_binds.push((link_id, None));
}
Ok(result) => {
Err(oneshot::error::TryRecvError::Empty) => {}
}
}
for (link_id, result) in completed_binds {
let Some(pending) = self.pending_endpoint_binds.remove(&link_id) else {
continue;
};
progressed = true;
match result {
Some(LinkEndpointBindResult::Bound) if self.active_links.contains_key(&link_id) => {
self.owned_endpoint_bindings.insert(link_id);
// Registering the route and publishing LRPROOF are a
// post-bind transaction. A conflicting owner must never
// observe either side effect.
Self::stage_required_link_control(
&self.transport_tx,
&mut self.pending_link_control,
pending.register_link,
);
Self::stage_required_link_control(
&self.transport_tx,
&mut self.pending_link_control,
pending.proof,
);
}
Some(LinkEndpointBindResult::Bound) => {
// The candidate was closed while Bind was in flight. We
// own this fresh endpoint, but never published RegisterLink,
// so release it without deregistering another local role.
Self::stage_endpoint_cleanup(
&self.transport_tx,
&mut self.pending_link_control,
&mut self.pending_endpoint_cleanups,
link_id,
LinkEndpointRole::Responder,
false,
);
}
Some(result) => {
tracing::error!(
link_id = %hex::encode(link_id),
result = ?result,
"responder Link endpoint binding failed"
);
self.pending_endpoint_binds.remove(&link_id);
failed.push(link_id);
progressed = true;
// The candidate never acquired endpoint ownership. In
// particular, AlreadyBound/Conflict belong to a different
// owner and must not be unbound or deregistered here.
self.close_active_link(link_id, CloseReason::DestinationClosed, false);
}
Err(oneshot::error::TryRecvError::Closed) => {
self.pending_endpoint_binds.remove(&link_id);
failed.push(link_id);
progressed = true;
None => {
tracing::error!(
link_id = %hex::encode(link_id),
"responder Link endpoint binding result channel closed"
);
self.close_active_link(link_id, CloseReason::DestinationClosed, false);
}
Err(oneshot::error::TryRecvError::Empty) => {}
}
}
for link_id in failed {
self.close_active_link(link_id, CloseReason::DestinationClosed, false);
}
let mut completed_sends = Vec::new();
let mut failed_sends = Vec::new();
for (index, pending) in self.pending_endpoint_sends.iter_mut().enumerate() {
@@ -868,20 +918,58 @@ impl LinkManager {
"established Link endpoint rejected a staged send"
);
if final_unbind {
Self::stage_link_control(
Self::stage_endpoint_cleanup(
&self.transport_tx,
&mut self.pending_link_control,
crate::link_endpoint::unbind_message(link_id, role),
);
Self::stage_link_control(
&self.transport_tx,
&mut self.pending_link_control,
TransportMessage::DeregisterDestination { hash: link_id },
&mut self.pending_endpoint_cleanups,
link_id,
role,
true,
);
} else {
self.close_active_link(link_id, CloseReason::DestinationClosed, false);
}
}
let mut completed_cleanups = Vec::new();
for (index, pending) in self.pending_endpoint_cleanups.iter_mut().enumerate() {
match pending.result_rx.try_recv() {
Ok(LinkEndpointUnbindResult::Unbound | LinkEndpointUnbindResult::NotBound) => {
if pending.deregister_on_success {
Self::stage_required_link_control(
&self.transport_tx,
&mut self.pending_link_control,
TransportMessage::DeregisterDestination {
hash: pending.link_id,
},
);
}
completed_cleanups.push(index);
progressed = true;
}
Ok(LinkEndpointUnbindResult::RoleMismatch) => {
tracing::error!(
link_id = %hex::encode(pending.link_id),
role = ?pending.role,
"refusing to deregister Link destination owned by another endpoint role"
);
completed_cleanups.push(index);
progressed = true;
}
Err(oneshot::error::TryRecvError::Closed) => {
tracing::error!(
link_id = %hex::encode(pending.link_id),
role = ?pending.role,
"Link endpoint cleanup result channel closed"
);
completed_cleanups.push(index);
progressed = true;
}
Err(oneshot::error::TryRecvError::Empty) => {}
}
}
for index in completed_cleanups.into_iter().rev() {
self.pending_endpoint_cleanups.swap_remove(index);
}
while let Ok(event) = self.endpoint_lifecycle_rx.try_recv() {
self.handle_endpoint_terminal(event);
progressed = true;
@@ -1282,6 +1370,42 @@ impl LinkManager {
true
}
/// Stage ownership/cleanup control without dropping it at the ordinary
/// protocol retry limit. These messages are finite per Link and must
/// survive transient ingress backpressure to preserve endpoint ordering.
fn stage_required_link_control(
transport_tx: &mpsc::Sender<TransportMessage>,
pending: &mut VecDeque<TransportMessage>,
message: TransportMessage,
) -> bool {
if pending.is_empty() {
match transport_tx.try_send(message) {
Ok(()) => return true,
Err(mpsc::error::TrySendError::Full(message)) => {
pending.push_back(message);
return true;
}
Err(mpsc::error::TrySendError::Closed(_)) => return false,
}
}
pending.push_back(message);
true
}
fn stage_endpoint_cleanup(
transport_tx: &mpsc::Sender<TransportMessage>,
pending_link_control: &mut VecDeque<TransportMessage>,
pending_endpoint_cleanups: &mut Vec<crate::link_endpoint::PendingLinkEndpointCleanup>,
link_id: [u8; 16],
role: LinkEndpointRole,
deregister_on_success: bool,
) {
let (message, pending) =
crate::link_endpoint::cleanup_message(link_id, role, deregister_on_success);
pending_endpoint_cleanups.push(pending);
let _ = Self::stage_required_link_control(transport_tx, pending_link_control, message);
}
fn endpoint_role(role: LinkRole) -> LinkEndpointRole {
match role {
LinkRole::Initiator => LinkEndpointRole::Initiator,
@@ -1539,10 +1663,9 @@ impl LinkManager {
"link proof packet built"
);
// Reserve both transport slots before publishing either half of the
// handshake. Registering the Link before its proof is observable is
// essential: a fast initiator may answer the proof immediately, and
// transport must already know where to dispatch that first Link packet.
// Publish only the bind attempt now. RegisterLink and LRPROOF remain a
// private post-bind transaction until the actor confirms this manager
// acquired fresh endpoint ownership.
let transport_tx = self.transport_tx.clone();
let bind_permit = match transport_tx.try_reserve() {
Ok(permit) => permit,
@@ -1555,28 +1678,6 @@ impl LinkManager {
return;
}
};
let register_permit = match transport_tx.try_reserve() {
Ok(permit) => permit,
Err(error) => {
tracing::warn!(
link_id = hex::encode(link_id),
error = %error,
"link request rejected — transport queue cannot register Link"
);
return;
}
};
let proof_permit = match transport_tx.try_reserve() {
Ok(permit) => permit,
Err(error) => {
tracing::warn!(
link_id = hex::encode(link_id),
error = %error,
"link request rejected — transport queue cannot send proof"
);
return;
}
};
// LXMF DIRECT uses resource transfer past `LINK_PACKET_MAX_CONTENT`;
// the manager default remains AcceptAll for backwards compatibility,
@@ -1620,22 +1721,27 @@ impl LinkManager {
lifecycle_tx: self.endpoint_lifecycle_tx.clone(),
result_tx: bind_result_tx,
});
self.pending_endpoint_binds.insert(link_id, bind_result_rx);
register_permit.send(TransportMessage::RegisterLink {
self.pending_endpoint_binds.insert(
link_id,
destination_hash: self.destination_hash,
interface_id,
next_hop: None,
remaining_hops: 0,
initiator: false,
});
proof_permit.send(TransportMessage::OutboundAttached {
request: OutboundRequest {
raw: Bytes::from(proof_raw),
destination_hash: link_id,
PendingResponderEndpointBind {
result_rx: bind_result_rx,
register_link: TransportMessage::RegisterLink {
link_id,
destination_hash: self.destination_hash,
interface_id,
next_hop: None,
remaining_hops: 0,
initiator: false,
},
proof: TransportMessage::OutboundAttached {
request: OutboundRequest {
raw: Bytes::from(proof_raw),
destination_hash: link_id,
},
interface_id,
},
},
interface_id,
});
);
tracing::info!(
link_id = hex::encode(link_id),
@@ -3436,6 +3542,7 @@ impl LinkManager {
return false;
};
let endpoint_role = Self::endpoint_role(active.link.role());
let owns_endpoint = self.owned_endpoint_bindings.remove(&link_id);
// Python removes responder Links from the owning Destination when they
// close. Keep the Rust Destination's live-link bookkeeping in sync.
if let Some(destination) = self.destination.as_mut() {
@@ -3450,7 +3557,7 @@ impl LinkManager {
.map(|identity| identity.0)
.collect();
if send_teardown {
if send_teardown && owns_endpoint {
if let Some(teardown_data) = active.link.teardown(reason) {
endpoint_closing = Self::send_link_close_packet(
&self.transport_tx,
@@ -3466,22 +3573,19 @@ impl LinkManager {
}
self.backchannel_links.retain(|_, lid| *lid != link_id);
self.pending_endpoint_binds.remove(&link_id);
if !endpoint_closing {
Self::stage_link_control(
if !endpoint_closing && owns_endpoint {
Self::stage_endpoint_cleanup(
&self.transport_tx,
&mut self.pending_link_control,
crate::link_endpoint::unbind_message(link_id, endpoint_role),
&mut self.pending_endpoint_cleanups,
link_id,
endpoint_role,
true,
);
}
if let Ok(mut ids) = self.link_identities.lock() {
ids.remove(&link_id);
}
if !endpoint_closing {
let _ = self
.transport_tx
.try_send(TransportMessage::DeregisterDestination { hash: link_id });
}
if let Some(ref tx) = self.accounting_event_tx {
if tx
.send(LinkManagerAccountingEvent::LinkClosed { link_id })
@@ -3546,6 +3650,39 @@ impl LinkManager {
}
}
async fn drain_shutdown_link_ownership(&mut self) {
self.close_all_active_links(CloseReason::DestinationClosed);
loop {
self.flush_pending_link_control();
self.poll_link_endpoints();
self.flush_pending_link_control();
if self.pending_endpoint_binds.is_empty()
&& self.pending_endpoint_sends.is_empty()
&& self.pending_endpoint_cleanups.is_empty()
&& self.pending_link_control.is_empty()
{
return;
}
if self.transport_tx.is_closed() {
tracing::warn!(
pending_binds = self.pending_endpoint_binds.len(),
pending_sends = self.pending_endpoint_sends.len(),
pending_cleanups = self.pending_endpoint_cleanups.len(),
pending_control = self.pending_link_control.len(),
"transport closed before Link endpoint shutdown ownership could drain"
);
self.pending_endpoint_binds.clear();
self.pending_endpoint_sends.clear();
self.pending_endpoint_cleanups.clear();
self.pending_link_control.clear();
return;
}
tokio::time::sleep(std::time::Duration::from_millis(1)).await;
}
}
fn send_link_close_packet(
transport_tx: &mpsc::Sender<TransportMessage>,
pending_link_control: &mut VecDeque<TransportMessage>,
@@ -5728,18 +5865,21 @@ mod tests {
segment_routing: HashMap::new(),
},
);
lm.owned_endpoint_bindings.insert(link_id);
assert_eq!(lm.active_link_count(), 1);
lm.handle_event(DestinationEvent::LinkClosed { link_id });
assert_eq!(lm.active_link_count(), 0);
assert_eq!(closed_rx.try_recv().unwrap(), link_id);
assert!(
matches!(
next_transport_message(&mut rx).unwrap(),
TransportMessage::DeregisterDestination { hash } if hash == link_id
),
"link manager must deregister closed link destination"
);
let TransportMessage::UnbindLinkEndpoint { result_tx, .. } = rx.try_recv().unwrap() else {
panic!("link manager must release its endpoint before deregistration");
};
let _ = result_tx.send(LinkEndpointUnbindResult::Unbound);
assert!(lm.poll_link_endpoints());
assert!(matches!(
next_transport_message(&mut rx).unwrap(),
TransportMessage::DeregisterDestination { hash } if hash == link_id
));
let _ = identity_key;
}
@@ -5810,6 +5950,7 @@ mod tests {
segment_routing: HashMap::new(),
},
);
lm.owned_endpoint_bindings.insert(link_id);
lm.handle_inbound_packet(&close_raw, 2);
assert_eq!(
@@ -5827,13 +5968,17 @@ mod tests {
assert_eq!(closed_rx.try_recv().unwrap(), link_id);
assert!(lm.backchannel_links.is_empty());
assert!(lm.link_identities.lock().unwrap().get(&link_id).is_none());
assert!(
matches!(
next_transport_message(&mut transport_rx).unwrap(),
TransportMessage::DeregisterDestination { hash } if hash == link_id
),
"verified remote close must deregister link destination"
);
let TransportMessage::UnbindLinkEndpoint { result_tx, .. } =
transport_rx.try_recv().unwrap()
else {
panic!("verified remote close must unbind before deregistration");
};
let _ = result_tx.send(LinkEndpointUnbindResult::Unbound);
assert!(lm.poll_link_endpoints());
assert!(matches!(
next_transport_message(&mut transport_rx).unwrap(),
TransportMessage::DeregisterDestination { hash } if hash == link_id
));
}
#[test]
@@ -5910,6 +6055,17 @@ mod tests {
lm.handle_link_request(&raw, 1);
assert_eq!(lm.active_link_count(), 1);
let TransportMessage::BindLinkEndpoint {
result_tx,
lifecycle_tx,
..
} = rx.try_recv().expect("Link bind should be queued")
else {
panic!("expected endpoint bind before Link registration");
};
let _ = result_tx.send(LinkEndpointBindResult::Bound);
std::mem::forget(lifecycle_tx);
assert!(lm.poll_link_endpoints());
let registration =
next_transport_message(&mut rx).expect("Link registration should be queued");
assert!(matches!(
@@ -6827,6 +6983,7 @@ mod tests {
assert_eq!(binding.role, LinkEndpointRole::Responder);
let _ = result_tx.send(LinkEndpointBindResult::Bound);
std::mem::forget(lifecycle_tx);
assert!(manager.poll_link_endpoints());
assert!(matches!(
transport_rx.try_recv(),
@@ -6879,6 +7036,223 @@ mod tests {
assert_eq!(manager.link_interface(&initiator.link_id), None);
}
#[test]
fn responder_bind_conflict_publishes_no_handshake_or_foreign_cleanup() {
for result in [
LinkEndpointBindResult::AlreadyBound,
LinkEndpointBindResult::Conflict {
interface_id: 17,
role: LinkEndpointRole::Responder,
},
] {
let identity = Identity::new();
let destination_hash = Destination::hash_from_name_and_identity(
"endpoint.bind-conflict",
Some(&identity.hash),
);
let (transport_tx, mut transport_rx) = mpsc::channel(16);
let (_event_tx, event_rx) = mpsc::channel(16);
let mut manager = LinkManager::with_destination(
transport_tx,
event_rx,
&identity,
"endpoint.bind-conflict",
identity.get_signing_key(),
);
let (initiator, request_data) = Link::new_initiator(destination_hash, 1);
manager.handle_link_request(&link_request_raw(destination_hash, &request_data), 17);
let TransportMessage::BindLinkEndpoint {
lifecycle_tx,
result_tx,
..
} = transport_rx.try_recv().expect("endpoint bind")
else {
panic!("first command must be the isolated bind attempt");
};
let _ = result_tx.send(result);
drop(lifecycle_tx);
assert!(manager.poll_link_endpoints());
assert_eq!(manager.active_link_count(), 0);
assert!(!manager.owned_endpoint_bindings.contains(&initiator.link_id));
assert!(manager.pending_link_control.is_empty());
assert!(manager.pending_endpoint_cleanups.is_empty());
assert!(
transport_rx.try_recv().is_err(),
"conflict must emit no RegisterLink, LRPROOF, unbind, or deregistration"
);
}
}
#[tokio::test]
async fn responder_conflict_leaves_preexisting_transport_endpoint_usable() {
let (actor, transport_tx) = rns_transport::actor::TransportActor::new();
let actor_task = tokio::spawn(actor.run());
let (interface_tx, mut interface_rx) = mpsc::channel(8);
transport_tx
.send(TransportMessage::RegisterInterface {
id: 17,
entry: rns_transport::messages::InterfaceEntry::new(
"existing-link-owner".into(),
rns_transport::constants::InterfaceMode::Gateway,
rns_transport::constants::InterfaceDirection::bidirectional(),
115_200,
500,
interface_tx,
),
})
.await
.unwrap();
let identity = Identity::new();
let destination_hash = Destination::hash_from_name_and_identity(
"endpoint.actor-conflict",
Some(&identity.hash),
);
let (initiator, request_data) = Link::new_initiator(destination_hash, 1);
let link_id = initiator.link_id;
let (existing_lifecycle_tx, mut existing_lifecycle_rx) = mpsc::unbounded_channel();
let (bind_result_tx, bind_result_rx) = oneshot::channel();
transport_tx
.send(TransportMessage::BindLinkEndpoint {
binding: LinkEndpointBinding {
link_id,
interface_id: 17,
role: LinkEndpointRole::Responder,
},
lifecycle_tx: existing_lifecycle_tx,
result_tx: bind_result_tx,
})
.await
.unwrap();
assert_eq!(bind_result_rx.await.unwrap(), LinkEndpointBindResult::Bound);
let (_event_tx, event_rx) = mpsc::channel(8);
let mut manager = LinkManager::with_destination(
transport_tx.clone(),
event_rx,
&identity,
"endpoint.actor-conflict",
identity.get_signing_key(),
);
manager.handle_link_request(&link_request_raw(destination_hash, &request_data), 17);
for _ in 0..100 {
manager.poll_link_endpoints();
if manager.pending_endpoint_binds.is_empty() {
break;
}
tokio::task::yield_now().await;
}
assert!(manager.pending_endpoint_binds.is_empty());
assert_eq!(manager.active_link_count(), 0);
assert!(
interface_rx.try_recv().is_err(),
"conflicting manager must not publish LRPROOF"
);
assert!(matches!(
existing_lifecycle_rx.try_recv(),
Err(mpsc::error::TryRecvError::Empty)
));
let raw = Bytes::from(LinkManager::build_link_data_packet(
link_id,
rns_wire::context::PacketContext::None,
b"still owned",
));
let (send_result_tx, send_result_rx) = oneshot::channel();
transport_tx
.send(TransportMessage::SendLinkEndpoint {
link_id,
role: LinkEndpointRole::Responder,
request: OutboundRequest {
raw: raw.clone(),
destination_hash: link_id,
},
result_tx: send_result_tx,
})
.await
.unwrap();
assert!(matches!(
send_result_rx.await.unwrap(),
LinkEndpointSendResult::Sent | LinkEndpointSendResult::Queued { .. }
));
assert_eq!(interface_rx.recv().await, Some(raw));
assert!(matches!(
existing_lifecycle_rx.try_recv(),
Err(mpsc::error::TryRecvError::Empty)
));
let (unbind_result_tx, unbind_result_rx) = oneshot::channel();
transport_tx
.send(TransportMessage::UnbindLinkEndpoint {
link_id,
role: LinkEndpointRole::Responder,
result_tx: unbind_result_tx,
})
.await
.unwrap();
assert_eq!(
unbind_result_rx.await.unwrap(),
LinkEndpointUnbindResult::Unbound
);
let _ = transport_tx.send(TransportMessage::Shutdown).await;
actor_task.await.unwrap();
}
#[test]
fn late_bound_result_releases_only_the_unpublished_endpoint() {
let identity = Identity::new();
let destination_hash =
Destination::hash_from_name_and_identity("endpoint.late-bound", Some(&identity.hash));
let (transport_tx, mut transport_rx) = mpsc::channel(16);
let (_event_tx, event_rx) = mpsc::channel(16);
let mut manager = LinkManager::with_destination(
transport_tx,
event_rx,
&identity,
"endpoint.late-bound",
identity.get_signing_key(),
);
let (initiator, request_data) = Link::new_initiator(destination_hash, 1);
manager.handle_link_request(&link_request_raw(destination_hash, &request_data), 23);
let TransportMessage::BindLinkEndpoint {
lifecycle_tx,
result_tx,
..
} = transport_rx.try_recv().expect("endpoint bind")
else {
panic!("expected isolated endpoint bind");
};
assert!(manager.close_active_link(
initiator.link_id,
CloseReason::DestinationClosed,
false
));
assert!(transport_rx.try_recv().is_err());
let _ = result_tx.send(LinkEndpointBindResult::Bound);
std::mem::forget(lifecycle_tx);
assert!(manager.poll_link_endpoints());
let TransportMessage::UnbindLinkEndpoint {
link_id,
role,
result_tx,
} = transport_rx.try_recv().expect("late ownership cleanup")
else {
panic!("late Bound must transfer into exact cleanup");
};
assert_eq!(link_id, initiator.link_id);
assert_eq!(role, LinkEndpointRole::Responder);
let _ = result_tx.send(LinkEndpointUnbindResult::Unbound);
assert!(manager.poll_link_endpoints());
assert!(
transport_rx.try_recv().is_err(),
"unpublished candidate must not deregister a different local Link role"
);
}
#[test]
fn responder_rejects_wrong_interface_before_link_delivery() {
let (initiator, responder) = handshaken_link_pair();
@@ -6941,6 +7315,7 @@ mod tests {
manager
.active_links
.insert(link_id, active_link_entry_at(responder, 10));
manager.owned_endpoint_bindings.insert(link_id);
manager
.send_link_packet(&link_id, b"must fail closed")
@@ -6957,6 +7332,13 @@ mod tests {
assert!(manager.poll_link_endpoints());
assert_eq!(manager.active_link_count(), 0);
assert!(manager.pending_endpoint_sends.is_empty());
let TransportMessage::UnbindLinkEndpoint { result_tx, .. } =
transport_rx.try_recv().unwrap()
else {
panic!("send rejection must release the exact endpoint first");
};
let _ = result_tx.send(LinkEndpointUnbindResult::Unbound);
assert!(manager.poll_link_endpoints());
assert!(matches!(
next_transport_message(&mut transport_rx),
Ok(TransportMessage::DeregisterDestination { hash }) if hash == link_id
@@ -7009,6 +7391,7 @@ mod tests {
manager
.active_links
.insert(link_id, active_link_entry_at(responder, 12));
manager.owned_endpoint_bindings.insert(link_id);
assert!(manager.close_link(link_id, CloseReason::DestinationClosed, true));
let TransportMessage::SendLinkEndpointAndUnbind {
@@ -7043,6 +7426,7 @@ mod tests {
manager
.active_links
.insert(link_id, active_link_entry_at(responder, 12));
manager.owned_endpoint_bindings.insert(link_id);
assert!(manager.close_link(link_id, CloseReason::DestinationClosed, true));
let TransportMessage::SendLinkEndpointAndUnbind { result_tx, .. } =
@@ -7053,12 +7437,64 @@ mod tests {
let _ = result_tx.send(LinkEndpointSendResult::NotBound);
assert!(manager.poll_link_endpoints());
assert!(manager.pending_endpoint_sends.is_empty());
let TransportMessage::UnbindLinkEndpoint { result_tx, .. } =
transport_rx.try_recv().unwrap()
else {
panic!("rejected atomic close must fall back to explicit unbind");
};
let _ = result_tx.send(LinkEndpointUnbindResult::NotBound);
assert!(manager.poll_link_endpoints());
assert!(matches!(
next_transport_message(&mut transport_rx),
Ok(TransportMessage::DeregisterDestination { hash }) if hash == link_id
));
}
#[tokio::test]
async fn shutdown_drains_owned_endpoint_cleanup_after_ingress_backpressure() {
let (_initiator, responder) = handshaken_link_pair();
let link_id = responder.link_id;
let (transport_tx, mut transport_rx) = mpsc::channel(1);
transport_tx.send(TransportMessage::Shutdown).await.unwrap();
let (_event_tx, event_rx) = mpsc::channel(1);
let mut manager = LinkManager::new(transport_tx, event_rx, [0x77; 16], None);
manager
.active_links
.insert(link_id, active_link_entry_at(responder, 12));
manager.owned_endpoint_bindings.insert(link_id);
let shutdown = tokio::spawn(async move {
manager.drain_shutdown_link_ownership().await;
});
assert!(matches!(
transport_rx.recv().await,
Some(TransportMessage::Shutdown)
));
let Some(TransportMessage::UnbindLinkEndpoint {
link_id: unbound,
role,
result_tx,
}) = transport_rx.recv().await
else {
panic!("shutdown must retain the endpoint unbind while ingress is full");
};
assert_eq!(unbound, link_id);
assert_eq!(role, LinkEndpointRole::Responder);
assert!(!shutdown.is_finished());
assert!(
tokio::time::timeout(std::time::Duration::from_millis(10), transport_rx.recv())
.await
.is_err(),
"shutdown must await unbind ownership before deregistering"
);
let _ = result_tx.send(LinkEndpointUnbindResult::Unbound);
assert!(matches!(
transport_rx.recv().await,
Some(TransportMessage::DeregisterDestination { hash }) if hash == link_id
));
shutdown.await.unwrap();
}
fn resource_advertisement_packet(sender_link: &Link, advertisement: &[u8]) -> Vec<u8> {
let encrypted = sender_link
.encrypt(advertisement)
@@ -10310,10 +10746,24 @@ mod tests {
let active = lm.get_link(&link_id).unwrap();
assert_eq!(active.state, LinkState::Handshake);
let outbound = next_transport_message(&mut transport_rx);
assert!(
outbound.is_ok(),
"proof packet should be queued for sending"
);
let TransportMessage::BindLinkEndpoint {
result_tx,
lifecycle_tx,
..
} = transport_rx.try_recv().expect("endpoint bind")
else {
panic!("endpoint bind must precede the responder handshake transaction");
};
let _ = result_tx.send(LinkEndpointBindResult::Bound);
std::mem::forget(lifecycle_tx);
assert!(lm.poll_link_endpoints());
assert!(matches!(
next_transport_message(&mut transport_rx),
Ok(TransportMessage::RegisterLink { link_id: registered, .. }) if registered == link_id
));
assert!(matches!(
next_transport_message(&mut transport_rx),
Ok(TransportMessage::OutboundAttached { .. })
));
}
}
+17 -68
View File
@@ -932,51 +932,6 @@ pub struct LinkSession {
pub resource_offers: mpsc::Receiver<LinkSessionResourceOffer>,
}
/// Ensures a cancelled or failed handshake cannot leave its temporary Link
/// destination registered in the transport actor. Once the session actor owns
/// cleanup, `disarm` transfers that responsibility.
struct DestinationRegistrationGuard {
transport_tx: mpsc::Sender<TransportMessage>,
link_id: [u8; 16],
endpoint_bound: bool,
armed: bool,
}
impl DestinationRegistrationGuard {
fn new(transport_tx: mpsc::Sender<TransportMessage>, link_id: [u8; 16]) -> Self {
Self {
transport_tx,
link_id,
endpoint_bound: false,
armed: true,
}
}
fn endpoint_bound(&mut self) {
self.endpoint_bound = true;
}
fn disarm(&mut self) {
self.armed = false;
}
}
impl Drop for DestinationRegistrationGuard {
fn drop(&mut self) {
if self.armed {
if self.endpoint_bound {
let _ = self
.transport_tx
.try_send(crate::link_endpoint::unbind_message(
self.link_id,
LinkEndpointRole::Initiator,
));
}
deregister_destination(&self.transport_tx, self.link_id);
}
}
}
impl LinkSession {
pub async fn connect(
transport_tx: mpsc::Sender<TransportMessage>,
@@ -996,7 +951,11 @@ impl LinkSession {
})
.await
.map_err(|_| LinkSessionError::TransportUnavailable)?;
let mut registration = DestinationRegistrationGuard::new(transport_tx.clone(), link_id);
let mut registration = crate::link_endpoint::LinkEndpointCleanupGuard::new(
transport_tx.clone(),
link_id,
LinkEndpointRole::Initiator,
);
let request = build_link_request_packet(config.destination_hash, &request_data);
if transport_tx
@@ -1114,8 +1073,8 @@ impl LinkSession {
resource_offer_tx,
phy_stats_tx,
},
registration,
));
registration.disarm();
Ok(Self {
handle,
@@ -1180,6 +1139,7 @@ async fn run_session_actor(
>,
mut command_rx: mpsc::Receiver<LinkSessionCommand>,
channels: SessionActorChannels,
mut registration: crate::link_endpoint::LinkEndpointCleanupGuard,
) {
let SessionActorChannels {
transport_tx,
@@ -1442,9 +1402,9 @@ async fn run_session_actor(
fail_outbound_resources(&mut link, &mut state.resources, &event_tx);
fail_inbound_resources(&mut link, &mut state.resources, &event_tx);
if !endpoint_closing {
let _ =
crate::link_endpoint::unbind(&transport_tx, link_id, LinkEndpointRole::Initiator).await;
deregister_destination(&transport_tx, link_id);
let _ = registration.cleanup().await;
} else {
registration.disarm();
}
let _ = event_tx
.send(LinkSessionEvent::Closed {
@@ -3947,24 +3907,6 @@ async fn send_raw(
.map_err(|_| LinkSessionError::TransportUnavailable)
}
fn deregister_destination(transport_tx: &mpsc::Sender<TransportMessage>, link_id: [u8; 16]) {
let message = TransportMessage::DeregisterDestination { hash: link_id };
match transport_tx.try_send(message) {
Ok(()) | Err(mpsc::error::TrySendError::Closed(_)) => {}
Err(mpsc::error::TrySendError::Full(message)) => {
// Cleanup must not be lost merely because the transport actor is
// momentarily busy. Handshake guards can call this from Drop, so
// enqueue asynchronously instead of blocking the current task.
if let Ok(runtime) = tokio::runtime::Handle::try_current() {
let transport_tx = transport_tx.clone();
runtime.spawn(async move {
let _ = transport_tx.send(message).await;
});
}
}
}
}
fn build_link_request_packet(destination_hash: [u8; 16], request_data: &[u8]) -> Bytes {
let header = rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
@@ -4500,6 +4442,12 @@ mod tests {
command_tx: command_tx.clone(),
phy_stats_rx,
};
let mut registration = crate::link_endpoint::LinkEndpointCleanupGuard::new(
transport_tx.clone(),
link_id,
LinkEndpointRole::Initiator,
);
registration.endpoint_bound();
tokio::spawn(run_session_actor(
(initiator, channel),
@@ -4514,6 +4462,7 @@ mod tests {
resource_offer_tx,
phy_stats_tx,
},
registration,
));
assert_eq!(
+14 -54
View File
@@ -41,32 +41,6 @@ pub const DEFAULT_RNCP_APP_NAME: &str = "rncp.receive";
/// `FAILED` on a loaded peer.
const RNCP_POST_PROOF_SETTLE: Duration = Duration::from_millis(250);
struct RncpLinkGuard {
transport_tx: mpsc::Sender<TransportMessage>,
link_id: [u8; 16],
endpoint_bound: bool,
cleanup_required: bool,
}
impl Drop for RncpLinkGuard {
fn drop(&mut self) {
if !self.cleanup_required {
return;
}
if self.endpoint_bound {
let _ = self
.transport_tx
.try_send(crate::link_endpoint::unbind_message(
self.link_id,
LinkEndpointRole::Initiator,
));
}
let _ = self
.transport_tx
.try_send(TransportMessage::DeregisterDestination { hash: self.link_id });
}
}
async fn send_endpoint_packet(
transport_tx: &mpsc::Sender<TransportMessage>,
link_id: [u8; 16],
@@ -557,12 +531,11 @@ pub async fn rncp_send_file(request: RncpSendRequest<'_>) -> Result<RncpOutcome,
})
.await
.map_err(|_| RncpError::TransportUnavailable)?;
let mut registration = RncpLinkGuard {
transport_tx: transport_tx.clone(),
let mut registration = crate::link_endpoint::LinkEndpointCleanupGuard::new(
transport_tx.clone(),
link_id,
endpoint_bound: false,
cleanup_required: true,
};
LinkEndpointRole::Initiator,
);
let link_req_pkt = build_link_request_packet(dest_hash, &link_request_data);
transport_tx
@@ -584,7 +557,7 @@ pub async fn rncp_send_file(request: RncpSendRequest<'_>) -> Result<RncpOutcome,
)
.await
.map_err(|_| RncpError::TransportUnavailable)?;
registration.endpoint_bound = true;
registration.endpoint_bound();
let rtt_pkt = build_data_packet(link_id, rns_wire::context::PacketContext::Lrrtt, &rtt_data);
send_endpoint_packet(&transport_tx, link_id, rtt_pkt).await?;
@@ -685,13 +658,9 @@ pub async fn rncp_send_file(request: RncpSendRequest<'_>) -> Result<RncpOutcome,
false
};
if !endpoint_closing {
let _ =
crate::link_endpoint::unbind(&transport_tx, link_id, LinkEndpointRole::Initiator).await;
registration.endpoint_bound = false;
cleanup_destination(&transport_tx, link_id).await;
registration.cleanup_required = false;
let _ = registration.cleanup().await;
} else {
registration.cleanup_required = false;
registration.disarm();
}
transfer_result?;
@@ -1035,10 +1004,6 @@ async fn wait_for_valid_rncp_proof(
Ok((proof.rtt_data, proof.interface_id))
}
async fn cleanup_destination(transport_tx: &mpsc::Sender<TransportMessage>, link_id: [u8; 16]) {
let _ = transport_tx.try_send(TransportMessage::DeregisterDestination { hash: link_id });
}
fn build_link_request_packet(dest_hash: [u8; 16], request_data: &[u8]) -> Bytes {
let header = rns_wire::header::PacketHeader {
flags: rns_wire::flags::PacketFlags {
@@ -1159,12 +1124,11 @@ pub async fn rncp_fetch_file(request: RncpFetchRequest<'_>) -> Result<RncpFetchO
})
.await
.map_err(|_| RncpError::TransportUnavailable)?;
let mut registration = RncpLinkGuard {
transport_tx: transport_tx.clone(),
let mut registration = crate::link_endpoint::LinkEndpointCleanupGuard::new(
transport_tx.clone(),
link_id,
endpoint_bound: false,
cleanup_required: true,
};
LinkEndpointRole::Initiator,
);
let link_req_pkt = build_link_request_packet(dest_hash, &link_request_data);
transport_tx
@@ -1186,7 +1150,7 @@ pub async fn rncp_fetch_file(request: RncpFetchRequest<'_>) -> Result<RncpFetchO
)
.await
.map_err(|_| RncpError::TransportUnavailable)?;
registration.endpoint_bound = true;
registration.endpoint_bound();
let rtt_pkt = build_data_packet(link_id, rns_wire::context::PacketContext::Lrrtt, &rtt_data);
send_endpoint_packet(&transport_tx, link_id, rtt_pkt).await?;
@@ -1523,13 +1487,9 @@ pub async fn rncp_fetch_file(request: RncpFetchRequest<'_>) -> Result<RncpFetchO
false
};
if !endpoint_closing {
let _ =
crate::link_endpoint::unbind(&transport_tx, link_id, LinkEndpointRole::Initiator).await;
registration.endpoint_bound = false;
cleanup_destination(&transport_tx, link_id).await;
registration.cleanup_required = false;
let _ = registration.cleanup().await;
} else {
registration.cleanup_required = false;
registration.disarm();
}
let (file_name, payload) = result?;
+7 -45
View File
@@ -324,12 +324,11 @@ pub async fn rnsh_client_execute(
})
.await
.map_err(|_| RnshError::TransportUnavailable)?;
let mut registration = RnshLinkGuard {
transport_tx: transport_tx.clone(),
let mut registration = crate::link_endpoint::LinkEndpointCleanupGuard::new(
transport_tx.clone(),
link_id,
endpoint_bound: false,
cleanup_required: true,
};
LinkEndpointRole::Initiator,
);
let link_req_pkt = build_link_request_packet(destination_hash, &request_data);
transport_tx
@@ -363,7 +362,7 @@ pub async fn rnsh_client_execute(
)
.await
.map_err(|_| RnshError::TransportUnavailable)?;
registration.endpoint_bound = true;
registration.endpoint_bound();
let mut endpoint = ClientLinkEndpoint {
attached_interface,
lifecycle_rx: &mut endpoint_lifecycle_rx,
@@ -428,14 +427,12 @@ pub async fn rnsh_client_execute(
match message {
RnshMessage::VersionInfo(version) => {
if version.protocol_version != PROTOCOL_VERSION {
cleanup_destination(&transport_tx, link_id).await;
return Err(RnshError::Remote("incompatible rnsh protocol".into()));
}
tokio::time::sleep(Duration::from_millis(75)).await;
break;
}
RnshMessage::Error(err) => {
cleanup_destination(&transport_tx, link_id).await;
return Err(RnshError::Remote(
err.msg.unwrap_or_else(|| "remote error".into()),
));
@@ -485,7 +482,6 @@ pub async fn rnsh_client_execute(
{
Ok(return_code) => return_code,
Err(error) => {
cleanup_destination(&transport_tx, link_id).await;
return Err(error);
}
};
@@ -503,13 +499,9 @@ pub async fn rnsh_client_execute(
false
};
if !endpoint_closing {
let _ =
crate::link_endpoint::unbind(&transport_tx, link_id, LinkEndpointRole::Initiator).await;
registration.endpoint_bound = false;
cleanup_destination(&transport_tx, link_id).await;
registration.cleanup_required = false;
let _ = registration.cleanup().await;
} else {
registration.cleanup_required = false;
registration.disarm();
}
Ok(RnshClientOutcome {
@@ -519,32 +511,6 @@ pub async fn rnsh_client_execute(
})
}
struct RnshLinkGuard {
transport_tx: mpsc::Sender<TransportMessage>,
link_id: [u8; 16],
endpoint_bound: bool,
cleanup_required: bool,
}
impl Drop for RnshLinkGuard {
fn drop(&mut self) {
if !self.cleanup_required {
return;
}
if self.endpoint_bound {
let _ = self
.transport_tx
.try_send(crate::link_endpoint::unbind_message(
self.link_id,
LinkEndpointRole::Initiator,
));
}
let _ = self
.transport_tx
.try_send(TransportMessage::DeregisterDestination { hash: self.link_id });
}
}
struct ClientLinkEndpoint<'a> {
attached_interface: InterfaceId,
lifecycle_rx: &'a mut mpsc::UnboundedReceiver<LinkEndpointLifecycleEvent>,
@@ -1874,10 +1840,6 @@ async fn wait_for_valid_link_proof(
})
}
async fn cleanup_destination(transport_tx: &mpsc::Sender<TransportMessage>, link_id: [u8; 16]) {
let _ = transport_tx.try_send(TransportMessage::DeregisterDestination { hash: link_id });
}
async fn send_keepalive_response(
transport_tx: &mpsc::Sender<TransportMessage>,
link_id: [u8; 16],