zc2 0.0.50

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
//! Measuring and drawing: the primitives every `zc bench` view is built from.
//!
//! One rule runs through all of it — measure what the eye sees, never what is
//! stored. Colour escapes occupy no columns, so a `len()` on a coloured string
//! is always wrong, and a table padded by `len()` comes out ragged the moment
//! a value is coloured.

use std::time::Duration;

/// How wide a string looks on screen: colour escapes take no columns, and a
/// count of `char`s is what every padding decision here needs.
pub(crate) fn visible_width(s: &str) -> usize {
    let mut n = 0;
    let mut chars = s.chars();
    while let Some(c) = chars.next() {
        if c == '\u{1b}' {
            for e in chars.by_ref() {
                if e == 'm' {
                    break;
                }
            }
        } else {
            n += 1;
        }
    }
    n
}

/// Pad `s` to `width` columns, measuring what is visible rather than what is
/// stored — the reason the old tables came out ragged once a name was longer
/// than its hard-coded column.
pub(crate) fn pad(s: &str, width: usize, right: bool) -> String {
    let fill = " ".repeat(width.saturating_sub(visible_width(s)));
    match right {
        true => format!("{fill}{s}"),
        false => format!("{s}{fill}"),
    }
}

/// Drop trailing spaces from every line. Columns pad to align; the padding on
/// the last column of a row is just whitespace nobody wants in a log or a
/// copied selection.
pub(crate) fn trim_lines(block: &str) -> String {
    let mut out = String::with_capacity(block.len());
    for line in block.split_inclusive('\n') {
        let (text, nl) = match line.strip_suffix('\n') {
            Some(t) => (t, "\n"),
            None => (line, ""),
        };
        out.push_str(text.trim_end());
        out.push_str(nl);
    }
    out
}

/// The eighth-width block characters, so a bar can end part-way through a
/// cell. Without them every bar is rounded to a whole column, and the small
/// buckets of a histogram — the tail, which is the interesting part — all
/// round to nothing and read as zero.
const EIGHTHS: [char; 8] = [' ', '▏', '▎', '▍', '▌', '▋', '▊', '▉'];

/// A proportional bar `width` cells wide, to an eighth of a cell.
pub(crate) fn bar(count: u64, max: u64, width: usize) -> String {
    if width == 0 {
        return String::new();
    }
    let units = match max {
        0 => 0.0,
        max => count as f64 / max as f64 * width as f64,
    };
    let full = (units.floor() as usize).min(width);
    let rem = ((units - units.floor()) * 8.0).round() as usize;
    let mut out = "█".repeat(full);
    if rem > 0 && full < width {
        out.push(EIGHTHS[rem.min(7)]);
    }
    let drawn = visible_width(&out);
    out.push_str(&" ".repeat(width.saturating_sub(drawn)));
    out
}

/// One bar holding two quantities, drawn so the split survives losing colour:
/// solid blocks for the first, shaded for the second. `zc bench` uses it for
/// free-versus-billed work, where mistaking one for the other is the whole
/// point of showing it.
pub(crate) fn split_bar(a: u64, b: u64, width: usize) -> (String, String) {
    let total = a + b;
    if total == 0 || width == 0 {
        return (" ".repeat(width), String::new());
    }
    let na = ((a as f64 / total as f64) * width as f64).round() as usize;
    // Never let a non-zero share round away to nothing: a bar that says a
    // third of the work was billed, when in truth one request was, is a
    // smaller lie than a bar that says none of it was.
    let na = match (a, na) {
        (0, _) => 0,
        (_, 0) => 1,
        (_, n) => n.min(width.saturating_sub(if b > 0 { 1 } else { 0 })),
    };
    ("█".repeat(na), "▒".repeat(width - na))
}

/// The eight sparkline heights, low to high.
const SPARKS: [char; 8] = ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];

/// A sparkline of `vals`, scaled between its own low and high. Answers the one
/// question a single rate figure cannot: is this steady, climbing, or falling
/// apart.
pub(crate) fn spark(vals: &[f64]) -> String {
    if vals.is_empty() {
        return String::new();
    }
    let lo = vals.iter().copied().fold(f64::INFINITY, f64::min);
    let hi = vals.iter().copied().fold(f64::NEG_INFINITY, f64::max);
    if !lo.is_finite() || !hi.is_finite() || (hi - lo).abs() < f64::EPSILON {
        return SPARKS[SPARKS.len() / 2].to_string().repeat(vals.len());
    }
    vals.iter()
        .map(|v| {
            let i = ((v - lo) / (hi - lo) * (SPARKS.len() - 1) as f64).round() as usize;
            SPARKS[i.min(SPARKS.len() - 1)]
        })
        .collect()
}

/// A box sized to its own contents. The old one had a 43-column border around
/// 41 columns of text, which is why the title never lined up.
pub(crate) fn boxed(lines: &[String]) -> String {
    use colored::Colorize;
    let inner = lines.iter().map(|l| visible_width(l)).max().unwrap_or(0) + 4;
    let mut out = String::new();
    out.push_str(&format!(
        "  {}\n",
        format!("╭{}╮", "─".repeat(inner)).cyan()
    ));
    for line in lines {
        out.push_str(&format!(
            "  {}  {}  {}\n",
            "│".cyan(),
            pad(line, inner - 4, false),
            "│".cyan()
        ));
    }
    out.push_str(&format!(
        "  {}\n",
        format!("╰{}╯", "─".repeat(inner)).cyan()
    ));
    out
}

/// The terminal's width in columns, asked of the terminal itself.
///
/// `$COLUMNS` is a shell variable, not an environment one: bash and zsh both
/// keep it to themselves, so a child process almost never sees it and the
/// whole view used to lay itself out for the 96-column fallback whatever the
/// window actually was. `TIOCGWINSZ` is what the terminal will answer.
/// `$COLUMNS` stays as an override — it is how a test, or someone recording a
/// terminal, pins the width.
pub(crate) fn term_width() -> usize {
    if let Some(w) = std::env::var("COLUMNS")
        .ok()
        .and_then(|c| c.trim().parse::<usize>().ok())
        .filter(|w| *w >= 40)
    {
        return w.min(220);
    }
    ioctl_width().filter(|w| *w >= 40).unwrap_or(96).min(220)
}

/// The window width from the controlling terminal, or `None` when stdout is
/// not one (a pipe, a file, CI).
#[cfg(unix)]
fn ioctl_width() -> Option<usize> {
    use std::io::IsTerminal;
    if !std::io::stdout().is_terminal() {
        return None;
    }
    // SAFETY: `winsize` is plain old data that the kernel fills in; we pass a
    // pointer to a local that outlives the call and read it only on success.
    unsafe {
        let mut ws: libc::winsize = std::mem::zeroed();
        match libc::ioctl(libc::STDOUT_FILENO, libc::TIOCGWINSZ, &mut ws) {
            0 if ws.ws_col > 0 => Some(ws.ws_col as usize),
            _ => None,
        }
    }
}

#[cfg(not(unix))]
fn ioctl_width() -> Option<usize> {
    None
}

/// `100000` → `100 000`. Long runs are the ones worth watching, and a
/// six-digit counter is unreadable without separators.
pub(crate) fn grouped(n: u64) -> String {
    let digits = n.to_string();
    let mut out = String::with_capacity(digits.len() + digits.len() / 3);
    for (i, c) in digits.chars().enumerate() {
        if i > 0 && (digits.len() - i).is_multiple_of(3) {
            out.push('\u{2009}');
        }
        out.push(c);
    }
    out
}

/// Microseconds as something readable at a glance: `820µs`, `4.2ms`, `1.35s`.
pub(crate) fn fmt_us(us: u64) -> String {
    match us {
        0 => "—".to_string(),
        us if us < 1_000 => format!("{us}µs"),
        us if us < 1_000_000 => format!("{:.1}ms", us as f64 / 1_000.0),
        us => format!("{:.2}s", us as f64 / 1_000_000.0),
    }
}

/// A millisecond figure, formatted the same way `fmt_us` formats a duration
/// -- so the "expected" and "delivered" halves of a comparison always read in
/// the same units.
pub(crate) fn fmt_ms(ms: f64) -> String {
    fmt_us((ms.max(0.0) * 1000.0).round() as u64)
}

/// A duration for an axis label, where the figure is a round number by
/// construction: `250ms`, not `250.0ms`. One decimal on every tick is noise
/// on eleven rows of them.
pub(crate) fn fmt_tick(us: u64) -> String {
    let s = fmt_us(us);
    match s.strip_suffix("ms").and_then(|n| n.strip_suffix(".0")) {
        Some(n) => format!("{n}ms"),
        None => match s.strip_suffix('s').and_then(|n| n.strip_suffix(".00")) {
            Some(n) => format!("{n}s"),
            None => s,
        },
    }
}

/// A duration precise enough to compare two runs by: `20.9s` where
/// [`short_duration`] would round to `20s`, and the same as `short_duration`
/// once a run is long enough for tenths to be noise.
pub(crate) fn precise_duration(d: std::time::Duration) -> String {
    match d.as_secs() {
        0..=59 => format!("{:.1}s", d.as_secs_f64()),
        _ => short_duration(d),
    }
}

/// A yen figure, in the same shape everywhere: four decimals for a total,
/// six for a per-request amount, where a bench job costs ~0.001.
pub(crate) fn fmt_yen(v: f64) -> String {
    format!("{v:.4}")
}

/// How much longer, from what has been done so far. `None` before there is
/// enough to extrapolate from.
pub(crate) fn eta(done: u64, total: u64, elapsed: Duration) -> Option<Duration> {
    if done == 0 || done >= total {
        return None;
    }
    let per = elapsed.as_secs_f64() / done as f64;
    Some(Duration::from_secs_f64(per * (total - done) as f64))
}

/// `4h32m`, `12m04s`, `47s` — short enough to sit on a status line.
pub(crate) fn short_duration(d: Duration) -> String {
    let s = d.as_secs();
    match s {
        0..=59 => format!("{s}s"),
        60..=3599 => format!("{}m{:02}s", s / 60, s % 60),
        _ => format!("{}h{:02}m", s / 3600, (s % 3600) / 60),
    }
}

/// Wrap `s` to `width` visible columns, continuation lines indented by
/// `indent`. Splits on spaces, which is safe with colour: an escape sequence
/// never contains one, so a token carries its own colouring with it.
pub(crate) fn wrap_visible(s: &str, width: usize, indent: usize) -> Vec<String> {
    let hang = " ".repeat(indent);
    let mut lines: Vec<String> = Vec::new();
    let mut line = String::new();
    let mut used = 0usize;
    for word in s.split(' ').filter(|w| !w.is_empty()) {
        let w = visible_width(word);
        if !line.is_empty() && used + 1 + w > width {
            lines.push(std::mem::take(&mut line));
            line.push_str(&hang);
            used = indent;
        }
        if !line.is_empty() && !line.ends_with(' ') {
            line.push(' ');
            used += 1;
        }
        line.push_str(word);
        used += w;
    }
    if !line.trim().is_empty() {
        lines.push(line);
    }
    lines
}

/// The first candidate whose every line fits `width`, or the last one when
/// none does. How every header here decides what to drop.
pub(crate) fn fit(width: usize, candidates: &[String]) -> String {
    candidates
        .iter()
        .find(|c| c.lines().all(|l| visible_width(l) <= width))
        .cloned()
        .unwrap_or_else(|| candidates.last().cloned().unwrap_or_default())
}

/// Secondary text: labels, units, bucket edges, column headings.
///
/// NOT `colored`'s `.dimmed()`, which emits SGR 2 ("faint"). Faint is the
/// worst-supported attribute in the ANSI set: some terminals ignore it, and
/// some — macOS Terminal among them — render it at so little contrast against
/// a dark background that it vanishes. Every label in this view was drawn
/// that way once, and on such a terminal the whole scaffold of the report
/// disappeared: bars with no axis, columns with no headings, a notes section
/// with the note missing and only the marker left.
///
/// A 256-colour grey is a real colour. It cannot be rendered as nothing, and
/// xterm-256 support is universal in a way SGR 2 is not.
pub(crate) trait Muted {
    /// Secondary weight: readable, clearly not the figure.
    fn muted(&self) -> String;
    /// Secondary weight with emphasis, for a note's leading marker.
    fn muted_bold(&self) -> String;
}

impl<T: std::fmt::Display + ?Sized> Muted for T {
    fn muted(&self) -> String {
        let s = self.to_string();
        match colored::control::SHOULD_COLORIZE.should_colorize() {
            true => format!("\x1b[38;5;245m{s}\x1b[0m"),
            false => s,
        }
    }

    fn muted_bold(&self) -> String {
        let s = self.to_string();
        match colored::control::SHOULD_COLORIZE.should_colorize() {
            true => format!("\x1b[1;38;5;245m{s}\x1b[0m"),
            false => s,
        }
    }
}

/// A worker name short enough to sit on the live line.
pub(crate) fn short_worker(name: &str) -> String {
    let trimmed = name.strip_prefix("worker-zc-worker-").unwrap_or(name);
    match trimmed.chars().count() > 22 {
        true => format!("{}…", trimmed.chars().take(21).collect::<String>()),
        false => trimmed.to_string(),
    }
}

/// What distinguishes one worker from its siblings on the same node:
/// `dd715b7f-w2` → `w2`, `worker-zc-worker-i9-1` → `1`. The node is already
/// on the line above, so repeating it would only push the line wider.
pub(crate) fn worker_leaf(worker: &str) -> String {
    let node = super::metrics::node_of(worker);
    match worker.rsplit_once(&format!("{node}-")) {
        Some((_, leaf)) if !leaf.is_empty() => leaf.to_string(),
        _ => worker.to_string(),
    }
}

/// `colored`'s override is process-global, so two tests that set it
/// disagree when they run at the same time: one asserting plain text saw
/// `\x1b[38;5;245mp50\x1b[0m` because another had just turned colour on.
/// Every test that touches it takes this lock first.
#[cfg(test)]
pub(crate) fn colour_lock() -> std::sync::MutexGuard<'static, ()> {
    static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
    LOCK.lock().unwrap_or_else(|e| e.into_inner())
}

#[cfg(test)]
mod tests {
    use super::*;
    use colored::Colorize;

    fn plain(s: &str) -> String {
        let mut out = String::new();
        let mut chars = s.chars();
        while let Some(c) = chars.next() {
            if c == '\u{1b}' {
                for e in chars.by_ref() {
                    if e == 'm' {
                        break;
                    }
                }
            } else {
                out.push(c);
            }
        }
        out
    }

    #[test]
    fn width_is_what_the_eye_sees_not_what_is_stored() {
        let _colour = colour_lock();
        colored::control::set_override(true);
        let coloured = "abc".red().to_string();
        assert!(coloured.len() > 3);
        assert_eq!(visible_width(&coloured), 3);
        colored::control::unset_override();
    }

    #[test]
    fn padding_lines_up_coloured_and_plain_alike() {
        let _colour = colour_lock();
        colored::control::set_override(true);
        let a = pad(&"ab".green().to_string(), 6, false);
        let b = pad("ab", 6, false);
        assert_eq!(visible_width(&a), visible_width(&b));
        colored::control::unset_override();
    }

    #[test]
    fn a_bar_is_proportional_and_never_overflows_its_width() {
        assert_eq!(visible_width(&bar(0, 10, 8)), 8);
        assert_eq!(visible_width(&bar(10, 10, 8)), 8);
        assert_eq!(visible_width(&bar(99, 10, 8)), 8);
        assert_eq!(bar(10, 10, 8), "████████");
        assert_eq!(bar(5, 10, 8), "████    ");
    }

    #[test]
    fn a_small_share_still_draws_something() {
        // 1 in 400 over 28 cells is 0.07 of a cell. Rounded to whole cells it
        // is nothing; in eighths it is a mark you can see.
        let b = bar(1, 400, 28);
        assert!(b.trim().is_empty() || b.starts_with('▏'), "{b:?}");
        let b = bar(12, 400, 28);
        assert!(!b.trim().is_empty(), "a 3% bucket must be visible");
    }

    #[test]
    fn a_split_bar_reads_without_colour() {
        let (a, b) = split_bar(3, 1, 8);
        assert_eq!(a, "██████");
        assert_eq!(b, "▒▒");
        assert_eq!(visible_width(&format!("{a}{b}")), 8);
    }

    #[test]
    fn a_single_billed_request_is_not_rounded_away() {
        // 1 billed in 10 000 is 0.002 of a 20-cell bar. Rounding it to zero
        // would draw "nothing was billed", which is the one thing the bar
        // must never say when something was.
        let (_, billed) = split_bar(9_999, 1, 20);
        assert!(!billed.is_empty(), "a billed request must leave a mark");
    }

    #[test]
    fn a_split_bar_with_nothing_in_it_is_blank() {
        let (a, b) = split_bar(0, 0, 6);
        assert_eq!(a, "      ");
        assert_eq!(b, "");
    }

    #[test]
    fn a_sparkline_has_one_cell_per_sample() {
        let s = spark(&[1.0, 2.0, 3.0, 4.0]);
        assert_eq!(s.chars().count(), 4);
        assert_eq!(s.chars().next(), Some('▁'));
        assert_eq!(s.chars().last(), Some('█'));
    }

    #[test]
    fn a_flat_rate_draws_a_flat_line_not_a_divide_by_zero() {
        let s = spark(&[7.0, 7.0, 7.0]);
        assert_eq!(s.chars().count(), 3);
        assert!(s.chars().all(|c| c == s.chars().next().unwrap()));
    }

    #[test]
    fn secondary_text_is_a_colour_not_the_faint_attribute() {
        let _colour = colour_lock();
        colored::control::set_override(true);
        let m = "p50".muted();
        assert!(!m.contains("\x1b[2m"), "SGR 2 disappears on some terminals");
        assert!(m.contains("38;5;245"), "a real 256-colour grey: {m:?}");
        assert_eq!(visible_width(&m), 3);
        colored::control::unset_override();
    }

    #[test]
    fn secondary_text_carries_no_escapes_when_colour_is_off() {
        let _colour = colour_lock();
        colored::control::set_override(false);
        assert_eq!("p50".muted(), "p50");
        assert_eq!("o".muted_bold(), "o");
        colored::control::unset_override();
    }

    #[test]
    fn an_axis_label_is_a_round_number() {
        assert_eq!(fmt_tick(250_000), "250ms");
        assert_eq!(fmt_tick(1_000_000), "1s");
        assert_eq!(fmt_tick(1_240_000), "1.24s");
        assert_eq!(fmt_tick(820), "820µs");
    }

    #[test]
    fn a_short_run_is_timed_to_a_tenth() {
        assert_eq!(precise_duration(Duration::from_millis(20_900)), "20.9s");
        assert_eq!(precise_duration(Duration::from_secs(600)), "10m00s");
    }

    #[test]
    fn a_duration_reads_in_the_unit_that_suits_it() {
        assert_eq!(short_duration(Duration::from_secs(9)), "9s");
        assert_eq!(short_duration(Duration::from_secs(64)), "1m04s");
        assert_eq!(short_duration(Duration::from_secs(7200)), "2h00m");
    }

    #[test]
    fn how_much_longer_is_extrapolated_from_what_is_done() {
        let left = eta(10, 110, Duration::from_secs(10)).unwrap();
        assert_eq!(left.as_secs(), 100);
        assert!(eta(0, 100, Duration::from_secs(1)).is_none());
        assert!(eta(100, 100, Duration::from_secs(1)).is_none());
    }

    #[test]
    fn a_long_counter_reads_at_a_glance() {
        assert_eq!(grouped(786), "786");
        assert_eq!(plain(&grouped(100_000)), "100\u{2009}000");
    }

    #[test]
    fn a_worker_name_is_shortened_to_fit_the_line() {
        assert_eq!(short_worker("worker-zc-worker-i9-1"), "i9-1");
        assert_eq!(short_worker("dd715b7f-w0"), "dd715b7f-w0");
        assert!(short_worker(&"x".repeat(40)).chars().count() <= 22);
    }

    #[test]
    fn wrapping_counts_columns_not_bytes() {
        let _colour = colour_lock();
        colored::control::set_override(true);
        let text = format!("{} two three four five six", "one".red());
        let lines = wrap_visible(&text, 12, 4);
        assert!(lines.len() > 1, "{lines:?}");
        for l in &lines {
            assert!(visible_width(l) <= 12, "{l:?} is {}", visible_width(l));
        }
        colored::control::unset_override();
    }

    #[test]
    fn a_header_drops_what_does_not_fit_rather_than_wrapping() {
        let wide = "a".repeat(80);
        let narrow = "a".repeat(20);
        assert_eq!(fit(100, &[wide.clone(), narrow.clone()]), wide);
        assert_eq!(fit(40, &[wide.clone(), narrow.clone()]), narrow);
        // Nothing fits: the shortest candidate is still better than nothing.
        assert_eq!(fit(5, &[wide, narrow.clone()]), narrow);
    }

    #[test]
    fn the_terminal_width_can_be_pinned_for_a_recording() {
        // Safety: single-threaded test, and the variable is read, not cached.
        std::env::set_var("COLUMNS", "132");
        assert_eq!(term_width(), 132);
        std::env::set_var("COLUMNS", "12");
        assert!(term_width() >= 40, "an absurd width falls back");
        std::env::remove_var("COLUMNS");
    }
}