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