plumbrs 0.24.0

A high-performance HTTP/1.1 and HTTP/2 benchmarking tool
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
use crate::Options;
use crate::client::ClientType;
use crate::client::hyper::*;
use crate::client::hyper_h2::*;
use crate::client::hyper_legacy::*;
#[cfg(feature = "mcp")]
use crate::client::hyper_mcp::http_hyper_mcp;
use crate::client::hyper_chunked::http_hyper_chunked;
use crate::client::hyper_rt1::{RequestBody, http_hyper_rt1};
#[cfg(all(target_os = "linux", feature = "monoio"))]
use crate::client::monoio::*;
#[cfg(feature = "compio")]
use crate::client::compio::*;
use crate::client::reqwest::*;
#[cfg(all(target_os = "linux", feature = "tokio_uring"))]
use crate::client::tokio_uring::*;
use crate::client::utils::build_http_connection_legacy;
use crate::metrics::Metrics;
use crate::stats::RealtimeStats;
use crate::stats::Statistics;
use atomic_time::AtomicDuration;
use atomic_time::AtomicInstant;
#[cfg(all(target_os = "linux", feature = "monoio"))]
use io_uring;

use std::sync::Arc;
use std::thread;
use std::time::Duration;
use std::time::Instant;

use crossterm::{cursor, execute, terminal};
use tokio::runtime::Builder;
use tokio::task::JoinSet;

use anyhow::Result;
use std::sync::atomic::Ordering;

use tabled::builder::Builder as TableBuilder;
use tabled::settings::object::Columns;
use tabled::settings::{Alignment, Modify, Style, Width};

pub fn run_tokio_engines(opts: Options) -> Result<()> {
    let mut handles: Vec<_> = Vec::with_capacity(opts.threads);
    let instances = opts.threads / opts.multithreaded.unwrap_or(1);

    println!(
        "{} {} runtime{} started ({} total connections, {} per thread)",
        instances,
        match opts.multithreaded {
            None => "single-threaded".to_string(),
            Some(n) => format!("multi-threaded/{}", n),
        },
        if opts.threads > 1 { "s" } else { "" },
        opts.connections,
        opts.connections / opts.threads
    );

    let mut runtime_stats: Vec<RealtimeStats> = Vec::with_capacity(instances);
    runtime_stats.resize_with(instances, Default::default);
    let rt_stats = Arc::new(runtime_stats);

    let start = Instant::now();

    // spawn tasks...
    let meters = Builder::new_multi_thread()
        .enable_all()
        .worker_threads(1)
        .build()
        .unwrap();

    let clone_stats = Arc::clone(&rt_stats);
    meters.spawn(async move {
        let ctrl_c_handle = tokio::spawn(async move {
            tokio::signal::ctrl_c().await.ok();
            // Restore cursor on Ctrl+C
            let _ = execute!(std::io::stdout(), cursor::Show);
            println!();
            std::process::exit(0);
        });

        meter(clone_stats).await;

        ctrl_c_handle.abort();
    });

    let connections_per_instance = opts.connections / instances;
    let reminder = opts.connections % instances;

    for id in 0..instances {
        let mut opts = opts.clone();
        let stats = rt_stats.clone();
        opts.connections = if id < reminder {
            connections_per_instance + 1
        } else {
            connections_per_instance
        };

        let handle = thread::spawn(move || -> Result<(Statistics, Metrics)> {
            #[cfg(all(target_os = "linux", feature = "tokio_uring"))]
            if matches!(opts.client_type, ClientType::TokioUring) {
                return tokio_uring_thread(id, opts, stats);
            }
            #[cfg(all(target_os = "linux", feature = "monoio"))]
            if matches!(opts.client_type, ClientType::Monoio) {
                return monoio_thread(id, opts, stats);
            }
            #[cfg(feature = "compio")]
            if matches!(opts.client_type, ClientType::Compio) {
                return compio_thread(id, opts, stats);
            }
            tokio_thread(id, opts, stats)
        });

        handles.push(handle);
    }

    let coll = handles.into_iter().map(|h| h.join().expect("thread error"));
    let out: Vec<(Statistics, Metrics)> = coll.collect::<Result<Vec<_>, _>>()?;
    let duration = start.elapsed().as_micros() as u64;

    let (total_stats, total_metrics) = out.into_iter().fold(
        (Statistics::default(), Metrics::default()),
        |(acc_s, mut acc_m), (s, m)| {
            acc_m.aggregate(&m);
            (acc_s + s, acc_m)
        },
    );

    let total = total_stats;
    print_results(&total, duration, opts.threads, opts.metrics, &total_metrics);
    Ok(())
}

fn pretty_lat(l: f64) -> String {
    if l >= 1_000_000.0 {
        format!("{:.2}s", l / 1_000_000.0)
    } else if l >= 1_000.0 {
        format!("{:.2}ms", l / 1_000.0)
    } else {
        format!("{:.2}µs", l)
    }
}

fn print_results(
    total: &Statistics,
    duration: u64,
    threads: usize,
    show_metrics: bool,
    total_metrics: &Metrics,
) {
    println!();

    // Summary table
    print_summary(total, threads);

    // Stats table
    print_stats(total, duration);

    // Errors table
    print_errors(total, duration);

    // Latency table
    print_latency(total);

    // Display metrics if enabled
    if show_metrics {
        total_metrics.display();
    }
}

fn print_summary(total: &Statistics, threads: usize) {
    println!("Summary:");

    let total_ok = total.ok();
    let total_conn = total.conn();
    let total_3xx = total.status_3xx();
    let total_4xx = total.status_4xx();
    let total_5xx = total.status_5xx();
    let total_err = total.errors();
    let idle_perc = total.idle() / (threads as f64) * 100.0;

    let mut builder = TableBuilder::default();
    builder.push_record(["", "okay", "conn", "3xx", "4xx", "5xx", "err", "%idle"]);
    builder.push_record([
        "total",
        &total_ok.to_string(),
        &total_conn.to_string(),
        &total_3xx.to_string(),
        &total_4xx.to_string(),
        &total_5xx.to_string(),
        &total_err.to_string(),
        &format!("{:.2}", idle_perc),
    ]);
    let table = builder
        .build()
        .with(Style::sharp())
        .with(Modify::new(Columns::new(1..)).with(Alignment::right()))
        .to_string();
    println!("{}", table);
}

fn print_stats(total: &Statistics, duration: u64) {
    let total_ok = total.ok();

    let ok_sec = if duration > 0 {
        total_ok * 1000000 / duration
    } else {
        0
    };
    let mut builder = TableBuilder::default();
    builder.push_record(["status", "total", "rate"]);
    let mut has_stats = false;

    if total_ok > 0 {
        builder.push_record(["200", &total_ok.to_string(), &ok_sec.to_string()]);
        has_stats = true;
    }

    for (key, total_value) in total.http_status().iter() {
        let per_sec = if duration > 0 {
            total_value * 1000000 / duration
        } else {
            0
        };
        builder.push_record([
            &key.to_string(),
            &total_value.to_string(),
            &per_sec.to_string(),
        ]);
        has_stats = true;
    }

    if has_stats {
        println!();
        println!(" Stats:");
        let table = builder
            .build()
            .with(Style::sharp())
            .with(Modify::new(Columns::new(1..)).with(Alignment::right()))
            .to_string();
        println!("{}", table);
    }
}

fn print_errors(total: &Statistics, duration: u64) {
    let errors: Vec<_> = total.errors_map().iter().collect();
    if !errors.is_empty() {
        println!();
        println!(" Errors:");
        let mut builder = TableBuilder::default();
        builder.push_record(["error", "count", "rate/sec"]);
        for (key, total_value) in &errors {
            let per_sec = if duration > 0 {
                *total_value * 1000000 / duration
            } else {
                0
            };
            let error_str = key.to_string();
            let truncated = if error_str.len() > 55 {
                format!("{}", &error_str[..54])
            } else {
                error_str
            };
            builder.push_record([&truncated, &total_value.to_string(), &per_sec.to_string()]);
        }

        let table = builder
            .build()
            .with(Style::sharp())
            .with(Modify::new(Columns::first()).with(Width::truncate(55)))
            .with(Modify::new(Columns::new(1..)).with(Alignment::right()))
            .to_string();
        println!("{}", table);
    }
}

fn print_latency(total: &Statistics) {
    if let Some(ref latency) = total.latency {
        println!();
        println!(" Latency:");
        let mut builder = TableBuilder::default();
        builder.push_record(["", "p50", "p75", "p90", "p99", "min", "mean", "max"]);
        builder.push_record([
            "value",
            &pretty_lat(latency.value_at_quantile(0.50) as f64),
            &pretty_lat(latency.value_at_quantile(0.75) as f64),
            &pretty_lat(latency.value_at_quantile(0.95) as f64),
            &pretty_lat(latency.value_at_quantile(0.99) as f64),
            &pretty_lat(latency.min() as f64),
            &pretty_lat(latency.mean()),
            &pretty_lat(latency.max() as f64),
        ]);
        let table = builder
            .build()
            .with(Style::sharp())
            .with(Modify::new(Columns::new(1..)).with(Alignment::right()))
            .to_string();
        println!("{}", table);
    }
}

fn tokio_thread(
    id: usize,
    opts: Options,
    rt_stats: Arc<Vec<RealtimeStats>>,
) -> Result<(Statistics, Metrics)> {
    let opts = Arc::new(opts);
    let start = Instant::now();
    let park_time = Arc::new(AtomicInstant::new(start));
    let total_park_time = Arc::new(AtomicDuration::new(Duration::default()));

    let runtime = match opts.multithreaded {
        None => Builder::new_current_thread()
            .enable_all()
            .worker_threads(1)
            .global_queue_interval(opts.global_queue_interval.unwrap_or(31))
            .event_interval(opts.event_interval.unwrap_or(61))
            .max_io_events_per_tick(opts.max_io_events_per_tick.unwrap_or(1024))
            .thread_name(format!("plumbrs-{}/s", id))
            .build()
            .unwrap(),

        Some(num_threads) => {
            #[cfg(tokio_unstable)]
            match opts.disable_lifo_slot {
                true => Builder::new_multi_thread()
                    .disable_lifo_slot()
                    .enable_all()
                    .worker_threads(num_threads)
                    .global_queue_interval(opts.global_queue_interval.unwrap_or(61))
                    .event_interval(opts.event_interval.unwrap_or(61))
                    .max_io_events_per_tick(opts.max_io_events_per_tick.unwrap_or(1024))
                    .thread_name(format!("plumbrs-{}/m", id))
                    .on_thread_park({
                        let park_time = Arc::clone(&park_time);
                        move || {
                            park_time.store(Instant::now(), Ordering::Relaxed);
                        }
                    })
                    .on_thread_unpark({
                        let park_time = Arc::clone(&park_time);
                        let total_park_time = Arc::clone(&total_park_time);
                        move || {
                            let delta = Instant::now() - park_time.load(Ordering::Relaxed);
                            total_park_time.store(
                                total_park_time.load(Ordering::Relaxed) + delta,
                                Ordering::Relaxed,
                            );
                        }
                    })
                    .build()
                    .unwrap(),

                false => Builder::new_multi_thread()
                    .enable_all()
                    .worker_threads(num_threads)
                    .global_queue_interval(opts.global_queue_interval.unwrap_or(61))
                    .event_interval(opts.event_interval.unwrap_or(61))
                    .max_io_events_per_tick(opts.max_io_events_per_tick.unwrap_or(1024))
                    .thread_name(format!("plumbrs-{}/m", id))
                    .on_thread_park({
                        let park_time = Arc::clone(&park_time);
                        move || {
                            park_time.store(Instant::now(), Ordering::Relaxed);
                        }
                    })
                    .on_thread_unpark({
                        let park_time = Arc::clone(&park_time);
                        let total_park_time = Arc::clone(&total_park_time);
                        move || {
                            let delta = Instant::now() - park_time.load(Ordering::Relaxed);
                            total_park_time.store(
                                total_park_time.load(Ordering::Relaxed) + delta,
                                Ordering::Relaxed,
                            );
                        }
                    })
                    .build()
                    .unwrap(),
            }

            #[cfg(not(tokio_unstable))]
            Builder::new_multi_thread()
                .enable_all()
                .worker_threads(num_threads)
                .global_queue_interval(opts.global_queue_interval.unwrap_or(61))
                .event_interval(opts.event_interval.unwrap_or(61))
                .max_io_events_per_tick(opts.max_io_events_per_tick.unwrap_or(1024))
                .thread_name(format!("plumbrs-{}/m", id))
                .on_thread_park({
                    let park_time = Arc::clone(&park_time);
                    move || {
                        park_time.store(Instant::now(), Ordering::Relaxed);
                    }
                })
                .on_thread_unpark({
                    let park_time = Arc::clone(&park_time);
                    let total_park_time = Arc::clone(&total_park_time);
                    move || {
                        let delta = Instant::now() - park_time.load(Ordering::Relaxed);
                        total_park_time.store(
                            total_park_time.load(Ordering::Relaxed) + delta,
                            Ordering::Relaxed,
                        );
                    }
                })
                .build()
                .unwrap()
        }
    };

    let mut stats = runtime.block_on(async { spawn_tasks(id, opts, rt_stats).await });

    stats.idle_time(
        total_park_time.load(Ordering::Relaxed).as_secs_f64() / start.elapsed().as_secs_f64(),
    );

    let metrics = Metrics::new(&runtime.metrics());

    Ok((stats, metrics))
}

#[cfg(all(target_os = "linux", feature = "tokio_uring"))]
fn tokio_uring_thread(
    id: usize,
    opts: Options,
    rt_stats: Arc<Vec<RealtimeStats>>,
) -> Result<(Statistics, Metrics)> {
    let metrics = Metrics::default();
    let opts = Arc::new(opts);

    let num_entries = opts.uring_entries.next_power_of_two();
    let cqsize = num_entries * 2;

    let mut uring = tokio_uring::uring_builder();

    uring.setup_single_issuer().setup_cqsize(cqsize);

    if let Some(idle) = opts.uring_sqpoll {
        uring.setup_sqpoll(idle);
    } else {
        uring.setup_coop_taskrun().setup_taskrun_flag();
    }

    let stats = tokio_uring::builder()
        .entries(num_entries) // Large ring size is critical for throughput
        .uring_builder(&uring)
        .start(async move {
            let handle = tokio_uring::spawn(async move { spawn_tasks(id, opts, rt_stats).await });

            handle.await.unwrap()
        });

    Ok((stats, metrics))
}

#[cfg(all(target_os = "linux", feature = "monoio"))]
fn monoio_thread(
    id: usize,
    opts: Options,
    rt_stats: Arc<Vec<RealtimeStats>>,
) -> Result<(Statistics, Metrics)> {
    let metrics = Metrics::default();
    let opts = Arc::new(opts);

    let num_entries = opts.uring_entries.next_power_of_two();
    let cqsize = num_entries * 2;

    let mut uring = io_uring::IoUring::builder();

    uring.setup_single_issuer().setup_cqsize(cqsize);

    if let Some(idle) = opts.uring_sqpoll {
        uring.setup_sqpoll(idle);
    } else {
        uring.setup_coop_taskrun().setup_taskrun_flag();
    }

    let stats = monoio::RuntimeBuilder::<monoio::IoUringDriver>::new()
        .with_entries(num_entries)
        .uring_builder(uring)
        .build()
        .expect("Failed to build monoio runtime")
        .block_on(async move {
            let mut tasks = Vec::new();

            for con in 0..opts.connections {
                let opts_clone = Arc::clone(&opts);
                let stats_clone = Arc::clone(&rt_stats);

                tasks.push(monoio::spawn(async move {
                    http_monoio(id, con, opts_clone, &stats_clone[id]).await
                }));
            }

            let mut statistics = Statistics::default();
            for task in tasks {
                match task.await {
                    s => statistics = statistics + s,
                }
            }

            statistics
        });

    Ok((stats, metrics))
}

#[cfg(feature = "compio")]
fn compio_thread(
    id: usize,
    opts: Options,
    rt_stats: Arc<Vec<RealtimeStats>>,
) -> Result<(Statistics, Metrics)> {
    let metrics = Metrics::default();
    let opts = Arc::new(opts);

    let mut proactor_builder = compio::driver::ProactorBuilder::new();

    #[cfg(target_os = "linux")]
    {
        let num_entries = opts.uring_entries.next_power_of_two();
        proactor_builder.capacity(num_entries);

        if let Some(idle) = opts.uring_sqpoll {
            proactor_builder.sqpoll_idle(std::time::Duration::from_millis(idle as u64));
        } else {
            proactor_builder.coop_taskrun(true).taskrun_flag(true);
        }
    }

    #[cfg(not(target_os = "linux"))]
    {
        proactor_builder.capacity(4096);
    }

    let stats = compio::runtime::Runtime::builder()
        .with_proactor(proactor_builder)
        .build()
        .expect("Failed to build compio runtime")
        .block_on(async move {
            let mut tasks = Vec::new();

            for con in 0..opts.connections {
                let opts_clone = Arc::clone(&opts);
                let stats_clone = Arc::clone(&rt_stats);

                tasks.push(compio::runtime::spawn(async move {
                    http_compio(id, con, opts_clone, &stats_clone[id]).await
                }));
            }

            let mut statistics = Statistics::default();
            for task in tasks {
                match task.await {
                    s => statistics = statistics + s.unwrap(),
                }
            }

            statistics
        });

    Ok((stats, metrics))
}

async fn spawn_tasks(
    id: usize,
    opts: Arc<Options>,
    rt_stats: Arc<Vec<RealtimeStats>>,
) -> Statistics {
    let mut tasks = JoinSet::new();
    let mut statistics = Statistics::default();

    let client = if matches!(opts.client_type, ClientType::HyperRt1) {
        Some(build_http_connection_legacy::<RequestBody>(&opts))
    } else {
        None
    };

    for con in 0..opts.connections {
        let opts = Arc::clone(&opts);
        let stats = Arc::clone(&rt_stats);

        match opts.client_type {
            ClientType::Auto => {
                if opts.body.len() > 1 {
                    tasks.spawn(
                        async move { http_hyper_chunked(id, con, opts, &stats[id]).await },
                    );
                } else {
                    #[cfg(feature = "mcp")]
                    {
                        if opts.mcp || opts.mcp_sse {
                            tasks.spawn(
                                async move { http_hyper_mcp(id, con, opts, &stats[id]).await },
                            );
                        } else {
                            tasks.spawn(async move { http_hyper(id, con, opts, &stats[id]).await });
                        }
                    }
                    #[cfg(not(feature = "mcp"))]
                    {
                        tasks.spawn(async move { http_hyper(id, con, opts, &stats[id]).await });
                    }
                }
            }
            ClientType::Hyper => {
                tasks.spawn(async move { http_hyper(id, con, opts, &stats[id]).await });
            }
            ClientType::HyperChunked => {
                tasks.spawn(async move { http_hyper_chunked(id, con, opts, &stats[id]).await });
            }
            ClientType::HyperLegacy => {
                tasks.spawn(async move { http_hyper_legacy(id, con, opts, &stats[id]).await });
            }
            ClientType::HyperRt1 => {
                let con_client = client.as_ref().unwrap().clone();
                tasks.spawn(
                    async move { http_hyper_rt1(id, con, opts, con_client, &stats[id]).await },
                );
            }
            ClientType::HyperH2 => {
                tasks.spawn(async move { http_hyper_h2(id, con, opts, &stats[id]).await });
            }
            #[cfg(feature = "mcp")]
            ClientType::HyperMcp => {
                tasks.spawn(async move { http_hyper_mcp(id, con, opts, &stats[id]).await });
            }
            ClientType::Reqwest => {
                tasks.spawn(async move { http_reqwest(id, con, opts, &stats[id]).await });
            }
            #[cfg(all(target_os = "linux", feature = "tokio_uring"))]
            ClientType::TokioUring => {
                tasks.spawn_local(async move { http_io_uring(id, con, opts, &stats[id]).await });
            }
            #[cfg(all(target_os = "linux", feature = "monoio"))]
            ClientType::Monoio => {
                // Monoio tasks are spawned in monoio_thread, not here
            }
            #[cfg(feature = "compio")]
            ClientType::Compio => {
                // Compio tasks are spawned in compio_thread, not here
            }
            ClientType::Help => (),
        }
    }

    while let Some(res) = tasks.join_next().await {
        match res {
            Ok(s) => statistics = statistics + s,
            Err(err) => {
                if opts.verbose {
                    eprintln!("Unable to join task: {}", err);
                }
            }
        }
    }

    statistics
}

pub async fn meter(rt_stats: Arc<Vec<RealtimeStats>>) {
    const SPINNER: &[&str] = &["", "", "", "", "", "", "", "", "", ""];
    let mut spinner_idx = 0;

    loop {
        tokio::time::sleep(Duration::from_millis(1000)).await;
        let mut total_ok = 0u64;
        let mut total_err = 0u64;
        let mut total_fail = 0u64;

        for stats in rt_stats.iter() {
            total_ok += stats.ok.swap(0, Ordering::Relaxed);
            total_err += stats.err.swap(0, Ordering::Relaxed);
            total_fail += stats.fail.swap(0, Ordering::Relaxed);
        }

        print!(
            "\r{} Stats: ok: {total_ok}/sec, fail: {total_fail}/sec, err: {total_err}/sec",
            SPINNER[spinner_idx]
        );
        let _ = execute!(
            std::io::stdout(),
            terminal::Clear(terminal::ClearType::UntilNewLine)
        );

        spinner_idx = (spinner_idx + 1) % SPINNER.len();
    }
}