Skip to main content

saluki_components/config/
metrics_endpoint_routing.rs

1//! Builds endpoint routing groups from exact-name and literal-prefix metric allow lists.
2
3use std::collections::{BTreeMap, HashMap};
4
5use saluki_error::{generic_error, GenericError};
6
7use crate::common::datadog::routing::{RoutingTargetCatalog, RoutingTargetSet};
8
9/// Sorts literal prefixes and removes duplicates and prefixes covered by another prefix.
10pub fn compact_metric_prefixes(prefixes: &mut Vec<String>) {
11    prefixes.sort_unstable();
12    if !prefixes.is_empty() {
13        let mut retained = 0;
14        for next in 1..prefixes.len() {
15            if !prefixes[next].starts_with(&prefixes[retained]) {
16                retained += 1;
17                prefixes.swap(retained, next);
18            }
19        }
20        prefixes.truncate(retained + 1);
21    }
22}
23
24/// A group of configured endpoints that share exact-name and prefix metric allowlists.
25#[derive(Clone, Debug, Eq, PartialEq)]
26pub struct EndpointAllowlistGroup {
27    /// Configured endpoint identities targeted by this policy.
28    pub endpoints: Vec<String>,
29
30    /// Exact metric names permitted to reach these endpoints.
31    pub metric_allowlist: Vec<String>,
32    /// Literal metric-name prefixes permitted to reach these endpoints.
33    pub metric_prefix_allowlist: Vec<String>,
34}
35
36impl EndpointAllowlistGroup {
37    /// Returns the routing targets that receive this group's filtered metric stream.
38    ///
39    /// Every API key configured for one of the group's endpoints is a target.
40    pub fn targets(&self, catalog: &RoutingTargetCatalog) -> RoutingTargetSet {
41        catalog.select(|target| {
42            self.endpoints
43                .iter()
44                .any(|endpoint| endpoint == target.configured_endpoint())
45        })
46    }
47}
48
49/// Endpoint-aware selective metric-routing configuration.
50#[derive(Debug, Eq, PartialEq)]
51pub struct MetricsEndpointRoutingConfiguration {
52    selected_endpoints: Vec<String>,
53    policy_groups: Vec<EndpointAllowlistGroup>,
54}
55
56impl MetricsEndpointRoutingConfiguration {
57    /// Resolves endpoint policies against the primary endpoint and the configured additional endpoints.
58    ///
59    /// An empty policy map preserves ordinary endpoint routing. Every policy key must exactly match a key in
60    /// `additional_endpoints` or `primary_endpoint`; this prevents a typo from silently leaving an intended
61    /// capacity-saving destination on the unfiltered path. Equivalent allow lists are grouped so they can share one
62    /// filtered encoder branch.
63    ///
64    /// # Errors
65    ///
66    /// Returns an error if a policy names neither the primary endpoint nor an endpoint configured in
67    /// `additional_endpoints`.
68    pub fn new(
69        metric_allowlists: &HashMap<String, Vec<String>>, metric_prefix_allowlists: &HashMap<String, Vec<String>>,
70        primary_endpoint: &str, additional_endpoints: &HashMap<String, Vec<String>>,
71    ) -> Result<Self, GenericError> {
72        let mut selected_endpoints = metric_allowlists
73            .keys()
74            .chain(metric_prefix_allowlists.keys())
75            .cloned()
76            .collect::<Vec<_>>();
77        selected_endpoints.sort_unstable();
78        selected_endpoints.dedup();
79        let mut grouped_endpoints = BTreeMap::<(Vec<String>, Vec<String>), Vec<String>>::new();
80        for endpoint in &selected_endpoints {
81            if endpoint != primary_endpoint && !additional_endpoints.contains_key(endpoint) {
82                return Err(generic_error!(
83                    "Experimental metrics endpoint-routing policy endpoint '{}' does not match the configured primary \
84                     endpoint and is not present in `additional_endpoints`; correct the endpoint, add it and its API \
85                     key to `additional_endpoints`, or remove it from \
86                     `experimental.metrics_endpoint_routing.metric_allowlist` and \
87                     `experimental.metrics_endpoint_routing.metric_prefix_allowlist`.",
88                    endpoint
89                ));
90            }
91
92            let mut canonical_allowlist = metric_allowlists.get(endpoint).cloned().unwrap_or_default();
93            canonical_allowlist.sort_unstable();
94            canonical_allowlist.dedup();
95            let mut canonical_prefixes = metric_prefix_allowlists.get(endpoint).cloned().unwrap_or_default();
96            compact_metric_prefixes(&mut canonical_prefixes);
97            // Exact names covered by a prefix do not change the policy's matching behavior.
98            canonical_allowlist.retain(|name| {
99                let index = canonical_prefixes.partition_point(|prefix| prefix <= name);
100                index == 0 || !name.starts_with(&canonical_prefixes[index - 1])
101            });
102            if !canonical_allowlist.is_empty() || !canonical_prefixes.is_empty() {
103                grouped_endpoints
104                    .entry((canonical_allowlist, canonical_prefixes))
105                    .or_default()
106                    .push(endpoint.clone());
107            }
108        }
109
110        let policy_groups = grouped_endpoints
111            .into_iter()
112            .map(|((metric_allowlist, metric_prefix_allowlist), mut endpoints)| {
113                endpoints.sort_unstable();
114                EndpointAllowlistGroup {
115                    endpoints,
116                    metric_allowlist,
117                    metric_prefix_allowlist,
118                }
119            })
120            .collect();
121
122        Ok(Self {
123            selected_endpoints,
124            policy_groups,
125        })
126    }
127
128    /// Returns every configured endpoint removed from the ordinary unfiltered metric path.
129    pub fn selected_endpoints(&self) -> &[String] {
130        &self.selected_endpoints
131    }
132
133    /// Returns the routing targets that receive the unfiltered metric stream.
134    ///
135    /// These are the targets whose configured endpoint has no policy.
136    pub fn unfiltered_targets(&self, catalog: &RoutingTargetCatalog) -> RoutingTargetSet {
137        catalog.select(|target| {
138            self.selected_endpoints
139                .binary_search_by(|endpoint| endpoint.as_str().cmp(target.configured_endpoint()))
140                .is_err()
141        })
142    }
143
144    /// Returns the filtered routing groups that require an encoder branch.
145    ///
146    /// Selected endpoints with an empty allowlist are absent because they receive no metric payloads.
147    pub fn policy_groups(&self) -> &[EndpointAllowlistGroup] {
148        &self.policy_groups
149    }
150}
151
152#[cfg(test)]
153mod tests {
154    use std::collections::HashMap;
155
156    use super::*;
157
158    const PRIMARY: &str = "https://primary.example.com";
159
160    fn additional_endpoints() -> HashMap<String, Vec<String>> {
161        HashMap::from([
162            ("https://secondary-a.example.com".to_string(), vec!["key-a".to_string()]),
163            ("https://secondary-b.example.com".to_string(), vec!["key-b".to_string()]),
164            ("https://secondary-c.example.com".to_string(), vec!["key-c".to_string()]),
165        ])
166    }
167
168    fn routing(
169        metric_allowlists: &HashMap<String, Vec<String>>, metric_prefix_allowlists: &HashMap<String, Vec<String>>,
170    ) -> Result<MetricsEndpointRoutingConfiguration, GenericError> {
171        MetricsEndpointRoutingConfiguration::new(
172            metric_allowlists,
173            metric_prefix_allowlists,
174            PRIMARY,
175            &additional_endpoints(),
176        )
177    }
178
179    #[test]
180    fn empty_policy_map_preserves_the_ordinary_endpoint_path() {
181        let allowlists = HashMap::new();
182
183        let config = routing(&allowlists, &HashMap::new()).expect("empty routing should be valid");
184        assert!(config.selected_endpoints().is_empty());
185        assert!(config.policy_groups().is_empty());
186    }
187
188    #[test]
189    fn groups_equivalent_primary_and_additional_allowlists_and_keeps_empty_policies_selected() {
190        let allowlists = HashMap::from([
191            (
192                PRIMARY.to_string(),
193                vec!["metric.b".to_string(), "metric.a".to_string(), "metric.a".to_string()],
194            ),
195            (
196                "https://secondary-b.example.com".to_string(),
197                vec!["metric.a".to_string(), "metric.b".to_string()],
198            ),
199            ("https://secondary-c.example.com".to_string(), Vec::new()),
200        ]);
201
202        let config = routing(&allowlists, &HashMap::new()).expect("configured endpoints should resolve");
203        assert_eq!(
204            config.selected_endpoints(),
205            [
206                "https://primary.example.com",
207                "https://secondary-b.example.com",
208                "https://secondary-c.example.com"
209            ]
210        );
211        assert_eq!(
212            config.policy_groups(),
213            [EndpointAllowlistGroup {
214                endpoints: vec![
215                    "https://primary.example.com".to_string(),
216                    "https://secondary-b.example.com".to_string()
217                ],
218                metric_allowlist: vec!["metric.a".to_string(), "metric.b".to_string()],
219                metric_prefix_allowlist: vec![],
220            }]
221        );
222    }
223
224    #[test]
225    fn rejects_a_policy_that_does_not_name_a_configured_endpoint() {
226        let allowlists = HashMap::from([("https://typo.example.com".to_string(), vec!["metric.a".to_string()])]);
227
228        let error = routing(&allowlists, &HashMap::new()).expect_err("unknown endpoint should be rejected");
229        let message = error.to_string();
230        assert!(message.contains("https://typo.example.com"));
231        assert!(message.contains("primary endpoint"));
232        assert!(message.contains("additional_endpoints"));
233    }
234
235    #[test]
236    fn combines_policy_maps_and_groups_equivalent_name_and_prefix_lists() {
237        let names = HashMap::from([
238            (
239                PRIMARY.to_string(),
240                vec!["exact".to_string(), "a.covered".to_string(), "b.covered".to_string()],
241            ),
242            ("https://secondary-a.example.com".to_string(), vec!["exact".to_string()]),
243        ]);
244        let prefixes = HashMap::from([
245            (
246                PRIMARY.to_string(),
247                vec![
248                    "b.".to_string(),
249                    "a.".to_string(),
250                    "a.".to_string(),
251                    "a.nested.".to_string(),
252                ],
253            ),
254            (
255                "https://secondary-a.example.com".to_string(),
256                vec!["a.".to_string(), "b.".to_string()],
257            ),
258            ("https://secondary-b.example.com".to_string(), vec!["a.".to_string()]),
259            ("https://secondary-c.example.com".to_string(), vec![]),
260        ]);
261        let config = routing(&names, &prefixes).unwrap();
262        assert_eq!(config.selected_endpoints().len(), 4);
263        assert_eq!(config.policy_groups().len(), 2);
264        let combined = config
265            .policy_groups()
266            .iter()
267            .find(|p| !p.metric_allowlist.is_empty())
268            .unwrap();
269        assert_eq!(combined.endpoints, [PRIMARY, "https://secondary-a.example.com"]);
270        assert_eq!(combined.metric_allowlist, ["exact"]);
271        assert_eq!(combined.metric_prefix_allowlist, ["a.", "b."]);
272        let prefix_only = config
273            .policy_groups()
274            .iter()
275            .find(|p| p.metric_allowlist.is_empty())
276            .unwrap();
277        assert_eq!(prefix_only.endpoints, ["https://secondary-b.example.com"]);
278        assert_eq!(prefix_only.metric_prefix_allowlist, ["a."]);
279    }
280
281    #[test]
282    fn different_prefixes_do_not_share_an_encoder_group() {
283        let names = HashMap::from([
284            (PRIMARY.to_string(), vec!["exact".to_string()]),
285            ("https://secondary-a.example.com".to_string(), vec!["exact".to_string()]),
286        ]);
287        let prefixes = HashMap::from([(PRIMARY.to_string(), vec!["a.".to_string()])]);
288        let config = routing(&names, &prefixes).unwrap();
289        assert_eq!(config.policy_groups().len(), 2);
290    }
291
292    #[test]
293    fn policies_resolve_to_complementary_routing_targets() {
294        let catalog = RoutingTargetCatalog::new(PRIMARY, &additional_endpoints()).unwrap();
295        let allowlists = HashMap::from([
296            (PRIMARY.to_string(), vec!["metric.a".to_string()]),
297            (
298                "https://secondary-b.example.com".to_string(),
299                vec!["metric.a".to_string()],
300            ),
301            ("https://secondary-c.example.com".to_string(), vec![]),
302        ]);
303        let config = routing(&allowlists, &HashMap::new()).unwrap();
304
305        let configured = |targets: &RoutingTargetSet| {
306            targets
307                .iter()
308                .map(|id| catalog.get(id).unwrap().configured_endpoint().to_string())
309                .collect::<Vec<_>>()
310        };
311        // Only the endpoint without a policy keeps the unfiltered stream.
312        assert_eq!(
313            configured(&config.unfiltered_targets(&catalog)),
314            ["https://secondary-a.example.com"]
315        );
316        let [group] = config.policy_groups() else {
317            panic!("expected one policy group");
318        };
319        assert_eq!(
320            configured(&group.targets(&catalog)),
321            [PRIMARY, "https://secondary-b.example.com"]
322        );
323    }
324
325    #[test]
326    fn rejects_unknown_endpoints_in_prefix_map_including_empty_policies() {
327        for list in [vec![], vec!["metric.".to_string()]] {
328            let prefixes = HashMap::from([("https://typo.example.com".to_string(), list)]);
329            let error = routing(&HashMap::new(), &prefixes).unwrap_err();
330            assert!(error.to_string().contains("metric_prefix_allowlist"));
331        }
332    }
333}