Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,25 @@ long-term supported release series.

## Unreleased

- A TCP download through TUN that arrives one segment at a time no longer
pays the whole chain of wake-ups, from the remote socket to the TUN
descriptor, for every segment. On the `LowMemory`, `Mobile` and
`MobilePlus` profiles the read of a flow's remote that follows a read below
8 KiB waits 1 ms, so that it takes several segments at once. It waits only
in a one-way stream (nothing uploaded since the previous read) whose reads
are at most 5 ms apart and that has run so for 25 ms: a request/response
exchange, a response that arrives within 25 ms and a stream whose reads
already carry several segments are read as before, and so is everything on
`Desktop` and `Throughput`. On macOS (M4 Pro, Freedom, one flow, `Mobile`,
medians of five runs) the engine's CPU per GiB falls from 16.3 s to 8.6 s
at 6 MiB/s, from 13.3 s to 4.2 s at 50 MiB/s and from 7.2 s to 2.7 s at
200 MiB/s when the segments arrive singly, and from 7.0 s to 5.8 s at
6 MiB/s when they arrive four at a time. Throughput is unchanged at every
rate, as are the unpaced download, a download at 1 MiB/s and the latency of
a 1 KiB and of a 64 KiB echo; the peak footprint is 0.5 MiB higher at
50 MiB/s. Not measured on a device yet. `xray-bench protocol-run` takes
`origin_rate_kib_s` and `origin_burst_bytes` for a TUN download, which pace
its origin to stand in for a link slower than the engine.
- The DNS resolver and the system SRV/TXT lookups refuse a name longer than
255 octets, the limit Xray-core's DNS client applies through Go's
`dnsmessage`. A name was read for up to 32 labels and pointers, about 2 KB,
Expand Down
107 changes: 104 additions & 3 deletions crates/xray-bench/src/protocol_bench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,14 @@ struct Request {
client_preface: bool,
#[serde(default)]
client_env: std::collections::BTreeMap<String, String>,
/// Average rate, in KiB/s, at which the origin of a TUN download writes.
/// Stands in for a link slower than the engine; absent means unpaced.
#[serde(default)]
origin_rate_kib_s: Option<u32>,
/// Bytes the paced origin writes at once: how many arrive together at
/// the engine's remote socket. Defaults to one 1448-byte segment.
#[serde(default)]
origin_burst_bytes: Option<usize>,
}

#[derive(Deserialize)]
Expand Down Expand Up @@ -58,6 +66,17 @@ fn io_error(source: io::Error) -> BenchError {
}
}

/// One MSS of a 1500-byte IPv4 path with TCP timestamps.
const DEFAULT_ORIGIN_BURST_BYTES: usize = 1448;

fn origin_pace(r: &Request) -> Option<stream_transport::OriginPace> {
r.origin_rate_kib_s
.map(|rate| stream_transport::OriginPace {
bytes_per_second: u64::from(rate) * 1024,
burst_bytes: r.origin_burst_bytes.unwrap_or(DEFAULT_ORIGIN_BURST_BYTES),
})
}

fn validate(r: &Request) -> Result<(), BenchError> {
if !matches!(r.path.as_str(), "socks" | "tun")
|| !matches!(
Expand All @@ -74,6 +93,13 @@ fn validate(r: &Request) -> Result<(), BenchError> {
|| (r.path == "tun" && (r.prepare_client || r.warmup))
|| (r.client_preface
&& (r.path != "socks" || matches!(r.traffic.as_str(), "tcp-latency" | "udp")))
|| ((r.origin_rate_kib_s.is_some() || r.origin_burst_bytes.is_some())
&& (r.path != "tun" || r.traffic != "download"))
|| (r.origin_burst_bytes.is_some() && r.origin_rate_kib_s.is_none())
|| r.origin_rate_kib_s
.is_some_and(|rate| !(1..=1024 * 1024).contains(&rate))
|| r.origin_burst_bytes
.is_some_and(|burst| !(1..=65536).contains(&burst))
{
return Err(invalid("invalid bounded protocol benchmark request"));
}
Expand Down Expand Up @@ -242,7 +268,13 @@ pub async fn run(args: Vec<String>) -> Result<(), BenchError> {
run_tcp_freedom_workload_on(socks, &options, local_non_loopback_ipv4()?).await?
}
(Some(fd), traffic) => {
run_tun_bulk(fd.raw(), &options, StreamBenchTraffic::parse(traffic)?).await?
run_tun_bulk(
fd.raw(),
&options,
StreamBenchTraffic::parse(traffic)?,
origin_pace(&r),
)
.await?
}
(None, traffic) => {
stream_transport::run_workload_with_preface_on(
Expand Down Expand Up @@ -309,6 +341,8 @@ pub async fn run(args: Vec<String>) -> Result<(), BenchError> {
"client_cpu_total_millis":samples.last().unwrap().cpu_millis,
"engine_binary":prepared.binary,"engine_sha256":engine_sha256,
"client_env":r.client_env,
"origin_rate_kib_s":r.origin_rate_kib_s,
"origin_burst_bytes":origin_pace(&r).map(|pace| pace.burst_bytes),
"tun_fd_buffers":link_buffers,
"latency_us":if matches!(r.traffic.as_str(), "udp" | "tcp-latency") {summarize_latency_us(outcome.latencies_us.clone())} else {None},
"ready_latency_us":if r.path=="tun" && !matches!(r.traffic.as_str(), "udp" | "tcp-latency") {summarize_latency_us(outcome.latencies_us)} else {None},
Expand Down Expand Up @@ -534,6 +568,7 @@ async fn run_tun_bulk(
fd: RawFd,
options: &BenchOptions,
traffic: StreamBenchTraffic,
origin_pace: Option<stream_transport::OriginPace>,
) -> Result<WorkloadOutcome, BenchError> {
let listener = TcpListener::bind((local_non_loopback_ipv4()?, 0))
.await
Expand All @@ -544,8 +579,28 @@ async fn run_tun_bulk(
let iterations = options.iterations;
let count = options.connections;
let server = tokio::spawn(async move {
stream_transport::run_target_server(listener, traffic, server_template, iterations, count)
.await
match origin_pace {
Some(pace) => {
stream_transport::run_paced_download_server(
listener,
server_template,
iterations,
count,
pace,
)
.await
}
None => {
stream_transport::run_target_server(
listener,
traffic,
server_template,
iterations,
count,
)
.await
}
}
});
// Abort the local fixture on error/timeout; its JoinSet cancels child flows.
struct Abort(tokio::task::AbortHandle);
Expand Down Expand Up @@ -748,6 +803,8 @@ mod tests {
warmup: false,
client_preface: false,
client_env: Default::default(),
origin_rate_kib_s: None,
origin_burst_bytes: None,
};
assert!(validate(&r).is_ok());
r.warmup = true;
Expand Down Expand Up @@ -778,6 +835,50 @@ mod tests {
assert!(validate(&r).is_err());
}

#[test]
fn origin_pace_is_bounded_and_only_for_tun_downloads() {
let mut r: Request = serde_json::from_value(json!({
"binary":"engine", "config":{}, "path":"tun", "traffic":"download",
"connections":1, "iterations":1, "payload_size":1024, "output":"result",
"origin_rate_kib_s":6144
}))
.unwrap();
assert!(validate(&r).is_ok());
let pace = origin_pace(&r).unwrap();
assert_eq!(pace.bytes_per_second, 6144 * 1024);
assert_eq!(pace.burst_bytes, DEFAULT_ORIGIN_BURST_BYTES);

r.origin_burst_bytes = Some(4 * 1448);
assert!(validate(&r).is_ok());
assert_eq!(origin_pace(&r).unwrap().burst_bytes, 4 * 1448);
r.origin_burst_bytes = Some(0);
assert!(validate(&r).is_err());
r.origin_burst_bytes = Some(65537);
assert!(validate(&r).is_err());
r.origin_burst_bytes = None;

r.origin_rate_kib_s = Some(0);
assert!(validate(&r).is_err());
r.origin_rate_kib_s = Some(1024 * 1024 + 1);
assert!(validate(&r).is_err());
r.origin_rate_kib_s = Some(6144);

r.traffic = "upload".into();
assert!(validate(&r).is_err());
r.traffic = "download".into();
r.path = "socks".into();
assert!(validate(&r).is_err());
r.path = "tun".into();

// A burst size without a rate paces nothing.
r.origin_rate_kib_s = None;
r.origin_burst_bytes = Some(1448);
assert!(validate(&r).is_err());
r.origin_burst_bytes = None;
assert!(validate(&r).is_ok());
assert!(origin_pace(&r).is_none());
}

#[test]
fn old_requests_keep_cold_direct_launch_defaults() {
let r: Request = serde_json::from_value(json!({
Expand Down
140 changes: 140 additions & 0 deletions crates/xray-bench/src/stream_transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -629,6 +629,98 @@ pub(super) async fn run_target_server(
.await
}

/// How a download origin spaces its writes to stand in for a link slower
/// than the engine: `burst_bytes` at a time, `bytes_per_second` on average.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct OriginPace {
pub(super) bytes_per_second: u64,
pub(super) burst_bytes: usize,
}

/// A download-only target whose flows write at `pace`. `TCP_NODELAY` keeps
/// every burst a separate arrival at the engine's remote socket.
pub(super) async fn run_paced_download_server(
listener: TcpListener,
template: Arc<Vec<u8>>,
iterations: usize,
connections: usize,
pace: OriginPace,
) -> Result<(), BenchError> {
let io_error = |action: &'static str| {
move |source| BenchError::Io {
action: action.to_owned(),
source,
}
};
let mut workers = JoinSet::new();
for _ in 0..connections {
let (mut stream, _) = listener
.accept()
.await
.map_err(io_error("accepting paced download connection"))?;
let template = Arc::clone(&template);
workers.spawn(async move {
stream
.set_nodelay(true)
.map_err(io_error("disabling Nagle on paced download"))?;
stream
.write_all(&[READY_BYTE])
.await
.map_err(io_error("writing paced download ready marker"))?;
write_pattern_paced(&mut stream, &template, iterations, pace)
.await
.map_err(io_error("writing paced benchmark download"))
});
}
while let Some(result) = workers.join_next().await {
result.map_err(|error| {
BenchError::InvalidArguments(format!("paced download flow failed: {error}"))
})??;
}
Ok(())
}

async fn write_pattern_paced<W>(
writer: &mut W,
template: &[u8],
iterations: usize,
pace: OriginPace,
) -> std::io::Result<()>
where
W: AsyncWrite + Unpin,
{
const TIMER_GRANULARITY: std::time::Duration = std::time::Duration::from_millis(1);
let total = template.len() * iterations;
let started = Instant::now();
let mut sent = 0_usize;
while sent < total {
let offset = sent % template.len();
let end = template
.len()
.min(offset + pace.burst_bytes)
.min(offset + total - sent);
writer.write_all(&template[offset..end]).await?;
sent += end - offset;
let due = started
+ std::time::Duration::from_secs_f64(sent as f64 / pace.bytes_per_second as f64);
loop {
let left = due.saturating_duration_since(Instant::now());
if left.is_zero() {
break;
}
// Tokio timers tick once a millisecond, and bursts of a few
// megabytes per second are closer together than that: sleep
// through whole ticks and yield through the rest.
if left > 2 * TIMER_GRANULARITY {
tokio::time::sleep(left - TIMER_GRANULARITY).await;
} else {
tokio::task::yield_now().await;
}
}
}
Ok(())
}

async fn run_target_server_with_preface(
listener: TcpListener,
traffic: StreamBenchTraffic,
Expand Down Expand Up @@ -1543,6 +1635,54 @@ mod tests {
.unwrap();
}

#[tokio::test]
async fn paced_download_keeps_the_rate_and_the_burst_size() {
let template = Arc::new((0..=255_u8).collect::<Vec<_>>());
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
let addr = listener.local_addr().unwrap();
// 4 KiB at 64 KiB/s in 256-byte bursts: 16 bursts over 62.5 ms.
let pace = OriginPace {
bytes_per_second: 64 * 1024,
burst_bytes: 256,
};
let server = tokio::spawn(run_paced_download_server(
listener,
Arc::clone(&template),
16,
1,
pace,
));
let mut client = TcpStream::connect(addr).await.unwrap();
let started = Instant::now();
let mut ready = [0];
client.read_exact(&mut ready).await.unwrap();
assert_eq!(ready[0], READY_BYTE);

let mut received = Vec::new();
let mut largest_read = 0;
let mut buffer = [0; 4096];
while received.len() < 16 * template.len() {
let read = client.read(&mut buffer).await.unwrap();
assert_ne!(read, 0, "paced download closed early");
largest_read = largest_read.max(read);
received.extend_from_slice(&buffer[..read]);
}
let elapsed = started.elapsed();
server.await.unwrap().unwrap();

assert!(received
.chunks(template.len())
.all(|chunk| chunk == &template[..]));
// The last burst is due 15/16 of the way through the nominal time.
assert!(
elapsed >= std::time::Duration::from_millis(55),
"{elapsed:?}"
);
assert!(elapsed < std::time::Duration::from_secs(2), "{elapsed:?}");
// A reader that keeps up sees separate bursts, not one stream.
assert!(largest_read < received.len(), "{largest_read}");
}

#[tokio::test]
async fn packet_up_replays_one_acknowledged_payload_per_iteration() {
let template = b"packet";
Expand Down
Loading
Loading