torrust_tracker/console/clients/checker/
service.rs

1use std::sync::Arc;
2
3use futures::FutureExt as _;
4use serde::Serialize;
5use tokio::task::{JoinError, JoinSet};
6use torrust_tracker_configuration::DEFAULT_TIMEOUT;
7
8use super::checks::{health, http, udp};
9use super::config::Configuration;
10use super::console::Console;
11use crate::console::clients::checker::printer::Printer;
12
13pub struct Service {
14    pub(crate) config: Arc<Configuration>,
15    pub(crate) console: Console,
16}
17
18#[derive(Debug, Clone, Serialize)]
19pub enum CheckResult {
20    Udp(Result<udp::Checks, udp::Checks>),
21    Http(Result<http::Checks, http::Checks>),
22    Health(Result<health::Checks, health::Checks>),
23}
24
25impl Service {
26    /// # Errors
27    ///
28    /// It will return an error if some of the tests panic or otherwise fail to run.
29    /// On success it will return a vector of `Ok(())` of [`CheckResult`].
30    ///
31    /// # Panics
32    ///
33    /// It would panic if `serde_json` produces invalid json for the `to_string_pretty` function.
34    pub async fn run_checks(self) -> Result<Vec<CheckResult>, JoinError> {
35        tracing::info!("Running checks for trackers ...");
36
37        let mut check_results = Vec::default();
38
39        let mut checks = JoinSet::new();
40        checks.spawn(
41            udp::run(self.config.udp_trackers.clone(), DEFAULT_TIMEOUT).map(|mut f| f.drain(..).map(CheckResult::Udp).collect()),
42        );
43        checks.spawn(
44            http::run(self.config.http_trackers.clone(), DEFAULT_TIMEOUT)
45                .map(|mut f| f.drain(..).map(CheckResult::Http).collect()),
46        );
47        checks.spawn(
48            health::run(self.config.health_checks.clone(), DEFAULT_TIMEOUT)
49                .map(|mut f| f.drain(..).map(CheckResult::Health).collect()),
50        );
51
52        while let Some(results) = checks.join_next().await {
53            check_results.append(&mut results?);
54        }
55
56        let json_output = serde_json::json!(check_results);
57        self.console
58            .println(&serde_json::to_string_pretty(&json_output).expect("it should consume valid json"));
59
60        Ok(check_results)
61    }
62}