forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

metrics_chart.rs299 lines, 9.7 KiBHistoryRawDownload
1//! The geometry of the runner metrics graphs on the runner's admin page. Pure functions: samples go
2//! in, plain numbers and SVG path data come out, and the view in `pages::admin_runners` writes the
3//! markup. The plot covers the last hour in 30 s buckets (120 points). A bucket with no sample is
4//! `None`, and a line breaks where two kept buckets are more than 30 s apart.
5
6use forge_ci::proto::RunnerSample;
7
8/// The width of the chart's viewBox. The SVG scales to its container with the aspect kept.
9pub const VIEW_W: f64 = 360.0;
10/// The height of the chart's viewBox.
11pub const VIEW_H: f64 = 110.0;
12/// Where the plot starts and ends on the x axis, and its top and bottom on the y axis.
13pub const X0: f64 = 40.0;
14pub const X1: f64 = 356.0;
15pub const Y0: f64 = 6.0;
16pub const Y1: f64 = 94.0;
17/// The time one bucket covers, in milliseconds.
18pub const BUCKET_MS: i64 = 30_000;
19/// The number of buckets across the hour.
20pub const BUCKETS: usize = 120;
21/// The longest gap between two samples that a line bridges, in milliseconds.
22const GAP_MS: i64 = 30_000;
23/// The hover tooltip's size and its distance from the crosshair, in viewBox units.
24const TIP_W: f64 = 128.0;
25const TIP_H: f64 = 40.0;
26const TIP_GAP: f64 = 8.0;
27
28/// The averages of the samples in one bucket.
29#[derive(Clone, Copy, Debug, PartialEq)]
30pub struct Bucket {
31 /// Start of the bucket, Unix milliseconds.
32 pub at_ms: i64,
33 /// The first and last sample times in the bucket, used to break a line at a gap.
34 pub first_ms: i64,
35 pub last_ms: i64,
36 pub cpu: f64,
37 pub mem_used: f64,
38 pub mem_total: f64,
39 pub rx: f64,
40 pub tx: f64,
41 pub disk_used: f64,
42 pub disk_total: f64,
43 /// The most jobs running in any sample of the bucket.
44 pub running: u32,
45}
46
47/// One line of the chart: its SVG path data and its CSS class.
48#[derive(Clone, Debug, PartialEq)]
49pub struct Path {
50 pub d: String,
51 pub class: &'static str,
52}
53
54/// The hover target of one bucket: a band over the bucket, a crosshair at its centre, and a tooltip
55/// box beside the crosshair.
56#[derive(Clone, Debug, PartialEq)]
57pub struct Hit {
58 pub x: f64,
59 pub w: f64,
60 pub cx: f64,
61 pub bucket: Bucket,
62 pub tip_x: f64,
63 pub tip_y: f64,
64 pub tip_w: f64,
65 pub tip_h: f64,
66}
67
68/// One line of a chart: how to read its value from a bucket, and its CSS class.
69pub type Series = (fn(&Bucket) -> f64, &'static str);
70
71/// Everything one chart draws, apart from its axis labels.
72#[derive(Clone, Debug, PartialEq)]
73pub struct Svg {
74 /// The y positions of the gridlines.
75 pub grids: Vec<f64>,
76 /// The y position and the value of each y label.
77 pub ticks: Vec<(f64, f64)>,
78 /// The x position and width of each band that marks running jobs.
79 pub bands: Vec<(f64, f64)>,
80 pub paths: Vec<Path>,
81 pub hits: Vec<Hit>,
82}
83
84/// Averages the samples of the last hour into `BUCKETS` buckets, oldest first. Samples before the
85/// window or after `now_ms` are left out.
86pub fn chart_points(samples: &[RunnerSample], now_ms: i64) -> Vec<Option<Bucket>> {
87 let start = now_ms - BUCKET_MS * BUCKETS as i64;
88 let mut sums: Vec<Option<(Bucket, f64)>> = vec![None; BUCKETS];
89 for s in samples {
90 if s.at_ms < start || s.at_ms > now_ms {
91 continue;
92 }
93 let index = (((s.at_ms - start) / BUCKET_MS) as usize).min(BUCKETS - 1);
94 let at_ms = start + index as i64 * BUCKET_MS;
95 let (bucket, count) = sums[index].get_or_insert((
96 Bucket {
97 at_ms,
98 first_ms: s.at_ms,
99 last_ms: s.at_ms,
100 cpu: 0.0,
101 mem_used: 0.0,
102 mem_total: 0.0,
103 rx: 0.0,
104 tx: 0.0,
105 disk_used: 0.0,
106 disk_total: 0.0,
107 running: 0,
108 },
109 0.0,
110 ));
111 bucket.first_ms = bucket.first_ms.min(s.at_ms);
112 bucket.last_ms = bucket.last_ms.max(s.at_ms);
113 bucket.cpu += f64::from(s.cpu_percent);
114 bucket.mem_used += s.mem_used_bytes as f64;
115 bucket.mem_total = bucket.mem_total.max(s.mem_total_bytes as f64);
116 bucket.rx += s.net_rx_bytes_per_s as f64;
117 bucket.tx += s.net_tx_bytes_per_s as f64;
118 bucket.disk_used += s.disk_used_bytes as f64;
119 bucket.disk_total = bucket.disk_total.max(s.disk_total_bytes as f64);
120 bucket.running = bucket.running.max(s.running_jobs);
121 *count += 1.0;
122 }
123 sums.into_iter()
124 .map(|slot| {
125 slot.map(|(mut bucket, count)| {
126 bucket.cpu /= count;
127 bucket.mem_used /= count;
128 bucket.rx /= count;
129 bucket.tx /= count;
130 bucket.disk_used /= count;
131 bucket
132 })
133 })
134 .collect()
135}
136
137/// The smallest "nice" number (1, 2, 2.5 or 5 times a power of ten) that is at least `value`.
138/// Zero gives 1.
139pub fn nice_max(value: u64) -> u64 {
140 if value <= 1 {
141 return 1;
142 }
143 let mut unit = 1u64;
144 while unit.saturating_mul(10) <= value {
145 unit *= 10;
146 }
147 [unit, unit * 2, unit * 5 / 2, unit * 5, unit * 10]
148 .into_iter()
149 .find(|candidate| *candidate >= value)
150 .unwrap_or(unit * 10)
151}
152
153/// The largest value of a series over the buckets, as a whole number of bytes per second, at least
154/// 1 KiB/s so a quiet network gets a readable scale.
155pub fn net_max(points: &[Option<Bucket>]) -> f64 {
156 let peak = points
157 .iter()
158 .flatten()
159 .map(|b| b.rx.max(b.tx))
160 .fold(0.0_f64, f64::max);
161 nice_max((peak.ceil() as u64).max(1024)) as f64
162}
163
164/// Builds the chart of `points`. `max` is the top of the y axis; `series` gives each line's value
165/// and CSS class. `band` marks the buckets where jobs ran.
166pub fn svg(points: &[Option<Bucket>], max: f64, series: &[Series], band: bool) -> Svg {
167 let max = if max > 0.0 { max } else { 1.0 };
168 let bw = bucket_width();
169 let bands = if band {
170 points
171 .iter()
172 .enumerate()
173 .filter(|(_, p)| p.is_some_and(|b| b.running > 0))
174 .map(|(i, _)| (X0 + i as f64 * bw, bw))
175 .collect()
176 } else {
177 Vec::new()
178 };
179 let paths = series
180 .iter()
181 .map(|(value, class)| Path {
182 d: line_d(points, *value, max),
183 class,
184 })
185 .collect();
186 let hits = points
187 .iter()
188 .enumerate()
189 .filter_map(|(i, p)| {
190 let bucket = (*p)?;
191 let cx = X0 + (i as f64 + 0.5) * bw;
192 let tip_x = if cx > (X0 + X1) / 2.0 {
193 cx - TIP_GAP - TIP_W
194 } else {
195 cx + TIP_GAP
196 };
197 Some(Hit {
198 x: X0 + i as f64 * bw,
199 w: bw,
200 cx,
201 bucket,
202 tip_x,
203 tip_y: Y0 + 2.0,
204 tip_w: TIP_W,
205 tip_h: TIP_H,
206 })
207 })
208 .collect();
209 Svg {
210 grids: vec![y_of(max / 2.0, max), y_of(max, max)],
211 ticks: vec![
212 (y_of(0.0, max), 0.0),
213 (y_of(max / 2.0, max), max / 2.0),
214 (y_of(max, max), max),
215 ],
216 bands,
217 paths,
218 hits,
219 }
220}
221
222fn bucket_width() -> f64 {
223 (X1 - X0) / BUCKETS as f64
224}
225
226fn y_of(value: f64, max: f64) -> f64 {
227 Y1 - (value / max).clamp(0.0, 1.0) * (Y1 - Y0)
228}
229
230/// The path of one series. A line is one `M` and `L` run; a bucket with no sample, or a gap of more
231/// than `GAP_MS` between two samples, starts a new `M`.
232fn line_d(points: &[Option<Bucket>], value: fn(&Bucket) -> f64, max: f64) -> String {
233 let bw = bucket_width();
234 let mut d = String::new();
235 let mut prev: Option<Bucket> = None;
236 for (i, point) in points.iter().enumerate() {
237 let Some(b) = point else {
238 prev = None;
239 continue;
240 };
241 let joined = prev.is_some_and(|q| b.first_ms - q.last_ms <= GAP_MS);
242 let x = X0 + (i as f64 + 0.5) * bw;
243 let y = y_of(value(b), max);
244 d.push_str(if joined { " L" } else { " M" });
245 d.push_str(&format!("{x:.1} {y:.1}"));
246 prev = Some(*b);
247 }
248 d.trim_start().to_owned()
249}
250
251#[cfg(test)]
252mod tests {
253 use super::*;
254
255 fn sample(at_ms: i64, cpu: f32) -> RunnerSample {
256 RunnerSample {
257 at_ms,
258 cpu_percent: cpu,
259 mem_used_bytes: 0,
260 mem_total_bytes: 0,
261 net_rx_bytes_per_s: 0,
262 net_tx_bytes_per_s: 0,
263 disk_used_bytes: 0,
264 disk_total_bytes: 0,
265 running_jobs: 0,
266 }
267 }
268
269 /// Samples in one bucket are averaged, an empty bucket is `None`, and a gap of over 30 s starts a
270 /// new line segment.
271 #[test]
272 fn buckets_average_and_a_gap_breaks_the_line() {
273 let now = 7_200_000;
274 let start = now - BUCKET_MS * BUCKETS as i64;
275 let samples = [
276 sample(start, 10.0),
277 sample(start + 5_000, 30.0),
278 // Bucket 1 is empty: the next sample comes 60 s after the last one above.
279 sample(start + 65_000, 50.0),
280 ];
281 let points = chart_points(&samples, now);
282 assert_eq!(points[0].map(|b| b.cpu), Some(20.0));
283 assert_eq!(points[1], None);
284 assert_eq!(points[2].map(|b| b.cpu), Some(50.0));
285 let d = line_d(&points, |b| b.cpu, 100.0);
286 assert_eq!(d.matches('M').count(), 2, "{d}");
287 assert_eq!(d.matches('L').count(), 0, "{d}");
288 }
289
290 #[test]
291 fn nice_max_rounds_up_to_one_two_two_and_a_half_or_five() {
292 assert_eq!(nice_max(0), 1);
293 assert_eq!(nice_max(10), 10);
294 assert_eq!(nice_max(11), 20);
295 assert_eq!(nice_max(1500), 2000);
296 assert_eq!(nice_max(2400), 2500);
297 assert_eq!(nice_max(3_145_728), 5_000_000);
298 }
299}