Files
shenandshen b656c1896a fix: improve SDK UDP throughput and transport selection
Yield during UDP receive bursts to let session consumers drain bounded queues. Prioritize measured RTT over protocol preference and enlarge user-space subnet TCP buffers with validated limits.

Add packet-level throughput diagnostics, transport selection coverage, and investigation records. SDK regression suite: 21 tests passed; local delay and throughput experiments documented.
2026-10-15 23:53:10 -07:00

227 lines
7.8 KiB
Rust

//! Native TCP-stack isolation over lossless channels or loopback UDP.
//! Includes the production wrapper so reactor/socket behavior stays identical.
#![allow(dead_code, unused_imports)]
mod foundation {
pub mod time {
pub use tokio::time::{Instant, sleep};
}
}
#[path = "../../../vendor/easytier/easytier-core/src/gateway/smoltcp/tokio_smoltcp/mod.rs"]
mod stack;
use smoltcp::{
phy::{DeviceCapabilities, Medium},
wire::{HardwareAddress, Ipv4Packet, TcpPacket},
};
use stack::{BufferSize, Net, NetConfig, channel_device::ChannelDevice};
use std::{
collections::{HashSet, VecDeque},
sync::{Arc, Mutex},
time::Duration,
};
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
sync::mpsc,
time::{Instant, timeout},
};
#[path = "support/wire_stats.rs"]
mod wire_stats;
use wire_stats::WireStats;
fn net(
ip: &str,
mtu: usize,
tx_kib: usize,
) -> (
Net,
mpsc::Sender<std::io::Result<Vec<u8>>>,
mpsc::Receiver<Vec<u8>>,
) {
let mut caps = DeviceCapabilities::default();
caps.medium = Medium::Ip;
caps.max_transmission_unit = mtu;
let (device, input, output) = ChannelDevice::new(caps);
let config = NetConfig::new(
smoltcp::iface::Config::new(HardwareAddress::Ip),
format!("{ip}/24").parse().unwrap(),
vec![],
Some(BufferSize {
tcp_rx_size: 1024 * 1024,
tcp_tx_size: tx_kib * 1024,
..Default::default()
}),
);
(Net::new(device, config), input, output)
}
async fn link(
mut output: mpsc::Receiver<Vec<u8>>,
input: mpsc::Sender<std::io::Result<Vec<u8>>>,
delay: Duration,
stats: Arc<Mutex<WireStats>>,
) {
let mut pending = VecDeque::new();
loop {
let deadline = pending
.front()
.map(|(at, _): &(Instant, Vec<u8>)| *at)
.unwrap_or_else(|| Instant::now() + Duration::from_secs(3600));
tokio::select! {
packet = output.recv() => {
let Some(packet) = packet else { return; };
stats.lock().unwrap().record(&packet);
pending.push_back((Instant::now() + delay, packet));
}
_ = tokio::time::sleep_until(deadline), if !pending.is_empty() => {
let (_, packet) = pending.pop_front().unwrap();
if input.send(Ok(packet)).await.is_err() { return; }
stats.lock().unwrap().received_packets += 1;
}
}
}
}
async fn udp_link(
mut output: mpsc::Receiver<Vec<u8>>,
input: mpsc::Sender<std::io::Result<Vec<u8>>>,
delay: Duration,
stats: Arc<Mutex<WireStats>>,
) {
let receiver = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
let destination = receiver.local_addr().unwrap();
let sender = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
let sender_stats = stats.clone();
let _sender = tokio_util::task::AbortOnDropHandle::new(tokio::spawn(async move {
while let Some(packet) = output.recv().await {
sender_stats.lock().unwrap().record(&packet);
assert_eq!(
sender.send_to(&packet, destination).await.unwrap(),
packet.len()
);
}
}));
let mut packet = vec![0u8; 65536];
let mut pending = VecDeque::new();
loop {
let deadline = pending
.front()
.map(|(at, _): &(Instant, Vec<u8>)| *at)
.unwrap_or_else(|| Instant::now() + Duration::from_secs(3600));
tokio::select! {
result = receiver.recv(&mut packet) => {
let len = result.unwrap();
stats.lock().unwrap().received_packets += 1;
pending.push_back((Instant::now()+delay,packet[..len].to_vec()));
}
_ = tokio::time::sleep_until(deadline), if !pending.is_empty() => {
let (_, packet) = pending.pop_front().unwrap();
if input.send(Ok(packet)).await.is_err() { return; }
}
}
}
}
async fn pipe(
udp: bool,
output: mpsc::Receiver<Vec<u8>>,
input: mpsc::Sender<std::io::Result<Vec<u8>>>,
delay: Duration,
stats: Arc<Mutex<WireStats>>,
) {
if udp {
udp_link(output, input, delay, stats).await;
} else {
link(output, input, delay, stats).await;
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[ignore = "manual TCP stack diagnostic; run release --ignored --nocapture"]
async fn sdk_tcp_stack_diagnostic() {
let mib = std::env::var("MESHPORT_TEST_MIB")
.map(|v| v.parse::<usize>().unwrap())
.unwrap_or(2);
assert!((1..=64).contains(&mib));
let delay_ms = std::env::var("MESHPORT_TEST_DELAY_MS")
.map(|v| v.parse::<u64>().unwrap())
.unwrap_or(29);
let mtu = std::env::var("MESHPORT_TEST_MTU")
.map(|v| v.parse::<usize>().unwrap())
.unwrap_or(1284);
assert!((576..=1500).contains(&mtu));
let tx_kib = std::env::var("MESHPORT_TEST_TX_KIB")
.map(|v| v.parse::<usize>().unwrap())
.unwrap_or(512);
assert!((16..=1024).contains(&tx_kib));
let mode = std::env::var("MESHPORT_TEST_LINK").unwrap_or_else(|_| "channel".to_owned());
assert!(matches!(mode.as_str(), "channel" | "udp"));
let udp = mode == "udp";
for download in [true, false] {
let (client, client_in, client_out) = net("10.254.90.1", mtu, tx_kib);
let (server, server_in, server_out) = net("10.254.90.2", mtu, tx_kib);
let client_stats = Arc::new(Mutex::new(WireStats::default()));
let server_stats = Arc::new(Mutex::new(WireStats::default()));
let ctask = tokio::spawn(pipe(
udp,
client_out,
server_in,
Duration::from_millis(delay_ms),
client_stats.clone(),
));
let stask = tokio::spawn(pipe(
udp,
server_out,
client_in,
Duration::from_millis(delay_ms),
server_stats.clone(),
));
let mut listener = server
.tcp_bind("10.254.90.2:9000".parse().unwrap())
.await
.unwrap();
let bytes = mib * 1024 * 1024;
let payload = vec![0x5a; bytes];
let transfer = async {
let (connection, accepted) = tokio::join!(
client.tcp_connect("10.254.90.2:9000".parse().unwrap(), 40000),
listener.accept()
);
let mut c = connection.unwrap();
let (mut s, _) = accepted.unwrap();
let start = Instant::now();
if download {
let (sent, _) = tokio::join!(s.write_all(&payload), async {
let mut b = vec![0; bytes];
c.read_exact(&mut b).await.unwrap();
assert_eq!(b, payload);
});
sent.unwrap();
} else {
let (sent, _) = tokio::join!(c.write_all(&payload), async {
let mut b = vec![0; bytes];
s.read_exact(&mut b).await.unwrap();
assert_eq!(b, payload);
});
sent.unwrap();
}
let elapsed = start.elapsed();
tokio::time::sleep(Duration::from_millis(delay_ms * 2 + 100)).await;
println!(
"{}",
serde_json::json!({"mode":mode,"tx_kib":tx_kib,"added_rtt_ms":delay_ms*2,"mtu":mtu,"mib":mib,
"direction":if download {"download"} else {"upload"},"mbps":bytes as f64*8.0/elapsed.as_secs_f64()/1e6,
"client_wire":client_stats.lock().unwrap().json(),"server_wire":server_stats.lock().unwrap().json()})
);
};
let result = timeout(Duration::from_secs(90), transfer).await;
ctask.abort();
stask.abort();
let _ = ctask.await;
let _ = stask.await;
result.unwrap();
}
}