Skip to main content

memseek_test/
progress.rs

1#![cfg(feature = "tui")]
2
3//! 实时进度计数与 TUI 渲染支撑(进度渲染见 [`crate::tui`],feature `tui`)。
4//!
5//! 设计约束:
6//!
7//! - **只读旁路**:进度只累加共享原子计数,展示的轮数/失败数与最终报告字段
8//!   一一对应(`times` / `failures` / `validate_failures`),但最终统计仍以
9//!   merge 后的 [`Recorder`](crate::recorder::Recorder) 为准,进度永不影响结果;
10//! - **热路径零锁**:并发任务每次记录只做 `Relaxed` 原子加,渲染在独立 Tokio
11//!   任务中按刷新间隔采样,不阻塞正在等响应的业务任务;
12//! - **仅 TUI 形态**:进度只随 feature `tui` 的 `with_tui` 启用,
13//!   非 TTY(CI/重定向)自动静默;
14//! - 本模块还提供 [`LogChannel`] 日志环形缓冲:框架内部警告与用户 tracing
15//!   日志都经它进日志区,避免与进度行字节级交错。
16
17use 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/// 日志环形缓冲(TUI 模式的日志区数据源)。
37///
38/// 实现 [`std::io::Write`](https://doc.rust-lang.org/std/io/trait.Write.html):
39/// 按行切分入队,超容量丢弃最旧;`Clone` 共享同一缓冲。
40/// 配合 feature `tui` 的 [`crate::tui::TuiOptions`] 使用:
41/// 也可作为 `tracing_subscriber::fmt::layer().with_writer(channel)`
42/// 的 writer,把业务日志接入日志区。
43#[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    /// 创建环形缓冲,最多保留 `max_lines` 行。
62    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    /// 推送一行(内部会去掉行尾换行)。
72    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    /// 当前缓冲内容(旧→新)。
83    pub fn lines(&self) -> Vec<String> {
84        self.inner.lock().unwrap().lines.iter().cloned().collect()
85    }
86
87    /// 取出全部内容并清空(用于 TUI 退出后的日志回放)。
88    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/// 进度计划(Manager 解析 `RunMode` 后注入)。
111#[derive(Debug, Clone, Copy)]
112pub(crate) enum ProgressPlan {
113    /// 总轮数(`RunMode::Times`)
114    Rounds(u64),
115    /// 总时长(`RunMode::Duration`)
116    Time(Duration),
117}
118
119/// 实时进度句柄,克隆共享同一份计数。
120///
121/// 由 [`ScenarioManager`](crate::manager::ScenarioManager) 按场景创建并注入
122/// [`RunnerConfig`](crate::runner::RunnerConfig);手动构造 `RunnerConfig`
123/// 时填 `None` 即可,仅不显示进度,功能不受影响。
124#[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    /// 当前场景序号(0 起)与场景总数;`total <= 1` 时不显示 `[n/N]`
134    scenario_index: usize,
135    scenario_total: usize,
136    started: Instant,
137    /// 已完成轮数(与报告 `times` 对齐:由 `record_duration` 累加)
138    rounds: AtomicU64,
139    /// run 成功次数(与报告 `success` 对齐)
140    success: AtomicU64,
141    failures: AtomicU64,
142    /// 超时类软失败次数(与报告 `timeouts` 对齐,由 `timeout_recorded` 累加)
143    timeouts: AtomicU64,
144    validate_failures: AtomicU64,
145    /// 收尾失败次数(不参与 succ/err 统计,单独展示)
146    teardown_failures: AtomicU64,
147    /// 当前在途请求数(`begin_round` / `end_round` 维护)
148    in_flight: AtomicU64,
149    /// 当前处于 setup 阶段的任务数
150    in_setup: AtomicU64,
151    /// 渲染循环停止标志
152    stop: AtomicBool,
153    /// TUI 模式激活时持有日志缓冲(否则为 `None`,不采集)
154    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    // ---------- 热路径钩子(由 Recorder / ScenarioRunner 调用) ----------
186
187    /// TUI 模式渲染任务(feature `tui`,须在 Tokio runtime 内调用)。
188    /// 进入 alternate screen 全屏渲染:顶部进度行 + 日志区;
189    /// 停止时恢复原屏幕。非 TTY 时返回不渲染的空守卫。
190    #[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            // 进入 alternate screen
208            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                // 回到左上角后清屏重绘,避免残留
215                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            // 恢复原屏幕
225            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    // ---------- 热路径钩子(由 Recorder / ScenarioRunner 调用) ----------
235
236    /// 一轮 `run` 开始:在途 +1
237    pub(crate) fn begin_round(&self) {
238        self.inner.in_flight.fetch_add(1, Ordering::Relaxed);
239    }
240
241    /// 一轮 `run` 结束:在途 -1
242    pub(crate) fn end_round(&self) {
243        self.inner.in_flight.fetch_sub(1, Ordering::Relaxed);
244    }
245
246    /// 进入 setup 阶段
247    pub(crate) fn begin_setup(&self) {
248        self.inner.in_setup.fetch_add(1, Ordering::Relaxed);
249    }
250
251    /// 退出 setup 阶段
252    pub(crate) fn end_setup(&self) {
253        self.inner.in_setup.fetch_sub(1, Ordering::Relaxed);
254    }
255
256    /// 记录一轮耗时(与报告 `times` 同步累加)
257    pub(crate) fn round_recorded(&self) {
258        self.inner.rounds.fetch_add(1, Ordering::Relaxed);
259    }
260
261    /// 记录一轮 run 结果
262    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    /// 记录一轮超时软失败(不计入 failures)
271    pub(crate) fn timeout_recorded(&self) {
272        self.inner.timeouts.fetch_add(1, Ordering::Relaxed);
273    }
274
275    /// 记录一轮 validate 结果
276    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    /// 记录一次 teardown 失败(成功不计数,避免刷屏)
283    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    /// 框架内部日志进 TUI 日志缓冲(带时间前缀);无缓冲时返回 `false`,由调用方落 tracing。
290    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
300/// 渲染任务的停止守卫:drop 即停止(异常路径兜底),正常路径应调用
301/// [`ProgressGuard::stop`] 以等待渲染任务收尾(恢复屏幕)。
302pub(crate) struct ProgressGuard {
303    inner: Arc<Inner>,
304    handle: Option<JoinHandle<()>>,
305}
306
307impl ProgressGuard {
308    /// 停止渲染并等待任务收尾。
309    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
326// ---------- 渲染 ----------
327
328/// 场景名展示宽度(按字符截断,保证单行长度可控)
329const NAME_WIDTH: usize = 20;
330
331/// 组装进度行文本(纯函数,便于测试);供 TUI 帧渲染使用。
332/// 多场景时带 `[n/N]` 前缀(单场景不显示)。
333fn 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    // setup 阶段(仅 Task 粒度):轮数尚未开始
346    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    // 成功/失败对账:succ = 有效通过(run 成功且 validate 通过),
370    // err = run 失败 + validate 失败;超时软失败单独以黄色显示
371    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        // 收尾失败单列(不计入 err):便于区分“压测失败”与“收尾失败”
391        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
413/// 名称按字符截断到 [`NAME_WIDTH`],不足补空格对齐
414fn 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
423/// `done / total` → 0.0 ~ 1.0;`total` 为 0 视为已完成
424fn 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
431/// 当前本地时间 `HH:MM:SS`(用于框架日志的时间前缀)
432fn 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
441/// 累计平均吞吐(attempts / 已用时),计 0 或耗时过短时返回 0
442fn 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        // 成功/失败对账:succ + err = 已完成轮数
478        assert!(line.contains("succ 249"), "{line}");
479        assert!(line.contains("err 1"), "{line}");
480        // 超时软失败单独计数,黄字着色由 color_option 覆盖
481        assert!(line.contains("timeout 3"), "{line}");
482        // fail 已由 err 取代,不得残留
483        assert!(!line.contains("fail"), "{line}");
484        // 默认无颜色
485        assert!(!line.contains('\x1b'), "{line}");
486        // 未进入 setup、无在途请求时不显示这些片段
487        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        // 无轮次完成时不显示 succ/err
506        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        // 收尾失败不计入 err(载荷侧口径不变)
522        assert!(line.contains("succ 1"), "{line}");
523        assert!(!line.contains("err"), "{line}");
524        assert!(!line.contains("fail"), "{line}");
525
526        // 收尾全部成功时不占用进度行
527        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"); // 超容量丢最旧
585        assert_eq!(channel.lines(), vec!["b", "c", "d"]);
586
587        // io::Write 按行切分,行尾换行不残留
588        std::io::Write::write_all(&mut channel, b"e\nf\n").unwrap();
589        assert_eq!(channel.lines(), vec!["d", "e", "f"]);
590
591        // drain 取出并清空
592        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        // 无日志通道时返回 false,调用方走 tracing 兜底
607        let p = Progress::new("s", ProgressPlan::Rounds(1), None, 0, 1);
608        assert!(!p.push_log("x"));
609    }
610}