archunit/common/extraction/
graph_cache.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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
use std::{
    collections::BTreeMap,
    sync::{OnceLock, RwLock},
};

use super::{
    CargoProject, DEFAULT_EXCLUDED_DIRECTORIES, GraphExtraction, SourceOptions,
    extract_graph::extract_graph_uncached,
};
use crate::common::{ArchUnitError, CheckLogger, CheckOptions, LogLevel, TechnicalError};

const CFG_POLICY: &str = "conservative-union";
const FEATURE_POLICY: &str = "cargo-metadata-declarations";
const IGNORE_SCOPE_POLICY: &str = "declaration-comments-v1";

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct GraphCacheKey {
    project: CargoProject,
    source_options: SourceOptions,
    excluded_directories: Vec<String>,
    cfg_policy: &'static str,
    feature_policy: &'static str,
    ignore_scope_policy: &'static str,
}

#[derive(Default)]
struct GraphCacheState {
    generation: u64,
    entries: BTreeMap<GraphCacheKey, GraphExtraction>,
}

static GRAPH_CACHE: OnceLock<RwLock<GraphCacheState>> = OnceLock::new();

fn graph_cache() -> &'static RwLock<GraphCacheState> {
    GRAPH_CACHE.get_or_init(|| RwLock::new(GraphCacheState::default()))
}

/// Builds the complete identity for inputs that can change graph extraction.
///
/// `CargoProject` includes canonical workspace and manifest paths, the target directory, workspace
/// members, target kinds/source roots, and Cargo dependency declarations. New extraction toggles
/// must be represented here before they are honored by the extractor.
fn build_graph_cache_key(project: &CargoProject, source_options: SourceOptions) -> GraphCacheKey {
    GraphCacheKey {
        project: project.clone(),
        source_options,
        excluded_directories: DEFAULT_EXCLUDED_DIRECTORIES
            .iter()
            .map(|directory| (*directory).to_owned())
            .collect(),
        cfg_policy: CFG_POLICY,
        feature_policy: FEATURE_POLICY,
        ignore_scope_policy: IGNORE_SCOPE_POLICY,
    }
}

/// Extracts or reuses the graph for one Cargo project and source configuration.
pub fn extract_graph(
    project: &CargoProject,
    source_options: SourceOptions,
) -> Result<GraphExtraction, ArchUnitError> {
    extract_graph_cached(project, source_options, false).map(|(extraction, _)| extraction)
}

/// Extracts a graph using the extraction-related settings from one architecture check.
///
/// [`CheckOptions::clears_cache`] empties the shared cache before extraction. Test, example, and
/// benchmark target selection is mapped from [`CheckOptions::includes_test_sources`].
pub fn extract_graph_with_options(
    project: &CargoProject,
    options: &CheckOptions,
) -> Result<GraphExtraction, ArchUnitError> {
    let source_options = SourceOptions::new().with_dev_targets(options.includes_test_sources());
    let logger = CheckLogger::new(options.logging());
    logger.validate()?;
    let (extraction, cached) =
        extract_graph_cached(project, source_options, options.clears_cache())?;
    if logger.is_enabled_for(LogLevel::Debug) {
        logger.log_progress(format!(
            "graph cache={}; clear requested={}; include test sources={}",
            if cached { "hit" } else { "miss" },
            options.clears_cache(),
            options.includes_test_sources(),
        ))?;
        logger.log_progress(format!(
            "extracted edges={}; diagnostics={}",
            extraction.graph().edges().len(),
            extraction.diagnostics().len()
        ))?;
        for edge in extraction.graph().edges() {
            if edge.is_self_edge() {
                logger.log_progress(format!("discovered file: {}", edge.source))?;
            } else {
                logger.log_progress(format!("dependency: {edge}"))?;
            }
        }
        for diagnostic in extraction.diagnostics() {
            logger.log_progress(format!("extraction diagnostic: {diagnostic:?}"))?;
        }
    }
    Ok(extraction)
}

/// Clears every memoized graph and its diagnostics in the current process.
pub fn clear_graph_cache() -> Result<(), ArchUnitError> {
    let mut cache = graph_cache()
        .write()
        .map_err(|_| cache_lock_error("clear"))?;
    cache.entries.clear();
    cache.generation = cache.generation.wrapping_add(1);
    Ok(())
}

fn extract_graph_cached(
    project: &CargoProject,
    source_options: SourceOptions,
    clear_before: bool,
) -> Result<(GraphExtraction, bool), ArchUnitError> {
    if clear_before {
        clear_graph_cache()?;
    }
    let key = build_graph_cache_key(project, source_options);
    let generation = {
        let cache = graph_cache().read().map_err(|_| cache_lock_error("read"))?;
        if let Some(extraction) = cache.entries.get(&key) {
            return Ok((extraction.clone(), true));
        }
        cache.generation
    };

    let extracted = extract_graph_uncached(project, source_options)?;
    let mut cache = graph_cache()
        .write()
        .map_err(|_| cache_lock_error("write"))?;
    if cache.generation != generation {
        return Ok((extracted, false));
    }
    Ok((cache.entries.entry(key).or_insert(extracted).clone(), false))
}

fn cache_lock_error(operation: &str) -> ArchUnitError {
    ArchUnitError::from(TechnicalError::new(format!(
        "could not {operation} the shared graph cache because its lock was poisoned"
    )))
}

#[cfg(test)]
mod tests {
    use super::{CFG_POLICY, build_graph_cache_key};
    use crate::common::{SourceOptions, locate_project};

    #[test]
    fn named_key_changes_with_source_options_and_captures_policy() {
        let project = locate_project().expect("this test runs inside a Cargo project");
        let production = build_graph_cache_key(&project, SourceOptions::new());
        let with_dev = build_graph_cache_key(&project, SourceOptions::new().with_dev_targets(true));

        assert_ne!(production, with_dev);
        assert_eq!(production.cfg_policy, CFG_POLICY);
        assert!(!production.excluded_directories.is_empty());
    }
}