tuwunel_admin/integrity/
check.rs1use futures::TryStreamExt;
2use tuwunel_core::{Result, err, implement, itertools::Itertools, utils::IterStream};
3use tuwunel_service::integrity::{Check, Summary, checks, find};
4
5use crate::{Context, admin_command};
6
7#[admin_command]
8pub(super) async fn integrity_check(&self, names: Vec<String>, limit: usize) -> Result {
9 if !names.is_empty() {
10 names.iter().try_for_each(|name| {
11 find(name)
12 .map(|_| ())
13 .ok_or_else(|| err!("no integrity check is named {name}"))
14 })?;
15
16 return self
17 .run_checks(names.iter().filter_map(|name| find(name)), limit)
18 .await;
19 }
20
21 let runnable = checks().filter(|check| check.runnable(self.services));
22
23 self.run_checks(runnable, limit).await?;
24
25 let skipped = checks()
26 .filter(|check| !check.runnable(self.services))
27 .map(|check| check.name);
28
29 if skipped.clone().next().is_none() {
30 return Ok(());
31 }
32
33 self.write_string(format!("\nSkipped on a writable database: {}\n", skipped.format(", ")))
34 .await
35}
36
37#[implement(Context, params = "<'_>")]
38async fn run_checks<Checks>(&self, checks: Checks, limit: usize) -> Result
39where
40 Checks: Iterator<Item = &'static Check> + Send,
41{
42 checks
43 .try_stream()
44 .try_for_each(async |check| self.report(check, limit).await)
45 .await
46}
47
48#[implement(Context, params = "<'_>")]
52async fn report(&self, check: &Check, limit: usize) -> Result {
53 match check.run(self.services, limit).await {
54 | Err(error) if error.is_interrupted() => Err(error),
55 | Err(error) => write!(self, "{}: failed: {error}\n", check.name).await,
56 | Ok(summary) => self.write_string(rendered(check, &summary)).await,
57 }
58}
59
60fn rendered(check: &Check, summary: &Summary) -> String {
61 match summary.findings() {
62 | 0 => format!("{}: clean\n", check.name),
63 | findings => {
64 let counts = summary
65 .counts
66 .iter()
67 .format_with(", ", |(kind, count), entry| {
68 entry(&format_args!("{kind}: {count}"))
69 });
70
71 let samples = summary
72 .samples
73 .iter()
74 .format_with("", |sample, entry| entry(&format_args!("- {sample}\n")));
75
76 format!("{}: {findings} found ({counts})\n{samples}", check.name)
77 },
78 }
79}