torrust_tracker/core/services/statistics/
setup.rs

1//! Setup for the tracker statistics.
2//!
3//! The [`factory`] function builds the structs needed for handling the tracker metrics.
4use crate::core::statistics;
5
6/// It builds the structs needed for handling the tracker metrics.
7///
8/// It returns:
9///
10/// - An statistics [`EventSender`](crate::core::statistics::EventSender) that allows you to send events related to statistics.
11/// - An statistics [`Repo`](crate::core::statistics::Repo) which is an in-memory repository for the tracker metrics.
12///
13/// When the input argument `tracker_usage_statistics`is false the setup does not run the event listeners, consequently the statistics
14/// events are sent are received but not dispatched to the handler.
15#[must_use]
16pub fn factory(tracker_usage_statistics: bool) -> (Option<Box<dyn statistics::EventSender>>, statistics::Repo) {
17    let mut stats_event_sender = None;
18
19    let mut stats_tracker = statistics::Keeper::new();
20
21    if tracker_usage_statistics {
22        stats_event_sender = Some(stats_tracker.run_event_listener());
23    }
24
25    (stats_event_sender, stats_tracker.repository)
26}
27
28#[cfg(test)]
29mod test {
30    use super::factory;
31
32    #[tokio::test]
33    async fn should_not_send_any_event_when_statistics_are_disabled() {
34        let tracker_usage_statistics = false;
35
36        let (stats_event_sender, _stats_repository) = factory(tracker_usage_statistics);
37
38        assert!(stats_event_sender.is_none());
39    }
40
41    #[tokio::test]
42    async fn should_send_events_when_statistics_are_enabled() {
43        let tracker_usage_statistics = true;
44
45        let (stats_event_sender, _stats_repository) = factory(tracker_usage_statistics);
46
47        assert!(stats_event_sender.is_some());
48    }
49}