iroh_bench/
iroh.rs

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