bestool 1.30.1

BES Deployment tooling
Documentation
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
use std::{
	io::{self, Stdout, Write},
	time::Duration,
};

use crossterm::{
	cursor::{Hide, MoveTo, Show},
	event::{self, Event, KeyCode, KeyEvent, KeyModifiers},
	execute, queue,
	style::{Attribute, Color, ResetColor, SetAttribute, SetForegroundColor},
	terminal::{
		Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode,
		enable_raw_mode,
	},
};
use miette::{IntoDiagnostic, Result};
use tokio::sync::mpsc::UnboundedReceiver;

use bestool_alertd::doctor::{
	check::{Check, CheckStatus},
	progress::DoctorEvent,
};

use super::{SweepSource, order};

const SPINNER_FRAMES: &[&str] = &[
	"", "", "", "", "", "", "", "", "", "",
];
const TICK: Duration = Duration::from_millis(80);

/// State of a single row in the TUI.
#[derive(Clone)]
enum RowState {
	Running,
	Completed(Check),
}

struct TuiRow {
	name: &'static str,
	state: RowState,
}

pub struct TuiOutcome {
	pub results: Vec<(Check, bool)>,
	pub interrupted: bool,
}

/// A single styled segment within a rendered line.
#[derive(Clone, Debug)]
struct Segment {
	text: String,
	style: SegStyle,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SegStyle {
	Plain,
	Dim,
	BoldFg(Color),
}

type StyledLine = Vec<Segment>;

fn plain<S: Into<String>>(s: S) -> Segment {
	Segment {
		text: s.into(),
		style: SegStyle::Plain,
	}
}
fn dim<S: Into<String>>(s: S) -> Segment {
	Segment {
		text: s.into(),
		style: SegStyle::Dim,
	}
}
fn bold_fg<S: Into<String>>(s: S, c: Color) -> Segment {
	Segment {
		text: s.into(),
		style: SegStyle::BoldFg(c),
	}
}

/// RAII guard that restores the terminal on drop (including on panic).
struct TerminalGuard {
	stdout: Stdout,
}

impl TerminalGuard {
	fn new() -> io::Result<Self> {
		let mut stdout = io::stdout();
		enable_raw_mode()?;
		execute!(stdout, EnterAlternateScreen, Hide)?;
		Ok(Self { stdout })
	}
}

impl Drop for TerminalGuard {
	fn drop(&mut self) {
		let _ = execute!(self.stdout, Show, LeaveAlternateScreen);
		let _ = disable_raw_mode();
	}
}

/// Run the live TUI until either the sweep finishes (progress channel closes
/// and every selected check has been seen) or the user interrupts (Ctrl+C / q).
pub async fn run_tui(
	selected_names: Vec<&'static str>,
	only_failing: bool,
	source: SweepSource,
	mut progress_rx: UnboundedReceiver<DoctorEvent>,
) -> Result<TuiOutcome> {
	let total = selected_names.len();
	let mut rows: Vec<TuiRow> = selected_names
		.into_iter()
		.map(|name| TuiRow {
			name,
			state: RowState::Running,
		})
		.collect();
	let mut spinner = 0usize;
	let mut interrupted = false;

	let mut guard = TerminalGuard::new().into_diagnostic()?;

	loop {
		drain_progress(&mut progress_rx, &mut rows);

		draw(
			&mut guard.stdout,
			&rows,
			total,
			&source,
			only_failing,
			spinner,
		)
		.into_diagnostic()?;

		if all_completed(&rows) {
			break;
		}

		if poll_for_quit(TICK).into_diagnostic()? {
			interrupted = true;
			break;
		}

		spinner = (spinner + 1) % SPINNER_FRAMES.len();

		if progress_rx.is_closed() && progress_rx.is_empty() && !all_completed(&rows) {
			// Sweep ended early (error or aborted) without producing all results.
			// Treat as interrupted so the caller exits non-zero.
			interrupted = true;
			break;
		}
	}

	drop(guard);

	let results: Vec<(Check, bool)> = rows
		.into_iter()
		.filter_map(|row| match row.state {
			RowState::Completed(check) => Some((check, true)),
			RowState::Running => None,
		})
		.collect();

	Ok(TuiOutcome {
		results,
		interrupted,
	})
}

fn drain_progress(rx: &mut UnboundedReceiver<DoctorEvent>, rows: &mut [TuiRow]) {
	while let Ok(evt) = rx.try_recv() {
		match evt {
			DoctorEvent::Completed(check) => {
				if let Some(row) = rows.iter_mut().find(|r| r.name == check.name) {
					row.state = RowState::Completed(check);
				}
			}
		}
	}
}

fn all_completed(rows: &[TuiRow]) -> bool {
	rows.iter().all(|r| matches!(r.state, RowState::Completed(_)))
}

/// Poll keyboard events for up to `timeout`. Returns true if the user pressed a
/// quit chord (Ctrl+C or q).
fn poll_for_quit(timeout: Duration) -> io::Result<bool> {
	if !event::poll(timeout)? {
		return Ok(false);
	}
	while event::poll(Duration::ZERO)? {
		if let Event::Key(KeyEvent {
			code, modifiers, ..
		}) = event::read()?
		{
			let ctrl_c =
				matches!(code, KeyCode::Char('c')) && modifiers.contains(KeyModifiers::CONTROL);
			let q = matches!(code, KeyCode::Char('q'));
			if ctrl_c || q {
				return Ok(true);
			}
		}
	}
	Ok(false)
}

fn draw(
	out: &mut Stdout,
	rows: &[TuiRow],
	total: usize,
	source: &SweepSource,
	only_failing: bool,
	spinner: usize,
) -> io::Result<()> {
	queue!(out, MoveTo(0, 0), Clear(ClearType::All))?;

	let mut lines: Vec<StyledLine> = Vec::new();
	if let Some(line) = source_line(source) {
		lines.push(line);
	}
	lines.extend(build_rows(rows, only_failing, spinner));
	lines.push(footer_line(rows, total, spinner));

	for line in lines {
		write_line(out, &line)?;
		out.write_all(b"\r\n")?;
	}
	out.flush()
}

fn write_line(out: &mut Stdout, line: &StyledLine) -> io::Result<()> {
	for seg in line {
		match seg.style {
			SegStyle::Plain => out.write_all(seg.text.as_bytes())?,
			SegStyle::Dim => {
				queue!(out, SetAttribute(Attribute::Dim))?;
				out.write_all(seg.text.as_bytes())?;
				queue!(out, SetAttribute(Attribute::Reset))?;
			}
			SegStyle::BoldFg(c) => {
				queue!(out, SetForegroundColor(c), SetAttribute(Attribute::Bold))?;
				out.write_all(seg.text.as_bytes())?;
				queue!(out, SetAttribute(Attribute::Reset), ResetColor)?;
			}
		}
	}
	Ok(())
}

fn source_line(source: &SweepSource) -> Option<StyledLine> {
	let text = match source {
		SweepSource::Local => return None,
		SweepSource::DaemonStreamed => "Source: alertd daemon (just now, on demand)".to_string(),
		SweepSource::DaemonCached { computed_at } => {
			let age = super::render::humanise_age_since(*computed_at);
			format!("Source: alertd daemon (computed {age} ago, at {computed_at})")
		}
	};
	Some(vec![dim(text)])
}

fn build_rows(rows: &[TuiRow], only_failing: bool, spinner: usize) -> Vec<StyledLine> {
	let name_width = rows.iter().map(|r| r.name.len()).max().unwrap_or(0);

	let mut ordered: Vec<&TuiRow> = rows
		.iter()
		.filter(|row| match &row.state {
			RowState::Running => true,
			RowState::Completed(check) => order::keep_under_filter(&check.status, only_failing),
		})
		.collect();
	ordered.sort_by(|a, b| sort_key(a).cmp(&sort_key(b)).then_with(|| a.name.cmp(b.name)));

	let mut lines = Vec::with_capacity(ordered.len());
	for row in ordered {
		match &row.state {
			RowState::Running => lines.push(row_line_running(row.name, name_width, spinner)),
			RowState::Completed(check) => {
				lines.push(row_line_completed(check, name_width));
				if let Some(reason) = reason_for(check) {
					lines.push(reason_line(reason, name_width));
				}
			}
		}
	}
	lines
}

fn sort_key(row: &TuiRow) -> u8 {
	match &row.state {
		RowState::Running => 0,
		RowState::Completed(check) => 1 + order::severity_key(&check.status),
	}
}

fn row_line_running(name: &str, name_width: usize, spinner: usize) -> StyledLine {
	let frame = SPINNER_FRAMES[spinner % SPINNER_FRAMES.len()];
	let pad = " ".repeat(name_width.saturating_sub(name.len()));
	vec![
		plain("  "),
		dim(format!("{frame:<4}")),
		plain("    "),
		plain(name.to_string()),
		plain(pad),
		plain("   "),
		dim(""),
	]
}

fn row_line_completed(check: &Check, name_width: usize) -> StyledLine {
	let (tag, color) = tag_for(check);
	let pad = " ".repeat(name_width.saturating_sub(check.name.len()));
	vec![
		plain("  "),
		bold_fg(format!("{tag:<4}"), color),
		plain("    "),
		plain(check.name.to_string()),
		plain(pad),
		plain("   "),
		plain(check.summary.clone()),
	]
}

fn reason_line(reason: &str, name_width: usize) -> StyledLine {
	let lead = " ".repeat(10 + name_width + 5);
	vec![plain(lead), dim(reason.to_string())]
}

fn reason_for(check: &Check) -> Option<&str> {
	match &check.status {
		CheckStatus::Pass => None,
		CheckStatus::Skip(r)
		| CheckStatus::Warning(r)
		| CheckStatus::Fail(r)
		| CheckStatus::Broken(r) => Some(r.as_str()),
	}
}

fn tag_for(check: &Check) -> (&'static str, Color) {
	match &check.status {
		CheckStatus::Pass => ("PASS", Color::Green),
		CheckStatus::Skip(_) => ("SKIP", Color::DarkGrey),
		CheckStatus::Warning(_) => ("WARN", Color::Yellow),
		CheckStatus::Broken(_) => ("BRKN", Color::Magenta),
		CheckStatus::Fail(_) => ("FAIL", Color::Red),
	}
}

fn footer_line(rows: &[TuiRow], total: usize, spinner: usize) -> StyledLine {
	let completed = rows
		.iter()
		.filter(|r| matches!(r.state, RowState::Completed(_)))
		.count();
	let frame = SPINNER_FRAMES[spinner % SPINNER_FRAMES.len()];
	vec![dim(format!("{frame} {completed} / {total} complete"))]
}

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

	fn line_text(line: &StyledLine) -> String {
		line.iter().map(|s| s.text.as_str()).collect()
	}

	#[test]
	fn build_rows_orders_running_then_pass_skip_warn_broken_fail() {
		let rows = vec![
			TuiRow {
				name: "z-fail",
				state: RowState::Completed(Check::fail("z-fail", "bad", "r")),
			},
			TuiRow {
				name: "a-pass",
				state: RowState::Completed(Check::pass("a-pass", "ok")),
			},
			TuiRow {
				name: "m-warn",
				state: RowState::Completed(Check::warning("m-warn", "deg", "r")),
			},
			TuiRow {
				name: "k-run",
				state: RowState::Running,
			},
			TuiRow {
				name: "b-skip",
				state: RowState::Completed(Check::skip("b-skip", "n/a", "r")),
			},
			TuiRow {
				name: "c-broken",
				state: RowState::Completed(Check::broken("c-broken", "broke", "r")),
			},
		];
		let lines = build_rows(&rows, false, 0);
		let joined: Vec<String> = lines.iter().map(line_text).collect();
		let positions = |needle: &str| {
			joined
				.iter()
				.position(|s| s.contains(needle))
				.unwrap_or_else(|| panic!("missing {needle}"))
		};
		assert!(positions("k-run") < positions("a-pass"));
		assert!(positions("a-pass") < positions("b-skip"));
		assert!(positions("b-skip") < positions("m-warn"));
		assert!(positions("m-warn") < positions("c-broken"));
		assert!(positions("c-broken") < positions("z-fail"));
	}

	#[test]
	fn build_rows_only_failing_drops_completed_pass_and_skip_but_keeps_running() {
		let rows = vec![
			TuiRow {
				name: "a-pass",
				state: RowState::Completed(Check::pass("a-pass", "ok")),
			},
			TuiRow {
				name: "b-skip",
				state: RowState::Completed(Check::skip("b-skip", "n/a", "r")),
			},
			TuiRow {
				name: "c-warn",
				state: RowState::Completed(Check::warning("c-warn", "deg", "r")),
			},
			TuiRow {
				name: "d-run",
				state: RowState::Running,
			},
		];
		let lines = build_rows(&rows, true, 0);
		let joined: Vec<String> = lines.iter().map(line_text).collect();
		assert!(joined.iter().any(|s| s.contains("d-run")));
		assert!(joined.iter().any(|s| s.contains("c-warn")));
		assert!(!joined.iter().any(|s| s.contains("a-pass")));
		assert!(!joined.iter().any(|s| s.contains("b-skip")));
	}

	#[test]
	fn footer_counts_completed_against_total() {
		let rows = vec![
			TuiRow {
				name: "a",
				state: RowState::Completed(Check::pass("a", "ok")),
			},
			TuiRow {
				name: "b",
				state: RowState::Completed(Check::warning("b", "deg", "r")),
			},
			TuiRow {
				name: "c",
				state: RowState::Running,
			},
		];
		let line = footer_line(&rows, 3, 0);
		assert!(line_text(&line).contains("2 / 3 complete"));
	}
}