Skip to main content

codeint_model/
metric.rs

1use std::borrow::Cow;
2use std::collections::BTreeMap;
3
4use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
5use serde::{Deserialize, Serialize};
6
7use crate::{CodeModel, RepoPath, SourceSet};
8
9#[cfg(test)]
10mod tests;
11
12pub const STRUCTURAL_REPORT_KEYS: [&str; 3] = ["files", "source_lines", "packages"];
13
14pub fn is_reserved_report_key(key: &str) -> bool {
15    Metric::from_key(key).is_some() || STRUCTURAL_REPORT_KEYS.contains(&key)
16}
17
18#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
19pub enum MetricKind {
20    SoftwareEntropy,
21    Hazards,
22}
23
24#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
25pub enum MetricScope {
26    AllSourceSets,
27    ProductionOnly,
28    RepositoryWide,
29}
30
31impl MetricScope {
32    pub const fn applies_to_source_set(self, source_set: SourceSet) -> bool {
33        match self {
34            MetricScope::AllSourceSets => true,
35            MetricScope::ProductionOnly => matches!(source_set, SourceSet::Production),
36            MetricScope::RepositoryWide => false,
37        }
38    }
39}
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
42#[serde(rename_all = "snake_case")]
43pub enum NewFindingsRule {
44    AnyNewFinding,
45    #[serde(alias = "numerator_rise_with_new_findings")]
46    NumeratorRise,
47    Never,
48}
49
50impl JsonSchema for NewFindingsRule {
51    fn schema_name() -> Cow<'static, str> {
52        Cow::Borrowed("NewFindingsRule")
53    }
54
55    fn schema_id() -> Cow<'static, str> {
56        Cow::Borrowed(concat!(module_path!(), "::NewFindingsRule"))
57    }
58
59    fn json_schema(_generator: &mut SchemaGenerator) -> Schema {
60        json_schema!({
61            "type": "string",
62            "enum": [
63                "any_new_finding",
64                "numerator_rise",
65                "numerator_rise_with_new_findings",
66                "never"
67            ]
68        })
69    }
70}
71
72#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
73pub enum MetricCapability {
74    None,
75    Imports,
76    HazardLines,
77    CoverageReport,
78}
79
80#[derive(Clone, Copy, Debug, PartialEq, Eq)]
81pub struct MetricDescriptor {
82    pub key: &'static str,
83    pub display_name: &'static str,
84    pub version: u32,
85    pub kind: MetricKind,
86    pub scope: MetricScope,
87    pub supports_diff_regression: bool,
88    pub default_new_findings_rule: NewFindingsRule,
89    pub required_capability: MetricCapability,
90    pub numerator_field: &'static str,
91}
92
93#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
94#[repr(usize)]
95pub enum Metric {
96    Erosion = 0,
97    CognitiveComplexity = 1,
98    Duplication = 2,
99    Verbosity = 3,
100    ImportCycles = 4,
101    Boundaries = 5,
102    OrphanFiles = 6,
103    TestGap = 7,
104    FileSize = 8,
105    Hazards = 9,
106    UnusedDependencies = 10,
107    UnlistedDependencies = 11,
108    DevInProductionDependencies = 12,
109}
110
111impl Metric {
112    pub const DESCRIPTORS: [(Metric, MetricDescriptor); 13] = [
113        (
114            Metric::Erosion,
115            MetricDescriptor {
116                key: "erosion",
117                display_name: "Erosion",
118                version: 2,
119                kind: MetricKind::SoftwareEntropy,
120                scope: MetricScope::AllSourceSets,
121                supports_diff_regression: true,
122                default_new_findings_rule: NewFindingsRule::NumeratorRise,
123                required_capability: MetricCapability::None,
124                numerator_field: "eroded_function_mass",
125            },
126        ),
127        (
128            Metric::CognitiveComplexity,
129            MetricDescriptor {
130                key: "cognitive_complexity",
131                display_name: "Cognitive complexity",
132                version: 2,
133                kind: MetricKind::SoftwareEntropy,
134                scope: MetricScope::AllSourceSets,
135                supports_diff_regression: true,
136                default_new_findings_rule: NewFindingsRule::NumeratorRise,
137                required_capability: MetricCapability::None,
138                numerator_field: "complex_cognitive_complexity",
139            },
140        ),
141        (
142            Metric::Duplication,
143            MetricDescriptor {
144                key: "duplication",
145                display_name: "Duplication",
146                version: 3,
147                kind: MetricKind::SoftwareEntropy,
148                scope: MetricScope::AllSourceSets,
149                supports_diff_regression: true,
150                default_new_findings_rule: NewFindingsRule::NumeratorRise,
151                required_capability: MetricCapability::None,
152                numerator_field: "clone_lines",
153            },
154        ),
155        (
156            Metric::Verbosity,
157            MetricDescriptor {
158                key: "verbosity",
159                display_name: "Verbosity",
160                version: 4,
161                kind: MetricKind::SoftwareEntropy,
162                scope: MetricScope::AllSourceSets,
163                supports_diff_regression: true,
164                default_new_findings_rule: NewFindingsRule::NumeratorRise,
165                required_capability: MetricCapability::None,
166                numerator_field: "verbose_lines",
167            },
168        ),
169        (
170            Metric::ImportCycles,
171            MetricDescriptor {
172                key: "import_cycles",
173                display_name: "Import cycles",
174                version: 3,
175                kind: MetricKind::SoftwareEntropy,
176                scope: MetricScope::AllSourceSets,
177                supports_diff_regression: true,
178                default_new_findings_rule: NewFindingsRule::AnyNewFinding,
179                required_capability: MetricCapability::Imports,
180                numerator_field: "modules_in_import_cycles",
181            },
182        ),
183        (
184            Metric::Boundaries,
185            MetricDescriptor {
186                key: "boundaries",
187                display_name: "Import boundaries",
188                version: 4,
189                kind: MetricKind::SoftwareEntropy,
190                scope: MetricScope::AllSourceSets,
191                supports_diff_regression: true,
192                default_new_findings_rule: NewFindingsRule::AnyNewFinding,
193                required_capability: MetricCapability::Imports,
194                numerator_field: "boundary_findings",
195            },
196        ),
197        (
198            Metric::OrphanFiles,
199            MetricDescriptor {
200                key: "orphan_files",
201                display_name: "Orphan files",
202                version: 2,
203                kind: MetricKind::SoftwareEntropy,
204                scope: MetricScope::ProductionOnly,
205                supports_diff_regression: true,
206                default_new_findings_rule: NewFindingsRule::AnyNewFinding,
207                required_capability: MetricCapability::Imports,
208                numerator_field: "orphan_files",
209            },
210        ),
211        (
212            Metric::TestGap,
213            MetricDescriptor {
214                key: "test_gap",
215                display_name: "Test gap",
216                version: 2,
217                kind: MetricKind::SoftwareEntropy,
218                scope: MetricScope::ProductionOnly,
219                supports_diff_regression: false,
220                default_new_findings_rule: NewFindingsRule::NumeratorRise,
221                required_capability: MetricCapability::CoverageReport,
222                numerator_field: "untested_function_mass",
223            },
224        ),
225        (
226            Metric::FileSize,
227            MetricDescriptor {
228                key: "file_size",
229                display_name: "File size",
230                version: 1,
231                kind: MetricKind::SoftwareEntropy,
232                scope: MetricScope::ProductionOnly,
233                supports_diff_regression: true,
234                default_new_findings_rule: NewFindingsRule::NumeratorRise,
235                required_capability: MetricCapability::None,
236                numerator_field: "excess_lines",
237            },
238        ),
239        (
240            Metric::Hazards,
241            MetricDescriptor {
242                key: "hazards",
243                display_name: "Hazards",
244                version: 2,
245                kind: MetricKind::Hazards,
246                scope: MetricScope::AllSourceSets,
247                supports_diff_regression: true,
248                default_new_findings_rule: NewFindingsRule::AnyNewFinding,
249                required_capability: MetricCapability::HazardLines,
250                numerator_field: "hazard_lines",
251            },
252        ),
253        (
254            Metric::UnusedDependencies,
255            MetricDescriptor {
256                key: "unused_dependencies",
257                display_name: "Unused dependencies",
258                version: 2,
259                kind: MetricKind::SoftwareEntropy,
260                scope: MetricScope::RepositoryWide,
261                supports_diff_regression: true,
262                default_new_findings_rule: NewFindingsRule::AnyNewFinding,
263                required_capability: MetricCapability::Imports,
264                numerator_field: "unused",
265            },
266        ),
267        (
268            Metric::UnlistedDependencies,
269            MetricDescriptor {
270                key: "unlisted_dependencies",
271                display_name: "Unlisted dependencies",
272                version: 2,
273                kind: MetricKind::SoftwareEntropy,
274                scope: MetricScope::RepositoryWide,
275                supports_diff_regression: true,
276                default_new_findings_rule: NewFindingsRule::AnyNewFinding,
277                required_capability: MetricCapability::Imports,
278                numerator_field: "unlisted",
279            },
280        ),
281        (
282            Metric::DevInProductionDependencies,
283            MetricDescriptor {
284                key: "dev_in_production_dependencies",
285                display_name: "Dev dependencies in production",
286                version: 2,
287                kind: MetricKind::SoftwareEntropy,
288                scope: MetricScope::RepositoryWide,
289                supports_diff_regression: true,
290                default_new_findings_rule: NewFindingsRule::AnyNewFinding,
291                required_capability: MetricCapability::Imports,
292                numerator_field: "dev_in_production",
293            },
294        ),
295    ];
296
297    pub const ALL: [Metric; 13] = [
298        Metric::DESCRIPTORS[0].0,
299        Metric::DESCRIPTORS[1].0,
300        Metric::DESCRIPTORS[2].0,
301        Metric::DESCRIPTORS[3].0,
302        Metric::DESCRIPTORS[4].0,
303        Metric::DESCRIPTORS[5].0,
304        Metric::DESCRIPTORS[6].0,
305        Metric::DESCRIPTORS[7].0,
306        Metric::DESCRIPTORS[8].0,
307        Metric::DESCRIPTORS[9].0,
308        Metric::DESCRIPTORS[10].0,
309        Metric::DESCRIPTORS[11].0,
310        Metric::DESCRIPTORS[12].0,
311    ];
312
313    pub const BUILT_IN_KEYS: [&'static str; 13] = [
314        Metric::DESCRIPTORS[0].1.key,
315        Metric::DESCRIPTORS[1].1.key,
316        Metric::DESCRIPTORS[2].1.key,
317        Metric::DESCRIPTORS[3].1.key,
318        Metric::DESCRIPTORS[4].1.key,
319        Metric::DESCRIPTORS[5].1.key,
320        Metric::DESCRIPTORS[6].1.key,
321        Metric::DESCRIPTORS[7].1.key,
322        Metric::DESCRIPTORS[8].1.key,
323        Metric::DESCRIPTORS[9].1.key,
324        Metric::DESCRIPTORS[10].1.key,
325        Metric::DESCRIPTORS[11].1.key,
326        Metric::DESCRIPTORS[12].1.key,
327    ];
328
329    pub const fn descriptor(self) -> &'static MetricDescriptor {
330        &Metric::DESCRIPTORS[self.index()].1
331    }
332
333    pub const fn key(self) -> &'static str {
334        self.descriptor().key
335    }
336
337    pub const fn display_name(self) -> &'static str {
338        self.descriptor().display_name
339    }
340
341    pub const fn version(self) -> u32 {
342        self.descriptor().version
343    }
344
345    pub const fn kind(self) -> MetricKind {
346        self.descriptor().kind
347    }
348
349    pub const fn scope(self) -> MetricScope {
350        self.descriptor().scope
351    }
352
353    pub const fn supports_diff_regression(self) -> bool {
354        self.descriptor().supports_diff_regression
355    }
356
357    pub const fn default_new_findings_rule(self) -> NewFindingsRule {
358        self.descriptor().default_new_findings_rule
359    }
360
361    pub const fn required_capability(self) -> MetricCapability {
362        self.descriptor().required_capability
363    }
364
365    pub const fn numerator_field(self) -> &'static str {
366        self.descriptor().numerator_field
367    }
368
369    pub fn from_key(key: &str) -> Option<Metric> {
370        Metric::DESCRIPTORS
371            .iter()
372            .find(|(_, descriptor)| descriptor.key == key)
373            .map(|(metric, _)| *metric)
374    }
375
376    pub fn built_in_versions() -> BTreeMap<&'static str, u32> {
377        Metric::DESCRIPTORS
378            .iter()
379            .map(|(_, descriptor)| (descriptor.key, descriptor.version))
380            .collect()
381    }
382
383    pub fn versions_with_plugins(metric_plugins: &[&dyn MetricPlugin]) -> BTreeMap<String, u32> {
384        let mut versions: BTreeMap<String, u32> = Metric::DESCRIPTORS
385            .iter()
386            .map(|(_, descriptor)| (descriptor.key.to_owned(), descriptor.version))
387            .collect();
388        for plugin in metric_plugins {
389            versions.insert(plugin.key().to_owned(), plugin.version());
390        }
391        versions
392    }
393
394    pub const fn index(self) -> usize {
395        self as usize
396    }
397}
398
399impl SourceSet {
400    pub const ALL: [SourceSet; 4] = [
401        SourceSet::Production,
402        SourceSet::Test,
403        SourceSet::Generated,
404        SourceSet::Vendored,
405    ];
406
407    pub const fn key(self) -> &'static str {
408        match self {
409            SourceSet::Production => "production",
410            SourceSet::Test => "test",
411            SourceSet::Generated => "generated",
412            SourceSet::Vendored => "vendored",
413        }
414    }
415}
416
417#[derive(Clone, Debug, PartialEq, Eq)]
418pub struct ExternalFinding {
419    pub id: String,
420    pub path: RepoPath,
421    pub line: u32,
422    pub end_line: Option<u32>,
423    pub message: String,
424}
425
426#[derive(Clone, Debug, PartialEq)]
427pub struct ExternalMetricMeasurement {
428    pub ratio: f64,
429    pub numerator: f64,
430    pub denominator: f64,
431    pub findings: Vec<ExternalFinding>,
432}
433
434#[derive(Debug, thiserror::Error)]
435pub enum MetricPluginError {
436    #[error("Metric plugin {plugin:?} returned a Finding with an empty id")]
437    EmptyFindingId { plugin: String },
438    #[error(
439        "Metric plugin {plugin:?} returned an invalid {field} {value}; it must be finite and non-negative"
440    )]
441    InvalidNumber {
442        plugin: String,
443        field: &'static str,
444        value: f64,
445    },
446    #[error("Metric plugin {plugin:?} returned a Finding with line 0; lines start at 1")]
447    InvalidFindingLine { plugin: String },
448    #[error("Metric plugin {plugin:?} failed during measure: {reason}")]
449    Call { plugin: String, reason: String },
450    #[error("Metric plugin {plugin:?} returned a Finding with an invalid path {path:?}")]
451    InvalidFindingPath { plugin: String, path: String },
452    #[error("Metric plugin {plugin:?} exceeded its memory cap of {memory_mb} MiB")]
453    MemoryLimitExceeded { plugin: String, memory_mb: u64 },
454    #[error("Metric plugin {plugin:?} exceeded its time limit of {timeout_ms} ms")]
455    TimeLimitExceeded { plugin: String, timeout_ms: u64 },
456    #[error(
457        "Metric plugin {plugin:?} returned an invalid ratio {ratio}; it must be finite and between 0 and 1"
458    )]
459    InvalidRatio { plugin: String, ratio: f64 },
460}
461
462pub trait MetricPlugin: Sync {
463    fn key(&self) -> &str;
464
465    fn name(&self) -> &str;
466
467    fn description(&self) -> &str;
468
469    fn version(&self) -> u32;
470
471    fn measure(&self, model: &CodeModel) -> Result<ExternalMetricMeasurement, MetricPluginError>;
472}