You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by wy...@apache.org on 2026/09/05 06:35:24 UTC
(maka) branch fix/peer-mesh-resilience created (now d555e67480)
This is an automated email from the ASF dual-hosted git repository.
M4n5ter pushed a change to branch fix/peer-mesh-resilience
in repository https://gitbox.apache.org/repos/asf/maka.git
at d555e67480 fix(peer): recover routes and preserve connectivity under stalls
This branch includes the following new commits:
new d555e67480 fix(peer): recover routes and preserve connectivity under stalls
The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org
(maka) 01/01: fix(peer): recover routes and preserve connectivity under stalls
Posted by wy...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
M4n5ter pushed a commit to branch fix/peer-mesh-resilience
in repository https://gitbox.apache.org/repos/asf/maka.git
commit d555e6748020d4298575a63769252f7e7e45547d
Author: M4n5ter <m4...@gmail.com>
AuthorDate: Sat Sep 5 14:35:00 2026 +0800
fix(peer): recover routes and preserve connectivity under stalls
---
native/runtime-host-peer/src/engine.rs | 850 ++++++++++++++++++---
.../src/engine/application_stream.rs | 4 +
native/runtime-host-peer/src/engine/peer_stream.rs | 176 +++--
.../runtime-host-peer/src/webrtc_direct/tests.rs | 1 +
.../runtime-host/src/__tests__/host-kernel.test.ts | 2 +-
.../runtime-host/src/__tests__/peer-native.test.ts | 10 +-
.../__tests__/session-subscription-client.test.ts | 60 +-
packages/runtime-host/src/client/connection.ts | 42 +-
packages/runtime-host/src/client/peer-client.ts | 9 +-
9 files changed, 952 insertions(+), 202 deletions(-)
diff --git a/native/runtime-host-peer/src/engine.rs b/native/runtime-host-peer/src/engine.rs
index d3262845ff..80b955dea6 100644
--- a/native/runtime-host-peer/src/engine.rs
+++ b/native/runtime-host-peer/src/engine.rs
@@ -82,13 +82,16 @@ const LISTENER_ADDRESS_QUIET_PERIOD: Duration = Duration::from_millis(250);
const COORDINATION_RETRY_INTERVAL: Duration = Duration::from_secs(1);
const TRANSIT_HOLE_PUNCH_RETRY_INTERVAL: Duration = Duration::from_secs(30);
const AUTOMATIC_RELAY_COOLDOWN: Duration = Duration::from_secs(30);
-const IDLE_CONNECTION_TIMEOUT: Duration = Duration::from_secs(10);
+const IDLE_CONNECTION_TIMEOUT: Duration = Duration::from_secs(60);
+const PING_INTERVAL: Duration = Duration::from_secs(2);
+const PING_TIMEOUT: Duration = Duration::from_secs(3);
+const MAX_CONSECUTIVE_PING_FAILURES: u8 = 3;
const TARGET_COORDINATION_RESERVATIONS: usize = 2;
const MAX_AUTOMATIC_RELAY_CANDIDATES: usize = 8;
const MAX_REMEMBERED_RELAY_FAILURES: u8 = 3;
const MAX_RELAY_ADDRESSES_PER_PEER: usize = 4;
const MAX_PUBLISHED_COORDINATION_RELAY_ADDRESSES: usize = 16;
-const TRANSIT_FALLBACK_DELAY: Duration = Duration::from_secs(3);
+const TRANSIT_FALLBACK_DELAY: Duration = Duration::from_millis(250);
const MAX_TRANSIT_RESERVATIONS: usize = 32;
const MAX_TRANSIT_CIRCUITS: usize = 8;
const MAX_TRANSIT_CIRCUITS_PER_PEER: usize = 2;
@@ -178,6 +181,16 @@ pub enum EngineCommand {
Stop {
result: oneshot::Sender<()>,
},
+ #[cfg(test)]
+ HasDirectConnection {
+ peer_id: PeerId,
+ result: oneshot::Sender<bool>,
+ },
+ #[cfg(test)]
+ CloseDirectConnections {
+ peer_id: PeerId,
+ result: oneshot::Sender<()>,
+ },
}
pub struct TransitPolicy {
@@ -250,7 +263,8 @@ struct Behaviour {
struct PendingConnect {
attempt_id: ConnectAttemptId,
peer_id: PeerId,
- result: oneshot::Sender<Result<PeerStream, PeerError>>,
+ // None keeps route discovery alive after a transit stream was delivered.
+ result: Option<oneshot::Sender<Result<PeerStream, PeerError>>>,
stream_kind: StreamKind,
deadline: Instant,
opening: Option<PendingStreamOpen>,
@@ -343,6 +357,27 @@ struct DirectConnectState {
pending: HashMap<u32, PendingConnect>,
active: HashMap<ConnectionId, usize>,
retiring_connections: HashSet<ConnectionId>,
+ health: HashMap<ConnectionId, ConnectionHealth>,
+}
+
+#[derive(Default)]
+struct ConnectionHealth {
+ failures: u8,
+ rtt: Option<Duration>,
+}
+
+impl ConnectionHealth {
+ fn observe(&mut self, result: Result<Duration, ping::Failure>) -> bool {
+ match result {
+ Ok(rtt) => {
+ self.failures = 0;
+ self.rtt = Some(self.rtt.map_or(rtt, |previous| (previous * 3 + rtt) / 4));
+ }
+ Err(ping::Failure::Unsupported) => return false,
+ Err(_) => self.failures = self.failures.saturating_add(1),
+ }
+ self.failures >= MAX_CONSECUTIVE_PING_FAILURES
+ }
}
enum PendingAttemptAdmission {
@@ -692,21 +727,18 @@ async fn run_endpoint_async(
};
let listen_addresses = if options.listen_addresses.is_empty() {
- vec![
- "/ip4/0.0.0.0/udp/0/quic-v1"
- .parse()
- .expect("constant multiaddr"),
- ]
+ default_listen_addresses()
} else {
options.listen_addresses
};
let mut pending_listeners = HashSet::new();
+ let mut configured_listeners = HashMap::new();
for address in &listen_addresses {
- pending_listeners.insert(
- swarm
- .listen_on(address.clone())
- .map_err(|error| PeerError::new("peer_native_failed", error.to_string()))?,
- );
+ let listener = swarm
+ .listen_on(address.clone())
+ .map_err(|error| PeerError::new("peer_native_failed", error.to_string()))?;
+ pending_listeners.insert(listener);
+ configured_listeners.insert(listener, address.clone());
}
let mut coordination_relays = HashMap::new();
for relay in &options.coordination_relays {
@@ -735,7 +767,6 @@ async fn run_endpoint_async(
let startup_deadline = Instant::now() + Duration::from_secs(10);
let mut address_quiet_deadline = None;
- let mut bound_addresses = HashSet::new();
loop {
let deadline = address_quiet_deadline
.unwrap_or(startup_deadline)
@@ -747,7 +778,6 @@ async fn run_endpoint_async(
address,
}) if !is_relayed_address(&address) => {
pending_listeners.remove(&listener_id);
- bound_addresses.insert(address_with_peer(address, local_peer_id));
if pending_listeners.is_empty() {
address_quiet_deadline = Some(Instant::now() + LISTENER_ADDRESS_QUIET_PERIOD);
}
@@ -764,7 +794,12 @@ async fn run_endpoint_async(
}
}
}
- let mut bound_addresses = bound_addresses.into_iter().collect::<Vec<_>>();
+ let mut bound_addresses = swarm
+ .listeners()
+ .filter(|address| !is_relayed_address(address))
+ .cloned()
+ .map(|address| address_with_peer(address, local_peer_id))
+ .collect::<Vec<_>>();
bound_addresses.sort_unstable_by_key(ToString::to_string);
transit.listen_addresses.clone_from(&bound_addresses);
if webrtc_stun_urls.is_some() {
@@ -776,7 +811,7 @@ async fn run_endpoint_async(
&mut coordination_relays,
&reachability,
&mut relay_anchors,
- &bound_addresses,
+ &transit.listen_addresses,
);
publish_connectivity(&swarm, &connectivity);
let _ = ready_tx.send(Ok(local_peer_id));
@@ -785,6 +820,12 @@ async fn run_endpoint_async(
let (stream_completed_tx, mut stream_completed_rx) =
mpsc::channel::<CompletedStream>(MAX_ESTABLISHED_CONNECTIONS as usize);
let mut direct = DirectConnectState::default();
+ direct.health.extend(
+ mesh_control
+ .connection_ids()
+ .into_iter()
+ .map(|id| (id, ConnectionHealth::default())),
+ );
let mut deadline_tick = tokio::time::interval(Duration::from_millis(100));
deadline_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
let mut discovered_relays = options
@@ -793,13 +834,27 @@ async fn run_endpoint_async(
let webrtc_cancellation = CancellationToken::new();
let mut incoming_webrtc_upgrades = JoinSet::new();
let mut outgoing_webrtc_upgrades = JoinSet::new();
+ let mut failed_listeners = Vec::new();
loop {
tokio::select! {
command = commands.recv() => match command {
+ #[cfg(test)]
+ Some(EngineCommand::HasDirectConnection { peer_id, result }) => {
+ let _ = result.send(stream_control.has_connection(peer_id, &direct.retiring_connections, &HashSet::new()));
+ }
+ #[cfg(test)]
+ Some(EngineCommand::CloseDirectConnections { peer_id, result }) => {
+ for (connection, _) in stream_control.eligible_connections(peer_id, &HashSet::new(), &HashSet::new()) {
+ direct.retiring_connections.insert(connection);
+ let _ = swarm.close_connection(connection);
+ }
+ let _ = result.send(());
+ }
Some(EngineCommand::Connect { options, stream_kind, result }) => {
if direct.pending.contains_key(&options.request_id)
- || direct.pending.values().any(|connect| connect.peer_id == options.peer_id)
+ || direct.pending.values().any(|connect| connect.peer_id == options.peer_id
+ && connect.stream_kind == stream_kind && connect.result.is_some())
{
let _ = result.send(Err(PeerError::new(
"peer_connect_in_progress",
@@ -850,7 +905,7 @@ async fn run_endpoint_async(
direct.pending.insert(request_id, PendingConnect {
attempt_id,
peer_id: options.peer_id,
- result,
+ result: Some(result),
stream_kind,
deadline: Instant::now() + options.deadline,
opening: None,
@@ -886,6 +941,7 @@ async fn run_endpoint_async(
request_id,
&mut direct.pending,
&direct.retiring_connections,
+ &direct.health,
stream_control.clone(),
mesh_control.clone(),
opened_tx.clone(),
@@ -937,6 +993,7 @@ async fn run_endpoint_async(
request_id,
&mut direct.pending,
&direct.retiring_connections,
+ &direct.health,
stream_control.clone(),
mesh_control.clone(),
opened_tx.clone(),
@@ -983,6 +1040,7 @@ async fn run_endpoint_async(
request_id,
&mut direct.pending,
&direct.retiring_connections,
+ &direct.health,
stream_control.clone(),
mesh_control.clone(),
opened_tx.clone(),
@@ -1067,7 +1125,7 @@ async fn run_endpoint_async(
UpgradeRole::Answerer,
UpgradeOptions {
stun_urls,
- udp_bind_addresses: vec!["0.0.0.0:0".to_owned()],
+ udp_bind_addresses: default_webrtc_bind_addresses(),
deadline: WEBRTC_UPGRADE_DEADLINE,
cancellation,
},
@@ -1139,7 +1197,7 @@ async fn run_endpoint_async(
&mut coordination_relays,
&reachability,
&mut relay_anchors,
- &bound_addresses,
+ &transit.listen_addresses,
);
maintain_coordination_relays(
&mut swarm,
@@ -1243,29 +1301,42 @@ async fn run_endpoint_async(
request_id,
&mut direct.pending,
&direct.retiring_connections,
+ &direct.health,
stream_control.clone(),
mesh_control.clone(),
opened_tx.clone(),
);
continue;
}
- waiter.cancellation.cancel();
+ // A usable transit path must not cancel an in-flight
+ // direct upgrade. Keep one maintenance attempt per peer
+ // while its streams are in use; it never opens or replays
+ // application requests.
+ let maintain_direct = waiter.stream_kind == StreamKind::Application
+ && opened.path.relay_peer_id().is_some()
+ && !direct.pending.values().any(|other| other.peer_id == waiter.peer_id && other.result.is_none());
+ let result_sender = waiter.result.take();
+ if !maintain_direct {
+ waiter.cancellation.cancel();
+ }
abort_pending_openings(&mut waiter);
let result = match waiter.stream_kind {
StreamKind::Application => {
- retire_direct_dials(
- &mut swarm,
- &mut direct.retiring_connections,
- waiter.dials,
- Some(connection_id),
- );
+ if !maintain_direct {
+ retire_direct_dials(
+ &mut swarm, &mut direct,
+ std::mem::take(&mut waiter.dials), Some(connection_id),
+ );
+ }
*direct.active.entry(connection_id).or_default() += 1;
- release_coordination_relays(
- &mut swarm,
- &mut coordination_relays,
- &waiter.coordination_relay_peers,
- &direct.active,
- );
+ if !maintain_direct {
+ release_coordination_relays(
+ &mut swarm,
+ &mut coordination_relays,
+ &waiter.coordination_relay_peers,
+ &direct.active,
+ );
+ }
Ok(spawn_stream(
waiter.peer_id,
opened.path,
@@ -1279,8 +1350,8 @@ async fn run_endpoint_async(
StreamKind::MeshControl => {
retire_direct_dials(
&mut swarm,
- &mut direct.retiring_connections,
- waiter.dials,
+ &mut direct,
+ std::mem::take(&mut waiter.dials),
Some(connection_id),
);
*direct.active.entry(connection_id).or_default() += 1;
@@ -1291,15 +1362,21 @@ async fn run_endpoint_async(
Some((
StreamCompletion::MeshControl {
connection_id,
- coordination_relay_peers: waiter
- .coordination_relay_peers,
+ coordination_relay_peers: std::mem::take(&mut waiter.coordination_relay_peers),
},
stream_completed_tx.clone(),
)),
))
}
};
- let _ = waiter.result.send(result);
+ if let Some(sender) = result_sender {
+ let _ = sender.send(result);
+ }
+ if maintain_direct {
+ waiter.dials.remove(&connection_id);
+ waiter.deadline = Instant::now() + TRANSIT_HOLE_PUNCH_RETRY_INTERVAL;
+ direct.pending.insert(request_id, waiter);
+ }
}
Err(application_stream::OpenStreamError::UnsupportedProtocol) => {
fail_pending_connect(
@@ -1337,6 +1414,7 @@ async fn run_endpoint_async(
request_id,
&mut direct.pending,
&direct.retiring_connections,
+ &direct.health,
stream_control.clone(),
mesh_control.clone(),
opened_tx.clone(),
@@ -1345,6 +1423,10 @@ async fn run_endpoint_async(
}
}
event = swarm.select_next_some() => {
+ if let SwarmEvent::ListenerClosed { listener_id, .. } = &event
+ && let Some(address) = configured_listeners.remove(listener_id) {
+ failed_listeners.push((address, Instant::now() + COORDINATION_RETRY_INTERVAL));
+ }
handle_swarm_event(
&mut swarm,
event,
@@ -1367,7 +1449,7 @@ async fn run_endpoint_async(
&mut coordination_relays,
&reachability,
&mut relay_anchors,
- &bound_addresses,
+ &transit.listen_addresses,
);
maintain_coordination_relays(
&mut swarm,
@@ -1388,6 +1470,7 @@ async fn run_endpoint_async(
request_id,
&mut direct.pending,
&direct.retiring_connections,
+ &direct.health,
stream_control.clone(),
mesh_control.clone(),
opened_tx.clone(),
@@ -1396,6 +1479,8 @@ async fn run_endpoint_async(
}
_ = deadline_tick.tick() => {
let now = Instant::now();
+ restore_listeners(&mut swarm, &mut configured_listeners, &mut failed_listeners, now);
+ maintain_direct_routes(&mut swarm, &mut direct, &mut coordination_relays, &stream_control, now);
rebalance_automatic_relays(
&mut swarm,
&mut coordination_relays,
@@ -1406,7 +1491,7 @@ async fn run_endpoint_async(
&mut coordination_relays,
&reachability,
&mut relay_anchors,
- &bound_addresses,
+ &transit.listen_addresses,
);
maintain_coordination_relays(
&mut swarm,
@@ -1429,7 +1514,7 @@ async fn run_endpoint_async(
&mut outgoing_webrtc_upgrades,
);
let expired = direct.pending.iter()
- .filter_map(|(request_id, item)| (item.deadline <= now).then_some(*request_id))
+ .filter_map(|(request_id, item)| (item.result.is_some() && item.deadline <= now).then_some(*request_id))
.collect::<Vec<_>>();
for request_id in expired {
if let Some(waiter) = direct.pending.remove(&request_id) {
@@ -1531,11 +1616,15 @@ fn build_swarm(
transit_relay_config(allowed_transit_peers),
),
dcutr: dcutr::Behaviour::new(key.public().to_peer_id()),
- identify: identify::Behaviour::new(identify::Config::new(
- IDENTIFY_PROTOCOL.to_owned(),
- key.public(),
- )),
- ping: ping::Behaviour::new(ping::Config::new()),
+ identify: identify::Behaviour::new(
+ identify::Config::new(IDENTIFY_PROTOCOL.to_owned(), key.public())
+ .with_push_listen_addr_updates(true),
+ ),
+ ping: ping::Behaviour::new(
+ ping::Config::new()
+ .with_interval(PING_INTERVAL)
+ .with_timeout(PING_TIMEOUT),
+ ),
application_stream,
mesh_control: mesh_stream,
webrtc_signaling: Toggle::from(webrtc_enabled.then_some(webrtc_signaling)),
@@ -1735,6 +1824,7 @@ fn update_connect_candidates(
let _ = swarm.close_connection(connection_id);
}
let changed = direct_changed || coordination_changed || transit_changed;
+ let mut retired_dials = HashMap::new();
if changed {
waiter.next_route_attempt = Instant::now();
waiter.transit_after = Instant::now();
@@ -1742,30 +1832,19 @@ fn update_connect_candidates(
waiter.retry_coordination = true;
}
if direct_changed {
- retire_pending_dials_by_origin(
- swarm,
- &mut direct.retiring_connections,
- waiter,
- DialOrigin::Direct,
- );
+ retired_dials.extend(take_pending_dials_by_origin(waiter, DialOrigin::Direct));
}
if coordination_changed {
- retire_pending_dials_by_origin(
- swarm,
- &mut direct.retiring_connections,
+ retired_dials.extend(take_pending_dials_by_origin(
waiter,
DialOrigin::Coordination,
- );
+ ));
}
if transit_changed {
- retire_pending_dials_by_origin(
- swarm,
- &mut direct.retiring_connections,
- waiter,
- DialOrigin::Transit,
- );
+ retired_dials.extend(take_pending_dials_by_origin(waiter, DialOrigin::Transit));
}
}
+ retire_direct_dials(swarm, direct, retired_dials, None);
release_coordination_relays(
swarm,
coordination_relays,
@@ -1838,7 +1917,14 @@ fn start_pending_webrtc_upgrades(
let Some(waiter) = pending.get_mut(&request_id) else {
continue;
};
- if waiter.stream_kind != StreamKind::Application || waiter.webrtc_active_attempt.is_some() {
+ if waiter.stream_kind != StreamKind::Application
+ || waiter.webrtc_active_attempt.is_some()
+ || signaling_control.has_connection(
+ waiter.peer_id,
+ retiring_connections,
+ &HashSet::new(),
+ )
+ {
continue;
}
let Some(relay_peer_id) = next_webrtc_relay_peer(
@@ -1888,7 +1974,7 @@ fn start_pending_webrtc_upgrades(
UpgradeRole::Offerer,
UpgradeOptions {
stun_urls,
- udp_bind_addresses: vec!["0.0.0.0:0".to_owned()],
+ udp_bind_addresses: default_webrtc_bind_addresses(),
deadline: WEBRTC_UPGRADE_DEADLINE,
cancellation,
},
@@ -2104,6 +2190,7 @@ fn maybe_open_peer_stream(
request_id: u32,
pending: &mut HashMap<u32, PendingConnect>,
retiring_connections: &HashSet<ConnectionId>,
+ health: &HashMap<ConnectionId, ConnectionHealth>,
application_control: application_stream::Control,
mesh_control: application_stream::Control,
opened_tx: mpsc::Sender<OpenedStream>,
@@ -2125,7 +2212,7 @@ fn maybe_open_peer_stream(
.union(&waiter.rejected_connections)
.copied()
.collect::<HashSet<_>>();
- if waiter.opening.is_some() {
+ if waiter.result.is_none() || waiter.opening.is_some() {
return;
}
let stream_kind = waiter.stream_kind;
@@ -2137,10 +2224,9 @@ fn maybe_open_peer_stream(
mesh_control.eligible_connections(peer_id, &excluded, &eligible_relay_peers)
}
};
- let Some((connection_id, _)) = candidates
- .into_iter()
- .min_by_key(|(_, path)| stream_candidate_priority(path))
- else {
+ let Some((connection_id, _)) = candidates.into_iter().min_by_key(|(connection_id, path)| {
+ stream_candidate_score(path, health.get(connection_id))
+ }) else {
return;
};
let attempt_id = waiter.attempt_id;
@@ -2187,6 +2273,20 @@ fn stream_candidate_priority(path: &PeerConnectionPath) -> u8 {
}
}
+fn stream_candidate_score(
+ path: &PeerConnectionPath,
+ health: Option<&ConnectionHealth>,
+) -> (u8, bool, Duration, u8) {
+ (
+ health.map_or(0, |health| health.failures),
+ path.relay_peer_id().is_some(),
+ health
+ .and_then(|health| health.rtt)
+ .unwrap_or(Duration::from_millis(100)),
+ stream_candidate_priority(path),
+ )
+}
+
async fn gracefully_disconnect(swarm: &mut Swarm<Behaviour>) {
let peers = swarm.connected_peers().copied().collect::<Vec<_>>();
for peer_id in peers {
@@ -2207,6 +2307,14 @@ fn handle_swarm_event(
direct: &mut DirectConnectState,
mut route_runtime: RouteRuntime<'_>,
) {
+ if matches!(
+ &event,
+ SwarmEvent::NewListenAddr { .. }
+ | SwarmEvent::ExpiredListenAddr { .. }
+ | SwarmEvent::ListenerClosed { .. }
+ ) {
+ refresh_listen_addresses(swarm, &mut route_runtime);
+ }
let connectivity_changed = matches!(
&event,
SwarmEvent::ConnectionEstablished { .. } | SwarmEvent::ConnectionClosed { .. }
@@ -2248,6 +2356,7 @@ fn handle_swarm_event(
let _ = swarm.close_connection(connection_id);
return;
}
+ direct.health.entry(connection_id).or_default();
if let Some(relay) = coordination_relays.get_mut(&peer_id) {
let lifecycle_owned = relay.pending_connection == Some(connection_id);
if lifecycle_owned {
@@ -2275,6 +2384,7 @@ fn handle_swarm_event(
connection_id,
..
} => {
+ direct.health.remove(&connection_id);
direct.retiring_connections.remove(&connection_id);
for connect in direct.pending.values_mut() {
remove_pending_dial(connect, connection_id);
@@ -2323,6 +2433,18 @@ fn handle_swarm_event(
publish_route_runtime(coordination_relays, &mut route_runtime);
}
}
+ SwarmEvent::Behaviour(BehaviourEvent::Ping(ping::Event {
+ connection, result, ..
+ })) => {
+ if direct
+ .health
+ .get_mut(&connection)
+ .is_some_and(|health| health.observe(result))
+ {
+ direct.retiring_connections.insert(connection);
+ let _ = swarm.close_connection(connection);
+ }
+ }
SwarmEvent::OutgoingConnectionError {
connection_id,
error,
@@ -2438,8 +2560,33 @@ fn handle_swarm_event(
}
SwarmEvent::Behaviour(BehaviourEvent::Identify(identify::Event::Received {
peer_id,
+ info,
..
})) => {
+ // Identify is authenticated by this peer's transport identity. Keep
+ // background dialing current when the remote changes interfaces;
+ // do not wait for the next application connection or Mesh sweep.
+ let routes = bounded_unique(
+ info.listen_addrs
+ .into_iter()
+ .filter(|address| {
+ !is_relayed_address(address)
+ && !address.iter().any(|p| matches!(p, Protocol::WebRTC))
+ })
+ .filter_map(|address| address_with_expected_peer(&address, peer_id).ok())
+ .collect(),
+ MAX_CONNECT_ROUTES_PER_CLASS,
+ );
+ for pending in direct
+ .pending
+ .values_mut()
+ .filter(|pending| pending.peer_id == peer_id && pending.result.is_none())
+ {
+ if pending.direct_routes != routes {
+ pending.direct_routes.clone_from(&routes);
+ pending.next_route_attempt = Instant::now();
+ }
+ }
if let Some(relay) = coordination_relays.get_mut(&peer_id) {
relay.identify_received = true;
}
@@ -2626,6 +2773,7 @@ fn reconcile_pending_transit_connects(
}
let now = Instant::now();
let mut unavailable = Vec::new();
+ let mut retired_dials = HashMap::new();
for (request_id, waiter) in &mut direct.pending {
if waiter.stream_kind != StreamKind::Application
|| waiter.transit_relay_peers.is_disjoint(revoked_relays)
@@ -2643,12 +2791,7 @@ fn reconcile_pending_transit_connects(
if let Some(opening) = waiter.opening.take() {
opening.task.abort();
}
- retire_pending_dials_by_origin(
- swarm,
- &mut direct.retiring_connections,
- waiter,
- DialOrigin::Transit,
- );
+ retired_dials.extend(take_pending_dials_by_origin(waiter, DialOrigin::Transit));
waiter.next_route_attempt = now;
waiter.transit_after = now;
if waiter.direct_routes.is_empty()
@@ -2658,6 +2801,7 @@ fn reconcile_pending_transit_connects(
unavailable.push(*request_id);
}
}
+ retire_direct_dials(swarm, direct, retired_dials, None);
for request_id in unavailable {
let Some(waiter) = direct.pending.remove(&request_id) else {
continue;
@@ -2675,22 +2819,21 @@ fn reconcile_pending_transit_connects(
}
}
-fn retire_pending_dials_by_origin(
- swarm: &mut Swarm<Behaviour>,
- retiring: &mut HashSet<ConnectionId>,
+fn take_pending_dials_by_origin(
waiter: &mut PendingConnect,
origin: DialOrigin,
-) {
+) -> HashMap<ConnectionId, DialOrigin> {
let connections = waiter
.dials
.iter()
.filter_map(|(connection_id, current)| (*current == origin).then_some(*connection_id))
.collect::<Vec<_>>();
- for connection_id in connections {
- remove_pending_dial(waiter, connection_id);
- retiring.insert(connection_id);
- let _ = swarm.close_connection(connection_id);
- }
+ connections
+ .into_iter()
+ .filter_map(|connection_id| {
+ remove_pending_dial(waiter, connection_id).map(|origin| (connection_id, origin))
+ })
+ .collect()
}
fn remove_pending_dial(
@@ -2713,14 +2856,16 @@ fn fail_pending_connect(
) {
waiter.cancellation.cancel();
abort_pending_openings(&mut waiter);
- retire_direct_dials(swarm, &mut direct.retiring_connections, waiter.dials, None);
+ retire_direct_dials(swarm, direct, waiter.dials, None);
release_coordination_relays(
swarm,
coordination_relays,
&waiter.coordination_relay_peers,
&direct.active,
);
- let _ = waiter.result.send(Err(error));
+ if let Some(result) = waiter.result {
+ let _ = result.send(Err(error));
+ }
}
fn abort_pending_openings(waiter: &mut PendingConnect) {
@@ -3121,8 +3266,102 @@ fn publish_route_runtime(
else {
return;
};
- let listen_addresses = reachability.borrow().listen_addresses.clone();
- publish_active_coordination_relays(relays, reachability, relay_anchors, &listen_addresses);
+ publish_active_coordination_relays(
+ relays,
+ reachability,
+ relay_anchors,
+ &runtime.transit.listen_addresses,
+ );
+}
+
+fn restore_listeners(
+ swarm: &mut Swarm<Behaviour>,
+ configured: &mut HashMap<ListenerId, Multiaddr>,
+ failed: &mut Vec<(Multiaddr, Instant)>,
+ now: Instant,
+) {
+ failed.retain_mut(|(address, next_attempt)| {
+ if *next_attempt > now {
+ return true;
+ }
+ match swarm.listen_on(address.clone()) {
+ Ok(listener) => {
+ configured.insert(listener, address.clone());
+ false
+ }
+ Err(_) => {
+ *next_attempt = now + COORDINATION_RETRY_INTERVAL;
+ true
+ }
+ }
+ });
+}
+
+fn default_listen_addresses() -> Vec<Multiaddr> {
+ let mut addresses = vec![
+ "/ip4/0.0.0.0/udp/0/quic-v1"
+ .parse()
+ .expect("constant address"),
+ "/ip4/0.0.0.0/tcp/0".parse().expect("constant address"),
+ ];
+ // Some kernels disable IPv6. An optional family must not prevent the
+ // endpoint from starting on the available family.
+ if std::net::UdpSocket::bind("[::]:0").is_ok() {
+ addresses.push("/ip6/::/udp/0/quic-v1".parse().expect("constant address"));
+ addresses.push("/ip6/::/tcp/0".parse().expect("constant address"));
+ }
+ addresses
+}
+
+pub(crate) fn default_webrtc_bind_addresses() -> Vec<String> {
+ let mut addresses = vec!["0.0.0.0:0".to_owned()];
+ if std::net::UdpSocket::bind("[::]:0").is_ok() {
+ addresses.push("[::]:0".to_owned());
+ }
+ addresses
+}
+
+fn refresh_listen_addresses(swarm: &mut Swarm<Behaviour>, runtime: &mut RouteRuntime<'_>) {
+ let local_peer = *swarm.local_peer_id();
+ let mut addresses = swarm
+ .listeners()
+ .filter(|address| {
+ !is_relayed_address(address)
+ && !address
+ .iter()
+ .any(|protocol| matches!(protocol, Protocol::WebRTC))
+ })
+ .cloned()
+ .map(|address| address_with_peer(address, local_peer))
+ .collect::<Vec<_>>();
+ addresses.sort_unstable_by_key(ToString::to_string);
+ addresses.dedup();
+ let transit = &mut runtime.transit;
+ if transit.listen_addresses == addresses {
+ return;
+ }
+ for address in transit.published_addresses.clone() {
+ if !addresses.contains(&address) {
+ swarm.remove_external_address(&address);
+ transit
+ .published_addresses
+ .retain(|current| current != &address);
+ }
+ }
+ if transit
+ .allowed_peers
+ .read()
+ .is_ok_and(|peers| !peers.is_empty())
+ {
+ let existing = swarm.external_addresses().cloned().collect::<HashSet<_>>();
+ for address in &addresses {
+ if !existing.contains(address) {
+ swarm.add_external_address(address.clone());
+ transit.published_addresses.push(address.clone());
+ }
+ }
+ }
+ transit.listen_addresses = addresses;
}
fn bounded_relay_addresses(mut addresses: Vec<Multiaddr>) -> Vec<Multiaddr> {
@@ -3485,6 +3724,62 @@ fn webrtc_debug(message: std::fmt::Arguments<'_>) {
}
}
+fn maintain_direct_routes(
+ swarm: &mut Swarm<Behaviour>,
+ direct: &mut DirectConnectState,
+ relays: &mut HashMap<PeerId, CoordinationRelay>,
+ control: &application_stream::Control,
+ now: Instant,
+) {
+ let background = direct
+ .pending
+ .iter()
+ .filter_map(|(id, pending)| pending.result.is_none().then_some(*id))
+ .collect::<Vec<_>>();
+ for id in background {
+ let pending = direct
+ .pending
+ .get(&id)
+ .expect("collected maintenance attempt");
+ let in_use = control
+ .eligible_connections(
+ pending.peer_id,
+ &HashSet::new(),
+ &pending.transit_relay_peers,
+ )
+ .iter()
+ .any(|(connection, _)| direct.active.contains_key(connection));
+ if !in_use {
+ let pending = direct
+ .pending
+ .remove(&id)
+ .expect("maintenance attempt exists");
+ fail_pending_connect(
+ swarm,
+ direct,
+ relays,
+ pending,
+ PeerError::new("peer_connect_cancelled", "peer streams were released"),
+ );
+ } else if pending.deadline <= now {
+ let mut pending = direct
+ .pending
+ .remove(&id)
+ .expect("maintenance attempt exists");
+ pending.cancellation.cancel();
+ retire_direct_dials(swarm, direct, std::mem::take(&mut pending.dials), None);
+ pending.cancellation = CancellationToken::new();
+ pending.webrtc_active_attempt = None;
+ pending.webrtc_attempted_relays.clear();
+ pending.rejected_connections.clear();
+ pending.deadline = now + TRANSIT_HOLE_PUNCH_RETRY_INTERVAL;
+ pending.next_route_attempt = now;
+ pending.retry_coordination = true;
+ direct.pending.insert(id, pending);
+ }
+ }
+}
+
fn retry_connect_routes(
swarm: &mut Swarm<Behaviour>,
direct: &mut DirectConnectState,
@@ -3502,7 +3797,12 @@ fn retry_connect_routes(
.union(&connect.rejected_connections)
.copied()
.collect::<HashSet<_>>();
- if stream_control.has_connection(peer_id, &excluded, &connect.transit_relay_peers) {
+ let allowed_relays = if connect.result.is_some() {
+ connect.transit_relay_peers.clone()
+ } else {
+ HashSet::new()
+ };
+ if stream_control.has_connection(peer_id, &excluded, &allowed_relays) {
continue;
}
connect.next_route_attempt = now + COORDINATION_RETRY_INTERVAL;
@@ -3534,7 +3834,8 @@ fn retry_connect_routes(
}
}
- if now >= connect.transit_after
+ if connect.result.is_some()
+ && now >= connect.transit_after
&& !connect
.dials
.values()
@@ -3607,15 +3908,27 @@ fn dial_direct_targets(
fn retire_direct_dials(
swarm: &mut Swarm<Behaviour>,
- retiring: &mut HashSet<ConnectionId>,
+ direct: &mut DirectConnectState,
dials: HashMap<ConnectionId, DialOrigin>,
retained: Option<ConnectionId>,
) {
for connection_id in dials.into_keys() {
- if retained == Some(connection_id) {
+ if retained == Some(connection_id)
+ || direct.active.contains_key(&connection_id)
+ || direct
+ .health
+ .get(&connection_id)
+ .is_some_and(|health| health.rtt.is_some() && health.failures == 0)
+ || direct.pending.values().any(|pending| {
+ pending
+ .opening
+ .as_ref()
+ .is_some_and(|opening| opening.connection_id == connection_id)
+ })
+ {
continue;
}
- retiring.insert(connection_id);
+ direct.retiring_connections.insert(connection_id);
let _ = swarm.close_connection(connection_id);
}
}
@@ -3628,6 +3941,223 @@ fn native_error(error: impl std::fmt::Display) -> PeerError {
mod tests {
use super::*;
+ #[test]
+ fn path_health_recovers_from_jitter_and_prefers_a_responsive_alternative() {
+ let mut health = ConnectionHealth::default();
+ assert!(!health.observe(Ok(Duration::from_millis(20))));
+ assert!(!health.observe(Err(ping::Failure::Timeout)));
+ let healthy = ConnectionHealth {
+ failures: 0,
+ rtt: Some(Duration::from_millis(50)),
+ };
+ assert!(
+ stream_candidate_score(
+ &PeerConnectionPath::Direct(DirectTransport::Tcp),
+ Some(&healthy)
+ ) < stream_candidate_score(
+ &PeerConnectionPath::Direct(DirectTransport::Quic),
+ Some(&health)
+ )
+ );
+ assert!(!health.observe(Ok(Duration::from_millis(24))));
+ assert_eq!(health.failures, 0);
+ assert!(!health.observe(Err(ping::Failure::Timeout)));
+ assert!(!health.observe(Err(ping::Failure::Timeout)));
+ assert!(health.observe(Err(ping::Failure::Timeout)));
+ }
+
+ #[tokio::test]
+ async fn listener_changes_refresh_advertised_and_transit_addresses() {
+ let allowed = Arc::new(RwLock::new(HashSet::from([PeerId::random()])));
+ let trusted = Arc::new(RwLock::new(HashSet::new()));
+ let BuiltSwarm { mut swarm, .. } = build_swarm(
+ identity::Keypair::generate_ed25519(),
+ allowed.clone(),
+ trusted.clone(),
+ false,
+ )
+ .unwrap();
+ let mut transit = TransitRuntime {
+ allowed_peers: allowed,
+ approved_relays: HashSet::new(),
+ trusted_relays: trusted,
+ reservations: HashSet::new(),
+ circuits: HashMap::new(),
+ listen_addresses: Vec::new(),
+ published_addresses: Vec::new(),
+ snapshot: Arc::new(RwLock::new(TransitSnapshot::default())),
+ };
+ let mut relays = HashMap::new();
+ let mut direct = DirectConnectState::default();
+ let (reachability, _) = watch::channel(ReachabilitySnapshot::default());
+ let mut anchors = RelayAnchorHistory::open(None, *swarm.local_peer_id()).await;
+ let first = swarm
+ .listen_on("/ip4/127.0.0.1/udp/0/quic-v1".parse().unwrap())
+ .unwrap();
+ for (step, count) in [1, 2, 1, 2].into_iter().enumerate() {
+ if step == 3 {
+ let mut configured = HashMap::new();
+ let mut failed = vec![(
+ "/ip4/127.0.0.1/udp/0/quic-v1".parse().unwrap(),
+ Instant::now(),
+ )];
+ restore_listeners(&mut swarm, &mut configured, &mut failed, Instant::now());
+ assert!(failed.is_empty());
+ assert_eq!(configured.len(), 1);
+ } else if count == 2 {
+ swarm
+ .listen_on("/ip4/127.0.0.1/tcp/0".parse().unwrap())
+ .unwrap();
+ } else if !transit.listen_addresses.is_empty() {
+ assert!(swarm.remove_listener(first));
+ }
+ tokio::time::timeout(Duration::from_secs(3), async {
+ loop {
+ let event = swarm.select_next_some().await;
+ handle_swarm_event(
+ &mut swarm,
+ event,
+ &mut relays,
+ &mut direct,
+ RouteRuntime {
+ reachability: Some(&reachability),
+ connectivity: None,
+ relay_anchors: Some(&mut anchors),
+ transit: &mut transit,
+ },
+ );
+ publish_active_coordination_relays(
+ &mut relays,
+ &reachability,
+ &mut anchors,
+ &transit.listen_addresses,
+ );
+ if transit.listen_addresses.len() == count {
+ break;
+ }
+ }
+ })
+ .await
+ .expect("listener event must update routes");
+ assert_eq!(
+ reachability.borrow().listen_addresses,
+ transit.listen_addresses
+ );
+ assert_eq!(swarm.external_addresses().count(), count);
+ }
+ assert!(
+ reachability.borrow().listen_addresses[0]
+ .iter()
+ .any(|protocol| matches!(protocol, Protocol::Tcp(_)))
+ );
+ anchors.close().await;
+ }
+
+ #[tokio::test(flavor = "multi_thread")]
+ async fn foreground_connect_does_not_wait_for_a_stalled_mesh_dial() {
+ let root = std::env::temp_dir().join(format!("maka-peer-dial-lanes-{}", PeerId::random()));
+ std::fs::create_dir_all(&root).unwrap();
+ let source = start(test_endpoint_options(root.join("source.key"))).unwrap();
+ let mut target = start(test_endpoint_options(root.join("target.key"))).unwrap();
+ let (result, mesh_response) = oneshot::channel();
+ source
+ .commands
+ .send(EngineCommand::Connect {
+ options: ConnectOptions {
+ request_id: 1,
+ peer_id: target.peer_id,
+ route_hints: vec!["/ip4/127.0.0.1/udp/9/quic-v1".parse().unwrap()],
+ coordination_relays: Vec::new(),
+ transit_relay_peers: Vec::new(),
+ deadline: Duration::from_secs(30),
+ },
+ stream_kind: StreamKind::MeshControl,
+ result,
+ })
+ .await
+ .unwrap();
+ let application = connect_test_stream(
+ &source,
+ target.peer_id,
+ test_listen_address(&target),
+ 2,
+ StreamKind::Application,
+ )
+ .await;
+ let mut incoming = tokio::time::timeout(Duration::from_secs(3), target.incoming.recv())
+ .await
+ .unwrap()
+ .unwrap();
+ let mesh = tokio::time::timeout(Duration::from_secs(3), mesh_response)
+ .await
+ .unwrap()
+ .unwrap()
+ .unwrap();
+ close_test_stream(mesh).await;
+ write_test_stream(&application, b"foreground-survives-mesh-release").await;
+ assert_eq!(
+ incoming.incoming.recv().await.unwrap().unwrap(),
+ b"foreground-survives-mesh-release"
+ );
+ close_test_stream(application).await;
+ close_test_stream(incoming).await;
+ stop_test_endpoint(source).await;
+ stop_test_endpoint(target).await;
+ std::fs::remove_dir_all(root).unwrap();
+ }
+
+ #[tokio::test(flavor = "multi_thread")]
+ async fn default_endpoint_accepts_each_available_ip_family_and_transport() {
+ let root = std::env::temp_dir().join(format!("maka-peer-dual-stack-{}", PeerId::random()));
+ std::fs::create_dir_all(&root).unwrap();
+ let mut options = test_endpoint_options(root.join("target.key"));
+ options.listen_addresses.clear();
+ let mut target = start(options).unwrap();
+ let routes = target.reachability.borrow().listen_addresses.clone();
+ for (index, (ipv6, tcp)) in [(false, false), (false, true), (true, false), (true, true)]
+ .into_iter()
+ .enumerate()
+ {
+ if ipv6 && std::net::UdpSocket::bind("[::]:0").is_err() {
+ continue;
+ }
+ let route = routes
+ .iter()
+ .find(|route| {
+ route.iter().any(|p| matches!(p, Protocol::Ip6(_))) == ipv6
+ && route.iter().any(|p| matches!(p, Protocol::Tcp(_))) == tcp
+ })
+ .expect("available family and transport must be advertised")
+ .clone();
+ let mut options = test_endpoint_options(root.join(format!("source-{index}.key")));
+ options.listen_addresses.clear();
+ let source = start(options).unwrap();
+ let stream =
+ connect_test_stream(&source, target.peer_id, route, 1, StreamKind::Application)
+ .await;
+ assert!(
+ matches!(
+ stream.path,
+ PeerConnectionPath::Direct(DirectTransport::Tcp)
+ ) == tcp
+ );
+ let mut inbound = tokio::time::timeout(Duration::from_secs(3), target.incoming.recv())
+ .await
+ .unwrap()
+ .unwrap();
+ write_test_stream(&stream, b"dual-stack").await;
+ assert_eq!(
+ inbound.incoming.recv().await.unwrap().unwrap(),
+ b"dual-stack"
+ );
+ close_test_stream(stream).await;
+ close_test_stream(inbound).await;
+ stop_test_endpoint(source).await;
+ }
+ stop_test_endpoint(target).await;
+ std::fs::remove_dir_all(root).unwrap();
+ }
+
#[test]
fn application_streams_commit_on_the_best_established_path() {
let relay_peer_id = PeerId::random();
@@ -3682,7 +4212,7 @@ mod tests {
PendingConnect {
attempt_id,
peer_id: PeerId::random(),
- result,
+ result: Some(result),
stream_kind: StreamKind::Application,
deadline: now,
opening: None,
@@ -3719,7 +4249,7 @@ mod tests {
let mut waiter = PendingConnect {
attempt_id,
peer_id: PeerId::random(),
- result,
+ result: Some(result),
stream_kind: StreamKind::Application,
deadline: now + Duration::from_secs(30),
opening: None,
@@ -3773,7 +4303,7 @@ mod tests {
let mut waiter = PendingConnect {
attempt_id: ConnectAttemptId(11),
peer_id: PeerId::random(),
- result,
+ result: Some(result),
stream_kind: StreamKind::Application,
deadline: now + Duration::from_secs(30),
opening: None,
@@ -4344,6 +4874,132 @@ mod tests {
};
assert_eq!(error.code, "peer_connect_cancelled");
+ // Transit delivery must leave direct discovery running without opening
+ // or interrupting another application stream.
+ configure_test_transit_with_reservations(
+ &source,
+ HashSet::new(),
+ vec![test_listen_address(&relay)],
+ )
+ .await;
+ let (result, closed) = oneshot::channel();
+ source
+ .commands
+ .send(EngineCommand::CloseDirectConnections {
+ peer_id: target.peer_id,
+ result,
+ })
+ .await
+ .unwrap();
+ closed.await.unwrap();
+ let transit_stream = connect_test_stream_through_transit(
+ &source,
+ target.peer_id,
+ relay.peer_id,
+ 50,
+ StreamKind::Application,
+ )
+ .await;
+ let mut transit_incoming =
+ tokio::time::timeout(Duration::from_secs(3), target.incoming.recv())
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(matches!(
+ transit_stream.path,
+ PeerConnectionPath::Transit { .. }
+ ));
+ let (result, updated) = oneshot::channel();
+ source
+ .commands
+ .send(EngineCommand::UpdateConnect {
+ request_id: 50,
+ candidates: ConnectCandidates {
+ route_hints: vec![test_listen_address(&target)],
+ coordination_relays: Vec::new(),
+ transit_relay_peers: vec![relay.peer_id],
+ },
+ result,
+ })
+ .await
+ .unwrap();
+ assert!(
+ updated.await.unwrap().unwrap(),
+ "transit must retain background route maintenance"
+ );
+ tokio::time::timeout(Duration::from_secs(5), async {
+ loop {
+ let (result, ready) = oneshot::channel();
+ source
+ .commands
+ .send(EngineCommand::HasDirectConnection {
+ peer_id: target.peer_id,
+ result,
+ })
+ .await
+ .unwrap();
+ if ready.await.unwrap() {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+ })
+ .await
+ .expect("direct path must appear without another application connect");
+ assert!(
+ target.incoming.try_recv().is_err(),
+ "maintenance must not open application streams"
+ );
+ write_test_stream(&transit_stream, b"transit-survives-upgrade").await;
+ assert_eq!(
+ transit_incoming.incoming.recv().await.unwrap().unwrap(),
+ b"transit-survives-upgrade"
+ );
+ let direct_stream = connect_test_stream(
+ &source,
+ target.peer_id,
+ test_listen_address(&target),
+ 51,
+ StreamKind::Application,
+ )
+ .await;
+ assert!(matches!(direct_stream.path, PeerConnectionPath::Direct(_)));
+ let mut direct_incoming =
+ tokio::time::timeout(Duration::from_secs(3), target.incoming.recv())
+ .await
+ .unwrap()
+ .unwrap();
+ // A route refresh may retire the maintenance dial, but not a stream
+ // another connect has already opened on that shared connection.
+ let (result, updated) = oneshot::channel();
+ source
+ .commands
+ .send(EngineCommand::UpdateConnect {
+ request_id: 50,
+ candidates: ConnectCandidates {
+ route_hints: Vec::new(),
+ coordination_relays: Vec::new(),
+ transit_relay_peers: vec![relay.peer_id],
+ },
+ result,
+ })
+ .await
+ .unwrap();
+ assert!(updated.await.unwrap().unwrap());
+ write_test_stream(&direct_stream, b"shared-direct-survives-route-refresh").await;
+ assert_eq!(
+ tokio::time::timeout(Duration::from_secs(3), direct_incoming.incoming.recv())
+ .await
+ .unwrap()
+ .unwrap()
+ .unwrap(),
+ b"shared-direct-survives-route-refresh"
+ );
+ close_test_stream(transit_stream).await;
+ close_test_stream(transit_incoming).await;
+ close_test_stream(direct_stream).await;
+ close_test_stream(direct_incoming).await;
+
let source_stream = connect_test_stream(
&source,
target.peer_id,
diff --git a/native/runtime-host-peer/src/engine/application_stream.rs b/native/runtime-host-peer/src/engine/application_stream.rs
index 4527cf59ff..14d4cf84e9 100644
--- a/native/runtime-host-peer/src/engine/application_stream.rs
+++ b/native/runtime-host-peer/src/engine/application_stream.rs
@@ -221,6 +221,10 @@ impl Control {
.is_empty()
}
+ pub(super) fn connection_ids(&self) -> Vec<ConnectionId> {
+ lock(&self.shared).connections.keys().copied().collect()
+ }
+
pub(super) fn eligible_connections(
&self,
peer_id: PeerId,
diff --git a/native/runtime-host-peer/src/engine/peer_stream.rs b/native/runtime-host-peer/src/engine/peer_stream.rs
index 0739e54684..5b461bdc36 100644
--- a/native/runtime-host-peer/src/engine/peer_stream.rs
+++ b/native/runtime-host-peer/src/engine/peer_stream.rs
@@ -70,7 +70,7 @@ pub enum StreamCommand {
pub(super) fn spawn_stream(
peer_id: PeerId,
path: PeerConnectionPath,
- stream: libp2p::swarm::Stream,
+ stream: impl futures::AsyncRead + futures::AsyncWrite + Unpin + Send + 'static,
completion: Option<(StreamCompletion, mpsc::Sender<CompletedStream>)>,
) -> PeerStream {
let (incoming_tx, incoming_rx) = mpsc::channel(QUEUE_CAPACITY);
@@ -80,73 +80,63 @@ pub(super) fn spawn_stream(
tokio::spawn(async move {
let _abort_guard = abort_guard;
let (mut reader, mut writer) = stream.split();
- let mut buffer = vec![0_u8; CHUNK_BYTES];
- let mut pending_read: Option<Result<Vec<u8>, PeerError>> = None;
- let mut finish_after_delivery = false;
- let mut close_result = None;
- loop {
- tokio::select! {
- biased;
- changed = abort_rx.changed() => {
- let _ = changed;
- break;
+ // Drive both halves independently. Awaiting a backpressured write in
+ // the read loop deadlocks when both peers send more than the window.
+ let close_result = {
+ let reading = async {
+ let mut buffer = vec![0_u8; CHUNK_BYTES];
+ loop {
+ match reader.read(&mut buffer).await {
+ Ok(0) => break,
+ Ok(size) => {
+ if incoming_tx.send(Ok(buffer[..size].to_vec())).await.is_err() {
+ break;
+ }
+ }
+ Err(error) => {
+ let _ = incoming_tx
+ .send(Err(PeerError::new("peer_native_failed", error.to_string())))
+ .await;
+ break;
+ }
+ }
}
- command = command_rx.recv() => match command {
- Some(StreamCommand::Write { bytes, result }) => {
- let outcome = tokio::select! {
- biased;
- _ = abort_rx.changed() => Err(PeerError::new(
- "peer_stream_aborted",
- "peer stream was aborted",
- )),
- outcome = async {
+ };
+ let writing = async {
+ while let Some(command) = command_rx.recv().await {
+ match command {
+ StreamCommand::Write { bytes, result } => {
+ let outcome = async {
writer.write_all(&bytes).await?;
- // Framed transports may buffer a complete write until flush.
writer.flush().await
- } => outcome.map_err(|error| {
+ }
+ .await
+ .map_err(|error: std::io::Error| {
PeerError::new("peer_native_failed", error.to_string())
- }),
- };
- let failed = outcome.is_err();
- let _ = result.send(outcome);
- if failed { break; }
- }
- Some(StreamCommand::Close { result }) => {
- let outcome = tokio::select! {
- biased;
- _ = abort_rx.changed() => Err(PeerError::new(
- "peer_stream_aborted",
- "peer stream was aborted",
- )),
- outcome = writer.close() => outcome.map_err(|error| {
+ });
+ let failed = outcome.is_err();
+ let _ = result.send(outcome);
+ if failed {
+ break;
+ }
+ }
+ StreamCommand::Close { result } => {
+ let outcome = writer.close().await.map_err(|error| {
PeerError::new("peer_native_failed", error.to_string())
- }),
- };
- close_result = Some((result, outcome));
- break;
+ });
+ return Some((result, outcome));
+ }
}
- None => break,
- },
- permit = incoming_tx.reserve(), if pending_read.is_some() => match permit {
- Ok(permit) => {
- permit.send(pending_read.take().expect("read is pending"));
- if finish_after_delivery { break; }
- }
- Err(_) => break,
- },
- read = reader.read(&mut buffer), if pending_read.is_none() => match read {
- Ok(0) => break,
- Ok(size) => pending_read = Some(Ok(buffer[..size].to_vec())),
- Err(error) => {
- pending_read = Some(Err(PeerError::new(
- "peer_native_failed",
- error.to_string(),
- )));
- finish_after_delivery = true;
- }
- },
+ }
+ None
+ };
+ tokio::select! {
+ biased;
+ _ = abort_rx.changed() => None,
+ result = writing => result,
+ _ = reading => None,
}
- }
+ };
if let Some((completion, completed)) = completion {
let (acknowledged, acknowledgment) = oneshot::channel();
if completed
@@ -172,3 +162,67 @@ pub(super) fn spawn_stream(
abort: abort_tx,
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use tokio_util::compat::TokioAsyncReadCompatExt;
+
+ #[tokio::test]
+ async fn simultaneous_large_writes_keep_reading_under_backpressure() {
+ let (left, right) = tokio::io::duplex(1024);
+ let mut left = spawn_stream(
+ PeerId::random(),
+ PeerConnectionPath::Direct(DirectTransport::Tcp),
+ left.compat(),
+ None,
+ );
+ let mut right = spawn_stream(
+ PeerId::random(),
+ PeerConnectionPath::Direct(DirectTransport::Tcp),
+ right.compat(),
+ None,
+ );
+ let (left_result, left_done) = oneshot::channel();
+ let (right_result, right_done) = oneshot::channel();
+ const BYTES: usize = 512 * 1024;
+ left.commands
+ .send(StreamCommand::Write {
+ bytes: vec![1; BYTES],
+ result: left_result,
+ })
+ .await
+ .unwrap();
+ right
+ .commands
+ .send(StreamCommand::Write {
+ bytes: vec![2; BYTES],
+ result: right_result,
+ })
+ .await
+ .unwrap();
+ async fn receive(stream: &mut PeerStream, expected: u8) {
+ let mut count = 0;
+ while count < BYTES {
+ let bytes = stream.incoming.recv().await.unwrap().unwrap();
+ assert!(bytes.iter().all(|byte| *byte == expected));
+ count += bytes.len();
+ }
+ assert_eq!(count, BYTES);
+ }
+ let outcome = tokio::time::timeout(std::time::Duration::from_secs(3), async {
+ let (left_ack, right_ack, _, _) = tokio::join!(
+ left_done,
+ right_done,
+ receive(&mut left, 2),
+ receive(&mut right, 1)
+ );
+ left_ack.unwrap().unwrap();
+ right_ack.unwrap().unwrap();
+ })
+ .await;
+ left.abort.send_replace(true);
+ right.abort.send_replace(true);
+ outcome.expect("simultaneous writes must not stop either reader");
+ }
+}
diff --git a/native/runtime-host-peer/src/webrtc_direct/tests.rs b/native/runtime-host-peer/src/webrtc_direct/tests.rs
index 7f39c842fe..9519272753 100644
--- a/native/runtime-host-peer/src/webrtc_direct/tests.rs
+++ b/native/runtime-host-peer/src/webrtc_direct/tests.rs
@@ -42,6 +42,7 @@ async fn authenticated_signaling_yields_a_libp2p_stream() {
let (signaling_a, signaling_b) = tokio::io::duplex(256 * 1024);
let options = UpgradeOptions {
deadline: Duration::from_secs(10),
+ udp_bind_addresses: crate::engine::default_webrtc_bind_addresses(),
..UpgradeOptions::default()
};
diff --git a/packages/runtime-host/src/__tests__/host-kernel.test.ts b/packages/runtime-host/src/__tests__/host-kernel.test.ts
index 2e330f305a..0e60d0d611 100644
--- a/packages/runtime-host/src/__tests__/host-kernel.test.ts
+++ b/packages/runtime-host/src/__tests__/host-kernel.test.ts
@@ -2240,7 +2240,7 @@ describe('non-serving Runtime Host kernel', () => {
error.cause.code === 'read_timeout' &&
error.cause.message.includes('host.status'),
),
- 5_000,
+ 12_000,
'automatic Runtime Host liveness check did not reject pending work',
);
await withTimeout(
diff --git a/packages/runtime-host/src/__tests__/peer-native.test.ts b/packages/runtime-host/src/__tests__/peer-native.test.ts
index c307b3425f..bda8a657e1 100644
--- a/packages/runtime-host/src/__tests__/peer-native.test.ts
+++ b/packages/runtime-host/src/__tests__/peer-native.test.ts
@@ -44,7 +44,7 @@ test('preserves transit route failures from the native boundary', () => {
assert.equal(error.message, 'no approved route');
});
-test('shares one peer endpoint, serializes same-peer connects, and cancels independently', async () => {
+test('shares one endpoint with independent application and Mesh dial lanes', async () => {
const directory = await mkdtemp(join(tmpdir(), 'maka-peer-abort-'));
const nativePath = join(directory, 'peer.cjs');
try {
@@ -184,18 +184,16 @@ module.exports = {
const application = client.connect(peerConnectInput('shared'));
await waitForRequestCount(native.default.stats, 2);
const queuedAbort = new AbortController();
- const cancelled = client.connectMeshControl(peerConnectInput('shared'), queuedAbort.signal);
+ const cancelled = client.connect(peerConnectInput('shared'), queuedAbort.signal);
queuedAbort.abort();
await assert.rejects(cancelled, /aborted/u);
const control = client.connectMeshControl(peerConnectInput('shared'));
- await waitForImmediate();
- assert.equal(native.default.stats.requests.length, 2);
- native.default.resolveConnect(2);
- await application;
await waitForRequestCount(native.default.stats, 3);
assert.equal(native.default.stats.requests.length, 3);
native.default.resolveConnect(3);
await control;
+ native.default.resolveConnect(2);
+ await application;
const preparedBeforeReopen = preparedPeerIds.length;
const reopenPhases: string[] = [];
diff --git a/packages/runtime-host/src/__tests__/session-subscription-client.test.ts b/packages/runtime-host/src/__tests__/session-subscription-client.test.ts
index 3f88772151..f6a7e5b551 100644
--- a/packages/runtime-host/src/__tests__/session-subscription-client.test.ts
+++ b/packages/runtime-host/src/__tests__/session-subscription-client.test.ts
@@ -1310,7 +1310,7 @@ test('probes an otherwise idle accepted Runtime Host connection', { timeout: 2_0
);
});
-test('accepts Session traffic as liveness while a route status observation is delayed', {
+test('tolerates a short Host stall without abandoning the connection', {
timeout: 5_000,
}, async () => {
const observed = deferred<HostStatusResult>();
@@ -1333,9 +1333,8 @@ test('accepts Session traffic as liveness while a route status observation is de
assert.ok(!('kind' in probe));
assert.equal(probe.operation, 'host.status');
- // Keep the status request pending past its original two-second deadline.
- // A valid Session frame in between proves the same authenticated
- // transport is alive and must extend that deadline.
+ // A transient pause beyond the old two-second deadline is recoverable.
+ // Only the eventual matching response completes the probe.
await delay(1_100);
await writeProtocolFrame(transport, {
kind: 'session.catalog.changed',
@@ -1362,6 +1361,59 @@ test('accepts Session traffic as liveness while a route status observation is de
);
});
+test('closes an unresponsive request path even while Host notifications continue', {
+ timeout: 12_000,
+}, async () => {
+ let received = 0;
+ let probes = 0;
+ await withProtocolPeer(
+ async (transport, hostEpoch, rootId) => {
+ await transport.read(1_000);
+ await writeProtocolFrame(transport, {
+ kind: 'accepted',
+ rootId,
+ hostEpoch,
+ connectionId: 'one-way-host',
+ selectedProtocol: RUNTIME_HOST_PROTOCOL_VERSION,
+ compatibilityEpoch: RUNTIME_HOST_COMPATIBILITY_EPOCH,
+ compositionId: 'maka.interactive',
+ compositionRevision: '1',
+ state: 'ready',
+ });
+ let revision = 0;
+ const notifications = setInterval(() => {
+ void writeProtocolFrame(transport, {
+ kind: 'session.catalog.changed',
+ revision: ++revision,
+ sessionId: 'shared-session',
+ }).catch(() => undefined);
+ }, 10);
+ try {
+ const probe = decodeClientFrame(await transport.read(1_000));
+ assert.ok(!('kind' in probe));
+ assert.equal(probe.operation, 'host.status');
+ await transport.closed;
+ } finally {
+ clearInterval(notifications);
+ }
+ },
+ async (connection) => {
+ connection.subscribeSessionCatalogChanges(() => {
+ received += 1;
+ });
+ await connection.closed;
+ assert.ok(received > 10, 'inbound events must remain active during the failed probe');
+ assert.equal(probes, 0, 'one-way events cannot acknowledge a probe');
+ },
+ {
+ livenessIntervalMs: 20,
+ onLivenessProbe: () => {
+ probes += 1;
+ },
+ },
+ );
+});
+
async function withProtocolPeer(
serve: (transport: FramedTransport, hostEpoch: string, rootId: string) => Promise<void>,
run: (connection: RuntimeHostConnection) => Promise<void>,
diff --git a/packages/runtime-host/src/client/connection.ts b/packages/runtime-host/src/client/connection.ts
index f9b9e85238..bceedd0abc 100644
--- a/packages/runtime-host/src/client/connection.ts
+++ b/packages/runtime-host/src/client/connection.ts
@@ -89,7 +89,9 @@ import {
const DEFAULT_CONNECT_TIMEOUT_MS = 500;
const DEFAULT_HANDSHAKE_TIMEOUT_MS = 2_000;
const DEFAULT_LIVENESS_INTERVAL_MS = 2_000;
-const DEFAULT_LIVENESS_TIMEOUT_MS = 2_000;
+// A bounded round trip tolerates short transport/Host stalls. Unrelated inbound
+// traffic must never extend it: receiving events does not prove requests work.
+const DEFAULT_LIVENESS_TIMEOUT_MS = 8_000;
const MAX_WEBSOCKET_FRAGMENTS = 256;
const MAX_WEBSOCKET_BUFFERED_CHUNKS = 256;
@@ -103,12 +105,9 @@ export interface ConnectRuntimeHostInput {
connectTimeoutMs?: number;
handshakeTimeoutMs?: number;
/**
- * Maximum quiet interval before an end-to-end Host liveness probe.
- * Any valid inbound frame restarts the quiet interval. A Host status
- * observer additionally uses this as its periodic observation cadence;
- * inbound traffic then extends an outstanding probe's progress deadline
- * without suppressing future status observations. Injectable so tests can
- * exercise the cadence without waiting the real default (2s).
+ * Interval between end-to-end Host liveness probes. Probes continue while
+ * inbound traffic is active; only a matching response proves a round trip.
+ * Injectable so tests can exercise the cadence without waiting 2 seconds.
*/
livenessIntervalMs?: number;
/**
@@ -680,7 +679,7 @@ class RuntimeHostConnectionImpl implements RuntimeHostConnection {
try {
while (true) {
const frame = decodeHostFrame(await this.#transport.read(0));
- this.#resetLivenessCheck();
+ this.#scheduleLivenessCheck();
if ('kind' in frame) {
if (isClientCapabilityHostFrameKind(frame.kind)) {
this.#clientCapabilities.accept(frame as ClientCapabilityHostFrame);
@@ -835,19 +834,8 @@ class RuntimeHostConnectionImpl implements RuntimeHostConnection {
this.#drainDomainRequests();
}
- #resetLivenessCheck(): void {
- // Any authenticated Host frame proves the transport is still making
- // progress, even when a periodic status observation is slow.
- this.#resetLivenessProbeDeadline();
- // A status observer needs periodic route observations even while other
- // Session traffic keeps the connection active.
- if (this.#onHostStatus) return;
- if (this.#livenessTimer) clearTimeout(this.#livenessTimer);
- this.#livenessTimer = undefined;
- this.#scheduleLivenessCheck();
- }
-
#scheduleLivenessCheck(): void {
+ // Inbound events do not postpone the next bidirectional probe.
if (this.#terminalError || this.#livenessTimer || this.#livenessProbePending) {
return;
}
@@ -860,7 +848,10 @@ class RuntimeHostConnectionImpl implements RuntimeHostConnection {
#startLivenessProbe(): void {
if (this.#terminalError || this.#livenessProbePending) return;
this.#livenessProbePending = true;
- this.#resetLivenessProbeDeadline();
+ this.#livenessProbeDeadline = setTimeout(() => {
+ this.#livenessProbeDeadline = undefined;
+ this.#fail(requestTimeoutError('host.status'));
+ }, DEFAULT_LIVENESS_TIMEOUT_MS);
void this.#requestOperation(
'host.status',
{},
@@ -885,15 +876,6 @@ class RuntimeHostConnectionImpl implements RuntimeHostConnection {
});
}
- #resetLivenessProbeDeadline(): void {
- if (!this.#livenessProbePending || this.#terminalError) return;
- if (this.#livenessProbeDeadline) clearTimeout(this.#livenessProbeDeadline);
- this.#livenessProbeDeadline = setTimeout(() => {
- this.#livenessProbeDeadline = undefined;
- this.#fail(requestTimeoutError('host.status'));
- }, DEFAULT_LIVENESS_TIMEOUT_MS);
- }
-
#acceptSubscriptionFrame(frame: SubscriptionFrame): void {
const subscription = this.#subscriptions.get(frame.subscriptionId);
if (!subscription) {
diff --git a/packages/runtime-host/src/client/peer-client.ts b/packages/runtime-host/src/client/peer-client.ts
index 539afd0e04..dcc1821cd8 100644
--- a/packages/runtime-host/src/client/peer-client.ts
+++ b/packages/runtime-host/src/client/peer-client.ts
@@ -475,20 +475,23 @@ class RuntimeHostPeerClientImpl implements RuntimeHostPeerClient {
signal: AbortSignal | undefined,
kind: 'application' | 'mesh-control',
): Promise<RuntimeHostPeerNativeStream> {
- const previous = this.#connectTails.get(input.peerId) ?? Promise.resolve();
+ // Mesh reconciliation must not consume the foreground application's dial
+ // budget. The native endpoint multiplexes both lanes over peer connections.
+ const lane = `${kind}:${input.peerId}`;
+ const previous = this.#connectTails.get(lane) ?? Promise.resolve();
let release!: () => void;
const turn = new Promise<void>((resolve) => {
release = resolve;
});
const tail = previous.then(() => turn);
- this.#connectTails.set(input.peerId, tail);
+ this.#connectTails.set(lane, tail);
try {
await waitForPeerConnectTurn(previous, signal);
return await this.#startConnect(input, signal, kind);
} finally {
release();
void tail.then(() => {
- if (this.#connectTails.get(input.peerId) === tail) this.#connectTails.delete(input.peerId);
+ if (this.#connectTails.get(lane) === tail) this.#connectTails.delete(lane);
});
}
}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org