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 #[clap(long = "clients", short = 'c', default_value = "1")]
37 pub clients: usize,
38 #[clap(long = "streams", short = 'n', default_value = "1")]
40 pub streams: usize,
41 #[clap(long = "max_streams", short = 'm', default_value = "1")]
43 pub max_streams: usize,
44 #[clap(long, default_value = "1G", value_parser = parse_byte_size)]
49 pub download_size: u64,
50 #[clap(long, default_value = "0", value_parser = parse_byte_size)]
55 pub upload_size: u64,
56 #[clap(long = "stats")]
58 pub stats: bool,
59 #[clap(long)]
64 pub metrics: bool,
65 #[clap(long = "unordered")]
67 pub read_unordered: bool,
68 #[clap(long, default_value = "1200")]
70 pub initial_mtu: u16,
71 #[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
191pub 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 info!("stream finished: {:?}", result);
228 results.lock().unwrap().push(result);
229 drop(permit);
230 });
231 }
232
233 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 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}