Skip to main content

architecture_tests/
lib.rs

1//! Architecture tests for the Saluki workspace.
2//!
3//! Unit tests in this crate report violations to intended architectural invariants.
4//!
5//! # Dependency guards
6//!
7//! Dependency guards reject unwanted direct or transitive dependencies between crates. [`graph::Workspace`] loads
8//! the package graph from Cargo metadata, including optional, feature-gated, and target-specific dependencies.
9//! Links join package IDs, so dependency renames don't hide them. Each guard chooses which dependency kinds to
10//! follow through [`graph::Links`]. Violations report the dependency route.
11//!
12//! # Symbol guards
13//!
14//! Symbol guards restrict which names code may mention, enforcing boundaries within a crate that dependency guards
15//! can't express. [`symbols::SourceTree`] parses every `.rs` file under selected directories, including test code.
16//! It matches names in paths, imports, and macro or attribute tokens, but ignores comments, doc text, and strings.
17//! Guards can also collect aliases with [`symbols::SourceTree::aliases`]. Matches report the source location;
18//! unreadable, invalid, or missing sources fail the scan.
19//!
20//! Module guards restrict which modules of a crate code may name. [`symbols::SourceTree::module_mentions`] matches
21//! only paths that start at `crate`, `self` or `super`, so a variable that shares a module's name doesn't match.
22//!
23//! # Limits
24//!
25//! Symbol guards don't resolve names. Unrelated items sharing a guarded identifier cause false positives.
26//! The guards can miss:
27//!
28//! - types inferred without a guarded identifier at the use site
29//! - aliases from private glob imports below crate-root scope or private bindings in other non-root files
30//! - aliases defined inside blocks or macro invocations
31//! - modules placed outside the scanned directories by `#[path]`
32//!
33//! Check for these gaps during review.
34#![deny(missing_docs)]
35
36pub mod graph;
37pub mod symbols;
38
39#[cfg(test)]
40mod tests {
41    use std::{
42        collections::BTreeSet,
43        path::{Path, PathBuf},
44    };
45
46    use guppy::graph::BuildTargetId;
47
48    use crate::{
49        graph::{direct_links_to_target_or_its_dependents, Dependencies, LinkKinds, Links, Workspace},
50        symbols::{Mention, SourceTree},
51    };
52
53    const MODEL: &str = "agent-data-plane-config";
54    const CONFIG_SYSTEM: &str = "agent-data-plane-config-system";
55    const DATADOG_CONFIG: &str = "datadog-agent-config";
56    const OVERLAY_MODEL: &str = "datadog-agent-config-overlay-model";
57    const CORPUS: &str = "datadog-agent-config-corpus";
58    const CONFIG_DOCS: &str = "datadog-agent-config-docs";
59    const BIN: &str = "agent-data-plane";
60
61    fn workspace() -> Workspace {
62        let manifest = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../Cargo.toml");
63        Workspace::load(&manifest).expect("load the workspace package graph")
64    }
65
66    #[track_caller]
67    fn assert_does_not_depend_on(from: &str, targets: &[&str]) {
68        let workspace = workspace();
69        let dependencies = Dependencies::new(workspace.member(from).unwrap(), Links::Built);
70        let routes: Vec<String> = targets
71            .iter()
72            .filter_map(|target| dependencies.route_to(&workspace.member(target).unwrap()))
73            .map(|route| route.to_string())
74            .collect();
75        assert!(
76            routes.is_empty(),
77            "`{from}` must not depend on {targets:?}:\n{}",
78            routes.join("\n")
79        );
80    }
81
82    #[track_caller]
83    fn assert_no_mentions(rule: &str, root: &Path, mentions: &[Mention]) {
84        let lines: Vec<String> = mentions
85            .iter()
86            .map(|mention| {
87                let path = mention.path.strip_prefix(root).unwrap_or(&mention.path);
88                Mention {
89                    path: path.to_path_buf(),
90                    ..mention.clone()
91                }
92                .to_string()
93            })
94            .collect();
95        assert!(lines.is_empty(), "{rule}:\n{}", lines.join("\n"));
96    }
97
98    /// The `panoramic` source directory and the names of its top-level modules, from `main.rs`.
99    fn panoramic() -> (PathBuf, BTreeSet<String>) {
100        let workspace = workspace();
101        let src = workspace
102            .member("panoramic")
103            .unwrap()
104            .manifest_path()
105            .parent()
106            .unwrap()
107            .as_std_path()
108            .join("src");
109        let main = syn::parse_file(&std::fs::read_to_string(src.join("main.rs")).unwrap()).unwrap();
110        let modules = main
111            .items
112            .iter()
113            .filter_map(|item| match item {
114                syn::Item::Mod(item) => Some(item.ident.to_string()),
115                _ => None,
116            })
117            .collect();
118        (src, modules)
119    }
120
121    #[track_caller]
122    fn assert_panoramic_module_names_none_of(module: &str, guarded: &BTreeSet<String>) {
123        let (src, modules) = panoramic();
124        assert!(modules.contains(module), "`panoramic` has no `{module}` module");
125        let tree = SourceTree::read(&[src.join(module)]).unwrap_or_else(|error| panic!("{error}"));
126        assert_no_mentions(
127            &format!("panoramic's `{module}` module must not name {guarded:?}"),
128            workspace().root(),
129            &tree.module_mentions(&src, guarded),
130        );
131    }
132
133    /// Adds to `out` each name `tree` binds from a module in `modules`.
134    fn bindings_from(
135        tree: &syn::UseTree, modules: &BTreeSet<String>, path: &mut Vec<String>, out: &mut BTreeSet<String>,
136    ) {
137        let from_module = |path: &[String]| {
138            path.iter()
139                .find(|segment| !matches!(segment.as_str(), "crate" | "self"))
140                .is_some_and(|segment| modules.contains(segment))
141        };
142        match tree {
143            syn::UseTree::Path(next) => {
144                path.push(next.ident.to_string());
145                bindings_from(&next.tree, modules, path, out);
146                path.pop();
147            }
148            syn::UseTree::Name(name) if from_module(path) => {
149                out.insert(name.ident.to_string());
150            }
151            syn::UseTree::Rename(rename) if from_module(path) => {
152                out.insert(rename.rename.to_string());
153            }
154            syn::UseTree::Group(group) => {
155                for tree in &group.items {
156                    bindings_from(tree, modules, path, out);
157                }
158            }
159            syn::UseTree::Name(_) | syn::UseTree::Rename(_) | syn::UseTree::Glob(_) => {}
160        }
161    }
162
163    /// Panoramic's core runs participants without knowing what they run or what steps check.
164    #[test]
165    fn panoramic_core_names_neither_participants_nor_steps() {
166        let guarded = BTreeSet::from(["participants".to_string(), "steps".to_string()]);
167        assert_panoramic_module_names_none_of("core", &guarded);
168    }
169
170    /// Participant types and steps meet only through the core.
171    #[test]
172    fn panoramic_participants_and_steps_do_not_name_each_other() {
173        assert_panoramic_module_names_none_of("participants", &BTreeSet::from(["steps".to_string()]));
174        assert_panoramic_module_names_none_of("steps", &BTreeSet::from(["participants".to_string()]));
175    }
176
177    /// The core, participant type and step modules name none of the binary's modules: the CLI, scheduling and
178    /// reports depend on them, and not the reverse.
179    #[test]
180    fn panoramic_core_participants_and_steps_name_no_binary_module() {
181        let isolated = ["core", "participants", "steps"];
182        let (src, modules) = panoramic();
183        let mut binary: BTreeSet<String> = modules
184            .into_iter()
185            .filter(|module| !isolated.contains(&module.as_str()))
186            .collect();
187        // The crate root's imports from binary modules are visible to every module below it as `crate::<name>`.
188        let main = syn::parse_file(&std::fs::read_to_string(src.join("main.rs")).unwrap()).unwrap();
189        let mut imported = BTreeSet::new();
190        for item in &main.items {
191            if let syn::Item::Use(item) = item {
192                bindings_from(&item.tree, &binary, &mut Vec::new(), &mut imported);
193            }
194        }
195        binary.extend(imported);
196        for module in isolated {
197            assert_panoramic_module_names_none_of(module, &binary);
198        }
199    }
200
201    /// Components take component-owned inputs; the binary adapts the shared model.
202    #[test]
203    fn saluki_components_does_not_depend_on_the_configuration_model() {
204        assert_does_not_depend_on("saluki-components", &[MODEL]);
205    }
206
207    /// Loading and translation belong outside runtime components.
208    #[test]
209    fn saluki_components_does_not_depend_on_the_configuration_system() {
210        assert_does_not_depend_on("saluki-components", &[CONFIG_SYSTEM]);
211    }
212
213    /// Components must not interpret source-specific configuration.
214    #[test]
215    fn saluki_components_does_not_depend_on_the_datadog_configuration_source() {
216        assert_does_not_depend_on("saluki-components", &[DATADOG_CONFIG]);
217    }
218
219    /// The configuration system produces data, not component instances.
220    #[test]
221    fn configuration_system_does_not_depend_on_saluki_components() {
222        assert_does_not_depend_on(CONFIG_SYSTEM, &["saluki-components"]);
223    }
224
225    /// Keep shared utilities independent of higher-level subsystems.
226    #[test]
227    fn saluki_common_depends_only_on_foundational_workspace_crates() {
228        let allowed = [
229            "saluki-antithesis",
230            "saluki-error",
231            "saluki-metrics",
232            "saluki-metrics-macros",
233            "stringtheory",
234        ];
235        let workspace = workspace();
236        let dependencies = Dependencies::new(workspace.member("saluki-common").unwrap(), Links::Built);
237        let mut routes: Vec<String> = dependencies
238            .workspace_members()
239            .filter(|package| !allowed.contains(&package.name()))
240            .filter_map(|package| dependencies.route_to(&package))
241            .map(|route| route.to_string())
242            .collect();
243        routes.sort();
244        assert!(
245            routes.is_empty(),
246            "`saluki-common` may depend only on {allowed:?} workspace crates:\n{}",
247            routes.join("\n")
248        );
249    }
250
251    /// The model is pure data, independent of other workspace crates.
252    #[test]
253    fn configuration_model_links_no_workspace_crate() {
254        let workspace = workspace();
255        let links: Vec<String> = workspace
256            .member(MODEL)
257            .unwrap()
258            .direct_links()
259            .filter(|link| link.to().in_workspace())
260            .map(|link| format!("{MODEL} -[{}]-> {}", LinkKinds(&link), link.to().name()))
261            .collect();
262        assert!(
263            links.is_empty(),
264            "`{MODEL}` must not link a workspace crate:\n{}",
265            links.join("\n")
266        );
267    }
268
269    /// Overlay metadata belongs to code generation and configuration validation, not runtime code.
270    /// Code generation build-depends on it, and the corpus tests check recordings against the support inventory.
271    #[test]
272    fn overlay_model_is_used_only_by_code_generation_and_configuration_tests() {
273        let build_dependents = [DATADOG_CONFIG, CONFIG_DOCS];
274        let dev_dependents = [CONFIG_SYSTEM, CORPUS];
275        let workspace = workspace();
276        let links: Vec<String> = workspace
277            .member(OVERLAY_MODEL)
278            .unwrap()
279            .reverse_direct_links()
280            .filter(|link| {
281                let from = link.from().name();
282                link.normal().is_present()
283                    || (link.build().is_present() && !build_dependents.contains(&from))
284                    || (link.dev().is_present() && !dev_dependents.contains(&from))
285            })
286            .map(|link| format!("{} -[{}]-> {OVERLAY_MODEL}", link.from().name(), LinkKinds(&link)))
287            .collect();
288        assert!(
289            links.is_empty(),
290            "`{OVERLAY_MODEL}` allows build links from {build_dependents:?} and dev links from {dev_dependents:?} \
291             only:\n{}",
292            links.join("\n")
293        );
294    }
295
296    /// The source model stays independent of workspace runtime code.
297    #[test]
298    fn datadog_configuration_source_depends_only_on_go_duration_through_normal_links() {
299        let workspace = workspace();
300        let dependencies = Dependencies::new(workspace.member(DATADOG_CONFIG).unwrap(), Links::Normal);
301        let mut routes: Vec<String> = dependencies
302            .workspace_members()
303            .filter(|package| package.name() != "go-duration")
304            .filter_map(|package| dependencies.route_to(&package))
305            .map(|route| route.to_string())
306            .collect();
307        routes.sort();
308        assert!(
309            routes.is_empty(),
310            "`{DATADOG_CONFIG}` may depend only on `go-duration` through normal links:\n{}",
311            routes.join("\n")
312        );
313    }
314
315    /// The binary needs the model for adapters, but its components must remain model-independent.
316    /// Check dependency names and aliases so renamed imports don't bypass this boundary.
317    #[test]
318    fn bin_components_name_neither_the_configuration_model_nor_crates_depending_on_it() {
319        let workspace = workspace();
320        let bin = workspace.member(BIN).unwrap();
321        let crates: BTreeSet<String> =
322            direct_links_to_target_or_its_dependents(&bin, &workspace.member(MODEL).unwrap())
323                .iter()
324                .map(|link| link.resolved_name().to_string())
325                .collect();
326        let bin_dir = bin.manifest_path().parent().unwrap().as_std_path();
327        let crate_root = bin
328            .build_target(&BuildTargetId::Binary(BIN))
329            .expect("binary target")
330            .path()
331            .as_std_path();
332
333        let aliases = SourceTree::read(&[bin_dir.join("src")])
334            .and_then(|tree| tree.aliases(crate_root, &crates))
335            .unwrap_or_else(|error| panic!("{error}"));
336        let names: BTreeSet<String> = crates.union(&aliases).cloned().collect();
337        let components = SourceTree::read(&[bin_dir.join("src/components")]).unwrap_or_else(|error| panic!("{error}"));
338
339        assert_no_mentions(
340            &format!("binary components must not name {crates:?} or their aliases {aliases:?}"),
341            workspace.root(),
342            &components.mentions(&names),
343        );
344    }
345
346    /// The binary uses typed configuration, not the raw-map library API.
347    /// Matching type names under any root catches re-exports and renamed imports.
348    #[test]
349    fn bin_names_no_raw_configuration_map_type() {
350        let workspace = workspace();
351        let bin_dir = workspace
352            .member(BIN)
353            .unwrap()
354            .manifest_path()
355            .parent()
356            .unwrap()
357            .as_std_path();
358        let dirs: Vec<PathBuf> = ["src", "tests"].iter().map(|dir| bin_dir.join(dir)).collect();
359        let names = BTreeSet::from(["GenericConfiguration".to_string(), "ConfigurationLoader".to_string()]);
360        let tree = SourceTree::read(&dirs).unwrap_or_else(|error| panic!("{error}"));
361
362        assert_no_mentions(
363            "the binary must not name the raw configuration map",
364            workspace.root(),
365            &tree.mentions(&names),
366        );
367    }
368}