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