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