mirror of
https://github.com/n0-computer/iroh.git
synced 2026-12-04 08:01:34 +00:00
tests(iroh): add more patchbay tests and improve existing tests (#4118)
## Description Based on #4119 to make reviewing easier. * Add a `left`/`right` API to `Pair`. We often want to run the same test with switched client/server roles, and the existing API was cumbersome for this. With `left` / `right` the sides are set via a variable, so it is straightforward to pass that into a run function called from multiple test functions (matrix style) * Parametrize the existing tests over switched client/server roles * Add NAT matrix tests to test all combinations of `(None, Home, Coporate)` NATs (Home is endpoint-indpendent, so holepunchable for us; Corporate is endpoint-dependant so not holepunchable for us). Tests that don't pass are ignored. * Adds two new tests: * Holepunch with many interfaces. It passes with 8 additional interfaces and fails with 16 (the latter are ignored until we make them pass) * Start on a hard nat (no holepunch), then switch uplink to an easy nat and validate that it holepunchs then mid-connection ## Change checklist <!-- Remove any that are not relevant. --> - [x] Self-review. - [x] Documentation updates following the [style guide](https://rust-lang.github.io/rfcs/1574-more-api-documentation-conventions.html#appendix-a-full-conventions-text), if relevant.
This commit is contained in:
+231
-290
@@ -26,17 +26,24 @@
|
||||
// via a cfg directive
|
||||
#![cfg(all(target_os = "linux", not(skip_patchbay)))]
|
||||
|
||||
use std::time::Duration;
|
||||
use std::{net::Ipv4Addr, time::Duration};
|
||||
|
||||
use ipnet::Ipv4Net;
|
||||
use iroh::endpoint::Side;
|
||||
use n0_error::{Result, StackResultExt, StdResultExt};
|
||||
use n0_error::{Result, StackResultExt};
|
||||
use n0_tracing_test::traced_test;
|
||||
use patchbay::{LinkCondition, LinkDirection, LinkLimits, Nat, TestGuard};
|
||||
use patchbay::{IfaceConfig, LinkCondition, LinkDirection, Nat};
|
||||
use testdir::testdir;
|
||||
use tracing::info;
|
||||
|
||||
use self::util::{Pair, PathWatcherExt, lab_with_relay, ping_accept, ping_open};
|
||||
|
||||
// Because we're in an integration test, we can't declare modules under patchbay/
|
||||
// without setting an explicit path.
|
||||
#[path = "patchbay/degrade.rs"]
|
||||
mod degrade;
|
||||
#[path = "patchbay/nat.rs"]
|
||||
mod nat;
|
||||
#[path = "patchbay/switch-uplink.rs"]
|
||||
mod switch_uplink;
|
||||
#[path = "patchbay/util.rs"]
|
||||
@@ -55,10 +62,6 @@ fn userns_ctor() {
|
||||
// ---
|
||||
|
||||
/// Two devices behind destination-independent NATs holepunch a direct connection.
|
||||
///
|
||||
/// Both devices connect through a relay first, then upgrade to a direct path.
|
||||
/// The client asserts that the connection starts as relayed, then waits for
|
||||
/// a direct (IP) path to be selected.
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn holepunch_simple() -> Result {
|
||||
@@ -89,47 +92,34 @@ async fn holepunch_simple() -> Result {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Adds a faster LAN interface and verifies the path becomes selected.
|
||||
/// Adds a faster LAN interface on one side and verifies the path switches to it.
|
||||
///
|
||||
/// The server sits on `nat1`. The client starts on `nat2` with a 4G-impaired
|
||||
/// link and has a second interface `eth1` connected to `nat1` (a LAN path),
|
||||
/// but `eth1` starts down. After holepunching over the impaired link, the test
|
||||
/// brings `eth1` up and waits for the selected path to change to the new,
|
||||
/// faster LAN address. A ping verifies the new path works.
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn change_ifaces() -> Result {
|
||||
/// The active side has two uplinks: eth0 (4G-impaired) and eth1 (LAN to the
|
||||
/// peer's NAT, starts down). After holepunching over 4G, eth1 comes up and
|
||||
/// the selected path should switch to the faster LAN link.
|
||||
async fn run_add_faster_link(active_side: Side) -> Result {
|
||||
let (lab, relay_map, _relay_guard, guard) = lab_with_relay(testdir!()).await?;
|
||||
let nat1 = lab.add_router("nat1").nat(Nat::Home).build().await?;
|
||||
let nat2 = lab.add_router("nat2").nat(Nat::Home).build().await?;
|
||||
let nat_a = lab.add_router("nat_a").nat(Nat::Home).build().await?;
|
||||
let nat_b = lab.add_router("nat_b").nat(Nat::Home).build().await?;
|
||||
|
||||
// Client has two uplinks (eth0=4G via nat2, eth1=LAN via nat1). eth1 starts down.
|
||||
let server = lab
|
||||
.add_device("server")
|
||||
.iface("eth0", nat1.id())
|
||||
let active = lab
|
||||
.add_device("active")
|
||||
.iface(
|
||||
"eth0",
|
||||
IfaceConfig::routed(nat_a.id()).condition(LinkCondition::Mobile4G, LinkDirection::Both),
|
||||
)
|
||||
.iface("eth1", IfaceConfig::routed(nat_b.id()).down())
|
||||
.build()
|
||||
.await?;
|
||||
let client = lab
|
||||
.add_device("client")
|
||||
.iface("eth0", nat2.id())
|
||||
.iface("eth1", nat1.id())
|
||||
let passive = lab
|
||||
.add_device("passive")
|
||||
.iface("eth0", nat_b.id())
|
||||
.build()
|
||||
.await?;
|
||||
client
|
||||
.iface("eth0")
|
||||
.unwrap()
|
||||
.set_condition(LinkCondition::Mobile4G, LinkDirection::Both)
|
||||
.await?;
|
||||
client.iface("eth1").unwrap().link_down().await?;
|
||||
|
||||
let timeout = Duration::from_secs(15);
|
||||
Pair::new(relay_map)
|
||||
.server(server, async move |_dev, _ep, conn| {
|
||||
ping_accept(&conn, timeout).await.context("ping_accept")?;
|
||||
conn.closed().await;
|
||||
Ok(())
|
||||
})
|
||||
.client(client, async move |dev, _ep, conn| {
|
||||
.left(active_side, active, async move |dev, _ep, conn| {
|
||||
let mut paths = conn.paths();
|
||||
assert!(paths.selected().is_relay(), "connection started relayed");
|
||||
let first = paths
|
||||
@@ -137,15 +127,13 @@ async fn change_ifaces() -> Result {
|
||||
.await
|
||||
.context("did not become direct")?;
|
||||
info!(addr=?first.remote_addr(), "connection became direct");
|
||||
ping_accept(&conn, timeout)
|
||||
.await
|
||||
.context("ping_accept before switch")?;
|
||||
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
|
||||
// Bring up the LAN interface to the other ep.
|
||||
info!("bring up eth1");
|
||||
info!("bring up faster link (eth1)");
|
||||
dev.iface("eth1").unwrap().link_up().await?;
|
||||
|
||||
// Wait for a new direct path to be established. We check is_ip() explicitly
|
||||
// to avoid triggering on a transient relay fallback during the switch.
|
||||
let next = paths
|
||||
.wait_selected(timeout, |p| {
|
||||
p.is_ip() && p.remote_addr() != first.remote_addr()
|
||||
@@ -153,8 +141,36 @@ async fn change_ifaces() -> Result {
|
||||
.await
|
||||
.context("did not switch paths")?;
|
||||
info!(addr=?next.remote_addr(), "new direct path established");
|
||||
ping_accept(&conn, timeout)
|
||||
.await
|
||||
.context("ping_accept after switch")?;
|
||||
|
||||
conn.closed().await;
|
||||
Ok(())
|
||||
})
|
||||
.right(passive, async move |_dev, _ep, conn| {
|
||||
let mut paths = conn.paths();
|
||||
assert!(paths.selected().is_relay(), "connection started relayed");
|
||||
let first = paths
|
||||
.wait_ip(timeout)
|
||||
.await
|
||||
.context("did not become direct")?;
|
||||
info!(addr=?first.remote_addr(), "connection became direct");
|
||||
ping_open(&conn, timeout)
|
||||
.await
|
||||
.context("ping_open before switch")?;
|
||||
|
||||
let next = paths
|
||||
.wait_selected(timeout, |p| {
|
||||
p.is_ip() && p.remote_addr() != first.remote_addr()
|
||||
})
|
||||
.await
|
||||
.context("did not switch paths")?;
|
||||
info!(addr=?next.remote_addr(), "new direct path established");
|
||||
ping_open(&conn, timeout)
|
||||
.await
|
||||
.context("ping_open after switch")?;
|
||||
|
||||
ping_open(&conn, timeout).await.context("ping_open")?;
|
||||
conn.close(0u32.into(), b"bye");
|
||||
Ok(())
|
||||
})
|
||||
@@ -164,48 +180,46 @@ async fn change_ifaces() -> Result {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Takes the client's link down for five seconds after holepunching, then brings it back.
|
||||
///
|
||||
/// After recovery, the test verifies that we can ping (via relay fallback or
|
||||
/// a re-established direct path), and then waits for a direct path to be
|
||||
/// selected again.
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn link_outage_recovery() -> Result {
|
||||
async fn add_faster_link_client() -> Result {
|
||||
run_add_faster_link(Side::Client).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn add_faster_link_server() -> Result {
|
||||
run_add_faster_link(Side::Server).await
|
||||
}
|
||||
|
||||
/// Takes one side's link down after holepunching, then brings it back.
|
||||
///
|
||||
/// After recovery, verifies connectivity (via relay fallback or re-established
|
||||
/// direct path), then waits for a direct path to be selected again.
|
||||
async fn run_link_outage_recovery(outage_side: Side, downtime: Duration) -> Result {
|
||||
let (lab, relay_map, _relay_guard, guard) = lab_with_relay(testdir!()).await?;
|
||||
let nat1 = lab.add_router("nat1").nat(Nat::Home).build().await?;
|
||||
let nat2 = lab.add_router("nat2").nat(Nat::Home).build().await?;
|
||||
let server = lab.add_device("server").uplink(nat1.id()).build().await?;
|
||||
let client = lab.add_device("client").uplink(nat2.id()).build().await?;
|
||||
let outage = lab.add_device("outage").uplink(nat1.id()).build().await?;
|
||||
let peer = lab.add_device("peer").uplink(nat2.id()).build().await?;
|
||||
let timeout = Duration::from_secs(15);
|
||||
Pair::new(relay_map)
|
||||
.server(server, async move |_dev, _ep, conn| {
|
||||
ping_accept(&conn, timeout).await.context("ping_accept 1")?;
|
||||
ping_accept(&conn, timeout).await.context("ping_accept 2")?;
|
||||
conn.closed().await;
|
||||
Ok(())
|
||||
})
|
||||
.client(client, async move |dev, _ep, conn| {
|
||||
.left(outage_side, outage, async move |dev, _ep, conn| {
|
||||
let mut paths = conn.paths();
|
||||
paths.wait_ip(timeout).await.context("initial holepunch")?;
|
||||
let downtime = Duration::from_secs(5);
|
||||
info!("holepunched, now killing link for {downtime:?}");
|
||||
// Take the link down.
|
||||
dev.iface("eth0").unwrap().link_down().await?;
|
||||
tokio::time::sleep(downtime).await;
|
||||
dev.iface("eth0").unwrap().link_up().await?;
|
||||
info!("link restored, waiting for recovery");
|
||||
|
||||
// After link recovery, we should be able to ping, either via relay
|
||||
// fallback or re-established direct path.
|
||||
ping_open(&conn, Duration::from_secs(30))
|
||||
ping_open(&conn, timeout)
|
||||
.await
|
||||
.context("ping_open after link_up")?;
|
||||
info!("connection recovered after link outage");
|
||||
|
||||
// Eventually the direct path should come back.
|
||||
paths
|
||||
.wait_ip(Duration::from_secs(30))
|
||||
.wait_ip(timeout)
|
||||
.await
|
||||
.context("did not re-establish direct path")?;
|
||||
ping_open(&conn, timeout)
|
||||
@@ -214,258 +228,185 @@ async fn link_outage_recovery() -> Result {
|
||||
conn.close(0u32.into(), b"bye");
|
||||
Ok(())
|
||||
})
|
||||
.right(peer, async move |_dev, _ep, conn| {
|
||||
ping_accept(&conn, timeout).await.context("ping_accept 1")?;
|
||||
ping_accept(&conn, timeout).await.context("ping_accept 2")?;
|
||||
conn.closed().await;
|
||||
Ok(())
|
||||
})
|
||||
.run()
|
||||
.await?;
|
||||
guard.ok();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ---
|
||||
// Degradation ladder: find where holepunching breaks under worsening conditions
|
||||
// ---
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn link_outage_recovery_client() -> Result {
|
||||
run_link_outage_recovery(Side::Client, Duration::from_secs(5)).await
|
||||
}
|
||||
|
||||
/// Increasingly degraded link conditions applied to one side of the connection.
|
||||
///
|
||||
/// Each level adds more latency, loss, and reordering. The levels are tested
|
||||
/// individually for both server-side and client-side impairment.
|
||||
const DEGRADE_LEVELS: &[LinkLimits] = &[
|
||||
// 0: mild - good wifi
|
||||
LinkLimits {
|
||||
latency_ms: 10,
|
||||
jitter_ms: 5,
|
||||
loss_pct: 0.5,
|
||||
reorder_pct: 0.0,
|
||||
rate_kbit: 0,
|
||||
duplicate_pct: 0.0,
|
||||
corrupt_pct: 0.0,
|
||||
},
|
||||
// 1: poor - bad wifi or 3G
|
||||
LinkLimits {
|
||||
latency_ms: 100,
|
||||
jitter_ms: 30,
|
||||
loss_pct: 3.0,
|
||||
reorder_pct: 3.0,
|
||||
rate_kbit: 0,
|
||||
duplicate_pct: 0.0,
|
||||
corrupt_pct: 0.0,
|
||||
},
|
||||
// 2: bad - congested 3G
|
||||
LinkLimits {
|
||||
latency_ms: 200,
|
||||
jitter_ms: 60,
|
||||
loss_pct: 5.0,
|
||||
reorder_pct: 5.0,
|
||||
rate_kbit: 0,
|
||||
duplicate_pct: 0.0,
|
||||
corrupt_pct: 0.0,
|
||||
},
|
||||
// 3: terrible - barely usable
|
||||
LinkLimits {
|
||||
latency_ms: 300,
|
||||
jitter_ms: 80,
|
||||
loss_pct: 8.0,
|
||||
reorder_pct: 8.0,
|
||||
rate_kbit: 0,
|
||||
duplicate_pct: 0.0,
|
||||
corrupt_pct: 0.0,
|
||||
},
|
||||
// 4: extreme - GEO satellite with heavy loss
|
||||
LinkLimits {
|
||||
latency_ms: 500,
|
||||
jitter_ms: 100,
|
||||
loss_pct: 12.0,
|
||||
reorder_pct: 12.0,
|
||||
rate_kbit: 0,
|
||||
duplicate_pct: 0.0,
|
||||
corrupt_pct: 0.0,
|
||||
},
|
||||
// 5: absurd - stress test
|
||||
LinkLimits {
|
||||
latency_ms: 800,
|
||||
jitter_ms: 200,
|
||||
loss_pct: 20.0,
|
||||
reorder_pct: 20.0,
|
||||
rate_kbit: 0,
|
||||
duplicate_pct: 0.0,
|
||||
corrupt_pct: 0.0,
|
||||
},
|
||||
];
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn link_outage_recovery_server() -> Result {
|
||||
run_link_outage_recovery(Side::Server, Duration::from_secs(5)).await
|
||||
}
|
||||
|
||||
/// Runs a single degradation level.
|
||||
///
|
||||
/// Creates two devices behind Home NATs, applies the given [`LinkLimits`] to
|
||||
/// `impaired_side`, then attempts to holepunch and ping. Returns the
|
||||
/// [`TestGuard`] on success so the caller can mark it as passed.
|
||||
async fn run_degrade_level(impaired_side: Side, level: usize) -> Result<TestGuard> {
|
||||
/// Starts one side behind a symmetric NAT (no holepunch possible), then replugs
|
||||
/// it to a Home NAT and verifies a direct path is established.
|
||||
async fn run_hard_nat_to_holepunchable(replug_side: Side) -> Result {
|
||||
let (lab, relay_map, _relay_guard, guard) = lab_with_relay(testdir!()).await?;
|
||||
let nat_easy = lab.add_router("nat_easy").nat(Nat::Home).build().await?;
|
||||
let nat_hard = lab
|
||||
.add_router("nat_hard")
|
||||
.nat(Nat::Corporate)
|
||||
.build()
|
||||
.await?;
|
||||
let nat_peer = lab.add_router("nat_peer").nat(Nat::Home).build().await?;
|
||||
|
||||
let replug = lab
|
||||
.add_device("replug")
|
||||
.uplink(nat_hard.id())
|
||||
.build()
|
||||
.await?;
|
||||
let stable = lab
|
||||
.add_device("stable")
|
||||
.uplink(nat_peer.id())
|
||||
.build()
|
||||
.await?;
|
||||
|
||||
let timeout = Duration::from_secs(15);
|
||||
Pair::new(relay_map)
|
||||
.left(replug_side, replug, async move |dev, _ep, conn| {
|
||||
let mut paths = conn.paths();
|
||||
assert!(paths.selected().is_relay(), "connection started relayed");
|
||||
|
||||
ping_accept(&conn, timeout)
|
||||
.await
|
||||
.context("ping 1 (relay)")?;
|
||||
|
||||
tokio::time::sleep(Duration::from_secs(3)).await;
|
||||
assert!(
|
||||
paths.selected().is_relay(),
|
||||
"should still be relayed behind symmetric NAT"
|
||||
);
|
||||
|
||||
info!("replug to holepunchable NAT");
|
||||
dev.iface("eth0").unwrap().replug(nat_easy.id()).await?;
|
||||
|
||||
paths
|
||||
.wait_ip(timeout)
|
||||
.await
|
||||
.context("did not become direct after replug")?;
|
||||
info!("connection became direct");
|
||||
|
||||
ping_accept(&conn, timeout)
|
||||
.await
|
||||
.context("ping 2 (direct)")?;
|
||||
conn.closed().await;
|
||||
Ok(())
|
||||
})
|
||||
.right(stable, async move |_dev, _ep, conn| {
|
||||
let mut paths = conn.paths();
|
||||
assert!(paths.selected().is_relay(), "connection started relayed");
|
||||
ping_open(&conn, timeout).await.context("ping 1 (relay)")?;
|
||||
paths
|
||||
.wait_ip(timeout)
|
||||
.await
|
||||
.context("did not become direct after replug")?;
|
||||
info!("connection became direct");
|
||||
ping_open(&conn, timeout).await.context("ping 2 (direct)")?;
|
||||
conn.close(0u32.into(), b"bye");
|
||||
Ok(())
|
||||
})
|
||||
.run()
|
||||
.await?;
|
||||
guard.ok();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn hard_nat_to_holepunchable_client() -> Result {
|
||||
run_hard_nat_to_holepunchable(Side::Client).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn hard_nat_to_holepunchable_server() -> Result {
|
||||
run_hard_nat_to_holepunchable(Side::Server).await
|
||||
}
|
||||
|
||||
/// Holepunching succeeds despite many unreachable local addresses on one side.
|
||||
async fn run_holepunch_many_addrs(many_addrs_side: Side, addr_count: u8) -> Result {
|
||||
let (lab, relay_map, _relay_guard, guard) = lab_with_relay(testdir!()).await?;
|
||||
let nat1 = lab.add_router("nat1").nat(Nat::Home).build().await?;
|
||||
let nat2 = lab.add_router("nat2").nat(Nat::Home).build().await?;
|
||||
let timeout = Duration::from_secs(20 + level as u64 * 10);
|
||||
|
||||
let limits = DEGRADE_LEVELS[level];
|
||||
let link_condition = LinkCondition::Manual(limits);
|
||||
|
||||
let server = lab
|
||||
.add_device("server")
|
||||
.iface("eth0", nat1.id())
|
||||
.build()
|
||||
.await?;
|
||||
let client = lab
|
||||
.add_device("client")
|
||||
.iface("eth0", nat2.id())
|
||||
.build()
|
||||
.await?;
|
||||
let impaired_device = match impaired_side {
|
||||
Side::Client => &client,
|
||||
Side::Server => &server,
|
||||
};
|
||||
impaired_device
|
||||
.iface("eth0")
|
||||
.unwrap()
|
||||
.set_condition(link_condition, LinkDirection::Both)
|
||||
.await?;
|
||||
|
||||
info!(?impaired_side, ?limits, %level, ?timeout, "degrade test start");
|
||||
|
||||
let result = tokio::time::timeout(
|
||||
timeout,
|
||||
Pair::new(relay_map)
|
||||
.server(server, async move |_dev, _ep, conn| {
|
||||
ping_accept(&conn, timeout).await.context("ping_accept")?;
|
||||
conn.closed().await;
|
||||
Ok(())
|
||||
})
|
||||
.client(client, async move |_dev, _ep, conn| {
|
||||
let mut paths = conn.paths();
|
||||
info!("waiting for connection to become direct");
|
||||
paths
|
||||
.wait_ip(timeout)
|
||||
.await
|
||||
.context("holepunch to direct")?;
|
||||
info!("direct path established, sending ping");
|
||||
ping_open(&conn, timeout).await.context("ping_open")?;
|
||||
info!("ping complete");
|
||||
conn.close(0u32.into(), b"bye");
|
||||
Ok(())
|
||||
})
|
||||
.run(),
|
||||
)
|
||||
.await
|
||||
.std_context("pair timed out")
|
||||
.flatten();
|
||||
|
||||
match &result {
|
||||
Ok(()) => tracing::event!(
|
||||
target: "test::_events::ladder_pass",
|
||||
tracing::Level::INFO,
|
||||
level,
|
||||
latency_ms = limits.latency_ms,
|
||||
loss_pct = limits.loss_pct,
|
||||
reorder_pct = limits.reorder_pct,
|
||||
impaired_side = ?impaired_side,
|
||||
"PASSED",
|
||||
),
|
||||
Err(err) => tracing::event!(
|
||||
target: "test::_events::ladder_fail",
|
||||
tracing::Level::WARN,
|
||||
level,
|
||||
latency_ms = limits.latency_ms,
|
||||
loss_pct = limits.loss_pct,
|
||||
reorder_pct = limits.reorder_pct,
|
||||
impaired_side = ?impaired_side,
|
||||
error = format!("{err:#}"),
|
||||
"FAILED",
|
||||
),
|
||||
let mut builder = lab.add_device("many_addrs").uplink(nat1.id());
|
||||
for i in 0..addr_count {
|
||||
builder = builder.iface(
|
||||
&format!("virt{i}"),
|
||||
IfaceConfig::dummy().addr(Ipv4Net::new_assert(Ipv4Addr::new(172, 16, 0, i + 1), 24)),
|
||||
);
|
||||
}
|
||||
let many_addrs = builder.build().await?;
|
||||
let plain = lab.add_device("plain").uplink(nat2.id()).build().await?;
|
||||
|
||||
result?;
|
||||
Ok(guard)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn degrade_server_0_mild() -> Result {
|
||||
run_degrade_level(Side::Server, 0).await?.ok();
|
||||
let timeout = Duration::from_secs(15);
|
||||
Pair::new(relay_map)
|
||||
.left(many_addrs_side, many_addrs, async move |_dev, _ep, conn| {
|
||||
let mut paths = conn.paths();
|
||||
assert!(paths.selected().is_relay(), "connection started relayed");
|
||||
paths
|
||||
.wait_ip(timeout)
|
||||
.await
|
||||
.context("holepunch to direct with many addrs")?;
|
||||
info!("connection became direct");
|
||||
ping_accept(&conn, timeout).await.context("ping_accept")?;
|
||||
conn.closed().await;
|
||||
Ok(())
|
||||
})
|
||||
.right(plain, async move |_dev, _ep, conn| {
|
||||
let mut paths = conn.paths();
|
||||
assert!(paths.selected().is_relay(), "connection started relayed");
|
||||
paths
|
||||
.wait_ip(timeout)
|
||||
.await
|
||||
.context("holepunch to direct with many addrs")?;
|
||||
info!("connection became direct");
|
||||
ping_open(&conn, timeout).await.context("ping_accept")?;
|
||||
conn.close(0u32.into(), b"bye");
|
||||
Ok(())
|
||||
})
|
||||
.run()
|
||||
.await?;
|
||||
guard.ok();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn degrade_server_1_poor() -> Result {
|
||||
run_degrade_level(Side::Server, 1).await?.ok();
|
||||
Ok(())
|
||||
async fn holepunch_many_addrs_client_8() -> Result {
|
||||
run_holepunch_many_addrs(Side::Client, 8).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn degrade_server_2_bad() -> Result {
|
||||
run_degrade_level(Side::Server, 2).await?.ok();
|
||||
Ok(())
|
||||
async fn holepunch_many_addrs_server_8() -> Result {
|
||||
run_holepunch_many_addrs(Side::Server, 8).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn degrade_server_3_terrible() -> Result {
|
||||
run_degrade_level(Side::Server, 3).await?.ok();
|
||||
Ok(())
|
||||
#[ignore = "not yet passing"]
|
||||
async fn holepunch_many_addrs_client_16() -> Result {
|
||||
run_holepunch_many_addrs(Side::Client, 16).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
#[ignore = "not yet passing reliably"]
|
||||
async fn degrade_server_4_extreme() -> Result {
|
||||
run_degrade_level(Side::Server, 4).await?.ok();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
#[ignore = "not yet passing reliably"]
|
||||
async fn degrade_server_5_absurd() -> Result {
|
||||
run_degrade_level(Side::Server, 5).await?.ok();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn degrade_client_0_mild() -> Result {
|
||||
run_degrade_level(Side::Client, 0).await?.ok();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn degrade_client_1_poor() -> Result {
|
||||
run_degrade_level(Side::Client, 1).await?.ok();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn degrade_client_2_bad() -> Result {
|
||||
run_degrade_level(Side::Client, 2).await?.ok();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn degrade_client_3_terrible() -> Result {
|
||||
run_degrade_level(Side::Client, 3).await?.ok();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
#[ignore = "not yet passing reliably"]
|
||||
async fn degrade_client_4_extreme() -> Result {
|
||||
run_degrade_level(Side::Client, 4).await?.ok();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
#[ignore = "not yet passing reliably"]
|
||||
async fn degrade_client_5_absurd() -> Result {
|
||||
run_degrade_level(Side::Client, 5).await?.ok();
|
||||
Ok(())
|
||||
#[ignore = "not yet passing"]
|
||||
async fn holepunch_many_addrs_server_16() -> Result {
|
||||
run_holepunch_many_addrs(Side::Server, 16).await
|
||||
}
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
//! Degradation ladder: find where holepunching breaks under worsening conditions
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use iroh::endpoint::Side;
|
||||
use n0_error::{Result, StackResultExt, StdResultExt};
|
||||
use n0_tracing_test::traced_test;
|
||||
use patchbay::{LinkCondition, LinkDirection, LinkLimits, Nat};
|
||||
use testdir::testdir;
|
||||
use tracing::info;
|
||||
|
||||
use super::util::{Pair, PathWatcherExt, lab_with_relay, ping_accept, ping_open};
|
||||
|
||||
/// Increasingly degraded link conditions applied to one side of the connection.
|
||||
///
|
||||
/// Each level adds more latency, loss, and reordering. The levels are tested
|
||||
/// individually for both server-side and client-side impairment.
|
||||
const DEGRADE_LEVELS: &[LinkLimits] = &[
|
||||
// 0: mild - good wifi
|
||||
LinkLimits {
|
||||
latency_ms: 10,
|
||||
jitter_ms: 5,
|
||||
loss_pct: 0.5,
|
||||
reorder_pct: 0.0,
|
||||
rate_kbit: 0,
|
||||
duplicate_pct: 0.0,
|
||||
corrupt_pct: 0.0,
|
||||
},
|
||||
// 1: poor - bad wifi or 3G
|
||||
LinkLimits {
|
||||
latency_ms: 100,
|
||||
jitter_ms: 30,
|
||||
loss_pct: 3.0,
|
||||
reorder_pct: 3.0,
|
||||
rate_kbit: 0,
|
||||
duplicate_pct: 0.0,
|
||||
corrupt_pct: 0.0,
|
||||
},
|
||||
// 2: bad - congested 3G
|
||||
LinkLimits {
|
||||
latency_ms: 200,
|
||||
jitter_ms: 60,
|
||||
loss_pct: 5.0,
|
||||
reorder_pct: 5.0,
|
||||
rate_kbit: 0,
|
||||
duplicate_pct: 0.0,
|
||||
corrupt_pct: 0.0,
|
||||
},
|
||||
// 3: terrible - barely usable
|
||||
LinkLimits {
|
||||
latency_ms: 300,
|
||||
jitter_ms: 80,
|
||||
loss_pct: 8.0,
|
||||
reorder_pct: 8.0,
|
||||
rate_kbit: 0,
|
||||
duplicate_pct: 0.0,
|
||||
corrupt_pct: 0.0,
|
||||
},
|
||||
// 4: extreme - GEO satellite with heavy loss
|
||||
LinkLimits {
|
||||
latency_ms: 500,
|
||||
jitter_ms: 100,
|
||||
loss_pct: 12.0,
|
||||
reorder_pct: 12.0,
|
||||
rate_kbit: 0,
|
||||
duplicate_pct: 0.0,
|
||||
corrupt_pct: 0.0,
|
||||
},
|
||||
// 5: absurd - stress test
|
||||
LinkLimits {
|
||||
latency_ms: 800,
|
||||
jitter_ms: 200,
|
||||
loss_pct: 20.0,
|
||||
reorder_pct: 20.0,
|
||||
rate_kbit: 0,
|
||||
duplicate_pct: 0.0,
|
||||
corrupt_pct: 0.0,
|
||||
},
|
||||
];
|
||||
|
||||
/// Runs a single degradation level.
|
||||
///
|
||||
/// Creates two devices behind Home NATs, applies the given [`LinkLimits`] to
|
||||
/// `impaired_side`, then attempts to holepunch and ping. Returns the
|
||||
/// [`TestGuard`] on success so the caller can mark it as passed.
|
||||
async fn run_degrade_level(impaired_side: Side, level: usize) -> Result<()> {
|
||||
let (lab, relay_map, _relay_guard, guard) = lab_with_relay(testdir!()).await?;
|
||||
let nat1 = lab.add_router("nat1").nat(Nat::Home).build().await?;
|
||||
let nat2 = lab.add_router("nat2").nat(Nat::Home).build().await?;
|
||||
let timeout = Duration::from_secs(20 + level as u64 * 10);
|
||||
|
||||
let limits = DEGRADE_LEVELS[level];
|
||||
let link_condition = LinkCondition::Manual(limits);
|
||||
|
||||
let server = lab
|
||||
.add_device("server")
|
||||
.iface("eth0", nat1.id())
|
||||
.build()
|
||||
.await?;
|
||||
let client = lab
|
||||
.add_device("client")
|
||||
.iface("eth0", nat2.id())
|
||||
.build()
|
||||
.await?;
|
||||
let impaired_device = match impaired_side {
|
||||
Side::Client => &client,
|
||||
Side::Server => &server,
|
||||
};
|
||||
impaired_device
|
||||
.iface("eth0")
|
||||
.unwrap()
|
||||
.set_condition(link_condition, LinkDirection::Both)
|
||||
.await?;
|
||||
|
||||
info!(?impaired_side, ?limits, %level, ?timeout, "degrade test start");
|
||||
|
||||
let result = tokio::time::timeout(
|
||||
timeout,
|
||||
Pair::new(relay_map)
|
||||
.server(server, async move |_dev, _ep, conn| {
|
||||
ping_accept(&conn, timeout).await.context("ping_accept")?;
|
||||
conn.closed().await;
|
||||
Ok(())
|
||||
})
|
||||
.client(client, async move |_dev, _ep, conn| {
|
||||
let mut paths = conn.paths();
|
||||
info!("waiting for connection to become direct");
|
||||
paths
|
||||
.wait_ip(timeout)
|
||||
.await
|
||||
.context("holepunch to direct")?;
|
||||
info!("direct path established, sending ping");
|
||||
ping_open(&conn, timeout).await.context("ping_open")?;
|
||||
info!("ping complete");
|
||||
conn.close(0u32.into(), b"bye");
|
||||
Ok(())
|
||||
})
|
||||
.run(),
|
||||
)
|
||||
.await
|
||||
.std_context("pair timed out")
|
||||
.flatten();
|
||||
|
||||
match &result {
|
||||
Ok(()) => tracing::event!(
|
||||
target: "test::_events::ladder_pass",
|
||||
tracing::Level::INFO,
|
||||
level,
|
||||
latency_ms = limits.latency_ms,
|
||||
loss_pct = limits.loss_pct,
|
||||
reorder_pct = limits.reorder_pct,
|
||||
impaired_side = ?impaired_side,
|
||||
"PASSED",
|
||||
),
|
||||
Err(err) => tracing::event!(
|
||||
target: "test::_events::ladder_fail",
|
||||
tracing::Level::WARN,
|
||||
level,
|
||||
latency_ms = limits.latency_ms,
|
||||
loss_pct = limits.loss_pct,
|
||||
reorder_pct = limits.reorder_pct,
|
||||
impaired_side = ?impaired_side,
|
||||
error = format!("{err:#}"),
|
||||
"FAILED",
|
||||
),
|
||||
}
|
||||
|
||||
result?;
|
||||
guard.ok();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn degrade_server_0_mild() -> Result {
|
||||
run_degrade_level(Side::Server, 0).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn degrade_server_1_poor() -> Result {
|
||||
run_degrade_level(Side::Server, 1).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn degrade_server_2_bad() -> Result {
|
||||
run_degrade_level(Side::Server, 2).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn degrade_server_3_terrible() -> Result {
|
||||
run_degrade_level(Side::Server, 3).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
#[ignore = "not yet passing reliably"]
|
||||
async fn degrade_server_4_extreme() -> Result {
|
||||
run_degrade_level(Side::Server, 4).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
#[ignore = "not yet passing reliably"]
|
||||
async fn degrade_server_5_absurd() -> Result {
|
||||
run_degrade_level(Side::Server, 5).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn degrade_client_0_mild() -> Result {
|
||||
run_degrade_level(Side::Client, 0).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn degrade_client_1_poor() -> Result {
|
||||
run_degrade_level(Side::Client, 1).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn degrade_client_2_bad() -> Result {
|
||||
run_degrade_level(Side::Client, 2).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn degrade_client_3_terrible() -> Result {
|
||||
run_degrade_level(Side::Client, 3).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
#[ignore = "not yet passing reliably"]
|
||||
async fn degrade_client_4_extreme() -> Result {
|
||||
run_degrade_level(Side::Client, 4).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
#[ignore = "not yet passing reliably"]
|
||||
async fn degrade_client_5_absurd() -> Result {
|
||||
run_degrade_level(Side::Client, 5).await
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
//! NAT traversal matrix tests.
|
||||
//!
|
||||
//! Tests holepunching across combinations of NAT types (None, Home, Corporate).
|
||||
//!
|
||||
//! - None: no NAT, publicly routable
|
||||
//! - Home: endpoint-independent mapping (EIM), address-and-port-dependent
|
||||
//! filtering (APDF), port-preserving (typical home router)
|
||||
//! - Corporate: endpoint-dependent mapping (EDM), APDF, random ports per
|
||||
//! destination (enterprise firewall, cloud NAT)
|
||||
//!
|
||||
//! Every test expects a direct path to be established. Tests where holepunching
|
||||
//! is not yet working are marked `#[ignore]`.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use n0_error::{Result, StackResultExt};
|
||||
use n0_tracing_test::traced_test;
|
||||
use patchbay::Nat;
|
||||
use testdir::testdir;
|
||||
use tracing::info;
|
||||
|
||||
use super::util::{Pair, PathWatcherExt, lab_with_relay};
|
||||
use crate::util::{ping_accept, ping_open};
|
||||
|
||||
async fn run_nat_holepunch(nat_server: Nat, nat_client: Nat) -> Result {
|
||||
let (lab, relay_map, _relay_guard, guard) = lab_with_relay(testdir!()).await?;
|
||||
let router_server = lab.add_router("nat_server").nat(nat_server).build().await?;
|
||||
let router_client = lab.add_router("nat_client").nat(nat_client).build().await?;
|
||||
let server = lab
|
||||
.add_device("server")
|
||||
.uplink(router_server.id())
|
||||
.build()
|
||||
.await?;
|
||||
let client = lab
|
||||
.add_device("client")
|
||||
.uplink(router_client.id())
|
||||
.build()
|
||||
.await?;
|
||||
|
||||
let timeout = Duration::from_secs(15);
|
||||
Pair::new(relay_map)
|
||||
.server(server, async move |_dev, _ep, conn| {
|
||||
let mut paths = conn.paths();
|
||||
assert!(paths.selected().is_relay(), "connection started relayed");
|
||||
paths
|
||||
.wait_ip(timeout)
|
||||
.await
|
||||
.context("holepunch to direct")?;
|
||||
info!("connection became direct");
|
||||
ping_accept(&conn, timeout).await?;
|
||||
conn.closed().await;
|
||||
Ok(())
|
||||
})
|
||||
.client(client, async move |_dev, _ep, conn| {
|
||||
let mut paths = conn.paths();
|
||||
assert!(paths.selected().is_relay(), "connection started relayed");
|
||||
paths
|
||||
.wait_ip(timeout)
|
||||
.await
|
||||
.context("holepunch to direct")?;
|
||||
info!("connection became direct");
|
||||
ping_open(&conn, timeout).await?;
|
||||
conn.close(0u32.into(), b"bye");
|
||||
Ok(())
|
||||
})
|
||||
.run()
|
||||
.await?;
|
||||
|
||||
guard.ok();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn nat_none_x_none() -> Result {
|
||||
run_nat_holepunch(Nat::None, Nat::None).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn nat_none_x_home() -> Result {
|
||||
run_nat_holepunch(Nat::None, Nat::Home).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn nat_home_x_none() -> Result {
|
||||
run_nat_holepunch(Nat::Home, Nat::None).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn nat_none_x_corporate() -> Result {
|
||||
run_nat_holepunch(Nat::None, Nat::Corporate).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
#[ignore = "not yet passing"]
|
||||
async fn nat_corporate_x_none() -> Result {
|
||||
run_nat_holepunch(Nat::Corporate, Nat::None).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn nat_home_x_home() -> Result {
|
||||
run_nat_holepunch(Nat::Home, Nat::Home).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
#[ignore = "not yet passing"]
|
||||
async fn nat_home_x_corporate() -> Result {
|
||||
run_nat_holepunch(Nat::Home, Nat::Corporate).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
#[ignore = "not yet passing"]
|
||||
async fn nat_corporate_x_home() -> Result {
|
||||
run_nat_holepunch(Nat::Corporate, Nat::Home).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
#[ignore = "not yet passing"]
|
||||
async fn nat_corporate_x_corporate() -> Result {
|
||||
run_nat_holepunch(Nat::Corporate, Nat::Corporate).await
|
||||
}
|
||||
@@ -22,25 +22,6 @@ use tracing::info;
|
||||
|
||||
use crate::util::{Pair, PathWatcherExt, lab_with_relay, ping_accept, ping_open};
|
||||
|
||||
fn router_preset(ip: IpSupport) -> RouterPreset {
|
||||
match ip {
|
||||
IpSupport::V4Only => RouterPreset::Home,
|
||||
IpSupport::V6Only => RouterPreset::IspV6,
|
||||
IpSupport::DualStack => RouterPreset::Home,
|
||||
}
|
||||
}
|
||||
|
||||
fn path_switched(to: IpSupport, previous: &[TransportAddr], new: &TransportAddr) -> bool {
|
||||
if previous.contains(new) {
|
||||
return false;
|
||||
}
|
||||
match to {
|
||||
IpSupport::V4Only => matches!(new, TransportAddr::Ip(a) if a.ip().is_ipv4()),
|
||||
IpSupport::V6Only => matches!(new, TransportAddr::Ip(a) if a.ip().is_ipv6()),
|
||||
IpSupport::DualStack => matches!(new, TransportAddr::Ip(_)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds the lab topology and runs a single uplink switch test.
|
||||
///
|
||||
/// The topology has three routers:
|
||||
@@ -78,99 +59,76 @@ async fn run_switch_uplink(switching_side: Side, from: IpSupport, to: IpSupport)
|
||||
.await?
|
||||
.id();
|
||||
|
||||
let (server_uplink, client_uplink) = match switching_side {
|
||||
Side::Client => (observer_id, from_id),
|
||||
Side::Server => (from_id, observer_id),
|
||||
};
|
||||
let server = lab
|
||||
.add_device("server")
|
||||
.uplink(server_uplink)
|
||||
.build()
|
||||
.await?;
|
||||
let client = lab
|
||||
.add_device("client")
|
||||
.uplink(client_uplink)
|
||||
let switcher = lab.add_device("switcher").uplink(from_id).build().await?;
|
||||
let observer = lab
|
||||
.add_device("observer")
|
||||
.uplink(observer_id)
|
||||
.build()
|
||||
.await?;
|
||||
|
||||
info!(?switching_side, ?from, ?to, "switch uplink test start");
|
||||
|
||||
/// The switching side: holepunches, pings, replugs to a new router, pings again.
|
||||
///
|
||||
/// Waits for the peer to close the connection after the second ping succeeds.
|
||||
async fn do_switch(
|
||||
dev: patchbay::Device,
|
||||
conn: iroh::endpoint::Connection,
|
||||
timeout: Duration,
|
||||
to_id: patchbay::NodeId,
|
||||
) -> Result {
|
||||
let mut paths = conn.paths();
|
||||
paths.wait_ip(timeout).await.context("initial holepunch")?;
|
||||
ping_accept(&conn, timeout)
|
||||
.await
|
||||
.context("ping_accept before switch")?;
|
||||
dev.iface("eth0").unwrap().replug(to_id).await?;
|
||||
ping_accept(&conn, timeout)
|
||||
.await
|
||||
.context("ping_accept after switch")?;
|
||||
conn.closed().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The observing side: holepunches, pings, waits for the path to change, pings again.
|
||||
///
|
||||
/// After the switching side replugs, the observer sees the selected path change
|
||||
/// to match the expected address family (or a new address for same-family switches).
|
||||
/// Closes the connection after the second ping succeeds.
|
||||
async fn do_observe(
|
||||
conn: iroh::endpoint::Connection,
|
||||
timeout: Duration,
|
||||
to: IpSupport,
|
||||
) -> Result {
|
||||
let mut paths = conn.paths();
|
||||
paths.wait_ip(timeout).await.context("initial holepunch")?;
|
||||
ping_open(&conn, timeout)
|
||||
.await
|
||||
.context("ping_open before switch")?;
|
||||
let previous: Vec<TransportAddr> = paths
|
||||
.get()
|
||||
.iter()
|
||||
.map(|p| p.remote_addr().clone())
|
||||
.collect();
|
||||
paths
|
||||
.wait_selected(timeout, |p| path_switched(to, &previous, p.remote_addr()))
|
||||
.await
|
||||
.context("path did not switch")?;
|
||||
ping_open(&conn, timeout)
|
||||
.await
|
||||
.context("ping_open after switch")?;
|
||||
conn.close(0u32.into(), b"bye");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
let pair = Pair::new(relay_map);
|
||||
let pair = match switching_side {
|
||||
Side::Client => pair
|
||||
.server(server, async move |_dev, _ep, conn| {
|
||||
do_observe(conn, timeout, to).await
|
||||
})
|
||||
.client(client, async move |dev, _ep, conn| {
|
||||
do_switch(dev, conn, timeout, to_id).await
|
||||
}),
|
||||
Side::Server => pair
|
||||
.server(server, async move |dev, _ep, conn| {
|
||||
do_switch(dev, conn, timeout, to_id).await
|
||||
})
|
||||
.client(client, async move |_dev, _ep, conn| {
|
||||
do_observe(conn, timeout, to).await
|
||||
}),
|
||||
};
|
||||
pair.run().await?;
|
||||
Pair::new(relay_map)
|
||||
.left(switching_side, switcher, async move |dev, _ep, conn| {
|
||||
let mut paths = conn.paths();
|
||||
paths.wait_ip(timeout).await.context("initial holepunch")?;
|
||||
ping_accept(&conn, timeout)
|
||||
.await
|
||||
.context("ping_accept before switch")?;
|
||||
dev.iface("eth0").unwrap().replug(to_id).await?;
|
||||
ping_accept(&conn, timeout)
|
||||
.await
|
||||
.context("ping_accept after switch")?;
|
||||
conn.closed().await;
|
||||
Ok(())
|
||||
})
|
||||
.right(observer, async move |_dev, _ep, conn| {
|
||||
let mut paths = conn.paths();
|
||||
paths.wait_ip(timeout).await.context("initial holepunch")?;
|
||||
let previous: Vec<TransportAddr> = paths
|
||||
.get()
|
||||
.iter()
|
||||
.map(|p| p.remote_addr().clone())
|
||||
.collect();
|
||||
ping_open(&conn, timeout)
|
||||
.await
|
||||
.context("ping_open before switch")?;
|
||||
paths
|
||||
.wait_selected(timeout, |p| path_switched(to, &previous, p.remote_addr()))
|
||||
.await
|
||||
.context("path did not switch")?;
|
||||
ping_open(&conn, timeout)
|
||||
.await
|
||||
.context("ping_open after switch")?;
|
||||
conn.close(0u32.into(), b"bye");
|
||||
Ok(())
|
||||
})
|
||||
.run()
|
||||
.await?;
|
||||
|
||||
guard.ok();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn router_preset(ip: IpSupport) -> RouterPreset {
|
||||
match ip {
|
||||
IpSupport::V4Only => RouterPreset::Home,
|
||||
IpSupport::V6Only => RouterPreset::IspV6,
|
||||
IpSupport::DualStack => RouterPreset::Home,
|
||||
}
|
||||
}
|
||||
|
||||
fn path_switched(to: IpSupport, previous: &[TransportAddr], new: &TransportAddr) -> bool {
|
||||
if previous.contains(new) {
|
||||
return false;
|
||||
}
|
||||
match to {
|
||||
IpSupport::V4Only => matches!(new, TransportAddr::Ip(a) if a.ip().is_ipv4()),
|
||||
IpSupport::V6Only => matches!(new, TransportAddr::Ip(a) if a.ip().is_ipv6()),
|
||||
IpSupport::DualStack => matches!(new, TransportAddr::Ip(_)),
|
||||
}
|
||||
}
|
||||
|
||||
// --- Client switches uplink ---
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
+80
-19
@@ -8,6 +8,7 @@ use iroh::{
|
||||
use iroh_metrics::MetricsGroupSet;
|
||||
use n0_error::{Result, StackResultExt, StdResultExt, anyerr, ensure_any};
|
||||
use n0_future::{boxed::BoxFuture, task::AbortOnDropHandle};
|
||||
use noq::Side;
|
||||
use patchbay::{Device, IpSupport, Lab, OutDir, TestGuard};
|
||||
use tokio::sync::{Barrier, oneshot};
|
||||
use tracing::{Instrument, debug, error, error_span, event, info};
|
||||
@@ -73,14 +74,40 @@ async fn spawn_relay(lab: &Lab) -> Result<(RelayMap, AbortOnDropHandle<()>)> {
|
||||
/// Type alias for boxed run functions used in [`Pair`].
|
||||
type RunFn = Box<dyn 'static + Send + FnOnce(Device, Endpoint, Connection) -> BoxFuture<Result>>;
|
||||
|
||||
fn box_fn<F, Fut>(f: F) -> RunFn
|
||||
where
|
||||
F: FnOnce(Device, Endpoint, Connection) -> Fut + Send + 'static,
|
||||
Fut: Future<Output = Result> + Send + 'static,
|
||||
{
|
||||
Box::new(move |dev, ep, conn| Box::pin(f(dev, ep, conn)))
|
||||
}
|
||||
|
||||
/// Builder for two connected endpoints in a lab.
|
||||
///
|
||||
/// Use this to quickly create two endpoints on two different devices and create a
|
||||
/// connection between them that starts as relay-only.
|
||||
///
|
||||
/// Two construction paths:
|
||||
///
|
||||
/// ```ignore
|
||||
/// // Explicit server/client assignment:
|
||||
/// Pair::new(relay_map)
|
||||
/// .server(server_dev, async |dev, ep, conn| { ... })
|
||||
/// .client(client_dev, async |dev, ep, conn| { ... })
|
||||
/// .run().await?;
|
||||
///
|
||||
/// // Side-swapped assignment (for matrix tests):
|
||||
/// Pair::new(relay_map)
|
||||
/// .left(some_side, dev_a, async |dev, ep, conn| { ... })
|
||||
/// .right(dev_b, async |dev, ep, conn| { ... })
|
||||
/// .run().await?;
|
||||
/// ```
|
||||
pub struct Pair {
|
||||
relay_map: RelayMap,
|
||||
server: Option<(Device, RunFn)>,
|
||||
client: Option<(Device, RunFn)>,
|
||||
server_dev: Option<Device>,
|
||||
client_dev: Option<Device>,
|
||||
server_fn: Option<RunFn>,
|
||||
client_fn: Option<RunFn>,
|
||||
}
|
||||
|
||||
impl Pair {
|
||||
@@ -88,20 +115,53 @@ impl Pair {
|
||||
pub fn new(relay_map: RelayMap) -> Self {
|
||||
Self {
|
||||
relay_map,
|
||||
server: None,
|
||||
client: None,
|
||||
server_dev: None,
|
||||
client_dev: None,
|
||||
server_fn: None,
|
||||
client_fn: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Places a device and closure on the given [`Side`].
|
||||
///
|
||||
/// Use with [`.right()`](Self::right) for matrix tests that swap sides.
|
||||
pub fn left<F, Fut>(mut self, side: Side, device: Device, run_fn: F) -> Self
|
||||
where
|
||||
F: FnOnce(Device, Endpoint, Connection) -> Fut + Send + 'static,
|
||||
Fut: Future<Output = Result> + Send + 'static,
|
||||
{
|
||||
let (dev_slot, fn_slot) = match side {
|
||||
Side::Server => (&mut self.server_dev, &mut self.server_fn),
|
||||
Side::Client => (&mut self.client_dev, &mut self.client_fn),
|
||||
};
|
||||
*dev_slot = Some(device);
|
||||
*fn_slot = Some(box_fn(run_fn));
|
||||
self
|
||||
}
|
||||
|
||||
/// Places a device and closure on whichever [`Side`] was not set by [`.left()`](Self::left).
|
||||
pub fn right<F, Fut>(self, device: Device, run_fn: F) -> Self
|
||||
where
|
||||
F: FnOnce(Device, Endpoint, Connection) -> Fut + Send + 'static,
|
||||
Fut: Future<Output = Result> + Send + 'static,
|
||||
{
|
||||
let remaining = match (&self.server_dev, &self.client_dev) {
|
||||
(Some(_), None) => Side::Client,
|
||||
(None, Some(_)) => Side::Server,
|
||||
(None, None) => panic!("call .left() before .right()"),
|
||||
(Some(_), Some(_)) => panic!("both sides already assigned"),
|
||||
};
|
||||
self.left(remaining, device, run_fn)
|
||||
}
|
||||
|
||||
/// Sets the server device and run function.
|
||||
pub fn server<F, Fut>(mut self, device: Device, run_fn: F) -> Self
|
||||
where
|
||||
F: FnOnce(Device, Endpoint, Connection) -> Fut + Send + 'static,
|
||||
Fut: Future<Output = Result> + Send + 'static,
|
||||
{
|
||||
let run_fn: RunFn =
|
||||
Box::new(move |device, endpoint, conn| Box::pin(run_fn(device, endpoint, conn)));
|
||||
self.server = Some((device, run_fn));
|
||||
self.server_dev = Some(device);
|
||||
self.server_fn = Some(box_fn(run_fn));
|
||||
self
|
||||
}
|
||||
|
||||
@@ -111,9 +171,8 @@ impl Pair {
|
||||
F: FnOnce(Device, Endpoint, Connection) -> Fut + Send + 'static,
|
||||
Fut: Future<Output = Result> + Send + 'static,
|
||||
{
|
||||
let run_fn: RunFn =
|
||||
Box::new(move |device, endpoint, conn| Box::pin(run_fn(device, endpoint, conn)));
|
||||
self.client = Some((device, run_fn));
|
||||
self.client_dev = Some(device);
|
||||
self.client_fn = Some(box_fn(run_fn));
|
||||
self
|
||||
}
|
||||
|
||||
@@ -133,14 +192,16 @@ impl Pair {
|
||||
///
|
||||
/// Returns an error if any step or run function failed.
|
||||
pub async fn run(mut self) -> Result {
|
||||
let (server_device, server_run) = self
|
||||
.server
|
||||
let server_device = self.server_dev.take().context("Missing server device")?;
|
||||
let server_run = self
|
||||
.server_fn
|
||||
.take()
|
||||
.context("Missing server initialization")?;
|
||||
let (client_device, client_run) = self
|
||||
.client
|
||||
.context("Missing server run function")?;
|
||||
let client_device = self.client_dev.take().context("Missing client device")?;
|
||||
let client_run = self
|
||||
.client_fn
|
||||
.take()
|
||||
.context("Missing client initialization")?;
|
||||
.context("Missing client run function")?;
|
||||
|
||||
let (addr_tx, addr_rx) = oneshot::channel();
|
||||
let relay_map2 = self.relay_map.clone();
|
||||
@@ -334,7 +395,7 @@ impl PathWatcherExt for PathWatcher {
|
||||
}
|
||||
})
|
||||
.await
|
||||
.with_std_context(|_| "wait_selected timed out after {timeout:?}")?
|
||||
.with_std_context(|_| format!("wait_selected timed out after {timeout:?}"))?
|
||||
}
|
||||
}
|
||||
|
||||
@@ -355,7 +416,7 @@ pub async fn ping_open(conn: &Connection, timeout: Duration) -> Result {
|
||||
})
|
||||
.instrument(error_span!("ping_open"))
|
||||
.await
|
||||
.with_std_context(|_| "ping_open timed out after {timeout:?}")?
|
||||
.with_std_context(|_| format!("ping_open timed out after {timeout:?}"))?
|
||||
}
|
||||
|
||||
/// Accepts a bidi stream, reads 8 bytes of data, and sends the same data back.
|
||||
@@ -373,7 +434,7 @@ pub async fn ping_accept(conn: &Connection, timeout: Duration) -> Result {
|
||||
})
|
||||
.instrument(error_span!("ping_accept"))
|
||||
.await
|
||||
.with_std_context(|_| "ping_accept timed out after {timeout:?}")?
|
||||
.with_std_context(|_| format!("ping_accept timed out after {timeout:?}"))?
|
||||
}
|
||||
|
||||
fn watch_selected_path(conn: &Connection) {
|
||||
|
||||
Reference in New Issue
Block a user