iroh_bench/
noq.rs

1use std::{
2    net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
3    sync::Arc,
4    time::{Duration, Instant},
5};
6
7use bytes::Bytes;
8use n0_error::{Result, StdResultExt};
9use noq::{
10    Connection, Endpoint, RecvStream, SendStream, TransportConfig, crypto::rustls::QuicClientConfig,
11};
12use rustls::{
13    RootCertStore,
14    pki_types::{CertificateDer, PrivateKeyDer},
15};
16use tracing::{trace, warn};
17
18use crate::{
19    ClientStats, ConnectionSelector, EndpointSelector, Opt, client_handler, stats::TransferResult,
20};
21
22pub const ALPN: &[u8] = b"n0/noq-bench/0";
23
24/// Creates a server endpoint which runs on the given runtime
25pub fn server_endpoint(
26    rt: &tokio::runtime::Runtime,
27    cert: CertificateDer<'static>,
28    key: PrivateKeyDer<'static>,
29    opt: &Opt,
30) -> (SocketAddr, noq::Endpoint) {
31    let cert_chain = vec![cert];
32    let mut server_config = noq::ServerConfig::with_single_cert(cert_chain, key).unwrap();
33    server_config.transport = Arc::new(transport_config(opt.max_streams, opt.initial_mtu));
34
35    let addr = if opt.use_ipv6 {
36        IpAddr::V6(Ipv6Addr::LOCALHOST)
37    } else {
38        IpAddr::V4(Ipv4Addr::LOCALHOST)
39    };
40
41    let endpoint = {
42        let _guard = rt.enter();
43        noq::Endpoint::server(server_config, SocketAddr::new(addr, 0)).unwrap()
44    };
45    let server_addr = endpoint.local_addr().unwrap();
46    (server_addr, endpoint)
47}
48
49/// Create and run a client
50pub async fn client(
51    server_addr: SocketAddr,
52    server_cert: CertificateDer<'static>,
53    opt: Opt,
54) -> Result<ClientStats> {
55    let client_start = std::time::Instant::now();
56    let (endpoint, connection) = connect_client(server_addr, server_cert, opt).await?;
57    let client_connect_time = client_start.elapsed();
58    let mut res = client_handler(
59        EndpointSelector::Noq(endpoint),
60        ConnectionSelector::Noq(connection),
61        opt,
62    )
63    .await?;
64    res.connect_time = client_connect_time;
65    Ok(res)
66}
67
68/// Create a client endpoint and client connection
69pub async fn connect_client(
70    server_addr: SocketAddr,
71    server_cert: CertificateDer<'_>,
72    opt: Opt,
73) -> Result<(::noq::Endpoint, Connection)> {
74    let addr = if opt.use_ipv6 {
75        IpAddr::V6(Ipv6Addr::LOCALHOST)
76    } else {
77        IpAddr::V4(Ipv4Addr::LOCALHOST)
78    };
79
80    let endpoint = noq::Endpoint::client(SocketAddr::new(addr, 0)).unwrap();
81
82    let mut roots = RootCertStore::empty();
83    roots.add(server_cert).anyerr()?;
84
85    let provider = rustls::crypto::ring::default_provider();
86
87    let crypto = rustls::ClientConfig::builder_with_provider(provider.into())
88        .with_protocol_versions(&[&rustls::version::TLS13])
89        .unwrap()
90        .with_root_certificates(roots)
91        .with_no_client_auth();
92
93    let mut client_config =
94        noq::ClientConfig::new(Arc::new(QuicClientConfig::try_from(crypto).anyerr()?));
95    client_config.transport_config(Arc::new(transport_config(opt.max_streams, opt.initial_mtu)));
96
97    let connection = endpoint
98        .connect_with(client_config, server_addr, "localhost")
99        .unwrap()
100        .await
101        .std_context("unable to connect")?;
102    trace!("connected");
103
104    Ok((endpoint, connection))
105}
106
107pub fn transport_config(max_streams: usize, initial_mtu: u16) -> TransportConfig {
108    // High stream windows are chosen because the amount of concurrent streams
109    // is configurable as a parameter.
110    let mut config = TransportConfig::default();
111    config.max_concurrent_uni_streams(max_streams.try_into().unwrap());
112    config.initial_mtu(initial_mtu);
113    config.max_concurrent_multipath_paths(16);
114
115    let mut acks = noq::AckFrequencyConfig::default();
116    acks.ack_eliciting_threshold(10u32.into());
117    config.ack_frequency_config(Some(acks));
118
119    #[cfg(feature = "qlog")]
120    config.qlog_from_env("bench-iroh");
121
122    config
123}
124
125async fn drain_stream(
126    mut stream: RecvStream,
127    read_unordered: bool,
128) -> Result<(usize, Duration, u64)> {
129    let mut read = 0;
130
131    let download_start = Instant::now();
132    let mut first_byte = true;
133    let mut ttfb = download_start.elapsed();
134
135    let mut num_chunks: u64 = 0;
136
137    if read_unordered {
138        let mut stream = stream.into_unordered();
139        while let Some(chunk) = stream.read_chunk(usize::MAX).await.anyerr()? {
140            if first_byte {
141                ttfb = download_start.elapsed();
142                first_byte = false;
143            }
144            read += chunk.bytes.len();
145            num_chunks += 1;
146        }
147    } else {
148        // These are 32 buffers, for reading approximately 32kB at once
149        #[rustfmt::skip]
150        let mut bufs = [
151            Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(),
152            Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(),
153            Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(),
154            Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(),
155            Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(),
156            Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(),
157            Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(),
158            Bytes::new(), Bytes::new(), Bytes::new(), Bytes::new(),
159        ];
160
161        while let Some(n) = stream.read_many_chunks(&mut bufs[..]).await.anyerr()? {
162            if first_byte {
163                ttfb = download_start.elapsed();
164                first_byte = false;
165            }
166            read += bufs.iter().take(n).map(|buf| buf.len()).sum::<usize>();
167            num_chunks += 1;
168        }
169    }
170
171    Ok((read, ttfb, num_chunks))
172}
173
174async fn send_data_on_stream(stream: &mut SendStream, stream_size: u64) -> Result<()> {
175    const DATA: &[u8] = &[0xAB; 1024 * 1024];
176    let bytes_data = Bytes::from_static(DATA);
177
178    let full_chunks = stream_size / (DATA.len() as u64);
179    let remaining = (stream_size % (DATA.len() as u64)) as usize;
180
181    for _ in 0..full_chunks {
182        stream
183            .write_chunk(bytes_data.clone())
184            .await
185            .std_context("failed sending data")?;
186    }
187
188    if remaining != 0 {
189        stream
190            .write_chunk(bytes_data.slice(0..remaining))
191            .await
192            .std_context("failed sending data")?;
193    }
194
195    stream.finish().std_context("failed finishing stream")?;
196    stream
197        .stopped()
198        .await
199        .std_context("failed to wait for stream to be stopped")?;
200
201    Ok(())
202}
203
204pub async fn handle_client_stream(
205    connection: &Connection,
206    upload_size: u64,
207    read_unordered: bool,
208) -> Result<(TransferResult, TransferResult)> {
209    let start = Instant::now();
210
211    let (mut send_stream, recv_stream) = connection
212        .open_bi()
213        .await
214        .std_context("failed to open stream")?;
215
216    send_data_on_stream(&mut send_stream, upload_size).await?;
217
218    let upload_result = TransferResult::new(start.elapsed(), upload_size, Duration::default(), 0);
219
220    let start = Instant::now();
221    let (size, ttfb, num_chunks) = drain_stream(recv_stream, read_unordered).await?;
222    let download_result = TransferResult::new(start.elapsed(), size as u64, ttfb, num_chunks);
223
224    Ok((upload_result, download_result))
225}
226
227/// Take the provided endpoint and run the server
228pub async fn server(endpoint: Endpoint, opt: Opt) -> Result<()> {
229    let mut server_tasks = Vec::new();
230
231    // Handle only the expected amount of clients
232    for _ in 0..opt.clients {
233        let incoming = endpoint.accept().await.unwrap();
234        let accepting = match incoming.accept() {
235            Ok(accepting) => accepting,
236            Err(err) => {
237                warn!("incoming connection failed: {err:#}");
238                // we can carry on in these cases:
239                // this can be caused by retransmitted datagrams
240                continue;
241            }
242        };
243        let connection = accepting.await.std_context("handshake failed")?;
244
245        server_tasks.push(tokio::spawn(async move {
246            loop {
247                let (mut send_stream, recv_stream) = match connection.accept_bi().await {
248                    Err(::noq::ConnectionError::ApplicationClosed(_)) => break,
249                    Err(e) => {
250                        eprintln!("accepting stream failed: {e:?}");
251                        break;
252                    }
253                    Ok(stream) => stream,
254                };
255                trace!("stream established");
256
257                tokio::spawn(async move {
258                    drain_stream(recv_stream, opt.read_unordered).await?;
259                    send_data_on_stream(&mut send_stream, opt.download_size).await?;
260                    n0_error::Ok(())
261                });
262            }
263
264            if opt.stats {
265                println!("\nServer connection stats:\n{:#?}", connection.stats());
266            }
267        }));
268    }
269
270    // Await all the tasks. We have to do this to prevent the runtime getting dropped
271    // and all server tasks to be cancelled
272    for handle in server_tasks {
273        if let Err(e) = handle.await {
274            eprintln!("Server task error: {e:?}");
275        };
276    }
277
278    Ok(())
279}