spikes/gpui: the GPUI spikes' workspace, environment and meter

Plan section 6 step 1. A Cargo workspace of its own under spikes/gpui (own
lock, not a member of the root workspace, so the root's lock, deny policy,
notices and CI are untouched; it builds into the checkout's target/), on
gpui-kit pinned to =0.8.0. No gpui-kit release builds on Rust 1.94 (every
gpui-pre 0.3.x calls std::hint::cold_path, stable since 1.95), so the
workspace says rust-version 1.95.

- shell.sh: the toolchain (1.95.0, 1.94, stable or nightly, all from one
  pinned fenix), the native libraries, Mesa's lavapipe as the only Vulkan
  driver, Xvfb, openbox and the X tools, Noto Color Emoji and Noto Sans CJK.
- headless.sh: a private Xvfb display with openbox and a private session
  bus, never the desktop's; headless-wayland.sh: sway's headless backend.
- spike-common: CPU by thread group and memory from /proc once a second
  with the spike's counters (meter), proc-meter and damage-count for
  programs without a meter (the Slint app), Inter and the emoji/CJK fonts,
  the client's Lucide icons as GPUI assets, and the BGRA twin of
  voelin_media::convert::to_rgba.

From the interrupted 2026-10-25 attempt, kept; changed here: shell.sh takes
1.94 and nightly from the pinned fenix (the store paths it named were
garbage-collected), the README's headless-wayland.sh paragraph (sway, not
weston), its fmt command (-p, not --all), its toolchain and nixpkgs lines,
and the font docs (GPUI drops Noto Color Emoji from a fallback chain).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Opus 5.5 committed 2026-10-27 01:43:20 +03:00
1 parent 3930ef2945
commit c9859bcfb4
15 files changed
+10058

No files matched your search

+37
View File
@@ -0,0 +1,37 @@
//! Icons for `svg()`: the client's own Lucide SVGs
//! (`crates/voelin-ui/ui/assets/icons`, Lucide 1.48, read from the checkout
//! at run time) under `voelin/<name>.svg`, then gpui-kit-assets' complete
//! Lucide 1.43 catalog under `icons/<name>.svg` (what gpui-component's
//! `Icon` uses).
use std::borrow::Cow;
use std::path::PathBuf;
use gpui_kit::{AssetSource, Result, SharedString};
/// The client's icons first, then gpui-kit's catalog.
pub struct Assets {
client_icons: PathBuf,
}
impl Default for Assets {
fn default() -> Self {
Self {
client_icons: PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../../crates/voelin-ui/ui/assets/icons"),
}
}
}
impl AssetSource for Assets {
fn load(&self, path: &str) -> Result<Option<Cow<'static, [u8]>>> {
if let Some(name) = path.strip_prefix("voelin/") {
return Ok(std::fs::read(self.client_icons.join(name)).ok().map(Cow::Owned));
}
gpui_kit::assets::AllAssets.load(path)
}
fn list(&self, path: &str) -> Result<Vec<SharedString>> {
gpui_kit::assets::AllAssets.list(path)
}
}
+134
View File
@@ -0,0 +1,134 @@
//! Frames as BGRA, the byte order GPUI's `RenderImage` holds: the BGRA twin
//! of `voelin_media::convert::to_rgba` (the same `yuv` calls with the
//! channels swapped, BT.601 limited range), and the picture GPUI shows.
use std::sync::Arc;
use gpui_kit::RenderImage;
use voelin_media::frame::{FrameRef, PixelsRef, VideoFrame};
use yuv::{YuvBiPlanarImage, YuvConversionMode, YuvPlanarImage, YuvRange, YuvStandardMatrix};
const RANGE: YuvRange = YuvRange::Limited;
const MATRIX: YuvStandardMatrix = YuvStandardMatrix::Bt601;
fn u32_of(n: usize) -> Result<u32, String> {
u32::try_from(n).map_err(|_| format!("{n} does not fit a stride"))
}
/// Write `frame` as BGRA (alpha 255) into `out`, `stride` bytes per row.
pub fn to_bgra(frame: &VideoFrame, out: &mut [u8], stride: usize) -> Result<(), String> {
to_bgra_ref(&frame.view(), out, stride)
}
/// [`to_bgra`] of a borrowed frame; allocates nothing.
pub fn to_bgra_ref(frame: &FrameRef<'_>, out: &mut [u8], stride: usize) -> Result<(), String> {
frame.validate().map_err(|e| e.to_string())?;
let (w, h) = (frame.width, frame.height);
let row = w as usize * 4;
if stride < row || out.len() < stride * (h as usize - 1) + row {
return Err(format!("BGRA output of {} bytes is too small for {w}x{h}", out.len()));
}
let out_stride = u32_of(stride)?;
match &frame.pixels {
PixelsRef::I420 { y, u, v } => {
let image = YuvPlanarImage {
y_plane: y.data,
y_stride: u32_of(y.stride)?,
u_plane: u.data,
u_stride: u32_of(u.stride)?,
v_plane: v.data,
v_stride: u32_of(v.stride)?,
width: w,
height: h,
};
yuv::yuv420_to_bgra(&image, out, out_stride, RANGE, MATRIX).map_err(|e| e.to_string())
}
PixelsRef::Nv12 { y, uv } => {
let image = YuvBiPlanarImage {
y_plane: y.data,
y_stride: u32_of(y.stride)?,
uv_plane: uv.data,
uv_stride: u32_of(uv.stride)?,
width: w,
height: h,
};
yuv::yuv_nv12_to_bgra(
&image,
out,
out_stride,
RANGE,
MATRIX,
YuvConversionMode::Balanced,
)
.map_err(|e| e.to_string())
}
PixelsRef::Bgra(p) => {
for y in 0..h as usize {
out[y * stride..y * stride + row].copy_from_slice(p.row(y, row));
}
Ok(())
}
PixelsRef::Rgba(p) => {
for y in 0..h as usize {
let (src, dst) = (p.row(y, row), &mut out[y * stride..y * stride + row]);
for (d, s) in dst.chunks_exact_mut(4).zip(src.chunks_exact(4)) {
d.copy_from_slice(&[s[2], s[1], s[0], 255]);
}
}
Ok(())
}
}
}
/// The pixels as GPUI's image: one frame, BGRA, `width * 4` bytes per row.
pub fn render_image(width: u32, height: u32, bgra: Vec<u8>) -> Arc<RenderImage> {
let buffer = image::RgbaImage::from_raw(width, height, bgra).expect("a buffer of the size");
Arc::new(RenderImage::new([image::Frame::new(buffer)]))
}
/// `frame` converted into a new picture.
pub fn picture(frame: &VideoFrame) -> Result<Arc<RenderImage>, String> {
let stride = frame.width as usize * 4;
let mut bgra = vec![0u8; stride * frame.height as usize];
to_bgra(frame, &mut bgra, stride)?;
Ok(render_image(frame.width, frame.height, bgra))
}
#[cfg(test)]
mod tests {
use super::*;
use voelin_media::capture::synthetic::{Pattern, SyntheticScreen};
use voelin_media::convert;
/// BGRA is RGBA with red and blue swapped, pixel for pixel, for I420 and
/// for packed input.
#[test]
fn bgra_is_rgba_swapped() {
let picture = SyntheticScreen::with_pattern(64, 36, Pattern::Desktop).frame(3, 30);
let i420 = convert::to_i420(&picture).unwrap().into_owned();
let rgba_in =
VideoFrame::from_rgba(64, 36, 64 * 4, convert::to_rgba_vec(&picture).unwrap()).unwrap();
for frame in [&picture, &i420, &rgba_in] {
let mut rgba = vec![0; 64 * 36 * 4];
let mut bgra = vec![0; 64 * 36 * 4];
convert::to_rgba(frame, &mut rgba, 64 * 4).unwrap();
to_bgra(frame, &mut bgra, 64 * 4).unwrap();
for (r, b) in rgba.chunks_exact(4).zip(bgra.chunks_exact(4)) {
assert_eq!([r[2], r[1], r[0], r[3]], b);
}
}
}
#[test]
fn small_output_is_refused() {
let picture = SyntheticScreen::new(32, 32).frame(0, 30);
assert!(to_bgra(&picture, &mut [0; 16], 32 * 4).is_err());
}
#[test]
fn pictures_have_the_frame_size() {
let picture = SyntheticScreen::new(40, 20).frame(0, 30);
let image = super::picture(&picture).unwrap();
assert_eq!((image.size(0).width.0, image.size(0).height.0), (40, 20));
}
}
@@ -0,0 +1,96 @@
//! Counts how often a window's content changes, whatever draws it (GPUI,
//! Slint): XDamage events of a top-level window of the X display in
//! `DISPLAY`, one line per second (`damage/s`) and the mean at the end.
//!
//! `damage-count <window name substring> <seconds> [warm-up seconds]`
//!
//! Every damage report is subtracted at once, so a frame drawn with one
//! `PutImage` counts once; a frame drawn in several requests within 2 ms
//! counts once too.
use std::time::{Duration, Instant};
use x11rb::connection::Connection;
use x11rb::protocol::Event;
use x11rb::protocol::damage::{ConnectionExt as _, ReportLevel};
use x11rb::protocol::xproto::{AtomEnum, ConnectionExt as _, Window};
fn find(conn: &impl Connection, root: Window, needle: &str) -> anyhow::Result<Option<Window>> {
let tree = conn.query_tree(root)?.reply()?;
for &child in &tree.children {
let name = conn
.get_property(false, child, AtomEnum::WM_NAME, AtomEnum::ANY, 0, 1024)?
.reply()?
.value;
if String::from_utf8_lossy(&name).contains(needle) {
return Ok(Some(child));
}
if let Some(found) = find(conn, child, needle)? {
return Ok(Some(found));
}
}
Ok(None)
}
fn main() -> anyhow::Result<()> {
let mut args = std::env::args().skip(1);
let needle = args.next().ok_or_else(|| anyhow::anyhow!("no window name"))?;
let seconds: f64 = args.next().map_or(Ok(30.0), |s| s.parse())?;
let warmup: f64 = args.next().map_or(Ok(5.0), |s| s.parse())?;
let (conn, screen) = x11rb::connect(None)?;
let root = conn.setup().roots[screen].root;
let deadline = Instant::now() + Duration::from_secs(30);
let window = loop {
if let Some(w) = find(&conn, root, &needle)? {
break w;
}
anyhow::ensure!(Instant::now() < deadline, "no window named like {needle:?}");
std::thread::sleep(Duration::from_millis(200));
};
conn.damage_query_version(1, 1)?.reply()?;
let damage = conn.generate_id()?;
conn.damage_create(damage, window, ReportLevel::NON_EMPTY)?;
conn.flush()?;
let start = Instant::now();
let (mut second, mut in_second, mut counted, mut last_event) =
(start, 0u32, 0u64, None::<Instant>);
let mut steady_start = None;
loop {
let event = conn.poll_for_event()?;
let now = Instant::now();
match event {
Some(Event::DamageNotify(_)) => {
conn.damage_subtract(damage, x11rb::NONE, x11rb::NONE)?;
conn.flush()?;
if last_event.is_none_or(|t| now.duration_since(t) > Duration::from_millis(2)) {
in_second += 1;
if steady_start.is_some() {
counted += 1;
}
}
last_event = Some(now);
}
Some(_) => {}
None => std::thread::sleep(Duration::from_micros(500)),
}
if now.duration_since(second) >= Duration::from_secs(1) {
println!(
"{{\"t\": {:.1}, \"damage_per_s\": {in_second}}}",
now.duration_since(start).as_secs_f64()
);
second = now;
in_second = 0;
if steady_start.is_none() && now.duration_since(start).as_secs_f64() >= warmup {
steady_start = Some(now);
}
}
if now.duration_since(start).as_secs_f64() >= seconds {
let steady = steady_start.map_or(0.0, |s| now.duration_since(s).as_secs_f64());
println!(
"{{\"summary\": true, \"window\": {needle:?}, \"damage_per_s_mean\": {:.1}, \"steady_seconds\": {steady:.1}}}",
counted as f64 / steady.max(1e-6)
);
return Ok(());
}
}
}
+53
View File
@@ -0,0 +1,53 @@
//! CPU (process and thread groups, percent of one core) and resident memory
//! of another process, from `/proc/<pid>`, once a second, and the means
//! after a warm-up: the same numbers `spike_common::meter` gives for the
//! spikes, for a program that has no meter of its own (the Slint app).
//!
//! `proc-meter <pid> <seconds> [warm-up seconds]`
use std::time::Duration;
use serde_json::json;
use spike_common::meter::{Snapshot, cpu_between};
fn round(v: f64) -> f64 {
(v * 10.0).round() / 10.0
}
fn main() -> anyhow::Result<()> {
let mut args = std::env::args().skip(1);
let pid = args.next().ok_or_else(|| anyhow::anyhow!("no pid"))?;
let seconds: u64 = args.next().map_or(Ok(60), |s| s.parse())?;
let warmup: u64 = args.next().map_or(Ok(10), |s| s.parse())?;
let first = Snapshot::of(&pid);
let mut last = first.clone();
let mut steady = None;
for t in 1..=seconds {
std::thread::sleep(Duration::from_secs(1));
let now = Snapshot::of(&pid);
let (cpu, threads) = cpu_between(&last, &now);
println!(
"{}",
json!({"t": t, "cpu": round(cpu), "rss_mib": round(now.rss_mib()), "threads": threads.iter().map(|(k, v)| (k.clone(), json!(round(*v)))).collect::<serde_json::Map<_, _>>()})
);
if t == warmup {
steady = Some(now.clone());
}
last = now;
}
let start = steady.unwrap_or(first);
let (cpu, threads) = cpu_between(&start, &last);
println!(
"{}",
json!({
"summary": true,
"pid": pid,
"steady_seconds": seconds.saturating_sub(warmup),
"cpu_mean": round(cpu),
"threads_mean": threads.iter().map(|(k, v)| (k.clone(), json!(round(*v)))).collect::<serde_json::Map<_, _>>(),
"rss_mib_steady_start": round(start.rss_mib()),
"rss_mib_end": round(last.rss_mib()),
})
);
Ok(())
}
+80
View File
@@ -0,0 +1,80 @@
//! Fonts: Inter as the client bundles it (`crates/voelin-ui/ui/assets/fonts`,
//! read at build time, OFL), a colour emoji font (`SPIKE_EMOJI_FONT`) and
//! further fonts (`SPIKE_EXTRA_FONTS`, colon-separated: CJK), which
//! `shell.sh` points at Noto Color Emoji and Noto Sans CJK, added to GPUI's
//! text system so nothing depends on what fontconfig finds.
use std::borrow::Cow;
use gpui_kit::App;
/// The family name of the bundled UI font.
pub const UI_FAMILY: &str = "Inter";
/// The colour emoji font's family. GPUI's Linux text system draws a glyph in
/// colour only from a font whose PostScript name is `NotoColorEmoji`
/// (`check_is_known_emoji_font` in gpui-pre-wgpu's `cosmic_text_system.rs`).
pub const EMOJI_FAMILY: &str = "Noto Color Emoji";
const INTER: [&[u8]; 5] = [
include_bytes!("../../../../crates/voelin-ui/ui/assets/fonts/Inter-Regular.ttf"),
include_bytes!("../../../../crates/voelin-ui/ui/assets/fonts/Inter-Medium.ttf"),
include_bytes!("../../../../crates/voelin-ui/ui/assets/fonts/Inter-SemiBold.ttf"),
include_bytes!("../../../../crates/voelin-ui/ui/assets/fonts/Inter-Bold.ttf"),
include_bytes!("../../../../crates/voelin-ui/ui/assets/fonts/Inter-Italic.ttf"),
];
/// Add Inter, the emoji font and the extra fonts. Returns the emoji font's
/// path if it was added.
pub fn load(cx: &mut App) -> Option<String> {
let mut fonts: Vec<Cow<'static, [u8]>> = INTER.iter().map(|b| Cow::Borrowed(*b)).collect();
let extra = std::env::var("SPIKE_EXTRA_FONTS").unwrap_or_default();
for path in extra.split(':').filter(|p| !p.is_empty()) {
match std::fs::read(path) {
Ok(bytes) => fonts.push(Cow::Owned(bytes)),
Err(e) => log::warn!("no font at {path}: {e}"),
}
}
let mut added = None;
if let Some(path) = std::env::var("SPIKE_EMOJI_FONT").ok().filter(|p| !p.is_empty()) {
match std::fs::read(&path) {
Ok(bytes) => {
fonts.push(Cow::Owned(bytes));
added = Some(path);
}
Err(e) => log::warn!("no emoji font at {path}: {e}"),
}
}
if let Err(e) = cx.text_system().add_fonts(fonts) {
log::warn!("cannot add the fonts: {e:#}");
}
added
}
/// Inter with the colour emoji font and CJK after it. GPUI 0.3.9 keeps a
/// family in the chain only if it could be a primary font, which takes a
/// glyph for `m`: Noto Color Emoji has none and is dropped (`load_family` in
/// gpui-pre-wgpu's `cosmic_text_system.rs`), so colour emoji come from
/// cosmic-text's own fallback list, where DejaVu Sans (monochrome U+1F600 to
/// U+1F640) comes first (the composer's emoji probe).
pub fn ui_font() -> gpui_kit::Font {
gpui_kit::Font {
family: UI_FAMILY.into(),
features: gpui_kit::FontFeatures::default(),
fallbacks: Some(gpui_kit::FontFallbacks::from_fonts(vec![
EMOJI_FAMILY.into(),
"Noto Sans CJK SC".into(),
])),
weight: gpui_kit::FontWeight::NORMAL,
style: gpui_kit::FontStyle::Normal,
}
}
/// The colour emoji font alone, for text known to be emoji (a chat run
/// `voelin-ui-vm` marks as one, the picker). GPUI 0.3.9 refuses it as a
/// run's font for the reason given at [`ui_font`] and draws such a run in
/// its fallback font stack; docs/design/gpui-spikes.md has the patch that
/// lets it through.
pub fn emoji_font() -> gpui_kit::Font {
gpui_kit::Font { family: EMOJI_FAMILY.into(), fallbacks: None, ..ui_font() }
}
+47
View File
@@ -0,0 +1,47 @@
//! What the GPUI spikes share: the process's and its threads' CPU and memory
//! read from `/proc/self` once a second with the spike's own counters
//! ([`meter`]), logging, the fonts the client ships ([`fonts`]) and its
//! Lucide icons as GPUI assets ([`assets`]), and decoded frames as the BGRA
//! pictures GPUI shows ([`bgra`]).
pub mod assets;
pub mod bgra;
pub mod fonts;
pub mod meter;
/// Log to stderr: `RUST_LOG`, by default warnings and what GPUI says about
/// the GPU adapter and the display it picked.
pub fn init_logging() {
env_logger::Builder::from_env(
env_logger::Env::default().default_filter_or("warn,gpui_wgpu=info,gpui_linux=info"),
)
.format_timestamp_millis()
.init();
}
/// The value of `--name value` or `--name=value` among the arguments.
pub fn arg(name: &str) -> Option<String> {
let flag = format!("--{name}");
let mut args = std::env::args().skip(1);
while let Some(a) = args.next() {
if a == flag {
return args.next();
}
if let Some(v) = a.strip_prefix(&flag).and_then(|r| r.strip_prefix('=')) {
return Some(v.to_owned());
}
}
None
}
/// Whether `--name` is among the arguments.
pub fn flag(name: &str) -> bool {
let flag = format!("--{name}");
std::env::args().skip(1).any(|a| a == flag)
}
/// `WIDTHxHEIGHT` as numbers.
pub fn parse_size(text: &str) -> Option<(u32, u32)> {
let (w, h) = text.split_once('x')?;
Some((w.parse().ok()?, h.parse().ok()?))
}
+272
View File
@@ -0,0 +1,272 @@
//! CPU and memory of this process from `/proc/self`, by thread name, with
//! the spike's own counters, sampled once a second on a thread of their own.
//!
//! CPU is in percent of one core (200 = two cores busy). Threads are grouped
//! by name without a trailing number (`llvmpipe-12` → `llvmpipe`), so the
//! software renderer's share (Mesa's `llvmpipe-*` threads, which a GPU would
//! replace) is told apart from the decoder, the converter and GPUI's main
//! thread.
use std::collections::BTreeMap;
use std::fs;
use std::io::Write;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
use serde_json::{Value, json};
/// A number the spike counts up (frames shown) or sets (images alive); the
/// meter reports counters per second and gauges as they are.
#[derive(Clone, Default)]
pub struct Counter(Arc<AtomicU64>);
impl Counter {
/// Add one.
pub fn incr(&self) {
self.0.fetch_add(1, Ordering::Relaxed);
}
/// Add `n`.
pub fn add(&self, n: u64) {
self.0.fetch_add(n, Ordering::Relaxed);
}
/// Set (gauges).
pub fn set(&self, value: u64) {
self.0.store(value, Ordering::Relaxed);
}
/// The current value.
pub fn get(&self) -> u64 {
self.0.load(Ordering::Relaxed)
}
}
/// CPU ticks of the process and of each thread group, and the resident
/// memory, at one moment.
#[derive(Clone, Debug)]
pub struct Snapshot {
at: Instant,
process: u64,
threads: BTreeMap<String, u64>,
rss: u64,
}
/// `utime + stime` and the name of a `/proc/.../stat` line.
fn ticks_of(stat: &str) -> Option<(String, u64)> {
let open = stat.find('(')?;
let close = stat.rfind(')')?;
let name = stat.get(open + 1..close)?.to_owned();
let fields: Vec<&str> = stat.get(close + 1..)?.split_whitespace().collect();
// Fields 14 and 15 of proc(5); the remainder starts at field 3.
let utime: u64 = fields.get(11)?.parse().ok()?;
let stime: u64 = fields.get(12)?.parse().ok()?;
Some((name, utime + stime))
}
/// A thread's group: its name without a trailing number or separator.
pub fn group_of(name: &str) -> String {
let trimmed = name.trim_end_matches(|c: char| c.is_ascii_digit());
let trimmed = trimmed.trim_end_matches(['-', '_', ':', ' ', '#']);
if trimmed.is_empty() { name.to_owned() } else { trimmed.to_owned() }
}
impl Snapshot {
/// Read `/proc/self` now.
pub fn now() -> Self {
Self::of("self")
}
/// Read `/proc/<process>` now (`"self"` or a process id).
pub fn of(process: &str) -> Self {
let proc = format!("/proc/{process}");
let process = fs::read_to_string(format!("{proc}/stat"))
.ok()
.and_then(|s| ticks_of(&s))
.map_or(0, |(_, t)| t);
let mut threads = BTreeMap::new();
if let Ok(dir) = fs::read_dir(format!("{proc}/task")) {
for entry in dir.flatten() {
let Ok(stat) = fs::read_to_string(entry.path().join("stat")) else { continue };
if let Some((name, ticks)) = ticks_of(&stat) {
*threads.entry(group_of(&name)).or_insert(0) += ticks;
}
}
}
let rss = fs::read_to_string(format!("{proc}/statm"))
.ok()
.and_then(|s| s.split_whitespace().nth(1)?.parse::<u64>().ok())
.map_or(0, |pages| pages * rustix::param::page_size() as u64);
Self { at: Instant::now(), process, threads, rss }
}
/// Resident memory in MiB.
pub fn rss_mib(&self) -> f64 {
self.rss as f64 / (1024.0 * 1024.0)
}
}
/// CPU in percent of one core between two snapshots: the process's and each
/// thread group's (groups that exited in between count from zero).
pub fn cpu_between(a: &Snapshot, b: &Snapshot) -> (f64, BTreeMap<String, f64>) {
let hz = rustix::param::clock_ticks_per_second() as f64;
let secs = b.at.duration_since(a.at).as_secs_f64().max(1e-6);
let pct = |ticks: u64| ticks as f64 / hz / secs * 100.0;
let process = pct(b.process.saturating_sub(a.process));
let threads = b
.threads
.iter()
.map(|(name, &t)| (name.clone(), pct(t.saturating_sub(*a.threads.get(name).unwrap_or(&0)))))
.filter(|(_, p)| *p > 0.0)
.collect();
(process, threads)
}
/// What a run measures and how long.
pub struct Meter {
/// The run's settings, copied into every line.
pub config: Value,
/// Counted up; reported per second.
pub counters: Vec<(&'static str, Counter)>,
/// Set; reported as they are.
pub gauges: Vec<(&'static str, Counter)>,
/// Seconds not averaged at the start (start-up, the first keyframe).
pub warmup: Duration,
/// The whole run, warm-up included; the process exits after it.
pub duration: Duration,
/// JSON lines: one per second, then the summary (`"summary": true`).
pub out: Option<PathBuf>,
}
impl Meter {
/// Sample once a second on a thread; after `duration` write the summary
/// and end the process with `exit_code`.
pub fn start(self, exit_code: Arc<AtomicU64>) {
std::thread::Builder::new()
.name("spike-meter".into())
.spawn(move || self.run(&exit_code))
.expect("a meter thread");
}
fn run(self, exit_code: &AtomicU64) {
let mut out = self.out.as_ref().map(|p| fs::File::create(p).expect("the meter's file"));
let mut emit = |line: &Value| {
let text = line.to_string();
println!("{text}");
if let Some(f) = out.as_mut() {
let _ = writeln!(f, "{text}");
}
};
let start = Instant::now();
let values = |list: &[(&'static str, Counter)]| -> Vec<u64> {
list.iter().map(|(_, c)| c.get()).collect()
};
let mut last = Snapshot::now();
let mut last_counts = values(&self.counters);
let mut steady: Option<(Snapshot, Vec<u64>)> = None;
let mut cpu_samples: Vec<f64> = Vec::new();
let mut rss_max = last.rss_mib();
let rss_start = last.rss_mib();
let mut rss_steady_start = None;
loop {
std::thread::sleep(Duration::from_secs(1));
let now = Snapshot::now();
let counts = values(&self.counters);
let (cpu, threads) = cpu_between(&last, &now);
let secs = now.at.duration_since(last.at).as_secs_f64();
let rates: serde_json::Map<String, Value> = self
.counters
.iter()
.zip(counts.iter().zip(&last_counts))
.map(|((name, _), (c, l))| {
((*name).to_owned(), json!(round((c - l) as f64 / secs)))
})
.collect();
let gauges: serde_json::Map<String, Value> =
self.gauges.iter().map(|(n, g)| ((*n).to_owned(), json!(g.get()))).collect();
let elapsed = start.elapsed();
emit(&json!({
"t": round(elapsed.as_secs_f64()),
"cpu": round(cpu),
"threads": threads.iter().map(|(k, v)| (k.clone(), json!(round(*v)))).collect::<serde_json::Map<_, _>>(),
"rss_mib": round(now.rss_mib()),
"rates": rates,
"gauges": gauges,
}));
rss_max = rss_max.max(now.rss_mib());
if elapsed >= self.warmup {
if steady.is_none() {
steady = Some((now.clone(), counts.clone()));
rss_steady_start = Some(now.rss_mib());
} else {
cpu_samples.push(cpu);
}
}
if elapsed >= self.duration {
let (first, first_counts) =
steady.unwrap_or_else(|| (last.clone(), last_counts.clone()));
let (cpu, threads) = cpu_between(&first, &now);
let secs = now.at.duration_since(first.at).as_secs_f64().max(1e-6);
let rates: serde_json::Map<String, Value> = self
.counters
.iter()
.zip(counts.iter().zip(&first_counts))
.map(|((name, _), (c, f))| {
((*name).to_owned(), json!(round((c - f) as f64 / secs)))
})
.collect();
cpu_samples.sort_by(f64::total_cmp);
let pick = |q: f64| {
cpu_samples
.get(((cpu_samples.len() as f64 - 1.0) * q).round() as usize)
.copied()
.unwrap_or(cpu)
};
emit(&json!({
"summary": true,
"config": self.config,
"steady_seconds": round(secs),
"cpu_mean": round(cpu),
"cpu_p10": round(pick(0.1)),
"cpu_p90": round(pick(0.9)),
"threads_mean": threads.iter().map(|(k, v)| (k.clone(), json!(round(*v)))).collect::<serde_json::Map<_, _>>(),
"rates_mean": rates,
"gauges_end": gauges,
"rss_mib_start": round(rss_start),
"rss_mib_steady_start": rss_steady_start.map(round),
"rss_mib_end": round(now.rss_mib()),
"rss_mib_max": round(rss_max),
"rss_growth_mib_per_min": rss_steady_start.map(|s| round((now.rss_mib() - s) / secs * 60.0)),
}));
std::process::exit(exit_code.load(Ordering::Relaxed) as i32);
}
last = now;
last_counts = counts;
}
}
}
fn round(v: f64) -> f64 {
(v * 10.0).round() / 10.0
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn groups_drop_trailing_numbers() {
assert_eq!(group_of("llvmpipe-12"), "llvmpipe");
assert_eq!(group_of("tokio-runtime-w"), "tokio-runtime-w");
assert_eq!(group_of("spike-video"), "spike-video");
assert_eq!(group_of("1234"), "1234");
}
#[test]
fn stat_lines_parse_with_spaces_in_names() {
let line = "42 (a b) c) S 1 2 3 4 5 6 7 8 9 10 100 23 0 0 20 0 1 0 0";
assert_eq!(ticks_of(line), Some(("a b) c".to_owned(), 123)));
}
}