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_snafu::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 quinn;
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    Quinn(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}
78
79pub enum EndpointSelector {
80    Iroh(::iroh::Endpoint),
81    #[cfg(not(any(target_os = "freebsd", target_os = "openbsd", target_os = "netbsd")))]
82    Quinn(::quinn::Endpoint),
83}
84
85impl EndpointSelector {
86    pub async fn close(self) {
87        match self {
88            EndpointSelector::Iroh(endpoint) => {
89                endpoint.close().await;
90            }
91            #[cfg(not(any(target_os = "freebsd", target_os = "openbsd", target_os = "netbsd")))]
92            EndpointSelector::Quinn(endpoint) => {
93                endpoint.close(0u32.into(), b"");
94            }
95        }
96    }
97}
98
99pub enum ConnectionSelector {
100    Iroh(::iroh::endpoint::Connection),
101    #[cfg(not(any(target_os = "freebsd", target_os = "openbsd", target_os = "netbsd")))]
102    Quinn(::quinn::Connection),
103}
104
105impl ConnectionSelector {
106    pub fn stats(&self) {
107        match self {
108            ConnectionSelector::Iroh(connection) => {
109                println!("{:#?}", connection.stats());
110            }
111            #[cfg(not(any(target_os = "freebsd", target_os = "openbsd", target_os = "netbsd")))]
112            ConnectionSelector::Quinn(connection) => {
113                println!("{:#?}", connection.stats());
114            }
115        }
116    }
117
118    pub fn close(&self, error_code: u32, reason: &[u8]) {
119        match self {
120            ConnectionSelector::Iroh(connection) => {
121                connection.close(error_code.into(), reason);
122            }
123            #[cfg(not(any(target_os = "freebsd", target_os = "openbsd", target_os = "netbsd")))]
124            ConnectionSelector::Quinn(connection) => {
125                connection.close(error_code.into(), reason);
126            }
127        }
128    }
129}
130
131pub fn configure_tracing_subscriber() {
132    tracing::subscriber::set_global_default(
133        tracing_subscriber::FmtSubscriber::builder()
134            .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
135            .finish(),
136    )
137    .unwrap();
138}
139
140pub fn rt() -> Runtime {
141    Builder::new_current_thread().enable_all().build().unwrap()
142}
143
144fn parse_byte_size(s: &str) -> Result<u64, ParseIntError> {
145    let s = s.trim();
146
147    let multiplier = match s.chars().last() {
148        Some('T') => 1024 * 1024 * 1024 * 1024,
149        Some('G') => 1024 * 1024 * 1024,
150        Some('M') => 1024 * 1024,
151        Some('k') => 1024,
152        _ => 1,
153    };
154
155    let s = if multiplier != 1 {
156        &s[..s.len() - 1]
157    } else {
158        s
159    };
160
161    let base: u64 = u64::from_str(s)?;
162
163    Ok(base * multiplier)
164}
165
166#[derive(Default)]
167pub struct ClientStats {
168    upload_stats: Stats,
169    download_stats: Stats,
170    connect_time: std::time::Duration,
171}
172
173impl ClientStats {
174    pub fn print(&self, client_id: usize) {
175        println!();
176        println!("Client {client_id} stats:");
177
178        let ct = self.connect_time.as_nanos() as f64 / 1_000_000.0;
179        println!("Connect time: {ct}ms");
180
181        if self.upload_stats.total_size != 0 {
182            self.upload_stats.print("upload");
183        }
184
185        if self.download_stats.total_size != 0 {
186            self.download_stats.print("download");
187        }
188    }
189}
190
191/// Take the provided endpoint and run the client benchmark
192pub async fn client_handler(
193    endpoint: EndpointSelector,
194    connection: ConnectionSelector,
195    opt: Opt,
196) -> Result<ClientStats> {
197    let start = Instant::now();
198
199    let connection = Arc::new(connection);
200
201    let mut stats = ClientStats::default();
202    let mut first_error = None;
203
204    let sem = Arc::new(Semaphore::new(opt.max_streams));
205    let results = Arc::new(Mutex::new(Vec::new()));
206    for _ in 0..opt.streams {
207        let permit = sem.clone().acquire_owned().await.unwrap();
208        let results = results.clone();
209        let connection = connection.clone();
210        tokio::spawn(async move {
211            let result = match &*connection {
212                ConnectionSelector::Iroh(connection) => {
213                    iroh::handle_client_stream(connection, opt.upload_size, opt.read_unordered)
214                        .await
215                }
216                #[cfg(not(any(
217                    target_os = "freebsd",
218                    target_os = "openbsd",
219                    target_os = "netbsd"
220                )))]
221                ConnectionSelector::Quinn(connection) => {
222                    quinn::handle_client_stream(connection, opt.upload_size, opt.read_unordered)
223                        .await
224                }
225            };
226            // handle_client_stream(connection, opt.upload_size, opt.read_unordered).await;
227            info!("stream finished: {:?}", result);
228            results.lock().unwrap().push(result);
229            drop(permit);
230        });
231    }
232
233    // Wait for remaining streams to finish
234    let _ = sem.acquire_many(opt.max_streams as u32).await.unwrap();
235
236    stats.upload_stats.total_duration = start.elapsed();
237    stats.download_stats.total_duration = start.elapsed();
238
239    for result in results.lock().unwrap().drain(..) {
240        match result {
241            Ok((upload_result, download_result)) => {
242                stats.upload_stats.stream_finished(upload_result);
243                stats.download_stats.stream_finished(download_result);
244            }
245            Err(e) => {
246                if first_error.is_none() {
247                    first_error = Some(e);
248                }
249            }
250        }
251    }
252
253    // Explicit close of the connection, since handles can still be around due
254    // to `Arc`ing them
255    connection.close(0u32, b"Benchmark done");
256
257    endpoint.close().await;
258
259    if opt.stats {
260        println!("\nClient connection stats:\n{:#?}", connection.stats());
261    }
262
263    match first_error {
264        None => Ok(stats),
265        Some(e) => Err(e),
266    }
267}