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 #[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 #[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 => 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
221pub 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 info!("stream finished: {:?}", result);
257 results.lock().unwrap().push(result);
258 drop(permit);
259 });
260 }
261
262 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 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}