oha 0.6.5

Ohayou(おはよう), HTTP load generator, inspired by rakyll/hey with tui animation.
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
use byte_unit::Byte;
use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
use crossterm::ExecutableCommand;
use flume::TryRecvError;
use std::collections::BTreeMap;
use std::io;
use tui::backend::CrosstermBackend;
use tui::layout::{Constraint, Direction, Layout};
use tui::style::{Color, Style};
use tui::text::{Line, Span};
use tui::widgets::{BarChart, Block, Borders, Gauge, Paragraph};
use tui::Terminal;

use crate::client::{ClientError, RequestResult};
use crate::printer::PrintMode;
use crate::timescale::{TimeLabel, TimeScale};

/// When the monitor ends
pub enum EndLine {
    /// After a duration
    Duration(std::time::Duration),
    /// After n query done
    NumQuery(usize),
}

struct ColorScheme {
    light_blue: Option<Color>,
    green: Option<Color>,
    yellow: Option<Color>,
}

impl ColorScheme {
    fn new() -> ColorScheme {
        ColorScheme {
            light_blue: None,
            green: None,
            yellow: None,
        }
    }

    fn set_colors(&mut self) {
        self.light_blue = Some(Color::Cyan);
        self.green = Some(Color::Green);
        self.yellow = Some(Color::Yellow);
    }
}

pub struct Monitor {
    pub print_mode: PrintMode,
    pub end_line: EndLine,
    /// All workers sends each result to this channel
    pub report_receiver: flume::Receiver<Result<RequestResult, ClientError>>,
    // When started
    pub start: std::time::Instant,
    // Frame per scond of TUI
    pub fps: usize,
    pub disable_color: bool,
    pub stats_success_breakdown: bool,
}

impl Monitor {
    pub async fn monitor(self) -> Result<Vec<Result<RequestResult, ClientError>>, std::io::Error> {
        crossterm::terminal::enable_raw_mode()?;
        io::stdout().execute(crossterm::terminal::EnterAlternateScreen)?;
        io::stdout().execute(crossterm::cursor::Hide)?;

        let mut terminal = {
            let backend = CrosstermBackend::new(io::stdout());
            Terminal::new(backend)?
        };

        // Return this when ends to application print summary
        // We must not read all data from this due to computational cost.
        let mut all: Vec<Result<RequestResult, ClientError>> = Vec::new();
        // statics for HTTP status
        let mut status_dist: BTreeMap<http::StatusCode, usize> = Default::default();
        // statics for Error
        let mut error_dist: BTreeMap<String, usize> = Default::default();

        #[cfg(unix)]
        // Limit for number open files. eg. ulimit -n
        let nofile_limit = rlimit::getrlimit(rlimit::Resource::NOFILE);

        // None means auto timescale which depends on how long it takes
        let mut timescale_auto = None;

        let mut colors = ColorScheme::new();
        if !self.disable_color {
            colors.set_colors();
        }

        'outer: loop {
            let frame_start = std::time::Instant::now();
            loop {
                match self.report_receiver.try_recv() {
                    Ok(report) => {
                        match report.as_ref() {
                            Ok(report) => *status_dist.entry(report.status).or_default() += 1,
                            Err(e) => *error_dist.entry(e.to_string()).or_default() += 1,
                        }
                        all.push(report);
                    }
                    Err(TryRecvError::Empty) => {
                        break;
                    }
                    Err(TryRecvError::Disconnected) => {
                        // Application ends.
                        break 'outer;
                    }
                }
            }

            let now = std::time::Instant::now();
            let progress = match &self.end_line {
                EndLine::Duration(d) => {
                    ((now - self.start).as_secs_f64() / d.as_secs_f64()).clamp(0.0, 1.0)
                }
                EndLine::NumQuery(n) => (all.len() as f64 / *n as f64).clamp(0.0, 1.0),
            };

            let count = 32;

            let timescale = if let Some(timescale) = timescale_auto {
                timescale
            } else {
                TimeScale::from_elapsed(self.start.elapsed())
            };

            let bin = timescale.as_secs_f64();

            let mut bar_num_req = vec![0u64; count];
            let short_bin = (now - self.start).as_secs_f64() % bin;
            for r in all.iter().rev() {
                if let Ok(r) = r.as_ref() {
                    let past = (now - r.end).as_secs_f64();
                    let i = if past <= short_bin {
                        0
                    } else {
                        1 + ((past - short_bin) / bin) as usize
                    };
                    if i >= bar_num_req.len() {
                        break;
                    }
                    bar_num_req[i] += 1;
                }
            }

            let cols = bar_num_req
                .iter()
                .map(|x| x.to_string().chars().count())
                .max()
                .unwrap_or(0);

            let bar_num_req: Vec<(String, u64)> = bar_num_req
                .into_iter()
                .enumerate()
                .map(|(i, n)| {
                    (
                        {
                            let mut s = TimeLabel { x: i, timescale }.to_string();
                            if cols > s.len() {
                                for _ in 0..cols - s.len() {
                                    s.push(' ');
                                }
                            }
                            s
                        },
                        n,
                    )
                })
                .collect();

            let bar_num_req_str: Vec<(&str, u64)> =
                bar_num_req.iter().map(|(a, b)| (a.as_str(), *b)).collect();

            #[cfg(unix)]
            let nofile = match tokio::fs::read_dir("/dev/fd").await {
                Ok(mut dir) => {
                    let mut count = 0;
                    loop {
                        match dir.next_entry().await {
                            Ok(Some(_)) => count += 1,
                            Ok(None) => break Ok(count),
                            Err(err) => break Err(err),
                        }
                    }
                }
                Err(e) => Err(e),
            };

            terminal.draw(|f| {
                let row4 = Layout::default()
                    .direction(Direction::Vertical)
                    .constraints(
                        [
                            Constraint::Length(3),
                            Constraint::Length(8),
                            Constraint::Length(error_dist.len() as u16 + 2),
                            Constraint::Percentage(40),
                        ]
                        .as_ref(),
                    )
                    .split(f.size());

                let mid = Layout::default()
                    .direction(Direction::Horizontal)
                    .constraints([Constraint::Percentage(50), Constraint::Percentage(50)].as_ref())
                    .split(row4[1]);

                let bottom = Layout::default()
                    .direction(Direction::Horizontal)
                    .constraints([Constraint::Percentage(50), Constraint::Percentage(50)].as_ref())
                    .split(row4[3]);

                let gauge_label = match &self.end_line {
                    EndLine::Duration(d) => format!(
                        "{} / {}",
                        humantime::Duration::from(std::time::Duration::from_secs(
                            (now - self.start).as_secs_f64() as u64
                        )),
                        humantime::Duration::from(*d)
                    ),
                    EndLine::NumQuery(n) => format!("{} / {}", all.len(), n),
                };
                let gauge = Gauge::default()
                    .block(Block::default().title("Progress").borders(Borders::ALL))
                    .gauge_style(Style::default().fg(colors.light_blue.unwrap_or(Color::White)))
                    .label(Span::raw(gauge_label))
                    .ratio(progress);
                f.render_widget(gauge, row4[0]);

                let last_1_timescale = all
                    .iter()
                    .rev()
                    .filter_map(|r| r.as_ref().ok())
                    .take_while(|r| (now - r.end).as_secs_f64() <= timescale.as_secs_f64())
                    .collect::<Vec<_>>();

                let statics_text = vec![
                    Line::from(format!("Requests : {}", last_1_timescale.len())),
                    Line::from(vec![Span::styled(
                        format!(
                            "Slowest: {:.4} secs",
                            last_1_timescale
                                .iter()
                                .map(|r| r.duration())
                                .max()
                                .map(|d| d.as_secs_f64())
                                .unwrap_or(std::f64::NAN)
                        ),
                        Style::default().fg(colors.yellow.unwrap_or(Color::Reset)),
                    )]),
                    Line::from(vec![Span::styled(
                        format!(
                            "Fastest: {:.4} secs",
                            last_1_timescale
                                .iter()
                                .map(|r| r.duration())
                                .min()
                                .map(|d| d.as_secs_f64())
                                .unwrap_or(std::f64::NAN)
                        ),
                        Style::default().fg(colors.green.unwrap_or(Color::Reset)),
                    )]),
                    Line::from(vec![Span::styled(
                        format!(
                            "Average: {:.4} secs",
                            last_1_timescale
                                .iter()
                                .map(|r| r.duration())
                                .sum::<std::time::Duration>()
                                .as_secs_f64()
                                / last_1_timescale.len() as f64
                        ),
                        Style::default().fg(colors.light_blue.unwrap_or(Color::Reset)),
                    )]),
                    Line::from(format!(
                        "Data: {}",
                        Byte::from_bytes(
                            last_1_timescale
                                .iter()
                                .map(|r| r.len_bytes as u128)
                                .sum::<u128>()
                        )
                        .get_appropriate_unit(true)
                    )),
                    #[cfg(unix)]
                    // Note: Windows can open 255 * 255 * 255 files. So not showing on windows is OK.
                    Line::from(format!(
                        "Number of open files: {} / {}",
                        nofile
                            .map(|c| c.to_string())
                            .unwrap_or_else(|_| "Error".to_string()),
                        nofile_limit
                            .as_ref()
                            .map(|(s, _h)| s.to_string())
                            .unwrap_or_else(|_| "Unknown".to_string())
                    )),
                ];
                let statics_title = format!("statics for last {timescale}");
                let statics = Paragraph::new(statics_text).block(
                    Block::default()
                        .title(Span::raw(statics_title))
                        .borders(Borders::ALL),
                );
                f.render_widget(statics, mid[0]);

                let mut status_v: Vec<(http::StatusCode, usize)> =
                    status_dist.clone().into_iter().collect();
                status_v.sort_by_key(|t| std::cmp::Reverse(t.1));

                let statics2_text = status_v
                    .into_iter()
                    .map(|(status, count)| {
                        Line::from(format!("[{}] {} responses", status.as_str(), count))
                    })
                    .collect::<Vec<_>>();
                let statics2 = Paragraph::new(statics2_text).block(
                    Block::default()
                        .title("Status code distribution")
                        .borders(Borders::ALL),
                );
                f.render_widget(statics2, mid[1]);

                let mut error_v: Vec<(String, usize)> = error_dist.clone().into_iter().collect();
                error_v.sort_by_key(|t| std::cmp::Reverse(t.1));
                let errors_text = error_v
                    .into_iter()
                    .map(|(e, count)| Line::from(format!("[{count}] {e}")))
                    .collect::<Vec<_>>();
                let errors = Paragraph::new(errors_text).block(
                    Block::default()
                        .title("Error distribution")
                        .borders(Borders::ALL),
                );
                f.render_widget(errors, row4[2]);

                let title = format!(
                    "Requests / past {}{}. press -/+/a to change",
                    timescale,
                    if timescale_auto.is_none() {
                        " (auto)"
                    } else {
                        ""
                    }
                );

                let barchart = BarChart::default()
                    .block(
                        Block::default()
                            .title(Span::raw(title))
                            .style(
                                Style::default()
                                    .fg(colors.green.unwrap_or(Color::Reset))
                                    .bg(Color::Reset),
                            )
                            .borders(Borders::ALL),
                    )
                    .data(bar_num_req_str.as_slice())
                    .bar_width(
                        bar_num_req
                            .iter()
                            .map(|(s, _)| s.chars().count())
                            .max()
                            .map(|w| w + 2)
                            .unwrap_or(1) as u16,
                    );
                f.render_widget(barchart, bottom[0]);

                let resp_histo_width = 7;
                let resp_histo_data: Vec<(String, u64)> = {
                    let bins = if bottom[1].width < 2 {
                        0
                    } else {
                        (bottom[1].width as usize - 2) / (resp_histo_width + 1)
                    }
                    .max(2);
                    let values = all
                        .iter()
                        .rev()
                        .filter_map(|r| r.as_ref().ok())
                        .take_while(|r| (now - r.end).as_secs_f64() < timescale.as_secs_f64())
                        .map(|r| r.duration().as_secs_f64())
                        .collect::<Vec<_>>();

                    let histo = crate::histogram::histogram(&values, bins);
                    histo
                        .into_iter()
                        .map(|(label, v)| (format!("{label:.4}"), v as u64))
                        .collect()
                };

                let resp_histo_data_str: Vec<(&str, u64)> = resp_histo_data
                    .iter()
                    .map(|(l, v)| (l.as_str(), *v))
                    .collect();

                let resp_histo = BarChart::default()
                    .block(
                        Block::default()
                            .title("Response time histogram")
                            .style(
                                Style::default()
                                    .fg(colors.yellow.unwrap_or(Color::Reset))
                                    .bg(Color::Reset),
                            )
                            .borders(Borders::ALL),
                    )
                    .data(resp_histo_data_str.as_slice())
                    .bar_width(resp_histo_width as u16);
                f.render_widget(resp_histo, bottom[1]);
            })?;

            while crossterm::event::poll(std::time::Duration::from_secs(0))? {
                match crossterm::event::read()? {
                    Event::Key(KeyEvent {
                        code: KeyCode::Char('+'),
                        ..
                    }) => timescale_auto = Some(timescale.dec()),
                    Event::Key(KeyEvent {
                        code: KeyCode::Char('-'),
                        ..
                    }) => timescale_auto = Some(timescale.inc()),
                    Event::Key(KeyEvent {
                        code: KeyCode::Char('a'),
                        ..
                    }) => {
                        if timescale_auto.is_some() {
                            timescale_auto = None;
                        } else {
                            timescale_auto = Some(timescale)
                        }
                    }
                    // User pressed q or ctrl-c
                    Event::Key(KeyEvent {
                        code: KeyCode::Char('q'),
                        ..
                    })
                    | Event::Key(KeyEvent {
                        code: KeyCode::Char('c'),
                        modifiers: KeyModifiers::CONTROL,
                        ..
                    }) => {
                        std::io::stdout().execute(crossterm::terminal::LeaveAlternateScreen)?;
                        crossterm::terminal::disable_raw_mode()?;
                        std::io::stdout().execute(crossterm::cursor::Show)?;
                        let _ = crate::printer::print_result(
                            &mut std::io::stdout(),
                            self.print_mode,
                            self.start,
                            &all,
                            now - self.start,
                            self.disable_color,
                            self.stats_success_breakdown,
                        );
                        std::process::exit(libc::EXIT_SUCCESS);
                    }
                    _ => (),
                }
            }

            let per_frame = std::time::Duration::from_secs(1) / self.fps as u32;
            let elapsed = frame_start.elapsed();
            if per_frame > elapsed {
                tokio::time::sleep(per_frame - elapsed).await;
            }
        }

        std::io::stdout().execute(crossterm::terminal::LeaveAlternateScreen)?;
        crossterm::terminal::disable_raw_mode()?;
        std::io::stdout().execute(crossterm::cursor::Show)?;
        Ok(all)
    }
}