use std::time::Duration;
use colored::Colorize;
use super::layout::{
bar, eta, fmt_tick, fmt_us, grouped, pad, short_duration, short_worker, spark, split_bar,
trim_lines, visible_width, Muted,
};
use super::metrics::{
percentile_us, percentiles_us, Buckets, Ledger, Placement, RateRing, MAX_BUCKET_ROWS,
MIN_RATE_SAMPLES,
};
const TWO_COLUMN_MIN: usize = 104;
const MAX_VIEW_WIDTH: usize = 118;
#[derive(Clone, Copy)]
pub(crate) struct LiveView<'a> {
pub(crate) spin: char,
pub(crate) done: u64,
pub(crate) total: u64,
pub(crate) ok: u64,
pub(crate) failed: u64,
pub(crate) elapsed: Duration,
pub(crate) samples: &'a [u64],
pub(crate) ledger: &'a Ledger,
pub(crate) rates: &'a RateRing,
pub(crate) width: usize,
}
impl LiveView<'_> {
pub(crate) fn render(&self) -> String {
if self.width > MAX_VIEW_WIDTH {
return LiveView {
width: MAX_VIEW_WIDTH,
..*self
}
.render();
}
let mut out = String::new();
self.progress(&mut out);
self.distributions(&mut out);
self.placement(&mut out);
self.keys(&mut out);
trim_lines(&out)
}
fn progress(&self, out: &mut String) {
let w = self.width;
let pct = self.done as f64 / self.total.max(1) as f64;
let counter = format!("{} / {}", grouped(self.done), grouped(self.total));
let long_when = match eta(self.done, self.total, self.elapsed) {
Some(left) => format!(
"{} · eta {}",
short_duration(self.elapsed),
short_duration(left)
),
None => short_duration(self.elapsed),
};
let line = |b: &str, when: &str| {
format!(
" {} {}{} {} {}",
self.spin.to_string().cyan(),
pad(&counter, 20, false),
b,
pad(&format!("{:.1}%", pct * 100.0), 6, true),
when.muted(),
)
};
let when = match w.saturating_sub(visible_width(&line("", &long_when))) >= 8 {
true => long_when,
false => short_duration(self.elapsed),
};
let bar_w = w.saturating_sub(visible_width(&line("", &when))).min(34);
let filled = match (pct * bar_w as f64).round() as usize {
0 if pct > 0.0 => 1,
n => n,
};
let progress = format!(
"{}{}",
"█".repeat(filled.min(bar_w)).cyan(),
"·".repeat(bar_w.saturating_sub(filled)).muted()
);
out.push_str(&line(&progress, &when));
out.push('\n');
let (p50, _) = percentiles_us(self.samples);
let outcome = format!(
" {} · {}",
pad(
&format!("{} {}", grouped(self.ok).green(), "ok".muted()),
10,
false
),
match self.failed {
0 => format!("{} {}", "0".muted(), "failed".muted()),
n => format!("{} {}", grouped(n).red(), "failed".muted()),
},
);
let now = self.rates.now(5, self.done, self.elapsed);
let mean = self.done as f64 / self.elapsed.as_secs_f64().max(0.001);
let now_s = format!("{now:.1}");
let mean_s = format!("{mean:.1}");
let peak_s = self.rates.peak().to_string();
let tails = [
format!(
"{} {} · {} {} · {} {} · {} {}",
now_s.clone().yellow().bold(),
"req/s now".muted(),
mean_s,
"avg".muted(),
peak_s,
"peak".muted(),
fmt_us(p50),
"p50".muted(),
),
format!(
"{} {} · {} {}",
format!("{now:.1}").yellow().bold(),
"req/s".muted(),
fmt_us(p50),
"p50".muted(),
),
format!(
"{} {}",
format!("{now:.1}").yellow().bold(),
"req/s".muted()
),
];
let tail = tails
.iter()
.find(|t| visible_width(&outcome) + 4 + visible_width(t) <= w)
.cloned()
.unwrap_or_default();
let gap = w
.saturating_sub(visible_width(&outcome) + visible_width(&tail))
.max(2);
out.push_str(&format!("{outcome}{}{tail}\n", " ".repeat(gap)));
let series = self.rates.as_f64();
if !series.is_empty() {
let room = w.saturating_sub(24);
let shown: Vec<f64> = series.iter().rev().take(room).rev().copied().collect();
out.push_str(&format!(
" {}{} {}\n",
pad(&"rate".muted(), 8, false),
spark(&shown).green(),
format!("last {}s", shown.len()).muted(),
));
}
out.push('\n');
}
fn distributions(&self, out: &mut String) {
let lat = Buckets::of(self.samples, MAX_BUCKET_ROWS);
let thr = Buckets::linear(self.rates.per_second(), 7);
let lat_rows: Vec<usize> = lat.interesting().collect();
let lat_label_w = lat_rows
.iter()
.map(|i| visible_width(&lat.label(*i, &fmt_tick)))
.max()
.unwrap_or(8);
let thr_fmt = |v: u64| format!("{v} req/s");
let thr_rows: Vec<usize> = match self.rates.per_second().len() < MIN_RATE_SAMPLES {
true => Vec::new(),
false => thr.interesting().collect(),
};
let thr_label_w = thr_rows
.iter()
.map(|i| visible_width(&thr.label(*i, &thr_fmt)))
.max()
.unwrap_or(0);
let left_fixed = 2 + lat_label_w + 1 + 8 + 5;
let right_fixed = thr_label_w + 1 + 6 + 5;
let gutter = 6;
let room = self.width.saturating_sub(left_fixed + right_fixed + gutter) as f64;
let two_col = self.width >= TWO_COLUMN_MIN && !thr_rows.is_empty() && room >= 22.0;
let (lat_bar, thr_bar) = match two_col {
true => {
let l = ((room * 0.58) as usize).min(28);
(l, (room as usize - l).min(20))
}
false => (self.width.saturating_sub(left_fixed).min(34), 0),
};
let mut head = format!(
" {}{}{}{}",
pad(&"latency".bold().to_string(), lat_label_w + 1, false),
" ".repeat(lat_bar),
pad(&"n".muted(), 8, true),
pad(&"%".muted(), 5, true),
);
if two_col {
head.push_str(&format!(
" {} {}{}{}",
"│".muted(),
pad(
&"throughput".bold().to_string(),
thr_label_w + 1 + thr_bar,
false
),
pad(&"secs".muted(), 6, true),
pad(&"%".muted(), 5, true),
));
}
out.push_str(&head);
out.push('\n');
let lat_peak = lat.peak();
let thr_peak = thr.peak();
let lat_total = lat.total().max(1);
let thr_total = thr.total().max(1);
let (p50, p99) = percentiles_us(self.samples);
let extras = [
format!(
"{} {} {} {} {} {}",
"p50".muted(),
fmt_us(p50),
"p90".muted(),
fmt_us(percentile_us(self.samples, 90.0)),
"p99".muted(),
fmt_us(p99),
),
format!(
"{} {} {} {}",
"min".muted(),
fmt_us(self.samples.iter().copied().min().unwrap_or(0)),
"max".muted(),
fmt_us(self.samples.iter().copied().max().unwrap_or(0)),
),
];
for (row, i) in lat_rows.iter().enumerate() {
let n = lat.counts[*i];
let mut line = format!(
" {}{}{}{}",
pad(&lat.label(*i, &fmt_tick).muted(), lat_label_w + 1, false),
bar(n, lat_peak, lat_bar).cyan(),
pad(&grouped(n), 8, true),
pad(
&match n {
0 => String::new(),
_ => format!("{:.0}%", n as f64 / lat_total as f64 * 100.0),
}
.muted()
.to_string(),
5,
true
),
);
if two_col {
line.push_str(&format!(" {} ", "│".muted()));
if let Some(j) = thr_rows.get(row) {
let tn = thr.counts[*j];
line.push_str(&format!(
"{}{}{}{}",
pad(&thr.label(*j, &thr_fmt).muted(), thr_label_w + 1, false),
bar(tn, thr_peak, thr_bar).green(),
pad(&tn.to_string(), 6, true),
pad(
&format!("{:.0}%", tn as f64 / thr_total as f64 * 100.0)
.muted()
.to_string(),
5,
true
),
));
} else if let Some(extra) = row
.checked_sub(thr_rows.len() + 1)
.and_then(|k| extras.get(k))
{
line.push_str(extra);
}
}
out.push_str(&line);
out.push('\n');
}
if !two_col {
for e in &extras {
out.push_str(&format!(" {e}\n"));
}
}
out.push('\n');
}
fn placement(&self, out: &mut String) {
let w = self.width;
if self.ledger.is_empty() {
out.push_str(&format!(" {}\n\n", "nothing has been routed yet".muted()));
return;
}
let (free_n, _) = self.ledger.totals(Placement::Free);
let (billed_n, billed_zkcr) = self.ledger.totals(Placement::Billed);
let placed = self.ledger.placed().max(1);
let free_pct = format!("{:.0}%", free_n as f64 / placed as f64 * 100.0);
let billed_pct = format!("{:.0}%", billed_n as f64 / placed as f64 * 100.0);
let spend = format!("{billed_zkcr:.4}");
let summaries = [
format!(
"{} {} {} · {} {} {} {}",
"free".muted(),
free_pct.clone().green().bold(),
"of the work".muted(),
"billed".muted(),
billed_pct.clone().yellow().bold(),
spend.clone().yellow(),
"zkcr".muted(),
),
format!(
"{} {} · {} {} {}",
"free".muted(),
free_pct.clone().green().bold(),
"billed".muted(),
billed_pct.clone().yellow().bold(),
spend.clone().yellow(),
),
format!(
"{} {} {} {}",
free_pct.green().bold(),
"free".muted(),
billed_pct.yellow().bold(),
spend.yellow(),
),
];
let label = pad(&"placement".bold().to_string(), 11, false);
let (summary, bar_w) = summaries
.iter()
.map(|s| {
let room = w.saturating_sub(2 + 11 + 4 + visible_width(s)).min(40);
(s, room)
})
.find(|(_, room)| *room >= 12)
.unwrap_or_else(|| {
let last = summaries.last().unwrap();
(
last,
w.saturating_sub(2 + 11 + 4 + visible_width(last)).min(40),
)
});
if bar_w >= 8 {
let (free, billed) = split_bar(free_n, billed_n, bar_w);
out.push_str(&format!(
" {}{}{} {}\n\n",
label,
free.green(),
billed.yellow(),
summary
));
} else {
out.push_str(&format!(" {}{}\n\n", label, summary));
}
let cols = Columns::for_width(w);
out.push_str(&cols.header());
out.push('\n');
let mut last_class = None;
for (class, node, stat) in self.ledger.rows().into_iter().take(8) {
let shown_class = match Some(class) == last_class {
true => String::new(),
false => class.as_str().to_string(),
};
last_class = Some(class);
out.push_str(&cols.row(
&shown_class,
class,
&node,
&stat.via(),
stat.workers.len(),
stat.requests,
stat.requests as f64 / placed as f64 * 100.0,
stat.p50_us(),
stat.expectation.avg_expected_ms(),
stat.expectation.is_miscalibrated(),
stat.charged_zkcr,
));
out.push('\n');
}
if billed_n > 0 && self.done > 0 && self.done < self.total {
let projected = billed_zkcr / self.done as f64 * self.total as f64;
out.push_str(&format!(
" {}{} {} {}\n",
" ".repeat(11),
format!("{billed_n} of {} billed", grouped(self.done)).muted(),
"· projected total".muted(),
format!("{projected:.4} zkcr").yellow().bold(),
));
}
out.push('\n');
}
fn keys(&self, out: &mut String) {
let full = format!(
" {} {} · {} {}",
"ctrl-c".white(),
"stop & report".muted(),
"--json".white(),
"machine output".muted(),
);
let short = format!(" {} {}", "ctrl-c".white(), "stop & report".muted());
out.push_str(match visible_width(&full) <= self.width {
true => &full,
false => &short,
});
out.push('\n');
}
}
struct Columns {
class: usize,
node: usize,
via: usize,
req: usize,
share: usize,
p50: usize,
router: usize,
spend: usize,
}
impl Columns {
fn for_width(w: usize) -> Columns {
match w {
0..=71 => Columns {
class: 9,
node: 18,
via: 0,
req: 8,
share: 0,
p50: 0,
router: 0,
spend: 13,
},
72..=93 => Columns {
class: 9,
node: 22,
via: 0,
req: 8,
share: 7,
p50: 10,
router: 0,
spend: 13,
},
94..=113 => Columns {
class: 10,
node: 26,
via: 0,
req: 8,
share: 8,
p50: 11,
router: 16,
spend: 14,
},
_ => Columns {
class: 10,
node: 26,
via: 9,
req: 8,
share: 8,
p50: 11,
router: 16,
spend: 14,
},
}
}
fn cell(width: usize, text: String) -> String {
match width {
0 => String::new(),
w => pad(&text, w, true),
}
}
fn left(width: usize, text: String) -> String {
match width {
0 => String::new(),
w => pad(&text, w, false),
}
}
fn header(&self) -> String {
format!(
" {}{}{}{}{}{}{}{}",
" ".repeat(self.class),
pad(&"node".muted(), self.node, false),
Self::left(self.via, "via".muted()),
Self::cell(self.req, "req".muted()),
Self::cell(self.share, "share".muted()),
Self::cell(self.p50, "p50".muted()),
Self::cell(self.router, "router said".muted()),
Self::cell(self.spend, "spend".muted()),
)
}
#[allow(clippy::too_many_arguments)]
fn row(
&self,
shown_class: &str,
class: Placement,
node: &str,
via: &str,
workers: usize,
req: u64,
share: f64,
p50_us: u64,
expected_ms: Option<f64>,
miscalibrated: bool,
spend: f64,
) -> String {
let tint = match class {
Placement::Free => colored::Color::Green,
Placement::Billed => colored::Color::Yellow,
};
let name = match workers {
0 | 1 => short_worker(node),
n => format!("{} · {n} workers", short_worker(node)),
};
let router = match expected_ms {
Some(ms) => {
let t = super::layout::fmt_ms(ms);
match miscalibrated {
true => format!("{} {}", t, "⚠".red()),
false => t,
}
}
None => "—".muted(),
};
format!(
" {}{}{}{}{}{}{}{}",
pad(
&shown_class.color(tint).bold().to_string(),
self.class,
false
),
pad(&name.cyan().to_string(), self.node, false),
Self::left(self.via, via.muted()),
Self::cell(self.req, grouped(req)),
Self::cell(self.share, format!("{share:.1}%").muted()),
Self::cell(self.p50, fmt_us(p50_us)),
Self::cell(self.router, router),
Self::cell(
self.spend,
match class {
Placement::Free => "free".green().to_string(),
Placement::Billed => format!("{spend:.4} zkcr").yellow().to_string(),
}
),
)
}
}