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 n0_future::task;
11use stats::Stats;
12use tokio::{
13 runtime::{Builder, Runtime},
14 sync::Semaphore,
15};
16use tracing::info;
17use tracing_subscriber::{EnvFilter, Layer, fmt, layer::SubscriberExt, util::SubscriberInitExt};
18
19pub mod iroh;
20#[cfg(not(any(target_os = "freebsd", target_os = "openbsd", target_os = "netbsd")))]
21pub mod quinn;
22pub mod s2n;
23pub mod stats;
24
25#[derive(Parser, Debug, Clone, Copy)]
26#[clap(name = "iroh-bench")]
27pub enum Commands {
28 Iroh(Opt),
29 #[cfg(not(any(target_os = "freebsd", target_os = "openbsd", target_os = "netbsd")))]
30 Quinn(Opt),
31 S2n(s2n::Opt),
32}
33
34#[derive(Parser, Debug, Clone, Copy)]
35#[clap(name = "options")]
36pub struct Opt {
37 #[clap(long = "clients", short = 'c', default_value = "1")]
39 pub clients: usize,
40 #[clap(long = "streams", short = 'n', default_value = "1")]
42 pub streams: usize,
43 #[clap(long = "max_streams", short = 'm', default_value = "1")]
45 pub max_streams: usize,
46 #[clap(long, default_value = "1G", value_parser = parse_byte_size)]
51 pub download_size: u64,
52 #[clap(long, default_value = "0", value_parser = parse_byte_size)]
57 pub upload_size: u64,
58 #[clap(long = "stats")]
60 pub stats: bool,
61 #[clap(long)]
66 pub metrics: bool,
67 #[clap(long = "unordered")]
69 pub read_unordered: bool,
70 #[clap(long, default_value = "1200")]
72 pub initial_mtu: u16,
73 #[cfg(feature = "local-relay")]
77 #[clap(long, default_value_t = false)]
78 pub only_relay: bool,
79 #[clap(long, default_value_t = false)]
80 pub use_ipv6: bool,
81}
82
83pub enum EndpointSelector {
84 Iroh(::iroh::Endpoint),
85 #[cfg(not(any(target_os = "freebsd", target_os = "openbsd", target_os = "netbsd")))]
86 Quinn(::quinn::Endpoint),
87}
88
89impl EndpointSelector {
90 pub async fn close(self) {
91 match self {
92 EndpointSelector::Iroh(endpoint) => {
93 endpoint.close().await;
94 }
95 #[cfg(not(any(target_os = "freebsd", target_os = "openbsd", target_os = "netbsd")))]
96 EndpointSelector::Quinn(endpoint) => {
97 endpoint.close(0u32.into(), b"");
98 endpoint.wait_idle().await;
99 }
100 }
101 }
102}
103
104pub enum ConnectionSelector {
105 Iroh(::iroh::endpoint::Connection),
106 #[cfg(not(any(target_os = "freebsd", target_os = "openbsd", target_os = "netbsd")))]
107 Quinn(::quinn::Connection),
108}
109
110impl ConnectionSelector {
111 pub fn stats(&self) {
112 match self {
113 ConnectionSelector::Iroh(connection) => {
114 println!("{:#?}", connection.stats());
115 }
116 #[cfg(not(any(target_os = "freebsd", target_os = "openbsd", target_os = "netbsd")))]
117 ConnectionSelector::Quinn(connection) => {
118 println!("{:#?}", connection.stats());
119 }
120 }
121 }
122
123 pub fn close(&self, error_code: u32, reason: &[u8]) {
124 match self {
125 ConnectionSelector::Iroh(connection) => {
126 connection.close(error_code.into(), reason);
127 }
128 #[cfg(not(any(target_os = "freebsd", target_os = "openbsd", target_os = "netbsd")))]
129 ConnectionSelector::Quinn(connection) => {
130 connection.close(error_code.into(), reason);
131 }
132 }
133 }
134}
135
136pub fn configure_tracing_subscriber() {
137 let registry = tracing_subscriber::registry();
138 #[cfg(feature = "tokio-console")]
139 let registry = registry.with(console_subscriber::spawn());
140 registry
141 .with(
142 fmt::layer().with_filter(
143 EnvFilter::try_from_default_env()
144 .or_else(|_| EnvFilter::try_new("warn"))
145 .unwrap(),
146 ),
147 )
148 .init();
149}
150
151pub fn rt() -> Runtime {
152 Builder::new_current_thread().enable_all().build().unwrap()
153}
154
155fn parse_byte_size(s: &str) -> Result<u64, ParseIntError> {
156 let s = s.trim();
157
158 let multiplier = match s.chars().last() {
159 Some('T') => 1024 * 1024 * 1024 * 1024,
160 Some('G') => 1024 * 1024 * 1024,
161 Some('M') => 1024 * 1024,
162 Some('k') => 1024,
163 _ => 1,
164 };
165
166 let s = if multiplier != 1 {
167 &s[..s.len() - 1]
168 } else {
169 s
170 };
171
172 let base: u64 = u64::from_str(s)?;
173
174 Ok(base * multiplier)
175}
176
177#[derive(Default)]
178pub struct ClientStats {
179 upload_stats: Stats,
180 download_stats: Stats,
181 connect_time: std::time::Duration,
182}
183
184impl ClientStats {
185 pub fn print(&self, client_id: usize) {
186 println!();
187 println!("Client {client_id} stats:");
188
189 let ct = self.connect_time.as_nanos() as f64 / 1_000_000.0;
190 println!("Connect time: {ct}ms");
191
192 if self.upload_stats.total_size != 0 {
193 self.upload_stats.print("upload");
194 }
195
196 if self.download_stats.total_size != 0 {
197 self.download_stats.print("download");
198 }
199 }
200}
201
202pub async fn client_handler(
204 endpoint: EndpointSelector,
205 connection: ConnectionSelector,
206 opt: Opt,
207) -> Result<ClientStats> {
208 let start = Instant::now();
209
210 let connection = Arc::new(connection);
211
212 let mut stats = ClientStats::default();
213 let mut first_error = None;
214
215 let sem = Arc::new(Semaphore::new(opt.max_streams));
216 let results = Arc::new(Mutex::new(Vec::new()));
217 for i in 0..opt.streams {
218 let permit = sem.clone().acquire_owned().await.unwrap();
219 let results = results.clone();
220 let connection = connection.clone();
221 task::spawn_with_name(&format!("client-stream-{i}"), async move {
222 let result = match &*connection {
223 ConnectionSelector::Iroh(connection) => {
224 iroh::handle_client_stream(connection, opt.upload_size, opt.read_unordered)
225 .await
226 }
227 #[cfg(not(any(
228 target_os = "freebsd",
229 target_os = "openbsd",
230 target_os = "netbsd"
231 )))]
232 ConnectionSelector::Quinn(connection) => {
233 quinn::handle_client_stream(connection, opt.upload_size, opt.read_unordered)
234 .await
235 }
236 };
237 info!("stream finished: {:?}", result);
239 results.lock().unwrap().push(result);
240 drop(permit);
241 });
242 }
243
244 let _ = sem.acquire_many(opt.max_streams as u32).await.unwrap();
246
247 stats.upload_stats.total_duration = start.elapsed();
248 stats.download_stats.total_duration = start.elapsed();
249
250 for result in results.lock().unwrap().drain(..) {
251 match result {
252 Ok((upload_result, download_result)) => {
253 stats.upload_stats.stream_finished(upload_result);
254 stats.download_stats.stream_finished(download_result);
255 }
256 Err(e) => {
257 if first_error.is_none() {
258 first_error = Some(e);
259 }
260 }
261 }
262 }
263
264 connection.close(0u32, b"Benchmark done");
267
268 endpoint.close().await;
269
270 if opt.stats {
271 println!("\nClient connection stats:\n{:#?}", connection.stats());
272 }
273
274 match first_error {
275 None => Ok(stats),
276 Some(e) => Err(e),
277 }
278}