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