1#![cfg(feature = "tui")]
2
3use std::{
18 borrow::Cow,
19 collections::VecDeque,
20 fmt::Write as _,
21 io::IsTerminal,
22 sync::{
23 Arc, Mutex,
24 atomic::{AtomicBool, AtomicU64, Ordering},
25 },
26 time::{Duration, Instant},
27};
28
29use tokio::task::JoinHandle;
30
31use crate::{
32 report::{bar, fmt_duration, paint},
33 shutdown::Shutdown,
34};
35
36#[derive(Clone, Debug)]
44pub struct LogChannel {
45 inner: Arc<Mutex<LogBuf>>,
46}
47
48#[derive(Debug)]
49struct LogBuf {
50 lines: VecDeque<String>,
51 max_lines: usize,
52}
53
54impl Default for LogChannel {
55 fn default() -> Self {
56 Self::with_capacity(200)
57 }
58}
59
60impl LogChannel {
61 pub fn with_capacity(max_lines: usize) -> Self {
63 Self {
64 inner: Arc::new(Mutex::new(LogBuf {
65 lines: VecDeque::with_capacity(max_lines.min(1024)),
66 max_lines,
67 })),
68 }
69 }
70
71 pub fn push_line(&self, line: impl Into<String>) {
73 let mut buf = self.inner.lock().unwrap();
74 let line = line.into();
75 let line = line.strip_suffix('\n').unwrap_or(&line).to_string();
76 if buf.lines.len() == buf.max_lines {
77 buf.lines.pop_front();
78 }
79 buf.lines.push_back(line);
80 }
81
82 pub fn lines(&self) -> Vec<String> {
84 self.inner.lock().unwrap().lines.iter().cloned().collect()
85 }
86
87 pub fn drain(&self) -> Vec<String> {
89 let mut buf = self.inner.lock().unwrap();
90 buf.lines.drain(..).collect()
91 }
92}
93
94impl std::io::Write for LogChannel {
95 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
96 let text = String::from_utf8_lossy(buf);
97 for line in text.split('\n') {
98 if !line.is_empty() {
99 self.push_line(line);
100 }
101 }
102 Ok(buf.len())
103 }
104
105 fn flush(&mut self) -> std::io::Result<()> {
106 Ok(())
107 }
108}
109
110#[derive(Debug, Clone, Copy)]
112pub(crate) enum ProgressPlan {
113 Rounds(u64),
115 Time(Duration),
117}
118
119#[derive(Clone, Debug)]
125pub struct Progress {
126 inner: Arc<Inner>,
127}
128
129#[derive(Debug)]
130struct Inner {
131 name: Cow<'static, str>,
132 plan: ProgressPlan,
133 scenario_index: usize,
135 scenario_total: usize,
136 started: Instant,
137 rounds: AtomicU64,
139 success: AtomicU64,
141 failures: AtomicU64,
142 timeouts: AtomicU64,
144 validate_failures: AtomicU64,
145 teardown_failures: AtomicU64,
147 in_flight: AtomicU64,
149 in_setup: AtomicU64,
151 stop: AtomicBool,
153 log: Option<LogChannel>,
155}
156
157impl Progress {
158 pub(crate) fn new(
159 name: impl Into<Cow<'static, str>>,
160 plan: ProgressPlan,
161 log: Option<LogChannel>,
162 scenario_index: usize,
163 scenario_total: usize,
164 ) -> Self {
165 Self {
166 inner: Arc::new(Inner {
167 name: name.into(),
168 plan,
169 scenario_index,
170 scenario_total,
171 started: Instant::now(),
172 rounds: AtomicU64::new(0),
173 success: AtomicU64::new(0),
174 failures: AtomicU64::new(0),
175 timeouts: AtomicU64::new(0),
176 validate_failures: AtomicU64::new(0),
177 teardown_failures: AtomicU64::new(0),
178 in_flight: AtomicU64::new(0),
179 in_setup: AtomicU64::new(0),
180 stop: AtomicBool::new(false),
181 log,
182 }),
183 }
184 }
185 #[cfg(feature = "tui")]
191 pub(crate) fn start_tui(
192 &self,
193 channel: crate::LogChannel,
194 options: crate::tui::TuiOptions,
195 shutdown: Option<Shutdown>,
196 ) -> ProgressGuard {
197 if !std::io::stderr().is_terminal() {
198 return ProgressGuard {
199 inner: Arc::clone(&self.inner),
200 handle: None,
201 };
202 }
203 let inner = Arc::clone(&self.inner);
204 let task_inner = Arc::clone(&inner);
205 let handle = tokio::spawn(async move {
206 let mut writer = std::io::stderr();
207 let _ = std::io::Write::write(&mut writer, b"\x1b[?1049h");
209 let _ = std::io::Write::flush(&mut writer);
210 loop {
211 let stopping = shutdown.as_ref().is_some_and(|s| s.is_cancelled());
212 let line = render_line(&task_inner, stopping, options.color, options.bar_width);
213 let frame = crate::tui::render_frame(&line, &channel, &options);
214 let text = format!("\x1b[H\x1b[2J{frame}");
216 let _ = std::io::Write::write(&mut writer, text.as_bytes());
217 let _ = std::io::Write::flush(&mut writer);
218
219 if task_inner.stop.load(Ordering::Relaxed) {
220 break;
221 }
222 tokio::time::sleep(options.refresh).await;
223 }
224 let _ = std::io::Write::write(&mut writer, b"\x1b[?1049l");
226 let _ = std::io::Write::flush(&mut writer);
227 });
228 ProgressGuard {
229 inner,
230 handle: Some(handle),
231 }
232 }
233
234 pub(crate) fn begin_round(&self) {
238 self.inner.in_flight.fetch_add(1, Ordering::Relaxed);
239 }
240
241 pub(crate) fn end_round(&self) {
243 self.inner.in_flight.fetch_sub(1, Ordering::Relaxed);
244 }
245
246 pub(crate) fn begin_setup(&self) {
248 self.inner.in_setup.fetch_add(1, Ordering::Relaxed);
249 }
250
251 pub(crate) fn end_setup(&self) {
253 self.inner.in_setup.fetch_sub(1, Ordering::Relaxed);
254 }
255
256 pub(crate) fn round_recorded(&self) {
258 self.inner.rounds.fetch_add(1, Ordering::Relaxed);
259 }
260
261 pub(crate) fn result_recorded(&self, ok: bool) {
263 if ok {
264 self.inner.success.fetch_add(1, Ordering::Relaxed);
265 } else {
266 self.inner.failures.fetch_add(1, Ordering::Relaxed);
267 }
268 }
269
270 pub(crate) fn timeout_recorded(&self) {
272 self.inner.timeouts.fetch_add(1, Ordering::Relaxed);
273 }
274
275 pub(crate) fn validate_recorded(&self, ok: bool) {
277 if !ok {
278 self.inner.validate_failures.fetch_add(1, Ordering::Relaxed);
279 }
280 }
281
282 pub(crate) fn teardown_recorded(&self, ok: bool) {
284 if !ok {
285 self.inner.teardown_failures.fetch_add(1, Ordering::Relaxed);
286 }
287 }
288
289 pub(crate) fn push_log(&self, line: &str) -> bool {
291 if let Some(channel) = &self.inner.log {
292 channel.push_line(format!("[{} {line}]", now_hms()));
293 true
294 } else {
295 false
296 }
297 }
298}
299
300pub(crate) struct ProgressGuard {
303 inner: Arc<Inner>,
304 handle: Option<JoinHandle<()>>,
305}
306
307impl ProgressGuard {
308 pub(crate) async fn stop(mut self) {
310 self.inner.stop.store(true, Ordering::Relaxed);
311 if let Some(handle) = self.handle.take() {
312 let _ = handle.await;
313 }
314 }
315}
316
317impl Drop for ProgressGuard {
318 fn drop(&mut self) {
319 self.inner.stop.store(true, Ordering::Relaxed);
320 if let Some(handle) = self.handle.take() {
321 handle.abort();
322 }
323 }
324}
325
326const NAME_WIDTH: usize = 20;
330
331fn render_line(inner: &Inner, stopping: bool, color: bool, bar_width: usize) -> String {
334 let name = fit_name(&inner.name);
335 let mut line = String::with_capacity(128);
336 if inner.scenario_total > 1 {
337 let _ = write!(
338 line,
339 "[{}/{}] ",
340 inner.scenario_index + 1,
341 inner.scenario_total
342 );
343 }
344
345 if inner.in_setup.load(Ordering::Relaxed) > 0 {
347 let _ = write!(line, "{name} {}", paint("setup...", "33", color));
348 return line;
349 }
350
351 let elapsed = inner.started.elapsed();
352 let rounds = inner.rounds.load(Ordering::Relaxed);
353 let (fraction, progress) = match inner.plan {
354 ProgressPlan::Rounds(total) => (ratio(rounds, total), format!("{rounds}/{total}")),
355 ProgressPlan::Time(planned) => (
356 ratio(elapsed.as_millis() as u64, planned.as_millis() as u64),
357 format!("{}/{}", fmt_duration(elapsed), fmt_duration(planned)),
358 ),
359 };
360
361 let _ = write!(
362 line,
363 "{name} [{}] {:>5.1}% {progress:>15} {:>7} req/s",
364 bar(fraction, bar_width),
365 fraction * 100.0,
366 rate(rounds, elapsed),
367 );
368
369 if rounds > 0 {
372 let passed = inner
373 .success
374 .load(Ordering::Relaxed)
375 .saturating_sub(inner.validate_failures.load(Ordering::Relaxed));
376 let err = inner.failures.load(Ordering::Relaxed)
377 + inner.validate_failures.load(Ordering::Relaxed);
378 let timeouts = inner.timeouts.load(Ordering::Relaxed);
379 let _ = write!(line, " succ {passed}");
380 if err > 0 {
381 let _ = write!(line, " {}", paint(&format!("err {err}"), "31", color));
382 }
383 if timeouts > 0 {
384 let _ = write!(
385 line,
386 " {}",
387 paint(&format!("timeout {timeouts}"), "33", color)
388 );
389 }
390 let teardown_failures = inner.teardown_failures.load(Ordering::Relaxed);
392 if teardown_failures > 0 {
393 let _ = write!(
394 line,
395 " {}",
396 paint(&format!("cleanup {teardown_failures}"), "31", color)
397 );
398 }
399 }
400
401 let in_flight = inner.in_flight.load(Ordering::Relaxed);
402 if in_flight > 0 {
403 let _ = write!(line, " inflight {in_flight}");
404 }
405
406 if stopping {
407 let _ = write!(line, " {}", paint("stopping...", "33", color));
408 }
409
410 line
411}
412
413fn fit_name(name: &str) -> String {
415 if name.chars().count() <= NAME_WIDTH {
416 format!("{name:<NAME_WIDTH$}")
417 } else {
418 let head: String = name.chars().take(NAME_WIDTH - 1).collect();
419 format!("{head}…")
420 }
421}
422
423fn ratio(done: u64, total: u64) -> f64 {
425 if total == 0 {
426 return 1.0;
427 }
428 (done as f64 / total as f64).clamp(0.0, 1.0)
429}
430
431fn now_hms() -> String {
433 let now = std::time::SystemTime::now()
434 .duration_since(std::time::UNIX_EPOCH)
435 .unwrap_or_default()
436 .as_secs();
437 let (h, m, s) = (now / 3600 % 24, now / 60 % 60, now % 60);
438 format!("{h:02}:{m:02}:{s:02}")
439}
440
441fn rate(rounds: u64, elapsed: Duration) -> u64 {
443 let secs = elapsed.as_secs_f64();
444 if secs < 0.001 {
445 return 0;
446 }
447 (rounds as f64 / secs) as u64
448}
449
450#[cfg(test)]
451mod tests {
452 use super::*;
453
454 #[test]
455 fn line_shows_rounds_percent_and_rate() {
456 let p = Progress::new("login", ProgressPlan::Rounds(1000), None, 1, 3);
457 for _ in 0..250 {
458 p.round_recorded();
459 }
460 for _ in 0..249 {
461 p.result_recorded(true);
462 }
463 p.result_recorded(false);
464 for _ in 0..249 {
465 p.validate_recorded(true);
466 }
467 for _ in 0..3 {
468 p.timeout_recorded();
469 }
470
471 let line = render_line(&p.inner, false, false, 20);
472 assert!(line.contains("login"), "{line}");
473 assert!(line.contains("[2/3]"), "{line}");
474 assert!(line.contains("25.0%"), "{line}");
475 assert!(line.contains("250/1000"), "{line}");
476 assert!(line.contains("req/s"), "{line}");
477 assert!(line.contains("succ 249"), "{line}");
479 assert!(line.contains("err 1"), "{line}");
480 assert!(line.contains("timeout 3"), "{line}");
482 assert!(!line.contains("fail"), "{line}");
484 assert!(!line.contains('\x1b'), "{line}");
486 assert!(!line.contains("setup"), "{line}");
488 assert!(!line.contains("inflight"), "{line}");
489 }
490
491 #[test]
492 fn line_reports_setup_phase_and_stopping() {
493 let p = Progress::new("scn", ProgressPlan::Rounds(10), None, 0, 2);
494 p.begin_setup();
495 let line = render_line(&p.inner, false, false, 20);
496 assert!(line.contains("setup..."), "{line}");
497 assert!(line.contains("[1/2]"), "{line}");
498 assert!(!line.contains("req/s"), "{line}");
499
500 p.end_setup();
501 p.begin_round();
502 let line = render_line(&p.inner, true, false, 20);
503 assert!(line.contains("inflight 1"), "{line}");
504 assert!(line.contains("stopping..."), "{line}");
505 assert!(!line.contains("succ"), "{line}");
507 assert!(!line.contains("err"), "{line}");
508 }
509
510 #[test]
511 fn line_shows_teardown_failures_separately() {
512 let p = Progress::new("scn", ProgressPlan::Rounds(10), None, 0, 1);
513 p.round_recorded();
514 p.result_recorded(true);
515 p.teardown_recorded(true);
516 p.teardown_recorded(false);
517 p.teardown_recorded(false);
518
519 let line = render_line(&p.inner, false, false, 20);
520 assert!(line.contains("cleanup 2"), "{line}");
521 assert!(line.contains("succ 1"), "{line}");
523 assert!(!line.contains("err"), "{line}");
524 assert!(!line.contains("fail"), "{line}");
525
526 let ok = Progress::new("ok", ProgressPlan::Rounds(10), None, 0, 1);
528 ok.round_recorded();
529 ok.teardown_recorded(true);
530 let line = render_line(&ok.inner, false, false, 20);
531 assert!(!line.contains("cleanup"), "{line}");
532 }
533
534 #[test]
535 fn duration_plan_uses_elapsed_over_planned() {
536 let p = Progress::new(
537 "dur",
538 ProgressPlan::Time(Duration::from_secs(600)),
539 None,
540 0,
541 1,
542 );
543 let line = render_line(&p.inner, false, false, 20);
544 assert!(line.contains("0.0%"), "{line}");
545 assert!(line.contains("/600000.00ms"), "{line}");
546 }
547
548 #[test]
549 fn long_name_is_truncated_to_fixed_width() {
550 let p = Progress::new(
551 "a_very_long_scenario_name_indeed",
552 ProgressPlan::Rounds(1),
553 None,
554 0,
555 3,
556 );
557 let line = render_line(&p.inner, false, false, 20);
558 assert!(line.starts_with("[1/3] a_very_long_scenari…"), "{line}");
559 }
560
561 #[test]
562 fn single_scenario_hides_index_badge() {
563 let p = Progress::new("only", ProgressPlan::Rounds(1), None, 0, 1);
564 let line = render_line(&p.inner, false, false, 20);
565 assert!(!line.contains("[1/1]"), "单场景不应显示序号: {line}");
566 assert!(line.starts_with("only"), "{line}");
567 }
568
569 #[test]
570 fn color_option_paints_failures() {
571 let p = Progress::new("scn", ProgressPlan::Rounds(1), None, 0, 1);
572 p.round_recorded();
573 p.result_recorded(false);
574 let line = render_line(&p.inner, false, true, 20);
575 assert!(line.contains("\x1b[31merr 1\x1b[0m"), "{line}");
576 }
577
578 #[test]
579 fn log_channel_ring_buffer_and_write() {
580 let mut channel = LogChannel::with_capacity(3);
581 channel.push_line("a");
582 channel.push_line("b");
583 channel.push_line("c");
584 channel.push_line("d"); assert_eq!(channel.lines(), vec!["b", "c", "d"]);
586
587 std::io::Write::write_all(&mut channel, b"e\nf\n").unwrap();
589 assert_eq!(channel.lines(), vec!["d", "e", "f"]);
590
591 assert_eq!(channel.drain(), vec!["d", "e", "f"]);
593 assert!(channel.lines().is_empty());
594 }
595
596 #[test]
597 fn push_log_prefixes_time_in_tui_mode() {
598 let channel = LogChannel::with_capacity(10);
599 let p = Progress::new("s", ProgressPlan::Rounds(1), Some(channel.clone()), 0, 1);
600 assert!(p.push_log("boom"));
601 let lines = channel.lines();
602 assert_eq!(lines.len(), 1);
603 assert!(lines[0].starts_with('['), "{lines:?}");
604 assert!(lines[0].ends_with("boom]"), "{lines:?}");
605
606 let p = Progress::new("s", ProgressPlan::Rounds(1), None, 0, 1);
608 assert!(!p.push_log("x"));
609 }
610}