/
task.rs
343 lines (308 loc) · 12.7 KB
/
task.rs
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
use crate::{
input,
state::{
tasks::{Details, Task},
DetailsRef,
},
util::Percentage,
view::{
self, bold,
mini_histogram::{HistogramMetadata, MiniHistogram},
},
};
use std::{
cell::RefCell,
rc::Rc,
time::{Duration, SystemTime},
};
use tui::{
layout::{self, Layout},
text::{Span, Spans, Text},
widgets::{Block, List, ListItem, Paragraph},
};
pub(crate) struct TaskView {
task: Rc<RefCell<Task>>,
details: DetailsRef,
}
impl TaskView {
pub(super) fn new(task: Rc<RefCell<Task>>, details: DetailsRef) -> Self {
TaskView { task, details }
}
pub(crate) fn update_input(&mut self, _event: input::Event) {
// TODO :D
}
pub(crate) fn render<B: tui::backend::Backend>(
&mut self,
styles: &view::Styles,
frame: &mut tui::terminal::Frame<B>,
area: layout::Rect,
now: SystemTime,
) {
// Rows with the following info:
// - Task main attributes
// - task metadata
// - metrics
// - logs?
let task = &*self.task.borrow();
let details_ref = self.details.borrow();
let details = details_ref
.as_ref()
.filter(|details| details.task_id() == task.id());
let warnings: Vec<_> = task
.warnings()
.iter()
.map(|linter| {
ListItem::new(Text::from(Spans::from(vec![
styles.warning_wide(),
// TODO(eliza): it would be nice to handle singular vs plural...
Span::from(linter.format(task)),
])))
})
.collect();
let (controls_area, stats_area, poll_dur_area, fields_area, warnings_area) =
if warnings.is_empty() {
let chunks = Layout::default()
.direction(layout::Direction::Vertical)
.constraints(
[
// controls
layout::Constraint::Length(1),
// task stats
layout::Constraint::Length(8),
// poll duration
layout::Constraint::Length(9),
// fields
layout::Constraint::Percentage(60),
]
.as_ref(),
)
.split(area);
(chunks[0], chunks[1], chunks[2], chunks[3], None)
} else {
let chunks = Layout::default()
.direction(layout::Direction::Vertical)
.constraints(
[
// controls
layout::Constraint::Length(1),
// warnings (add 2 for top and bottom borders)
layout::Constraint::Length(warnings.len() as u16 + 2),
// task stats
layout::Constraint::Length(8),
// poll duration
layout::Constraint::Length(9),
// fields
layout::Constraint::Percentage(60),
]
.as_ref(),
)
.split(area);
(chunks[0], chunks[2], chunks[3], chunks[4], Some(chunks[1]))
};
let stats_area = Layout::default()
.direction(layout::Direction::Horizontal)
.constraints(
[
layout::Constraint::Percentage(50),
layout::Constraint::Percentage(50),
]
.as_ref(),
)
.split(stats_area);
// Only split the histogram area in half if we're also drawing a
// sparkline (which requires UTF-8 characters).
let poll_dur_area = if styles.utf8 {
Layout::default()
.direction(layout::Direction::Horizontal)
.constraints(
[
// 24 chars is long enough for the title "Poll Times Percentiles"
layout::Constraint::Length(24),
layout::Constraint::Min(50),
]
.as_ref(),
)
.split(poll_dur_area)
} else {
vec![poll_dur_area]
};
let percentiles_area = poll_dur_area[0];
let controls = Spans::from(vec![
Span::raw("controls: "),
bold(styles.if_utf8("\u{238B} esc", "esc")),
Span::raw(" = return to task list, "),
bold("q"),
Span::raw(" = quit"),
]);
// Just preallocate capacity for ID, name, target, total, busy, and idle.
let mut overview = Vec::with_capacity(7);
overview.push(Spans::from(vec![
bold("ID: "),
Span::raw(format!("{} ", task.id())),
task.state().render(styles),
]));
if let Some(name) = task.name() {
overview.push(Spans::from(vec![bold("Name: "), Span::raw(name)]));
}
overview.push(Spans::from(vec![
bold("Target: "),
Span::raw(task.target()),
]));
overview.push(Spans::from(vec![
bold("Location: "),
Span::raw(task.location()),
]));
let total = task.total(now);
let dur_percent = |name: &'static str, amt: Duration| -> Spans {
let percent = amt.as_secs_f64().percent_of(total.as_secs_f64());
Spans::from(vec![
bold(name),
dur(styles, amt),
Span::from(format!(" ({:.2}%)", percent)),
])
};
overview.push(Spans::from(vec![bold("Total Time: "), dur(styles, total)]));
overview.push(dur_percent("Busy: ", task.busy(now)));
overview.push(dur_percent("Idle: ", task.idle(now)));
let mut waker_stats = vec![Spans::from(vec![
bold("Current wakers: "),
Span::from(format!("{} (", task.waker_count())),
bold("clones: "),
Span::from(format!("{}, ", task.waker_clones())),
bold("drops: "),
Span::from(format!("{})", task.waker_drops())),
])];
let mut wakeups = vec![
bold("Woken: "),
Span::from(format!("{} times", task.wakes())),
];
// If the task has been woken, add the time since wake to its stats as well.
if let Some(since) = task.since_wake(now) {
wakeups.reserve(3);
wakeups.push(Span::raw(", "));
wakeups.push(bold("last woken:"));
wakeups.push(Span::from(format!(" {:?} ago", since)));
}
waker_stats.push(Spans::from(wakeups));
if task.self_wakes() > 0 {
waker_stats.push(Spans::from(vec![
bold("Self Wakes: "),
Span::from(format!(
"{} times ({}%)",
task.self_wakes(),
task.self_wake_percent()
)),
]));
}
let mut fields = Text::default();
fields.extend(task.formatted_fields().iter().cloned().map(Spans::from));
// If UTF-8 is disabled we can't draw the histogram sparklne.
if styles.utf8 {
let sparkline_area = poll_dur_area[1];
// Bit of a deadlock: We cannot know the highest bucket value without determining the number of buckets,
// and we cannot determine the number of buckets without knowing the width of the chart area which depends on
// the number of digits in the highest bucket value.
// So just assume here the number of digits in the highest bucket value is 3.
// If we overshoot, there will be empty columns/buckets at the right end of the chart.
// If we undershoot, the rightmost 1-2 columns/buckets will be hidden.
// We could get the max bucket value from the previous render though...
let (chart_data, metadata) = details
.map(|d| d.make_chart_data(sparkline_area.width - 3))
.unwrap_or_default();
let histogram_sparkline = MiniHistogram::default()
.block(styles.border_block().title("Poll Times Histogram"))
.data(&chart_data)
.metadata(metadata)
.duration_precision(2);
frame.render_widget(histogram_sparkline, sparkline_area);
}
if let Some(warnings_area) = warnings_area {
let warnings = List::new(warnings).block(styles.border_block().title("Warnings"));
frame.render_widget(warnings, warnings_area);
}
let task_widget = Paragraph::new(overview).block(styles.border_block().title("Task"));
let wakers_widget = Paragraph::new(waker_stats).block(styles.border_block().title("Waker"));
let fields_widget = Paragraph::new(fields).block(styles.border_block().title("Fields"));
let percentiles_widget = Paragraph::new(
details
.map(|details| details.make_percentiles_widget(styles))
.unwrap_or_default(),
)
.block(styles.border_block().title("Poll Times Percentiles"));
frame.render_widget(Block::default().title(controls), controls_area);
frame.render_widget(task_widget, stats_area[0]);
frame.render_widget(wakers_widget, stats_area[1]);
frame.render_widget(fields_widget, fields_area);
frame.render_widget(percentiles_widget, percentiles_area);
}
}
impl Details {
/// From the histogram, build a visual representation by trying to make as
// many buckets as the width of the render area.
fn make_chart_data(&self, width: u16) -> (Vec<u64>, HistogramMetadata) {
self.poll_times_histogram()
.map(|histogram| {
let step_size =
((histogram.max() - histogram.min()) as f64 / width as f64).ceil() as u64 + 1;
// `iter_linear` panics if step_size is 0
let data = if step_size > 0 {
let mut found_first_nonzero = false;
let data: Vec<u64> = histogram
.iter_linear(step_size)
.filter_map(|value| {
let count = value.count_since_last_iteration();
// Remove the 0s from the leading side of the buckets.
// Because HdrHistogram can return empty buckets depending
// on its internal state, as it approximates values.
if count == 0 && !found_first_nonzero {
None
} else {
found_first_nonzero = true;
Some(count)
}
})
.collect();
data
} else {
Vec::new()
};
let max_bucket = data.iter().max().copied().unwrap_or_default();
let min_bucket = data.iter().min().copied().unwrap_or_default();
(
data,
HistogramMetadata {
max_value: histogram.max(),
min_value: histogram.min(),
max_bucket,
min_bucket,
},
)
})
.unwrap_or_default()
}
/// Get the important percentile values from the histogram
fn make_percentiles_widget(&self, styles: &view::Styles) -> Text<'static> {
let mut text = Text::default();
let histogram = self.poll_times_histogram();
let percentiles = histogram.iter().flat_map(|histogram| {
let pairs = [10f64, 25f64, 50f64, 75f64, 90f64, 95f64, 99f64]
.iter()
.map(move |i| (*i, histogram.value_at_percentile(*i)));
pairs.map(|pair| {
Spans::from(vec![
bold(format!("p{:>2}: ", pair.0)),
dur(styles, Duration::from_nanos(pair.1)),
])
})
});
text.extend(percentiles);
text
}
}
fn dur(styles: &view::Styles, dur: std::time::Duration) -> Span<'static> {
const DUR_PRECISION: usize = 4;
// TODO(eliza): can we not have to use `format!` to make a string here? is
// there a way to just give TUI a `fmt::Debug` implementation, or does it
// have to be given a string in order to do layout stuff?
styles.time_units(format!("{:.prec$?}", dur, prec = DUR_PRECISION))
}