iroh_bench/
lib.rs

1use std::{
2    num::ParseIntError,
3    str::FromStr,
4    sync::{Arc, Mutex},
5    time::Instant,
6};
7
8use clap::Parser;
9use n0_error::Result;
10use stats::Stats;
11use tokio::{
12    runtime::{Builder, Runtime},
13    sync::Semaphore,
14};
15use tracing::info;
16
17pub mod iroh;
18#[cfg(not(any(target_os = "freebsd", target_os = "openbsd", target_os = "netbsd")))]
19pub mod noq;
20pub mod s2n;
21pub mod stats;
22
23#[derive(Parser, Debug, Clone, Copy)]
24#[clap(name = "iroh-bench")]
25pub enum Commands {
26    Iroh(Opt),
27    #[cfg(not(any(target_os = "freebsd", target_os = "openbsd", target_os = "netbsd")))]
28    Noq(Opt),
29    S2n(s2n::Opt),
30}
31
32#[derive(Parser, Debug, Clone, Copy)]
33#[clap(name = "options")]
34pub struct Opt {
35    /// The total number of clients which should be created
36    #[clap(long = "clients", short = 'c', default_value = "1")]
37    pub clients: usize,
38    /// The total number of streams which should be created
39    #[clap(long = "streams", short = 'n', default_value = "1")]
40    pub streams: usize,
41    /// The amount of concurrent streams which should be used
42    #[clap(long = "max_streams", short = 'm', default_value = "1")]
43    pub max_streams: usize,
44    /// Number of bytes to transmit from server to client
45    ///
46    /// This can use SI prefixes for sizes. E.g. 1M will transfer 1MiB, 10G
47    /// will transfer 10GiB.
48    #[clap(long, default_value = "1G", value_parser = parse_byte_size)]
49    pub download_size: u64,
50    /// Number of bytes to transmit from client to server
51    ///
52    /// This can use SI prefixes for sizes. E.g. 1M will transfer 1MiB, 10G
53    /// will transfer 10GiB.
54    #[clap(long, default_value = "0", value_parser = parse_byte_size)]
55    pub upload_size: u64,
56    /// Show connection stats the at the end of the benchmark
57    #[clap(long = "stats")]
58    pub stats: bool,
59    /// Show iroh library counter metrics at the end of the benchmark
60    ///
61    /// These metrics are process-wide, so contain metrics for
62    /// clients and the server all summed up.
63    #[clap(long)]
64    pub metrics: bool,
65    /// Whether to use the unordered read API
66    #[clap(long = "unordered")]
67    pub read_unordered: bool,
68    /// Starting guess for maximum UDP payload size
69    #[clap(long, default_value = "1200")]
70    pub initial_mtu: u16,
71    /// Whether to run a local relay and have the server and clients connect to that.
72    /// This will force all traffic over the relay and can be used to test
73    /// throughput for relay-only traffic.
74    #[cfg(feature = "local-relay")]
75    #[clap(long, default_value_t = false)]
76    pub only_relay: bool,
77    #[clap(long, default_value_t = false)]
78    pub use_ipv6: bool,
79
80    /// How many tokio worker threads to use for each endpoint in the benchmark.
81    ///
82    /// Defaults to 1, a single-threaded runtime.
83    /// Set this to 0 to have each endpoint use a full multi-threaded tokio runtime with as many
84    /// workers as CPU parallelism detected.
85    ///
86    /// Setting this to 2 is a very reasonable value.
87    /// When quinn runs a single connection, it can run one task (the EndpointDriver) for all
88    /// receive-based work, and one task (the ConnectionDriver) for all send-based tasks.
89    /// If quinn is only given a single worker, then work distribution may be unfair, resulting
90    /// in acknowledgements not being processed timely enough, causing congestion control issues,
91    /// although ideally that problem is fixed in some other way in quinn.
92    #[clap(long, default_value_t = 1)]
93    pub workers_per_ep: usize,
94}
95
96#[derive(Debug)]
97pub enum EndpointSelector {
98    Iroh(::iroh::Endpoint),
99    #[cfg(not(any(target_os = "freebsd", target_os = "openbsd", target_os = "netbsd")))]
100    Noq(::noq::Endpoint),
101}
102
103impl EndpointSelector {
104    pub async fn close(self) {
105        match self {
106            EndpointSelector::Iroh(endpoint) => {
107                endpoint.close().await;
108            }
109            #[cfg(not(any(target_os = "freebsd", target_os = "openbsd", target_os = "netbsd")))]
110            EndpointSelector::Noq(endpoint) => {
111                endpoint.close(0u32.into(), b"");
112                endpoint.wait_idle().await;
113            }
114        }
115    }
116}
117
118#[derive(Debug)]
119pub enum ConnectionSelector {
120    Iroh(::iroh::endpoint::Connection),
121    #[cfg(not(any(target_os = "freebsd", target_os = "openbsd", target_os = "netbsd")))]
122    Noq(::noq::Connection),
123}
124
125impl ConnectionSelector {
126    pub fn stats(&self) {
127        match self {
128            ConnectionSelector::Iroh(connection) => {
129                println!("{:#?}", connection.stats());
130            }
131            #[cfg(not(any(target_os = "freebsd", target_os = "openbsd", target_os = "netbsd")))]
132            ConnectionSelector::Noq(connection) => {
133                println!("{:#?}", connection.stats());
134            }
135        }
136    }
137
138    pub fn close(&self, error_code: u32, reason: &[u8]) {
139        match self {
140            ConnectionSelector::Iroh(connection) => {
141                connection.close(error_code.into(), reason);
142            }
143            #[cfg(not(any(target_os = "freebsd", target_os = "openbsd", target_os = "netbsd")))]
144            ConnectionSelector::Noq(connection) => {
145                connection.close(error_code.into(), reason);
146            }
147        }
148    }
149}
150
151pub fn configure_tracing_subscriber() {
152    tracing::subscriber::set_global_default(
153        tracing_subscriber::FmtSubscriber::builder()
154            .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
155            .finish(),
156    )
157    .unwrap();
158}
159
160pub fn rt(workers: usize) -> Runtime {
161    let mut builder = match workers {
162        // 0 means "use as many threads as detected CPU parallelism" implicitly.
163        0 => Builder::new_multi_thread(),
164        1 => Builder::new_current_thread(),
165        workers => {
166            let mut b = Builder::new_multi_thread();
167            b.worker_threads(workers);
168            b
169        }
170    };
171    builder.enable_all().build().unwrap()
172}
173
174fn parse_byte_size(s: &str) -> Result<u64, ParseIntError> {
175    let s = s.trim();
176
177    let multiplier = match s.chars().last() {
178        Some('T') => 1024 * 1024 * 1024 * 1024,
179        Some('G') => 1024 * 1024 * 1024,
180        Some('M') => 1024 * 1024,
181        Some('k') => 1024,
182        _ => 1,
183    };
184
185    let s = if multiplier != 1 {
186        &s[..s.len() - 1]
187    } else {
188        s
189    };
190
191    let base: u64 = u64::from_str(s)?;
192
193    Ok(base * multiplier)
194}
195
196#[derive(Debug, Default)]
197pub struct ClientStats {
198    upload_stats: Stats,
199    download_stats: Stats,
200    connect_time: std::time::Duration,
201}
202
203impl ClientStats {
204    pub fn print(&self, client_id: usize) {
205        println!();
206        println!("Client {client_id} stats:");
207
208        let ct = self.connect_time.as_nanos() as f64 / 1_000_000.0;
209        println!("Connect time: {ct}ms");
210
211        if self.upload_stats.total_size != 0 {
212            self.upload_stats.print("upload");
213        }
214
215        if self.download_stats.total_size != 0 {
216            self.download_stats.print("download");
217        }
218    }
219}
220
221/// Take the provided endpoint and run the client benchmark
222pub async fn client_handler(
223    endpoint: EndpointSelector,
224    connection: ConnectionSelector,
225    opt: Opt,
226) -> Result<ClientStats> {
227    let start = Instant::now();
228
229    let connection = Arc::new(connection);
230
231    let mut stats = ClientStats::default();
232    let mut first_error = None;
233
234    let sem = Arc::new(Semaphore::new(opt.max_streams));
235    let results = Arc::new(Mutex::new(Vec::new()));
236    for _ in 0..opt.streams {
237        let permit = sem.clone().acquire_owned().await.unwrap();
238        let results = results.clone();
239        let connection = connection.clone();
240        tokio::spawn(async move {
241            let result = match &*connection {
242                ConnectionSelector::Iroh(connection) => {
243                    iroh::handle_client_stream(connection, opt.upload_size, opt.read_unordered)
244                        .await
245                }
246                #[cfg(not(any(
247                    target_os = "freebsd",
248                    target_os = "openbsd",
249                    target_os = "netbsd"
250                )))]
251                ConnectionSelector::Noq(connection) => {
252                    noq::handle_client_stream(connection, opt.upload_size, opt.read_unordered).await
253                }
254            };
255            // handle_client_stream(connection, opt.upload_size, opt.read_unordered).await;
256            info!("stream finished: {:?}", result);
257            results.lock().unwrap().push(result);
258            drop(permit);
259        });
260    }
261
262    // Wait for remaining streams to finish
263    let _ = sem.acquire_many(opt.max_streams as u32).await.unwrap();
264
265    stats.upload_stats.total_duration = start.elapsed();
266    stats.download_stats.total_duration = start.elapsed();
267
268    for result in results.lock().unwrap().drain(..) {
269        match result {
270            Ok((upload_result, download_result)) => {
271                stats.upload_stats.stream_finished(upload_result);
272                stats.download_stats.stream_finished(download_result);
273            }
274            Err(e) => {
275                if first_error.is_none() {
276                    first_error = Some(e);
277                }
278            }
279        }
280    }
281
282    // Explicit close of the connection, since handles can still be around due
283    // to `Arc`ing them
284    connection.close(0u32, b"Benchmark done");
285
286    endpoint.close().await;
287
288    if opt.stats {
289        println!("\nClient connection stats:\n{:#?}", connection.stats());
290    }
291
292    match first_error {
293        None => Ok(stats),
294        Some(e) => Err(e),
295    }
296}