archunit/metrics/fluentapi/
metric_threshold_condition.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
use crate::checkable::execute_logged_check;
use crate::{
    checkable::{CheckResult, Checkable},
    common::{ArchUnitError, CheckOptions, Filter, UserError, gather_empty_test_violations},
    metrics::{
        MetricComparison, MetricMeasurement, gather_metric_threshold_violations,
        validate_metric_threshold,
    },
    violation::Violation,
};

use super::{
    CustomMetricSelection, DistanceMetricSelection, LcomMetricSelection, MetricSelection,
    logging::log_measurements,
};

/// Executable exact numeric threshold over one selected metric.
#[derive(Debug, Clone)]
#[must_use = "an architecture rule has no effect until it is checked"]
pub struct MetricThresholdCondition<Selection> {
    selection: Selection,
    comparison: MetricComparison,
    threshold: f64,
}

impl<Selection> MetricThresholdCondition<Selection> {
    pub(super) const fn new(
        selection: Selection,
        comparison: MetricComparison,
        threshold: f64,
    ) -> Self {
        Self {
            selection,
            comparison,
            threshold,
        }
    }

    /// Returns the exact numeric comparison.
    #[must_use]
    pub const fn comparison(&self) -> MetricComparison {
        self.comparison
    }

    /// Returns the configured threshold.
    #[must_use]
    pub const fn threshold(&self) -> f64 {
        self.threshold
    }

    /// Returns the underlying metric selection.
    #[must_use]
    pub const fn selection(&self) -> &Selection {
        &self.selection
    }
}

macro_rules! impl_threshold_checkable {
    ($selection:ty) => {
        impl Checkable for MetricThresholdCondition<$selection> {
            fn check_with(&self, options: &CheckOptions) -> CheckResult {
                execute_logged_check("metrics.threshold", options, |logger| {
                    self.selection.validate_configuration()?;
                    validate_metric_threshold(self.threshold).map_err(threshold_error)?;
                    logger.log_progress("calculating metric values")?;
                    let measurements = self.selection.measure_with(options)?;
                    logger.log_progress(format!("measurements={}", measurements.len()))?;
                    log_measurements(logger, &measurements, Some(self.threshold))?;
                    finish_threshold_check(
                        measurements,
                        self.selection.filters(),
                        self.selection.subject_label(),
                        self.comparison,
                        self.threshold,
                        options,
                    )
                })
            }
        }
    };
}

impl_threshold_checkable!(MetricSelection);
impl_threshold_checkable!(LcomMetricSelection);
impl_threshold_checkable!(DistanceMetricSelection);

impl<Calculation> Checkable for MetricThresholdCondition<CustomMetricSelection<Calculation>>
where
    Calculation: Fn(&crate::metrics::TypeInfo) -> f64,
{
    fn check_with(&self, options: &CheckOptions) -> CheckResult {
        execute_logged_check("metrics.threshold", options, |logger| {
            self.selection.validate_configuration()?;
            validate_metric_threshold(self.threshold).map_err(threshold_error)?;
            logger.log_progress("calculating custom metric values")?;
            let measurements = self.selection.measure_with(options)?;
            logger.log_progress(format!("measurements={}", measurements.len()))?;
            log_measurements(logger, &measurements, Some(self.threshold))?;
            finish_threshold_check(
                measurements,
                self.selection.filters(),
                self.selection.subject_label(),
                self.comparison,
                self.threshold,
                options,
            )
        })
    }
}

fn finish_threshold_check(
    measurements: Vec<MetricMeasurement>,
    filters: &[Filter],
    subject_label: &str,
    comparison: MetricComparison,
    threshold: f64,
    options: &CheckOptions,
) -> CheckResult {
    let empty = gather_empty_test_violations(
        &measurements,
        subject_label,
        filters,
        false,
        options.allows_empty_tests(),
    );
    if let Some(violation) = empty.into_iter().next() {
        return Ok(vec![Violation::from(violation)]);
    }

    Ok(
        gather_metric_threshold_violations(&measurements, comparison, threshold)
            .map_err(threshold_error)?
            .into_iter()
            .map(Violation::from)
            .collect(),
    )
}

fn threshold_error(error: crate::metrics::MetricThresholdError) -> ArchUnitError {
    ArchUnitError::from(UserError::with_source(
        "the metric threshold is invalid",
        error,
    ))
}