fix(tests): break the irtt-client/irtt-server dev-dependency cycle

irtt-client and irtt-server mutually dev-depended on each other for
cross-crate integration tests. That cycle blocks `cargo publish` for
either crate whenever the other doesn't already exist on the registry
at the required version, which is exactly the situation for a crate's
first-ever release (irtt-server has never been published before).

Introduce a new `irtt-integration-tests` crate (publish = false, no
library target) to own tests whose actual subject is the interaction
between two or more irtt-* production crates:

  crate-local behavior          -> crate's own tests/
  cross-crate/system behavior   -> irtt-integration-tests

Move every test that imports both irtt_client and irtt_server there:
the client-side support harness (hmac, large_packets, protocol_options,
fill_negotiation) and the server-side real-socket tests that drive a
real AsyncClient against a real Server (async_client, negotiation_policy,
fill_wire_bytes, traffic_class, wildcard_source). server_set.rs stays in
irtt-server/tests since it only uses irtt_proto as test machinery to
drive irtt-server directly, which is a normal one-directional test
dependency, not a peer relationship.

irtt-server's dev-dependency on irtt-client is dropped entirely now
that nothing under crates/irtt-server/tests needs it, which fully
breaks the cycle from that side.

irtt-client keeps a one-directional dev-dependency on irtt-server: a
handful of white-box unit tests in src/async_client/tests.rs assert on
private AsyncClient internals (socket, remote, test_hooks) while also
needing a real in-tree server for blocking/async equivalence checks, so
they can't move to an external crate without losing that access. Their
InTreeServer helper is duplicated locally rather than shared, matching
the existing precedent of irtt-cli's own tests/support/in_tree_server.rs.
This commit is contained in:
Nils Andreas Svee committed 2026-08-17 09:49:32 +07:00
1 parent e120cca9bc
commit 1753e91d5f
19 files changed
+106 -5

No files matched your search

-95
View File
@@ -1,95 +0,0 @@
use std::time::Duration;
use irtt_client::{AsyncClient, ClientConfig, ClientEvent, OpenOutcome, SocketConfig};
use irtt_proto::{Clock, ReceivedStats, StampAt};
use irtt_server::{Server, ServerConfig};
use tokio::{sync::oneshot, time::timeout};
#[tokio::test(flavor = "current_thread")]
async fn async_client_opens_echoes_receives_and_closes() {
timeout(Duration::from_secs(2), exercise_client_server())
.await
.expect("client/server integration exceeded its bounded runtime");
}
async fn exercise_client_server() {
let mut server = Server::bind("127.0.0.1:0".parse().unwrap(), ServerConfig::default())
.await
.unwrap();
let server_addr = server.local_addr().unwrap();
let (shutdown_tx, shutdown_rx) = oneshot::channel();
let server_task = tokio::spawn(async move {
server
.run(async {
let _ = shutdown_rx.await;
})
.await
});
let config = ClientConfig {
server_addr: server_addr.to_string(),
duration: Some(Duration::from_secs(1)),
interval: Duration::from_millis(100),
length: 64,
received_stats: ReceivedStats::Both,
stamp_at: StampAt::Both,
clock: Clock::Both,
open_timeouts: vec![Duration::from_millis(200)],
socket_config: SocketConfig {
recv_timeout: Some(Duration::from_millis(200)),
..SocketConfig::default()
},
probe_timeout: Duration::from_millis(200),
..ClientConfig::default()
};
let mut client = AsyncClient::connect(config).await.unwrap();
let opened = client.open().await.unwrap();
match &opened {
OpenOutcome::Started {
remote,
token,
negotiated,
event,
} => {
assert_eq!(*remote, server_addr);
assert_ne!(*token, 0);
assert_eq!(negotiated.params.received_stats, ReceivedStats::Both);
assert_eq!(negotiated.params.stamp_at, StampAt::Both);
assert_eq!(negotiated.params.clock, Clock::Both);
// A default client requests no fill, and this open succeeded under
// the default strict negotiation policy — which it could not have
// if the server had answered an absent request with its own default
// descriptor. The server still fills the payload with it.
assert_eq!(negotiated.params.server_fill, None);
assert!(matches!(event, ClientEvent::SessionStarted { .. }));
}
OpenOutcome::NoTestCompleted { .. } => panic!("normal client unexpectedly ran no-test"),
}
assert!(matches!(
client.send_probe().await.unwrap().as_slice(),
[ClientEvent::EchoSent {
seq: 0,
remote,
..
}] if *remote == server_addr
));
assert!(matches!(
client.recv().await.unwrap().as_slice(),
[ClientEvent::EchoReply {
seq: 0,
remote,
server_timing: Some(_),
received_stats: Some(_),
..
}] if *remote == server_addr
));
assert!(matches!(
client.close().await.unwrap().as_slice(),
[ClientEvent::SessionClosed { remote, .. }] if *remote == server_addr
));
shutdown_tx.send(()).unwrap();
server_task.await.unwrap().unwrap();
}
@@ -1,225 +0,0 @@
//! The server's capability restrictions as a real client sees them.
//!
//! The core tests are authoritative for the negotiated values; these exist to
//! prove the two ends agree over a socket. A restriction this server applies has
//! to arrive at `irtt-client` as one of the restrictions it already models: a
//! strict client refuses the changed value, and a loose one accepts it, records
//! it and runs the session. Nothing in the client changed for this — that is
//! what is being checked.
use std::time::Duration;
use irtt_client::{
AsyncClient, ClientConfig, NegotiationPolicy, NegotiationRestriction, OpenOutcome, SocketConfig,
};
use irtt_proto::{Clock, ReceivedStats, StampAt};
use irtt_server::{Server, ServerConfig, TimestampAllowance};
use tokio::{sync::oneshot, time::timeout};
#[tokio::test(flavor = "current_thread")]
async fn a_single_timestamp_allowance_reaches_a_strict_and_a_loose_client() {
timeout(Duration::from_secs(2), exercise_timestamp_restriction())
.await
.expect("the timestamp negotiation integration exceeded its bounded runtime");
}
async fn exercise_timestamp_restriction() {
let server = ServerConfig::default().with_timestamp_allowance(TimestampAllowance::Single);
let (server_addr, shutdown_tx, server_task) = serve(server).await;
let mut strict = client(server_addr, NegotiationPolicy::Strict).await;
let rejected = strict
.open()
.await
.expect_err("a strict client must refuse the reduced timestamp placement");
assert!(
rejected.to_string().contains("stamp-at"),
"the restriction names the timestamp placement: {rejected}"
);
let mut loose = client(server_addr, NegotiationPolicy::Loose).await;
let negotiated = match loose.open().await.unwrap() {
OpenOutcome::Started { negotiated, .. } => negotiated,
OpenOutcome::NoTestCompleted { .. } => panic!("normal client unexpectedly ran no-test"),
};
assert_eq!(
negotiated.params.stamp_at,
StampAt::Midpoint,
"a request for both instants is answered with the midpoint"
);
assert_eq!(
negotiated.params.clock,
Clock::Both,
"the clock is not restricted with it"
);
assert!(negotiated
.restrictions
.contains(&NegotiationRestriction::StampAtChanged {
requested: StampAt::Both,
negotiated: StampAt::Midpoint,
}));
probe(&mut loose).await;
loose.close().await.unwrap();
shutdown_tx.send(()).unwrap();
server_task.await.unwrap().unwrap();
}
#[tokio::test(flavor = "current_thread")]
async fn a_disallowed_dscp_reaches_a_strict_and_a_loose_client() {
timeout(Duration::from_secs(2), exercise_dscp_restriction())
.await
.expect("the DSCP negotiation integration exceeded its bounded runtime");
}
async fn exercise_dscp_restriction() {
let (server_addr, shutdown_tx, server_task) = serve(
ServerConfig::default()
.with_min_send_interval(Duration::ZERO)
.with_dscp_allowed(false),
)
.await;
// The client's configuration is a DSCP codepoint; 46 (EF) is raw byte 184 on
// the wire, and this test does not change either convention.
let with_dscp = |policy| ClientConfig {
dscp: 46,
..test_config(server_addr, policy)
};
let mut strict = AsyncClient::connect(with_dscp(NegotiationPolicy::Strict))
.await
.unwrap();
let rejected = strict
.open()
.await
.expect_err("a strict client must refuse the removed marking");
assert!(
rejected.to_string().contains("DSCP"),
"the restriction names DSCP: {rejected}"
);
let mut loose = AsyncClient::connect(with_dscp(NegotiationPolicy::Loose))
.await
.unwrap();
let negotiated = match loose.open().await.unwrap() {
OpenOutcome::Started { negotiated, .. } => negotiated,
OpenOutcome::NoTestCompleted { .. } => panic!("normal client unexpectedly ran no-test"),
};
assert_eq!(
negotiated.params.dscp, 0,
"the raw wire parameter is negotiated to zero"
);
assert!(negotiated
.restrictions
.contains(&NegotiationRestriction::DscpChanged {
requested: 46,
negotiated: 0,
}));
probe(&mut loose).await;
loose.close().await.unwrap();
shutdown_tx.send(()).unwrap();
server_task.await.unwrap().unwrap();
}
#[tokio::test(flavor = "current_thread")]
async fn a_default_server_restricts_nothing_an_ordinary_client_asks_for() {
timeout(Duration::from_secs(2), exercise_default_policy())
.await
.expect("the default policy integration exceeded its bounded runtime");
}
/// The controls are opt-in, and this is what that has to mean: an ordinary
/// client against an unconfigured server negotiates with no restriction at all,
/// under the default *strict* policy that would refuse one.
async fn exercise_default_policy() {
let (server_addr, shutdown_tx, server_task) = serve(ServerConfig::default()).await;
let mut client = AsyncClient::connect(ClientConfig {
dscp: 46,
..test_config(server_addr, NegotiationPolicy::Strict)
})
.await
.unwrap();
let negotiated = match client.open().await.unwrap() {
OpenOutcome::Started { negotiated, .. } => negotiated,
OpenOutcome::NoTestCompleted { .. } => panic!("normal client unexpectedly ran no-test"),
};
assert_eq!(negotiated.restrictions, Vec::new());
assert_eq!(negotiated.params.stamp_at, StampAt::Both);
assert_eq!(negotiated.params.clock, Clock::Both);
assert_eq!(negotiated.params.dscp, 184, "the raw byte for codepoint 46");
probe(&mut client).await;
client.close().await.unwrap();
shutdown_tx.send(()).unwrap();
server_task.await.unwrap().unwrap();
}
/// Starts one listener and returns its address, its shutdown trigger and its
/// task.
async fn serve(
config: ServerConfig,
) -> (
std::net::SocketAddr,
oneshot::Sender<()>,
tokio::task::JoinHandle<Result<(), irtt_server::ServerRuntimeError>>,
) {
let mut server = Server::bind("127.0.0.1:0".parse().unwrap(), config)
.await
.unwrap();
let server_addr = server.local_addr().unwrap();
let (shutdown_tx, shutdown_rx) = oneshot::channel();
let task = tokio::spawn(async move {
server
.run(async {
let _ = shutdown_rx.await;
})
.await
});
(server_addr, shutdown_tx, task)
}
/// A short deterministic client requesting both timestamps from both clocks.
fn test_config(server_addr: std::net::SocketAddr, policy: NegotiationPolicy) -> ClientConfig {
ClientConfig {
server_addr: server_addr.to_string(),
duration: Some(Duration::from_secs(1)),
interval: Duration::from_millis(100),
length: 64,
received_stats: ReceivedStats::Both,
stamp_at: StampAt::Both,
clock: Clock::Both,
negotiation_policy: policy,
open_timeouts: vec![Duration::from_millis(200)],
socket_config: SocketConfig {
recv_timeout: Some(Duration::from_millis(200)),
..SocketConfig::default()
},
probe_timeout: Duration::from_millis(200),
..ClientConfig::default()
}
}
async fn client(server_addr: std::net::SocketAddr, policy: NegotiationPolicy) -> AsyncClient {
AsyncClient::connect(test_config(server_addr, policy))
.await
.unwrap()
}
/// One probe, answered: a restricted session is an ordinary session.
async fn probe(client: &mut AsyncClient) {
client.send_probe().await.unwrap();
let events = client.recv().await.unwrap();
assert!(
events
.iter()
.any(|event| matches!(event, irtt_client::ClientEvent::EchoReply { seq: 0, .. })),
"the restricted session must answer an ordinary probe: {events:?}"
);
}
-216
View File
@@ -1,216 +0,0 @@
//! A negotiated fill over a real socket.
//!
//! The core tests are authoritative for fill bytes; this exists to prove the
//! whole path — negotiation, session, echo reply, UDP — puts the requested
//! pattern on the wire. It drives the server with the production protocol codecs
//! over a plain Tokio socket rather than through `AsyncClient`, because a
//! client's reply payload is not part of its event API and exposing it merely to
//! be asserted here would be the wrong trade.
use std::time::Duration;
use irtt_client::{
AsyncClient, ClientConfig, NegotiationPolicy, NegotiationRestriction, OpenOutcome, SocketConfig,
};
use irtt_proto::{
decode_echo_reply, decode_open_reply, echo_header_len, encode_request, Clock, Params,
ReceivedStats, RequestToEncode, ServerFill, StampAt,
};
use irtt_server::{Server, ServerConfig};
use tokio::{net::UdpSocket, sync::oneshot, time::timeout};
const DEADBEEF: &[u8] = &[0xde, 0xad, 0xbe, 0xef];
#[tokio::test(flavor = "current_thread")]
async fn a_negotiated_pattern_reaches_the_wire() {
timeout(Duration::from_secs(2), exercise_patterned_session())
.await
.expect("the fill integration exceeded its bounded runtime");
}
async fn exercise_patterned_session() {
let mut server = Server::bind("127.0.0.1:0".parse().unwrap(), ServerConfig::default())
.await
.unwrap();
let server_addr = server.local_addr().unwrap();
let (shutdown_tx, shutdown_rx) = oneshot::channel();
let server_task = tokio::spawn(async move {
server
.run(async {
let _ = shutdown_rx.await;
})
.await
});
let socket = UdpSocket::bind("127.0.0.1:0").await.unwrap();
socket.connect(server_addr).await.unwrap();
let requested = requested_params(24);
socket
.send(
&encode_request(
RequestToEncode::Open {
params: &requested,
no_test: false,
},
None,
)
.unwrap(),
)
.await
.unwrap();
let reply = decode_open_reply(&receive(&socket).await, None).unwrap();
let negotiated = reply.params;
assert_eq!(
negotiated.server_fill, requested.server_fill,
"a valid descriptor is returned unchanged, so strict negotiation holds"
);
// The request carries its own payload bytes, none of which may come back.
socket
.send(
&encode_request(
RequestToEncode::Echo {
token: reply.token,
sequence: 0,
params: &negotiated,
payload: &[0xa5; 24],
},
None,
)
.unwrap(),
)
.await
.unwrap();
let packet = receive(&socket).await;
let echo = decode_echo_reply(&packet, &negotiated, None).unwrap();
assert_eq!(packet.len() as i64, negotiated.length);
assert_eq!(
echo.payload,
DEADBEEF
.iter()
.copied()
.cycle()
.take(24)
.collect::<Vec<_>>()
);
socket
.send(&encode_request(RequestToEncode::Close { token: reply.token }, None).unwrap())
.await
.unwrap();
shutdown_tx.send(()).unwrap();
server_task.await.unwrap().unwrap();
}
#[tokio::test(flavor = "current_thread")]
async fn a_client_sees_the_fallback_as_a_negotiation_restriction() {
timeout(Duration::from_secs(2), exercise_fallback_negotiation())
.await
.expect("the negotiation integration exceeded its bounded runtime");
}
/// The fallback is deliberately visible to a client rather than hidden: a
/// descriptor this server could not honor comes back as the default one, which a
/// strict client refuses and a loose client accepts with a restriction recorded.
async fn exercise_fallback_negotiation() {
let mut server = Server::bind("127.0.0.1:0".parse().unwrap(), ServerConfig::default())
.await
.unwrap();
let server_addr = server.local_addr().unwrap();
let (shutdown_tx, shutdown_rx) = oneshot::channel();
let server_task = tokio::spawn(async move {
server
.run(async {
let _ = shutdown_rx.await;
})
.await
});
// `ClientConfig` accepts any non-empty descriptor within the wire bound, so
// an unknown one genuinely reaches the server.
let config = |policy| ClientConfig {
server_addr: server_addr.to_string(),
duration: Some(Duration::from_secs(1)),
interval: Duration::from_millis(100),
length: 64,
server_fill: Some("bogus".to_owned()),
negotiation_policy: policy,
open_timeouts: vec![Duration::from_millis(200)],
socket_config: SocketConfig {
recv_timeout: Some(Duration::from_millis(200)),
..SocketConfig::default()
},
probe_timeout: Duration::from_millis(200),
..ClientConfig::default()
};
let mut strict = AsyncClient::connect(config(NegotiationPolicy::Strict))
.await
.unwrap();
let rejected = strict
.open()
.await
.expect_err("a strict client must refuse the changed fill");
assert!(
rejected.to_string().contains("fill"),
"the restriction names the fill: {rejected}"
);
let mut loose = AsyncClient::connect(config(NegotiationPolicy::Loose))
.await
.unwrap();
match loose.open().await.unwrap() {
OpenOutcome::Started { negotiated, .. } => {
assert_eq!(
negotiated
.params
.server_fill
.map(|fill| fill.value)
.as_deref(),
Some("pattern:69727474"),
"the server reports the default descriptor it fell back to"
);
assert!(negotiated
.restrictions
.contains(&NegotiationRestriction::ServerFillChanged));
}
OpenOutcome::NoTestCompleted { .. } => panic!("normal client unexpectedly ran no-test"),
}
loose.close().await.unwrap();
shutdown_tx.send(()).unwrap();
server_task.await.unwrap().unwrap();
}
/// Params requesting a `deadbeef` fill and exactly `payload_len` payload bytes.
fn requested_params(payload_len: usize) -> Params {
let mut params = Params {
protocol_version: 1,
duration_ns: 1_000_000_000,
interval_ns: 100_000_000,
length: 0,
received_stats: ReceivedStats::Both,
stamp_at: StampAt::Both,
clock: Clock::Both,
dscp: 0,
server_fill: Some(ServerFill {
value: "pattern:deadbeef".to_owned(),
}),
};
params.length = (echo_header_len(false, &params) + payload_len) as i64;
params
}
/// One datagram, with a bounded wait so a lost reply fails rather than hangs.
async fn receive(socket: &UdpSocket) -> Vec<u8> {
let mut buffer = vec![0; 2048];
let read = timeout(Duration::from_secs(1), socket.recv(&mut buffer))
.await
.expect("the server must answer within the test's bound")
.unwrap();
buffer.truncate(read);
buffer
}
-225
View File
@@ -1,225 +0,0 @@
//! What the server's replies actually carry on the wire.
//!
//! Everything else about reply marking is decided deterministically in the
//! core, but "the core asked for 0xb8" is not the same claim as "the datagram
//! left the host with TOS 0xb8". These tests close that gap with real sockets:
//! a real [`AsyncClient`] against a real [`Server`], reading the traffic class
//! the kernel reports for each reply it receives.
//!
//! Linux only, because the receive-side ancillary metadata the client exposes
//! is. The production marking path is platform-independent and is compiled and
//! exercised everywhere; only this observation of it is not.
#![cfg(target_os = "linux")]
use std::{io, net::SocketAddr, time::Duration};
use irtt_client::{AsyncClient, ClientConfig, ClientEvent, OpenOutcome, PacketMeta, SocketConfig};
use irtt_proto::{Clock, ReceivedStats, StampAt};
use irtt_server::{Server, ServerConfig, ServerRuntimeError};
use tokio::{sync::oneshot, task::JoinHandle, time::timeout};
/// DSCP codepoints, as the client's configuration takes them, paired with the
/// raw TOS / Traffic Class byte each one occupies the upper six bits of. The
/// server negotiates and applies the raw byte; the shift is the client's
/// user-facing convention.
const EF: (u8, u8) = (46, 0xb8);
const CS1: (u8, u8) = (8, 0x20);
const UNMARKED: (u8, u8) = (0, 0x00);
#[tokio::test(flavor = "current_thread")]
async fn an_echo_reply_leaves_the_host_carrying_the_negotiated_traffic_class() {
timeout(Duration::from_secs(5), async {
let (server, addr) = bound_server("127.0.0.1:0".parse().unwrap())
.await
.expect("IPv4 loopback must be available");
let running = spawn(server);
let mut session = opened_session(addr, EF.0).await;
let meta = session.echo_packet_meta().await;
assert_eq!(meta.traffic_class, Some(EF.1), "the raw negotiated byte");
assert_eq!(meta.dscp, Some(EF.0), "its upper six bits");
assert_eq!(meta.ecn, Some(0), "and its low two");
running.stop().await;
})
.await
.expect("the wire traffic-class test exceeded its bounded runtime");
}
#[tokio::test(flavor = "current_thread")]
async fn one_listener_serving_many_sessions_leaks_no_marking_between_them() {
// The invariant that justifies applying the class before *every* send. One
// socket carries all three sessions, so a reply that did not set its own
// class would go out under whichever one the previous reply left behind.
// The order below returns to a marked session after another has sent, and
// ends on the unmarked one, which is the case a "skip the call for zero"
// optimization would break.
timeout(Duration::from_secs(10), async {
let (server, addr) = bound_server("127.0.0.1:0".parse().unwrap())
.await
.expect("IPv4 loopback must be available");
let running = spawn(server);
const MARKED: usize = 0;
const LIGHTLY_MARKED: usize = 1;
const UNMARKED_SESSION: usize = 2;
let mut sessions = [
opened_session(addr, EF.0).await,
opened_session(addr, CS1.0).await,
opened_session(addr, UNMARKED.0).await,
];
for (label, session, expected) in [
("first marked echo", MARKED, EF.1),
("a differently marked session", LIGHTLY_MARKED, CS1.1),
("back to the first session", MARKED, EF.1),
("an unmarked session last", UNMARKED_SESSION, UNMARKED.1),
] {
let meta = sessions[session].echo_packet_meta().await;
assert_eq!(
meta.traffic_class,
Some(expected),
"{label}: each reply carries its own session's marking"
);
}
running.stop().await;
})
.await
.expect("the cross-session leakage test exceeded its bounded runtime");
}
#[tokio::test(flavor = "current_thread")]
async fn an_ipv6_echo_reply_carries_the_negotiated_traffic_class() {
// One marked echo is enough here: the cross-session matrix above already
// pins the policy, and what this adds is the IPv6 Traffic Class option
// rather than the IPv4 TOS one.
timeout(Duration::from_secs(5), async {
let Some((server, addr)) = bound_server("[::1]:0".parse().unwrap()).await else {
return;
};
let running = spawn(server);
let mut session = opened_session(addr, EF.0).await;
let meta = session.echo_packet_meta().await;
assert_eq!(meta.traffic_class, Some(EF.1));
running.stop().await;
})
.await
.expect("the IPv6 wire traffic-class test exceeded its bounded runtime");
}
/// Binds a listener, or reports the family as unavailable on this host.
///
/// Only an address family this host does not have is skipped; any other bind
/// failure is a real failure.
async fn bound_server(addr: SocketAddr) -> Option<(Server, SocketAddr)> {
let server = match Server::bind(addr, unthrottled()).await {
Ok(server) => server,
Err(ServerRuntimeError::Bind { source, .. })
if matches!(
source.kind(),
io::ErrorKind::AddrNotAvailable | io::ErrorKind::Unsupported
) =>
{
return None;
}
Err(error) => panic!("unexpected loopback bind failure: {error}"),
};
let addr = server.local_addr().unwrap();
Some((server, addr))
}
/// A server that rate-limits nothing, so the cadence these tests drive replies
/// at cannot turn a marking assertion into a rate-limiting one.
fn unthrottled() -> ServerConfig {
ServerConfig::default().with_min_send_interval(Duration::ZERO)
}
/// A running listener and the handle that stops it.
struct Running {
shutdown: oneshot::Sender<()>,
task: JoinHandle<Result<(), ServerRuntimeError>>,
}
impl Running {
async fn stop(self) {
self.shutdown.send(()).unwrap();
self.task.await.unwrap().unwrap();
}
}
fn spawn(mut server: Server) -> Running {
let (shutdown, shutdown_rx) = oneshot::channel();
let task = tokio::spawn(async move {
server
.run(async {
let _ = shutdown_rx.await;
})
.await
});
Running { shutdown, task }
}
/// One client with an open session, and the sequence number its next echo will
/// carry — which the caller cannot infer once several sessions are interleaved.
struct OpenSession {
client: AsyncClient,
next_sequence: u32,
}
impl OpenSession {
/// Sends one echo and returns the receive metadata of its reply.
async fn echo_packet_meta(&mut self) -> PacketMeta {
let sequence = self.next_sequence;
self.next_sequence += 1;
self.client.send_probe().await.unwrap();
loop {
for event in self.client.recv().await.unwrap() {
if let ClientEvent::EchoReply {
seq, packet_meta, ..
} = event
{
assert_eq!(seq, sequence);
return packet_meta;
}
}
}
}
}
/// A client with an open session requesting `dscp` as a codepoint.
async fn opened_session(server_addr: SocketAddr, dscp: u8) -> OpenSession {
let config = ClientConfig {
server_addr: server_addr.to_string(),
duration: Some(Duration::from_secs(30)),
interval: Duration::from_millis(10),
length: 64,
dscp,
received_stats: ReceivedStats::Both,
stamp_at: StampAt::Both,
clock: Clock::Both,
open_timeouts: vec![Duration::from_millis(500)],
socket_config: SocketConfig {
recv_timeout: Some(Duration::from_millis(500)),
..SocketConfig::default()
},
probe_timeout: Duration::from_millis(500),
..ClientConfig::default()
};
let mut client = AsyncClient::connect(config).await.unwrap();
match client.open().await.unwrap() {
OpenOutcome::Started { negotiated, .. } => assert_eq!(
negotiated.params.dscp,
i64::from(dscp) << 2,
"the server negotiates the raw byte the codepoint asks for"
),
OpenOutcome::NoTestCompleted { .. } => panic!("a normal client unexpectedly ran no-test"),
}
OpenSession {
client,
next_sequence: 0,
}
}
-263
View File
@@ -1,263 +0,0 @@
//! A wildcard listener answers from the address the request was sent to.
//!
//! Every test here drives a real [`AsyncClient`], which reads from a *connected*
//! UDP socket. That connection is the assertion: the kernel discards any
//! datagram whose source is not the endpoint the client sent to, so a reply
//! that left from another of the host's addresses is indistinguishable from no
//! reply at all. An open, an echo and a close completing therefore prove the
//! source address, without the test having to inspect it.
//!
//! Compiled on the targets that implement wildcard source selection. Elsewhere
//! a wildcard bind is refused outright, which the runtime's own tests cover.
#![cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
use std::{
io,
net::{Ipv4Addr, SocketAddr, UdpSocket},
time::Duration,
};
use irtt_client::{AsyncClient, ClientConfig, ClientEvent, OpenOutcome, PacketMeta, SocketConfig};
use irtt_proto::{Clock, ReceivedStats, StampAt};
use irtt_server::{Server, ServerConfig, ServerRuntimeError};
use tokio::{sync::oneshot, task::JoinHandle, time::timeout};
/// EF, as the client's configuration takes it, and the raw TOS byte it occupies
/// the upper six bits of.
const EF_DSCP: u8 = 46;
const EF_TRAFFIC_CLASS: u8 = 0xb8;
#[tokio::test(flavor = "current_thread")]
async fn a_wildcard_ipv4_listener_replies_from_the_requested_address() {
timeout(Duration::from_secs(5), async {
let server = Server::bind("0.0.0.0:0".parse().unwrap(), unthrottled())
.await
.expect("a wildcard IPv4 listener must be supported on this target");
let port = server.local_addr().unwrap().port();
// A second loopback address makes this a genuine multi-homed case: the
// listener is bound to none of the host's addresses in particular, and
// the client contacts one the routing table would not have picked on
// its own. Hosts carrying only 127.0.0.1 — macOS, unless an alias is
// configured — still exercise the whole ancillary path, one address
// wide.
let target = SocketAddr::from((secondary_ipv4_loopback(), port));
let running = spawn(server);
let mut client = connected_client(target).await;
assert_started(&mut client, target).await;
let meta = echo_once(&mut client).await;
// Source selection is per-packet ancillary data and the traffic class
// is a socket-wide setting applied before the send. Both act on the
// same reply, so this is where they have to agree.
if cfg!(target_os = "linux") {
assert_eq!(
meta.traffic_class,
Some(EF_TRAFFIC_CLASS),
"a source-selected reply still carries its session's marking"
);
assert_eq!(meta.dscp, Some(EF_DSCP));
assert_eq!(meta.ecn, Some(0));
}
assert!(matches!(
client.close().await.unwrap().as_slice(),
[ClientEvent::SessionClosed { .. }]
));
running.stop().await;
})
.await
.expect("the wildcard IPv4 source-selection test exceeded its bounded runtime");
}
#[tokio::test(flavor = "current_thread")]
async fn an_ipv4_mapped_wildcard_listener_replies_from_the_requested_address() {
// `[::ffff:0.0.0.0]` is a wildcard that does not look like one. Linux
// accepts it as an IPv4 wildcard bind and `getsockname` reports it back
// unchanged, so a listener that only recognized `0.0.0.0` and `[::]` would
// take this for an explicit address and answer from a routing-selected
// source. macOS normalizes the bind to `[::]`, where this is simply the
// IPv6 wildcard case again.
timeout(Duration::from_secs(5), async {
let server = match Server::bind("[::ffff:0.0.0.0]:0".parse().unwrap(), unthrottled()).await
{
Ok(server) => server,
// FreeBSD refuses a mapped bind under its default `IPV6_V6ONLY`.
Err(ServerRuntimeError::Bind { source, .. }) if is_family_unavailable(&source) => {
eprintln!("skipping IPv4-mapped wildcard test: the bind is unavailable here");
return;
}
Err(error) => panic!("unexpected IPv4-mapped wildcard bind failure: {error}"),
};
let port = server.local_addr().unwrap().port();
let target = SocketAddr::from((secondary_ipv4_loopback(), port));
let running = spawn(server);
let mut client = connected_client(target).await;
assert_started(&mut client, target).await;
let meta = echo_once(&mut client).await;
// A mapped listener is `AF_INET6` but emits IPv4, and the IPv6 Traffic
// Class option does not reach those packets — it leaves their TOS at
// zero. Only the IPv4 option marks them, so this asserts the listener
// was read as the IPv4 one it is.
if cfg!(target_os = "linux") {
assert_eq!(
meta.traffic_class,
Some(EF_TRAFFIC_CLASS),
"a mapped listener's reply still carries its session's marking"
);
assert_eq!(meta.dscp, Some(EF_DSCP));
}
assert!(matches!(
client.close().await.unwrap().as_slice(),
[ClientEvent::SessionClosed { .. }]
));
running.stop().await;
})
.await
.expect("the IPv4-mapped wildcard test exceeded its bounded runtime");
}
#[tokio::test(flavor = "current_thread")]
async fn a_wildcard_ipv6_listener_replies_from_the_requested_address() {
timeout(Duration::from_secs(5), async {
if !ipv6_loopback_available() {
eprintln!("skipping wildcard IPv6 test: IPv6 loopback unavailable");
return;
}
let server = match Server::bind("[::]:0".parse().unwrap(), unthrottled()).await {
Ok(server) => server,
Err(ServerRuntimeError::Bind { source, .. }) if is_family_unavailable(&source) => {
eprintln!("skipping wildcard IPv6 test: IPv6 unavailable");
return;
}
Err(error) => panic!("unexpected wildcard IPv6 bind failure: {error}"),
};
let port = server.local_addr().unwrap().port();
let target: SocketAddr = format!("[::1]:{port}").parse().unwrap();
let running = spawn(server);
// Loopback is one address, so this does not prove multi-homed IPv6. It
// does exercise the parts that differ from IPv4: the received packet
// info, the interface index carried with it, and the source-selected
// IPv6 send.
let mut client = connected_client(target).await;
assert_started(&mut client, target).await;
echo_once(&mut client).await;
assert!(matches!(
client.close().await.unwrap().as_slice(),
[ClientEvent::SessionClosed { .. }]
));
running.stop().await;
})
.await
.expect("the wildcard IPv6 source-selection test exceeded its bounded runtime");
}
/// A local IPv4 address that is not the primary loopback one, where the host
/// has one.
///
/// Bindability is the test: an address this process can bind is one the host
/// accepts datagrams for. `127.0.0.0/8` supplies a second local destination on
/// hosts that carry the whole range, without touching interface configuration.
fn secondary_ipv4_loopback() -> Ipv4Addr {
let candidate = Ipv4Addr::new(127, 0, 0, 2);
if UdpSocket::bind((candidate, 0)).is_ok() {
return candidate;
}
eprintln!("{candidate} is not a local address on this host; using 127.0.0.1 instead");
Ipv4Addr::LOCALHOST
}
fn ipv6_loopback_available() -> bool {
match UdpSocket::bind("[::1]:0") {
Ok(_) => true,
Err(error) if is_family_unavailable(&error) => false,
Err(error) => panic!("unexpected IPv6 loopback bind failure: {error}"),
}
}
fn is_family_unavailable(error: &io::Error) -> bool {
matches!(
error.kind(),
io::ErrorKind::AddrNotAvailable | io::ErrorKind::Unsupported
)
}
fn unthrottled() -> ServerConfig {
ServerConfig::default().with_min_send_interval(Duration::ZERO)
}
async fn connected_client(server_addr: SocketAddr) -> AsyncClient {
let config = ClientConfig {
server_addr: server_addr.to_string(),
duration: Some(Duration::from_secs(30)),
interval: Duration::from_millis(10),
length: 64,
dscp: EF_DSCP,
received_stats: ReceivedStats::Both,
stamp_at: StampAt::Both,
clock: Clock::Both,
open_timeouts: vec![Duration::from_millis(500)],
socket_config: SocketConfig {
recv_timeout: Some(Duration::from_millis(500)),
..SocketConfig::default()
},
probe_timeout: Duration::from_millis(500),
..ClientConfig::default()
};
AsyncClient::connect(config).await.unwrap()
}
async fn assert_started(client: &mut AsyncClient, server_addr: SocketAddr) {
match client.open().await.unwrap() {
OpenOutcome::Started { remote, token, .. } => {
assert_eq!(remote, server_addr);
assert_ne!(token, 0);
}
OpenOutcome::NoTestCompleted { .. } => panic!("a normal client unexpectedly ran no-test"),
}
}
/// Sends one echo and returns its reply's receive metadata.
async fn echo_once(client: &mut AsyncClient) -> PacketMeta {
client.send_probe().await.unwrap();
loop {
for event in client.recv().await.unwrap() {
if let ClientEvent::EchoReply {
seq, packet_meta, ..
} = event
{
assert_eq!(seq, 0);
return packet_meta;
}
}
}
}
struct Running {
shutdown: oneshot::Sender<()>,
task: JoinHandle<Result<(), ServerRuntimeError>>,
}
impl Running {
async fn stop(self) {
self.shutdown.send(()).unwrap();
self.task.await.unwrap().unwrap();
}
}
fn spawn(mut server: Server) -> Running {
let (shutdown, shutdown_rx) = oneshot::channel();
let task = tokio::spawn(async move {
server
.run(async {
let _ = shutdown_rx.await;
})
.await
});
Running { shutdown, task }
}