Skip to main content

tak_cli/
progress.rs

1//! Progress for a benchmark run, on stderr.
2//!
3//! A long comparison — ten minutes of cold installs — is otherwise silent
4//! until it finishes. On a terminal this draws one bar that redraws in place.
5//! Anywhere else (CI logs) it prints a plain line at most every tenth of the
6//! way or every 30 seconds, since a carriage-return animation turns into
7//! thousands of lines in a log.
8//!
9//! The time remaining is estimated per subject: each subject's average sample
10//! so far, prepare included, times the samples it still has to take. One
11//! average over everything would be badly wrong exactly when it matters —
12//! when a 20-second cold install shares a run with a 300ms one.
13//!
14//! A subject's one-time `setup` is shown while it runs but is not a sample:
15//! it counts toward elapsed time and nothing else, so a minute-long clone
16//! does not make every later sample look a minute long.
17
18use crate::measure::Observer;
19use std::io::{IsTerminal, Write};
20use std::sync::atomic::{AtomicBool, Ordering};
21use std::sync::{Arc, Mutex, PoisonError};
22use std::thread::JoinHandle;
23use std::time::{Duration, Instant};
24
25/// How often a non-terminal prints, at most, when no tenth has been crossed.
26const LOG_EVERY: Duration = Duration::from_secs(30);
27
28/// How often the ticker wakes. A terminal bar redraws its elapsed time this
29/// often while a sample runs; a log checks whether LOG_EVERY has passed.
30const TICK: Duration = Duration::from_secs(1);
31
32/// The progress reporter. Samples can run for minutes — a cold install, or a
33/// prepare step that re-downloads everything — so a ticker thread keeps the
34/// output alive between them rather than only when one finishes.
35pub struct Bar {
36    state: Arc<Mutex<State>>,
37    stop: Arc<AtomicBool>,
38    ticker: Option<JoinHandle<()>>,
39}
40
41impl Bar {
42    pub fn new(label: &str, names: Vec<String>) -> Self {
43        let state = Arc::new(Mutex::new(State::new(label, names)));
44        let stop = Arc::new(AtomicBool::new(false));
45        let ticker = {
46            let (state, stop) = (Arc::clone(&state), Arc::clone(&stop));
47            std::thread::spawn(move || {
48                while !stop.load(Ordering::Relaxed) {
49                    std::thread::park_timeout(TICK);
50                    if !stop.load(Ordering::Relaxed) {
51                        lock(&state).tick();
52                    }
53                }
54            })
55        };
56        Bar {
57            state,
58            stop,
59            ticker: Some(ticker),
60        }
61    }
62
63    /// Stop the ticker and clear the bar so results print on a clean line.
64    /// Call once the run is over, whatever its outcome.
65    pub fn finish(&mut self) {
66        self.stop.store(true, Ordering::Relaxed);
67        if let Some(t) = self.ticker.take() {
68            t.thread().unpark();
69            t.join().ok();
70        }
71        lock(&self.state).clear();
72    }
73}
74
75impl Drop for Bar {
76    fn drop(&mut self) {
77        self.finish();
78    }
79}
80
81/// A panic elsewhere must not also take the progress output down with it.
82fn lock(state: &Mutex<State>) -> std::sync::MutexGuard<'_, State> {
83    state.lock().unwrap_or_else(PoisonError::into_inner)
84}
85
86impl Observer for Bar {
87    fn planned(&mut self, remaining: &[u64]) {
88        lock(&self.state).planned(remaining);
89    }
90    fn setting_up(&mut self, subject: usize) {
91        lock(&self.state).setting_up(subject);
92    }
93    fn started(&mut self, subject: usize) {
94        lock(&self.state).started(subject);
95    }
96    fn finished(&mut self, subject: usize, elapsed: Duration) {
97        lock(&self.state).finished(subject, elapsed);
98    }
99    fn dropped(&mut self, subject: usize) {
100        lock(&self.state).dropped(subject);
101    }
102}
103
104struct State {
105    label: String,
106    names: Vec<String>,
107    remaining: Vec<u64>,
108    /// Per subject: total time and count of finished samples.
109    spent: Vec<(Duration, u32)>,
110    done: u64,
111    current: Option<usize>,
112    /// Whether `current` is running its setup rather than a sample.
113    in_setup: bool,
114    started: Instant,
115    tty: bool,
116    last_log: Instant,
117    last_tenth: u64,
118    drawn: bool,
119}
120
121impl State {
122    fn new(label: &str, names: Vec<String>) -> Self {
123        let n = names.len();
124        let now = Instant::now();
125        State {
126            label: label.to_string(),
127            names,
128            remaining: vec![0; n],
129            spent: vec![(Duration::ZERO, 0); n],
130            done: 0,
131            current: None,
132            in_setup: false,
133            started: now,
134            tty: std::io::stderr().is_terminal(),
135            last_log: now,
136            last_tenth: 0,
137            drawn: false,
138        }
139    }
140
141    fn total(&self) -> u64 {
142        self.done + self.remaining.iter().sum::<u64>()
143    }
144
145    /// Estimated time left, or `None` until anything has been timed.
146    fn eta(&self) -> Option<Duration> {
147        let (all, n) = self
148            .spent
149            .iter()
150            .fold((Duration::ZERO, 0u32), |(t, c), &(d, k)| (t + d, c + k));
151        if n == 0 {
152            return None;
153        }
154        // A subject not yet timed is guessed at the average of those that
155        // were, which is replaced by its own the moment it has one.
156        let fallback = all / n;
157        let secs: f64 = self
158            .remaining
159            .iter()
160            .zip(&self.spent)
161            .map(|(&left, &(d, k))| {
162                let each = if k == 0 { fallback } else { d / k };
163                each.as_secs_f64() * left as f64
164            })
165            .sum();
166        Some(Duration::from_secs_f64(secs))
167    }
168
169    fn line(&self, width: usize) -> String {
170        let total = self.total().max(1);
171        let pct = self.done * 100 / total;
172        let eta = if self.remaining.iter().all(|&r| r == 0) && self.done > 0 {
173            "done".to_string()
174        } else {
175            self.eta()
176                .map_or_else(|| "estimating".to_string(), |d| format!("~{} left", fmt(d)))
177        };
178        let who = match self.current {
179            Some(i) if self.in_setup => format!("setup {}", self.names[i]),
180            Some(i) => self.names[i].clone(),
181            None => String::new(),
182        };
183        let tail = format!(
184            " {}/{} {pct:>3}%  {} elapsed, {eta}  {who}",
185            self.done,
186            total,
187            fmt(self.started.elapsed())
188        );
189        if !self.tty {
190            return format!("  {}:{tail}", self.label);
191        }
192        // Whatever width is left for the bar itself, within reason.
193        let room = width.saturating_sub(self.label.len() + tail.len() + 6);
194        let cells = room.clamp(10, 30);
195        let filled = (cells as u64 * self.done / total) as usize;
196        let line = format!(
197            "  {} [{}{}]{tail}",
198            self.label,
199            "#".repeat(filled),
200            "-".repeat(cells - filled)
201        );
202        line.chars().take(width.saturating_sub(1)).collect()
203    }
204
205    fn draw(&mut self, force: bool) {
206        if self.tty {
207            let width = std::env::var("COLUMNS")
208                .ok()
209                .and_then(|c| c.parse().ok())
210                .unwrap_or(80);
211            eprint!("\r\x1b[2K{}", self.line(width));
212            std::io::stderr().flush().ok();
213            self.drawn = true;
214            return;
215        }
216        let tenth = self.done * 10 / self.total().max(1);
217        if force || tenth > self.last_tenth || self.last_log.elapsed() >= LOG_EVERY {
218            eprintln!("{}", self.line(usize::MAX));
219            self.last_tenth = tenth;
220            self.last_log = Instant::now();
221        }
222    }
223
224    /// Called by the ticker between events: redraw a terminal bar so its
225    /// elapsed time keeps moving, and give a log its periodic line even while
226    /// one long sample is still running.
227    fn tick(&mut self) {
228        if self.total() == 0 {
229            return;
230        }
231        if self.tty {
232            if self.drawn {
233                self.draw(false);
234            }
235        } else if self.last_log.elapsed() >= LOG_EVERY {
236            self.draw(true);
237        }
238    }
239
240    fn clear(&mut self) {
241        if self.tty && self.drawn {
242            eprint!("\r\x1b[2K");
243            std::io::stderr().flush().ok();
244            self.drawn = false;
245        }
246    }
247}
248
249impl Observer for State {
250    fn planned(&mut self, remaining: &[u64]) {
251        self.remaining = remaining.to_vec();
252        self.draw(false);
253    }
254
255    fn setting_up(&mut self, subject: usize) {
256        self.current = Some(subject);
257        self.in_setup = true;
258        // Forced in a log too: a setup can take minutes, and the line saying
259        // which one is running is the only sign the run has not hung.
260        self.draw(true);
261    }
262
263    fn started(&mut self, subject: usize) {
264        self.current = Some(subject);
265        self.in_setup = false;
266        if self.tty {
267            self.draw(false);
268        }
269    }
270
271    fn finished(&mut self, subject: usize, elapsed: Duration) {
272        self.remaining[subject] = self.remaining[subject].saturating_sub(1);
273        let (d, k) = &mut self.spent[subject];
274        *d += elapsed;
275        *k += 1;
276        self.done += 1;
277        self.current = None;
278        let last = self.remaining.iter().all(|&r| r == 0);
279        self.draw(last);
280    }
281
282    fn dropped(&mut self, subject: usize) {
283        self.remaining[subject] = 0;
284        self.current = None;
285        self.in_setup = false;
286        self.draw(false);
287    }
288}
289
290/// `850ms`, `42s`, `3m05s`, `1h02m`.
291pub fn fmt(d: Duration) -> String {
292    let s = d.as_secs();
293    match s {
294        0 => format!("{}ms", d.as_millis()),
295        1..60 => format!("{s}s"),
296        60..3600 => format!("{}m{:02}s", s / 60, s % 60),
297        _ => format!("{}h{:02}m", s / 3600, (s % 3600) / 60),
298    }
299}
300
301#[cfg(test)]
302mod tests {
303    use super::*;
304
305    fn bar(names: &[&str]) -> State {
306        let mut b = State::new("b", names.iter().map(|s| s.to_string()).collect());
307        b.tty = false;
308        b.last_log = Instant::now();
309        b
310    }
311
312    #[test]
313    fn durations_read_naturally() {
314        assert_eq!(fmt(Duration::from_millis(850)), "850ms");
315        assert_eq!(fmt(Duration::from_secs(42)), "42s");
316        assert_eq!(fmt(Duration::from_secs(185)), "3m05s");
317        assert_eq!(fmt(Duration::from_secs(3720)), "1h02m");
318    }
319
320    /// The estimate prices each subject's remaining samples at its own speed,
321    /// so a slow subject's backlog is not averaged away by a fast one.
322    #[test]
323    fn the_estimate_is_per_subject() {
324        let mut b = bar(&["fast", "slow"]);
325        b.planned(&[11, 6]);
326        b.finished(0, Duration::from_millis(100));
327        b.finished(1, Duration::from_secs(20));
328        // 10 x 100ms + 5 x 20s
329        let eta = b.eta().unwrap().as_secs_f64();
330        assert!((eta - 101.0).abs() < 0.01, "{eta}");
331    }
332
333    #[test]
334    fn an_untimed_subject_is_guessed_at_the_average() {
335        let mut b = bar(&["a", "b"]);
336        b.planned(&[2, 3]);
337        assert_eq!(b.eta(), None, "nothing timed yet");
338        b.finished(0, Duration::from_secs(2));
339        // 1 x 2s for a, 3 x 2s for b until b has a time of its own
340        assert_eq!(b.eta(), Some(Duration::from_secs(8)));
341    }
342
343    #[test]
344    fn a_dropped_subject_leaves_the_estimate() {
345        let mut b = bar(&["a", "b"]);
346        b.planned(&[2, 5]);
347        b.finished(0, Duration::from_secs(1));
348        b.finished(1, Duration::from_secs(10));
349        b.dropped(1);
350        assert_eq!(b.eta(), Some(Duration::from_secs(1)));
351        assert_eq!(b.total(), 3);
352    }
353
354    #[test]
355    fn the_bar_fits_the_terminal() {
356        let mut b = bar(&["aube"]);
357        b.tty = true;
358        b.planned(&[40]);
359        for _ in 0..10 {
360            b.finished(0, Duration::from_millis(250));
361        }
362        let line = b.line(80);
363        assert!(line.chars().count() < 80, "{line}");
364        assert!(line.contains("10/40") && line.contains("25%"), "{line}");
365        assert!(line.contains("~7s left"), "{line}");
366    }
367
368    /// A log gets a line every LOG_EVERY even when no sample has finished —
369    /// the case of one very long prepare step or sample.
370    #[test]
371    fn a_log_hears_from_a_long_sample_before_it_finishes() {
372        let mut b = bar(&["slow"]);
373        b.planned(&[5]);
374        b.started(0);
375        let before = b.last_log;
376        b.tick();
377        assert_eq!(b.last_log, before, "too soon to log again");
378        b.last_log = Instant::now() - LOG_EVERY;
379        b.tick();
380        assert!(b.last_log > before, "the ticker logged mid-sample");
381    }
382
383    /// A setup is named while it runs but is not a sample: it neither
384    /// advances the count nor enters the estimate.
385    #[test]
386    fn setup_is_shown_but_not_counted() {
387        let mut b = bar(&["aube", "pnpm"]);
388        b.planned(&[2, 2]);
389        b.setting_up(1);
390        assert!(
391            b.line(usize::MAX).ends_with("setup pnpm"),
392            "{}",
393            b.line(usize::MAX)
394        );
395        assert_eq!((b.done, b.eta()), (0, None));
396        b.started(0);
397        assert!(
398            b.line(usize::MAX).ends_with(" aube"),
399            "{}",
400            b.line(usize::MAX)
401        );
402        b.finished(0, Duration::from_secs(1));
403        assert_eq!(b.eta(), Some(Duration::from_secs(3)));
404    }
405
406    /// The ticker thread starts and stops cleanly, and finishing twice (the
407    /// explicit call, then Drop) is harmless.
408    #[test]
409    fn the_ticker_stops_when_finished() {
410        let mut b = Bar::new("b", vec!["a".into()]);
411        b.planned(&[1]);
412        b.finished(0, Duration::from_millis(1));
413        b.finish();
414        assert!(b.ticker.is_none());
415    }
416}