Skip to main content

miden_node_tracing/
targets.rs

1/// Declares a crate's default tracing target and module-specific overrides.
2///
3/// Invoke once at the crate root before child module declarations. Configuration expressions
4/// retain the caller's scope, and the generated helper resolves targets at compile time and
5/// registers the map for [`declared_targets`]. Test builds collect callsites through the tracing
6/// crate's inventory and check that every rule is used for the enabled features.
7#[macro_export]
8#[expect(
9    clippy::crate_in_macro_def,
10    reason = "The generated helper refers to the registry in the caller's crate."
11)]
12macro_rules! declare_targets {
13    (default: $default:expr, $($(#[$attr:meta])* $module:literal => $target:expr),* $(,)?) => {
14        // Evaluate configuration alongside the declaration so caller names and macros keep scope.
15        #[doc(hidden)]
16        const __MIDEN_TRACING_TARGETS: $crate::TargetMap = $crate::TargetMap::new(
17            $default,
18            &[$($(#[$attr])* ($module, $target)),*],
19        );
20
21        #[doc(hidden)]
22        mod __miden_tracing_targets {
23            use super::__MIDEN_TRACING_TARGETS as TARGETS;
24
25            $crate::__private::inventory::submit! {
26                $crate::__private::DeclaredTargetMap(&TARGETS)
27            }
28
29            #[cfg(test)]
30            pub(super) struct Callsite {
31                pub(super) module: &'static str,
32            }
33
34            #[cfg(test)]
35            $crate::__private::inventory::collect!(Callsite);
36
37            #[test]
38            fn every_target_rule_has_a_compiled_callsite() {
39                for (index, (module, _)) in TARGETS.rules().iter().enumerate() {
40                    assert!(
41                        $crate::__private::inventory::iter::<Callsite>
42                            .into_iter()
43                            .any(|callsite| TARGETS.matching_rule(callsite.module) == Some(index)),
44                        "tracing target rule {} has no compiled callsites",
45                        module,
46                    );
47                }
48            }
49        }
50
51        macro_rules! tracing_target {
52            () => {{
53                // Inventory internals otherwise trigger unsafe_derive_deserialize on methods.
54                #[cfg(all(test, not(clippy)))]
55                $crate::__private::inventory::submit! {
56                    crate::__miden_tracing_targets::Callsite { module: module_path!() }
57                }
58
59                crate::__MIDEN_TRACING_TARGETS.resolve(module_path!())
60            }};
61        }
62    };
63}
64
65/// A target map registered by a linked crate's declaration.
66#[doc(hidden)]
67pub struct DeclaredTargetMap(pub &'static TargetMap);
68
69inventory::collect!(DeclaredTargetMap);
70
71/// Returns the sorted, unique default and override targets declared by linked crates.
72///
73/// Targets are available without executing instrumented code or enabling tracing output. Only
74/// declarations enabled for this build are included; explicit callsite overrides and targets
75/// from other instrumentation are included only if they also appear in a declaration.
76pub fn declared_targets() -> Vec<&'static str> {
77    let mut targets = Vec::new();
78    for DeclaredTargetMap(map) in inventory::iter::<DeclaredTargetMap> {
79        targets.push(map.default);
80        targets.extend(map.rules.iter().map(|(_, target)| *target));
81    }
82    targets.sort_unstable();
83    targets.dedup();
84    targets
85}
86
87/// Maps Rust module subtrees to diagnostic tracing targets.
88///
89/// The longest matching module prefix wins, independently of rule order. Prefixes match whole
90/// module names, so a rule for `node::db` matches `node::db::queries` but not `node::db_backup`.
91pub struct TargetMap {
92    default: &'static str,
93    rules: &'static [(&'static str, &'static str)],
94}
95
96impl TargetMap {
97    /// Creates a target map with a fallback for modules outside the configured subtrees.
98    pub const fn new(
99        default: &'static str,
100        rules: &'static [(&'static str, &'static str)],
101    ) -> Self {
102        Self { default, rules }
103    }
104
105    /// Resolves the target at compile time for use in static tracing metadata.
106    pub const fn resolve(&self, module: &str) -> &'static str {
107        match self.matching_rule(module) {
108            Some(index) => self.rules[index].1,
109            None => self.default,
110        }
111    }
112
113    /// Returns the configured module prefixes and their diagnostic targets.
114    pub const fn rules(&self) -> &'static [(&'static str, &'static str)] {
115        self.rules
116    }
117
118    /// Returns the index of the most specific rule, or none when the fallback applies.
119    pub const fn matching_rule(&self, module: &str) -> Option<usize> {
120        let mut best = None;
121        let mut longest = 0;
122        let mut index = 0;
123        while index < self.rules.len() {
124            let prefix = self.rules[index].0;
125            if prefix.len() > longest && module_matches(module, prefix) {
126                best = Some(index);
127                longest = prefix.len();
128            }
129            index += 1;
130        }
131        best
132    }
133}
134
135const fn module_matches(module: &str, prefix: &str) -> bool {
136    let module = module.as_bytes();
137    let prefix = prefix.as_bytes();
138    if module.len() < prefix.len() {
139        return false;
140    }
141    let mut index = 0;
142    while index < prefix.len() {
143        if module[index] != prefix[index] {
144            return false;
145        }
146        index += 1;
147    }
148    module.len() == prefix.len()
149        || (module.len() > prefix.len() + 1
150            && module[prefix.len()] == b':'
151            && module[prefix.len() + 1] == b':')
152}
153
154#[cfg(test)]
155mod tests {
156    use super::TargetMap;
157
158    const TARGETS: TargetMap = TargetMap::new(
159        "miden::storage",
160        &[
161            ("node::db::backup", "miden::storage::files"),
162            ("node::db", "miden::storage::sqlite"),
163        ],
164    );
165
166    #[test]
167    fn module_subtrees_use_the_most_specific_target() {
168        const TARGET: &str = TARGETS.resolve("node::db::backup::writer");
169        assert_eq!(TARGET, "miden::storage::files");
170        assert_eq!(TARGETS.resolve("node::db"), "miden::storage::sqlite");
171        assert_eq!(TARGETS.resolve("node::db::queries"), "miden::storage::sqlite");
172    }
173
174    #[test]
175    fn unrelated_modules_use_the_default() {
176        for module in ["node", "node::db_backup", "node::database", "node::d", "other::db"] {
177            assert_eq!(TARGETS.resolve(module), "miden::storage");
178        }
179    }
180}