Skip to main content

saluki_components/transforms/dogstatsd_mapper/
mod.rs

1use std::collections::HashMap;
2use std::num::NonZeroUsize;
3use std::sync::LazyLock;
4use std::time::Duration;
5
6use async_trait::async_trait;
7use regex::Regex;
8use saluki_core::cache::{Cache, CacheBuilder};
9use saluki_core::{
10    accounting::{MemoryBounds, MemoryBoundsBuilder},
11    components::{
12        transforms::{SynchronousTransform, SynchronousTransformBuilder},
13        BuildContext,
14    },
15    data_model::{
16        event::metric::{
17            context::{Context, ContextResolver, ContextResolverBuilder},
18            Metric,
19        },
20        tags::{SharedTagSet, TagSet},
21    },
22    topology::EventsBuffer,
23};
24use saluki_error::{generic_error, ErrorContext, GenericError};
25use stringtheory::MetaString;
26use tracing::warn;
27
28const MATCH_TYPE_WILDCARD: &str = "wildcard";
29const MATCH_TYPE_REGEX: &str = "regex";
30
31static ALLOWED_WILDCARD_MATCH_PATTERN: LazyLock<Regex> =
32    LazyLock::new(|| Regex::new(r"^[a-zA-Z0-9\-_*.]+$").expect("Invalid regex in ALLOWED_WILDCARD_MATCH_PATTERN"));
33
34/// DogStatsD mapper transform.
35pub struct DogStatsDMapperConfiguration {
36    /// Total size of the string interner used for contexts, in bytes.
37    context_string_interner_bytes: NonZeroUsize,
38
39    /// Maximum number of mapped results to cache.
40    ///
41    /// When set to `0`, the cache is disabled.
42    cache_size: usize,
43
44    /// Metric mapping profiles.
45    profiles: Vec<DogStatsDMapperProfile>,
46}
47
48/// A DogStatsD metric mapping profile.
49pub struct DogStatsDMapperProfile {
50    /// Profile name used in configuration errors.
51    pub name: String,
52
53    /// Metric-name prefix this profile applies to.
54    pub prefix: String,
55
56    /// Metric mappings evaluated for this profile.
57    pub mappings: Vec<DogStatsDMetricMapping>,
58}
59
60/// A metric-name mapping in a [`DogStatsDMapperProfile`].
61pub struct DogStatsDMetricMapping {
62    /// Pattern matched against the incoming metric name.
63    pub metric_match: String,
64
65    /// Pattern type: `wildcard`, `regex`, or empty for the default wildcard behavior.
66    pub match_type: String,
67
68    /// Metric name emitted after a match.
69    pub name: String,
70
71    /// Tags emitted after expanding capture groups.
72    pub tags: HashMap<String, String>,
73}
74
75impl DogStatsDMapperConfiguration {
76    /// Creates a DogStatsD mapper configuration.
77    pub fn new(
78        context_string_interner_bytes: NonZeroUsize, cache_size: usize, profiles: Vec<DogStatsDMapperProfile>,
79    ) -> Self {
80        Self {
81            context_string_interner_bytes,
82            cache_size,
83            profiles,
84        }
85    }
86
87    /// Validates the configured profiles and compiles their match patterns.
88    ///
89    /// This mirrors the Datadog Agent's `NewMetricMapper`, including its error messages:
90    /// <https://github.com/DataDog/datadog-agent/blob/e02f16838240688a60db91d6b99cd8fbecbd9750/comp/dogstatsd/mapper/mapper.go#L77-L118>
91    ///
92    /// # Errors
93    ///
94    /// Returns an error describing the first invalid profile or mapping.
95    fn compile_profiles(&self) -> Result<Vec<MappingProfile>, GenericError> {
96        let mut profiles = Vec::with_capacity(self.profiles.len());
97        for (profile_index, config_profile) in self.profiles.iter().enumerate() {
98            if config_profile.name.is_empty() {
99                return Err(generic_error!("missing profile name {}", profile_index));
100            }
101            if config_profile.prefix.is_empty() {
102                return Err(generic_error!("missing prefix for profile: {}", config_profile.name));
103            }
104
105            let mut profile = MappingProfile {
106                prefix: config_profile.prefix.clone(),
107                mappings: Vec::with_capacity(config_profile.mappings.len()),
108            };
109
110            for (mapping_index, mapping) in config_profile.mappings.iter().enumerate() {
111                let match_type = match mapping.match_type.as_str() {
112                    // Default to wildcard when not set.
113                    "" => MATCH_TYPE_WILDCARD,
114                    MATCH_TYPE_WILDCARD => MATCH_TYPE_WILDCARD,
115                    MATCH_TYPE_REGEX => MATCH_TYPE_REGEX,
116                    unknown => {
117                        return Err(generic_error!(
118                            "profile: {}, mapping num {}: invalid match type `{}`, expected `wildcard` or `regex`",
119                            config_profile.name,
120                            mapping_index,
121                            unknown,
122                        ))
123                    }
124                };
125                if mapping.name.is_empty() {
126                    return Err(generic_error!(
127                        "profile: {}, mapping num {}: name is required",
128                        config_profile.name,
129                        mapping_index
130                    ));
131                }
132                if mapping.metric_match.is_empty() {
133                    return Err(generic_error!(
134                        "profile: {}, mapping num {}: match is required",
135                        config_profile.name,
136                        mapping_index
137                    ));
138                }
139                let regex = build_regex(&mapping.metric_match, match_type)?;
140                profile.mappings.push(MetricMapping {
141                    name: mapping.name.clone(),
142                    tags: mapping.tags.clone(),
143                    regex,
144                });
145            }
146            profiles.push(profile);
147        }
148
149        Ok(profiles)
150    }
151
152    fn build_mapper(&self, context: BuildContext) -> Result<MetricMapper, GenericError> {
153        // Like the Datadog Agent, an invalid profile or mapping disables metric mapping entirely, rather than failing
154        // DogStatsD: metrics pass through unmapped, and the error is logged.
155        // https://github.com/DataDog/datadog-agent/blob/e02f16838240688a60db91d6b99cd8fbecbd9750/comp/dogstatsd/server/impl/server.go#L497-L507
156        let profiles = match self.compile_profiles() {
157            Ok(profiles) => profiles,
158            Err(e) => {
159                warn!("Could not create metric mapper: {}", e);
160                Vec::new()
161            }
162        };
163
164        let context_resolver =
165            ContextResolverBuilder::from_name(format!("{}/dsd_mapper/primary", context.component_id()))
166                .expect("resolver name is not empty")
167                .with_interner_capacity_bytes(self.context_string_interner_bytes)
168                .with_idle_context_expiration(Duration::from_secs(30))
169                .build();
170
171        let cache = match NonZeroUsize::new(self.cache_size) {
172            Some(capacity) => Some(
173                CacheBuilder::from_identifier(format!("{}/dsd_mapper/result_cache", context.component_id()))?
174                    .with_capacity(capacity)
175                    .build(),
176            ),
177            None => None,
178        };
179
180        Ok(MetricMapper {
181            context_resolver,
182            profiles,
183            cache,
184        })
185    }
186}
187
188/// Builds the regex for a mapping's match pattern.
189///
190/// This mirrors the Datadog Agent's `buildRegex`:
191/// <https://github.com/DataDog/datadog-agent/blob/e02f16838240688a60db91d6b99cd8fbecbd9750/comp/dogstatsd/mapper/mapper.go#L120-L136>
192fn build_regex(match_re: &str, match_type: &str) -> Result<Regex, GenericError> {
193    let mut pattern = match_re.to_owned();
194    if match_type == MATCH_TYPE_WILDCARD {
195        // Check it against the allowed wildcard pattern
196        if !ALLOWED_WILDCARD_MATCH_PATTERN.is_match(&pattern) {
197            return Err(generic_error!(
198                "invalid wildcard match pattern `{}`, it does not match allowed match regex `{}`",
199                pattern,
200                ALLOWED_WILDCARD_MATCH_PATTERN.as_str()
201            ));
202        }
203        if pattern.contains("**") {
204            return Err(generic_error!(
205                "invalid wildcard match pattern `{}`, it should not contain consecutive `*`",
206                pattern
207            ));
208        }
209        pattern = pattern.replace(".", "\\.");
210        pattern = pattern.replace("*", "([^.]*)");
211    }
212
213    let final_pattern = format!("^{}$", pattern);
214
215    Regex::new(&final_pattern).with_error_context(|| {
216        format!(
217            "Failed to compile regular expression `{}` for `{}` match type",
218            final_pattern, match_type
219        )
220    })
221}
222
223struct MappingProfile {
224    prefix: String,
225    mappings: Vec<MetricMapping>,
226}
227
228struct MetricMapping {
229    name: String,
230    tags: HashMap<String, String>,
231    regex: Regex,
232}
233
234#[derive(Clone)]
235struct CachedMapResult {
236    name: MetaString,
237    extra_tags: SharedTagSet,
238}
239
240struct MetricMapper {
241    profiles: Vec<MappingProfile>,
242    context_resolver: ContextResolver,
243    cache: Option<Cache<MetaString, Option<CachedMapResult>>>,
244}
245
246impl MetricMapper {
247    fn try_map(&mut self, context: &Context) -> Option<Context> {
248        // With no profiles, nothing can match. Skip the cache lookup, and the negative cache entry a miss would add, for
249        // every metric. This covers both the common case of no configured profiles and a mapper disabled by an invalid
250        // profile.
251        if self.profiles.is_empty() {
252            return None;
253        }
254
255        // TODO: We should really be able to immutably borrow both the incoming tag set and the cached extra tags and
256        // chain them together for our call into `resolve_with_origin_tags`, avoiding any allocations... but we need
257        // some supporting work on the `TagSet` side to make it possible.
258
259        let metric_name = context.name();
260        let tags = context.tags();
261        let origin_tags = context.origin_tags();
262        // TODO: If host-bearing remaps show measurable allocation overhead, preserve the context's underlying host
263        // representation through the resolver instead of rematerializing it from `&str`.
264        let host = context.host();
265
266        // See if we have a cached result for this metric name.
267        if let Some(cache) = &self.cache {
268            if let Some(cached) = cache.get(metric_name) {
269                return match cached {
270                    None => None,
271                    Some(result) => {
272                        let mut merged_tags = tags.clone();
273                        merged_tags.merge_shared(&result.extra_tags);
274
275                        self.context_resolver.resolve_with_optional_host_and_origin_tags(
276                            result.name.clone(),
277                            host,
278                            merged_tags,
279                            origin_tags.clone(),
280                        )
281                    }
282                };
283            }
284        }
285
286        // Slow path: iterate profiles and run regexes.
287        let mut new_name = String::new();
288        let mut expanded_tag_value = String::new();
289
290        for profile in &self.profiles {
291            if !metric_name.starts_with(&profile.prefix) && profile.prefix != "*" {
292                continue;
293            }
294
295            for mapping in &profile.mappings {
296                if let Some(captures) = mapping.regex.captures(metric_name) {
297                    new_name.clear();
298                    captures.expand(&mapping.name, &mut new_name);
299
300                    let mut extra_tags = TagSet::with_capacity(mapping.tags.len());
301                    for (tag_key, tag_value_expr) in &mapping.tags {
302                        expanded_tag_value.clear();
303                        expanded_tag_value.push_str(tag_key);
304                        expanded_tag_value.push(':');
305                        captures.expand(tag_value_expr, &mut expanded_tag_value);
306
307                        extra_tags.insert_tag(expanded_tag_value.as_str());
308                    }
309
310                    // Freeze the tags here so they can be shared / cached.
311                    let extra_tags = extra_tags.into_shared();
312
313                    let mut merged_tags = tags.clone();
314                    merged_tags.merge_shared(&extra_tags);
315
316                    let resolved = self.context_resolver.resolve_with_optional_host_and_origin_tags(
317                        new_name.as_str(),
318                        host,
319                        merged_tags,
320                        origin_tags.clone(),
321                    )?;
322
323                    if let Some(cache) = &self.cache {
324                        cache.insert(
325                            metric_name.clone(),
326                            Some(CachedMapResult {
327                                name: resolved.name().clone(),
328                                extra_tags,
329                            }),
330                        );
331                    }
332                    return Some(resolved);
333                }
334            }
335        }
336
337        // We also cache "negative" results -- no match for this metric in the configured profiles -- to save ourselves some work.
338        if let Some(cache) = &self.cache {
339            cache.insert(metric_name.clone(), None);
340        }
341        None
342    }
343
344    #[cfg(test)]
345    fn cache_len(&self) -> Option<usize> {
346        self.cache.as_ref().map(|c| c.len())
347    }
348
349    #[cfg(test)]
350    fn cache_contains(&self, metric_name: &str) -> bool {
351        self.cache
352            .as_ref()
353            .is_some_and(|c| c.get(&MetaString::from(metric_name)).is_some())
354    }
355}
356
357#[async_trait]
358impl SynchronousTransformBuilder for DogStatsDMapperConfiguration {
359    async fn build(&self, context: BuildContext) -> Result<Box<dyn SynchronousTransform + Send>, GenericError> {
360        let metric_mapper = self.build_mapper(context)?;
361        Ok(Box::new(DogStatsDMapper { metric_mapper }))
362    }
363}
364
365impl MemoryBounds for DogStatsDMapperConfiguration {
366    fn specify_bounds(&self, builder: &mut MemoryBoundsBuilder) {
367        let mut min = builder.minimum();
368        min
369            // Capture the size of the heap allocation when the component is built.
370            .with_single_value::<DogStatsDMapper>("component struct")
371            // We also allocate the backing storage for the string interner up front, which is used by our context
372            // resolver.
373            .with_fixed_amount("string interner", self.context_string_interner_bytes.get());
374
375        // Account for the per-name result cache when enabled.
376        if self.cache_size > 0 {
377            min.with_array::<(MetaString, Option<CachedMapResult>)>("mapper result cache", self.cache_size);
378        }
379    }
380}
381
382pub struct DogStatsDMapper {
383    metric_mapper: MetricMapper,
384}
385
386impl SynchronousTransform for DogStatsDMapper {
387    fn transform_buffer(&mut self, event_buffer: &mut EventsBuffer) {
388        for metric in event_buffer.events_mut::<Metric>() {
389            if let Some(new_context) = self.metric_mapper.try_map(metric.context()) {
390                *metric.context_mut() = new_context;
391            }
392        }
393    }
394}
395
396#[cfg(test)]
397mod tests {
398
399    use std::collections::HashMap;
400    use std::num::NonZeroUsize;
401
402    use saluki_core::{
403        components::{transforms::SynchronousTransform, BuildContext},
404        data_model::event::{
405            metric::{
406                context::{Context, ContextResolverBuilder},
407                Metric,
408            },
409            Event,
410        },
411        topology::EventsBuffer,
412    };
413    use saluki_error::GenericError;
414
415    use super::{
416        DogStatsDMapper, DogStatsDMapperConfiguration, DogStatsDMapperProfile, DogStatsDMetricMapping, MetricMapper,
417    };
418
419    macro_rules! metric_mapping {
420        (@match_type) => {
421            String::new()
422        };
423        (@match_type $match_type:expr) => {
424            $match_type.to_string()
425        };
426        ({
427            "match": $metric_match:expr,
428            $("match_type": $match_type:expr,)?
429            "name": $name:expr
430            $(, "tags": { $($tag_name:literal: $tag_value:expr),* $(,)? })?
431        }) => {
432            DogStatsDMetricMapping {
433                metric_match: $metric_match.to_string(),
434                match_type: metric_mapping!(@match_type $($match_type)?),
435                name: $name.to_string(),
436                tags: HashMap::from([$($(($tag_name.to_string(), $tag_value.to_string())),*)?]),
437            }
438        };
439    }
440
441    macro_rules! mapper_profiles {
442        ([$({
443            "name": $name:expr,
444            "prefix": $prefix:expr,
445            "mappings": [$($mapping:tt),* $(,)?]
446        }),* $(,)?]) => {
447            vec![$(DogStatsDMapperProfile {
448                name: $name.to_string(),
449                prefix: $prefix.to_string(),
450                mappings: vec![$(metric_mapping!($mapping)),*],
451            }),*]
452        };
453    }
454
455    fn counter_metric(name: &'static str, tags: &[&'static str]) -> Metric {
456        let context = Context::from_static_parts(name, tags);
457        Metric::counter(context, 1.0)
458    }
459
460    fn mapper(profiles: Vec<DogStatsDMapperProfile>) -> Result<MetricMapper, GenericError> {
461        mapper_with_cache(profiles, 1000)
462    }
463
464    fn mapper_with_cache(
465        profiles: Vec<DogStatsDMapperProfile>, cache_size: usize,
466    ) -> Result<MetricMapper, GenericError> {
467        let config =
468            DogStatsDMapperConfiguration::new(NonZeroUsize::new(64 * 1024).expect("not zero"), cache_size, profiles);
469        config.build_mapper(BuildContext::test_transform("test_mapper"))
470    }
471
472    fn assert_tags(context: &Context, expected_tags: &[&str]) {
473        for tag in expected_tags {
474            assert!(context.tags().has_tag(tag), "missing tag: {}", tag);
475        }
476        assert_eq!(context.tags().len(), expected_tags.len(), "unexpected number of tags");
477    }
478
479    #[track_caller]
480    fn assert_tags_for_case(context: &Context, expected_tags: &[&str], case: &str, input: &str) {
481        for tag in expected_tags {
482            assert!(
483                context.tags().has_tag(tag),
484                "[{case}] input {input:?}: missing tag {tag:?}"
485            );
486        }
487        assert_eq!(
488            context.tags().len(),
489            expected_tags.len(),
490            "[{case}] input {input:?}: unexpected number of tags"
491        );
492    }
493
494    fn simple_mapping_profile() -> Vec<DogStatsDMapperProfile> {
495        mapper_profiles!([{
496            "name": "test",
497            "prefix": "test.",
498            "mappings": [
499                {
500                    "match": "test.job.duration.*.*",
501                    "name": "test.job.duration",
502                    "tags": {
503                        "job_type": "$1",
504                        "job_name": "$2"
505                    }
506                }
507            ]
508        }])
509    }
510
511    #[tokio::test]
512    async fn config_driven_mappings_produce_expected_output() {
513        // Each case builds one mapper from `config`, then checks a series of inputs against it. A check is
514        // `(input_name, input_tags, expected)`, where `expected` is `Some((mapped_name, mapped_tags))` when the metric
515        // should be remapped, or `None` when it must pass through unmapped.
516        struct MapperCase {
517            description: &'static str,
518            config: Vec<DogStatsDMapperProfile>,
519            #[allow(clippy::type_complexity)]
520            checks: Vec<(
521                &'static str,
522                &'static [&'static str],
523                Option<(&'static str, &'static [&'static str])>,
524            )>,
525        }
526
527        let cases = vec![
528            MapperCase {
529                description: "wildcard mappings with capture-group tags",
530                config: mapper_profiles!([{
531                    "name": "test",
532                    "prefix": "test.",
533                    "mappings": [
534                        { "match": "test.job.duration.*.*", "name": "test.job.duration", "tags": { "job_type": "$1", "job_name": "$2" } },
535                        { "match": "test.job.size.*.*", "name": "test.job.size", "tags": { "foo": "$1", "bar": "$2" } }
536                    ]
537                }]),
538                checks: vec![
539                    (
540                        "test.job.duration.my_job_type.my_job_name",
541                        &[],
542                        Some(("test.job.duration", &["job_type:my_job_type", "job_name:my_job_name"])),
543                    ),
544                    (
545                        "test.job.size.my_job_type.my_job_name",
546                        &[],
547                        Some(("test.job.size", &["foo:my_job_type", "bar:my_job_name"])),
548                    ),
549                    ("test.job.size.not_match", &[], None),
550                ],
551            },
552            MapperCase {
553                description: "partial mapping, second mapping has no tags",
554                config: mapper_profiles!([{
555                    "name": "test",
556                    "prefix": "test.",
557                    "mappings": [
558                        { "match": "test.job.duration.*.*", "name": "test.job.duration", "tags": { "job_type": "$1" } },
559                        { "match": "test.task.duration.*.*", "name": "test.task.duration" }
560                    ]
561                }]),
562                checks: vec![
563                    (
564                        "test.job.duration.my_job_type.my_job_name",
565                        &[],
566                        Some(("test.job.duration", &["job_type:my_job_type"])),
567                    ),
568                    (
569                        "test.task.duration.my_job_type.my_job_name",
570                        &[],
571                        Some(("test.task.duration", &[])),
572                    ),
573                ],
574            },
575            MapperCase {
576                description: "regex expansion with ${n} syntax",
577                config: mapper_profiles!([{
578                    "name": "test",
579                    "prefix": "test.",
580                    "mappings": [
581                        { "match": "test.job.duration.*.*", "name": "test.job.duration", "tags": { "job_type": "${1}_x", "job_name": "${2}_y" } }
582                    ]
583                }]),
584                checks: vec![(
585                    "test.job.duration.my_job_type.my_job_name",
586                    &[],
587                    Some((
588                        "test.job.duration",
589                        &["job_type:my_job_type_x", "job_name:my_job_name_y"],
590                    )),
591                )],
592            },
593            MapperCase {
594                description: "capture groups expanded into the metric name",
595                config: mapper_profiles!([{
596                    "name": "test",
597                    "prefix": "test.",
598                    "mappings": [
599                        { "match": "test.job.duration.*.*", "name": "test.hello.$2.$1", "tags": { "job_type": "$1", "job_name": "$2" } }
600                    ]
601                }]),
602                checks: vec![(
603                    "test.job.duration.my_job_type.my_job_name",
604                    &[],
605                    Some((
606                        "test.hello.my_job_name.my_job_type",
607                        &["job_type:my_job_type", "job_name:my_job_name"],
608                    )),
609                )],
610            },
611            MapperCase {
612                description: "wildcard matches a segment before an underscore",
613                config: mapper_profiles!([{
614                    "name": "test",
615                    "prefix": "test.",
616                    "mappings": [
617                        { "match": "test.*_start", "name": "test.start", "tags": { "job": "$1" } }
618                    ]
619                }]),
620                checks: vec![("test.my_job_start", &[], Some(("test.start", &["job:my_job"])))],
621            },
622            MapperCase {
623                description: "mappings without any tags",
624                config: mapper_profiles!([{
625                    "name": "test",
626                    "prefix": "test.",
627                    "mappings": [
628                        { "match": "test.my-worker.start", "name": "test.worker.start" },
629                        { "match": "test.my-worker.stop.*", "name": "test.worker.stop" }
630                    ]
631                }]),
632                checks: vec![
633                    ("test.my-worker.start", &[], Some(("test.worker.start", &[]))),
634                    ("test.my-worker.stop.worker-name", &[], Some(("test.worker.stop", &[]))),
635                ],
636            },
637            MapperCase {
638                description: "all allowed wildcard characters",
639                config: mapper_profiles!([{
640                    "name": "test",
641                    "prefix": "test.",
642                    "mappings": [
643                        { "match": "test.abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ-01234567.*", "name": "test.alphabet" }
644                    ]
645                }]),
646                checks: vec![(
647                    "test.abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ-01234567.123",
648                    &[],
649                    Some(("test.alphabet", &[])),
650                )],
651            },
652            MapperCase {
653                description: "regex match type",
654                config: mapper_profiles!([{
655                    "name": "test",
656                    "prefix": "test.",
657                    "mappings": [
658                        { "match": "test\\.job\\.duration\\.(.*)", "match_type": "regex", "name": "test.job.duration", "tags": { "job_name": "$1" } },
659                        { "match": "test\\.task\\.duration\\.(.*)", "match_type": "regex", "name": "test.task.duration", "tags": { "task_name": "$1" } }
660                    ]
661                }]),
662                checks: vec![
663                    (
664                        "test.job.duration.my.funky.job$name-abc/123",
665                        &[],
666                        Some(("test.job.duration", &["job_name:my.funky.job$name-abc/123"])),
667                    ),
668                    (
669                        "test.task.duration.MY_task_name",
670                        &[],
671                        Some(("test.task.duration", &["task_name:MY_task_name"])),
672                    ),
673                ],
674            },
675            MapperCase {
676                description: "complex regex match type",
677                config: mapper_profiles!([{
678                    "name": "test",
679                    "prefix": "test.",
680                    "mappings": [
681                        { "match": "test\\.job\\.([a-z][0-9]-\\w+)\\.(.*)", "match_type": "regex", "name": "test.job", "tags": { "job_type": "$1", "job_name": "$2" } }
682                    ]
683                }]),
684                checks: vec![
685                    (
686                        "test.job.a5-foo.bar",
687                        &[],
688                        Some(("test.job", &["job_type:a5-foo", "job_name:bar"])),
689                    ),
690                    ("test.job.foo.bar-not-match", &[], None),
691                ],
692            },
693            MapperCase {
694                description: "multiple profiles matched by prefix",
695                config: mapper_profiles!([
696                    {
697                        "name": "test",
698                        "prefix": "foo.",
699                        "mappings": [ { "match": "foo.duration.*", "name": "foo.duration", "tags": { "name": "$1" } } ]
700                    },
701                    {
702                        "name": "test",
703                        "prefix": "bar.",
704                        "mappings": [
705                            { "match": "bar.count.*", "name": "bar.count", "tags": { "name": "$1" } },
706                            { "match": "foo.duration2.*", "name": "foo.duration2", "tags": { "name": "$1" } }
707                        ]
708                    }
709                ]),
710                checks: vec![
711                    (
712                        "foo.duration.foo_name1",
713                        &[],
714                        Some(("foo.duration", &["name:foo_name1"])),
715                    ),
716                    // `foo.duration2` only exists under the `bar.` prefix, so it can't be reached by a `foo.` metric.
717                    ("foo.duration2.foo_name1", &[], None),
718                    ("bar.count.bar_name1", &[], Some(("bar.count", &["name:bar_name1"]))),
719                    ("z.not.mapped", &[], None),
720                ],
721            },
722            MapperCase {
723                description: "wildcard prefix matches any metric",
724                config: mapper_profiles!([{
725                    "name": "test",
726                    "prefix": "*",
727                    "mappings": [ { "match": "foo.duration.*", "name": "foo.duration", "tags": { "name": "$1" } } ]
728                }]),
729                checks: vec![(
730                    "foo.duration.foo_name1",
731                    &[],
732                    Some(("foo.duration", &["name:foo_name1"])),
733                )],
734            },
735            MapperCase {
736                description: "only the first matching wildcard-prefixed profile applies",
737                config: mapper_profiles!([
738                    {
739                        "name": "test",
740                        "prefix": "*",
741                        "mappings": [ { "match": "foo.duration.*", "name": "foo.duration", "tags": { "name1": "$1" } } ]
742                    },
743                    {
744                        "name": "test",
745                        "prefix": "*",
746                        "mappings": [ { "match": "foo.duration.*", "name": "foo.duration", "tags": { "name2": "$1" } } ]
747                    }
748                ]),
749                // The single expected tag (and exact tag count) proves the second profile's `name2` tag was not applied.
750                checks: vec![(
751                    "foo.duration.foo_name",
752                    &[],
753                    Some(("foo.duration", &["name1:foo_name"])),
754                )],
755            },
756            MapperCase {
757                description: "only the first matching profile applies across differing prefixes",
758                config: mapper_profiles!([
759                    {
760                        "name": "test",
761                        "prefix": "foo.",
762                        "mappings": [ { "match": "foo.*.duration.*", "name": "foo.bar1.duration", "tags": { "bar": "$1", "foo": "$2" } } ]
763                    },
764                    {
765                        "name": "test",
766                        "prefix": "foo.bar.",
767                        "mappings": [ { "match": "foo.bar.duration.*", "name": "foo.bar2.duration", "tags": { "foo_bar": "$1" } } ]
768                    }
769                ]),
770                // The exact tag count proves the second profile's `foo_bar` tag was not applied.
771                checks: vec![(
772                    "foo.bar.duration.foo_name",
773                    &[],
774                    Some(("foo.bar1.duration", &["bar:bar", "foo:foo_name"])),
775                )],
776            },
777            MapperCase {
778                description: "regex expansion with (\\w+) groups",
779                config: mapper_profiles!([{
780                    "name": "test",
781                    "prefix": "test.",
782                    "mappings": [
783                        { "match": "test.user.(\\w+).action.(\\w+)", "match_type": "regex", "name": "test.user.action", "tags": { "user": "$1", "action": "$2" } }
784                    ]
785                }]),
786                checks: vec![(
787                    "test.user.john_doe.action.login",
788                    &[],
789                    Some(("test.user.action", &["user:john_doe", "action:login"])),
790                )],
791            },
792            MapperCase {
793                description: "existing metric tags are retained alongside mapped tags",
794                config: mapper_profiles!([{
795                    "name": "test",
796                    "prefix": "test.",
797                    "mappings": [
798                        { "match": "test.job.duration.*.*", "name": "test.job.duration.$2", "tags": { "job_type": "$1", "job_name": "$2" } }
799                    ]
800                }]),
801                checks: vec![(
802                    "test.job.duration.abc.def",
803                    &["foo:bar", "baz"],
804                    Some((
805                        "test.job.duration.def",
806                        &["foo:bar", "baz", "job_type:abc", "job_name:def"],
807                    )),
808                )],
809            },
810        ];
811
812        for case in cases {
813            let mut mapper = mapper(case.config)
814                .unwrap_or_else(|e| panic!("[{}] config should parse and build: {e}", case.description));
815
816            for (input_name, input_tags, expected) in case.checks {
817                let metric = counter_metric(input_name, input_tags);
818                match (mapper.try_map(metric.context()), expected) {
819                    (Some(context), Some((expected_name, expected_tags))) => {
820                        assert_eq!(
821                            context.name(),
822                            expected_name,
823                            "[{}] wrong mapped name for input {input_name:?}",
824                            case.description
825                        );
826                        assert_tags_for_case(&context, expected_tags, case.description, input_name);
827                    }
828                    (None, None) => {}
829                    (mapped, expected) => panic!(
830                        "[{}] input {input_name:?}: expected remap={}, got remap={}",
831                        case.description,
832                        expected.is_some(),
833                        mapped.is_some()
834                    ),
835                }
836            }
837        }
838    }
839
840    #[test]
841    fn invalid_mapper_configurations_are_rejected() {
842        // Each case is `(description, config, expected_error_substring)`. Empty required values reach the
843        // component's validation; missing fields are rejected at the configuration boundary.
844        let cases: Vec<(&str, Vec<DogStatsDMapperProfile>, &str)> = vec![
845            // Custom (present-but-empty) validation branches.
846            (
847                "profile with an empty name",
848                mapper_profiles!([{ "name": "", "prefix": "test.", "mappings": [] }]),
849                "missing profile name",
850            ),
851            (
852                "profile with an empty prefix",
853                mapper_profiles!([{ "name": "test", "prefix": "", "mappings": [] }]),
854                "missing prefix for profile: test",
855            ),
856            (
857                "mapping with an empty match",
858                mapper_profiles!([{ "name": "test", "prefix": "test.", "mappings": [{ "match": "", "name": "test.mapped" }] }]),
859                "match is required",
860            ),
861            (
862                "mapping with an empty name",
863                mapper_profiles!([{ "name": "test", "prefix": "test.", "mappings": [{ "match": "test.job.duration.*.*", "name": "", "tags": { "job_type": "$1" } }] }]),
864                "name is required",
865            ),
866            (
867                "second mapping with an empty name",
868                mapper_profiles!([{
869                    "name": "test",
870                    "prefix": "test.",
871                    "mappings": [
872                        { "match": "test.valid", "name": "mapped" },
873                        { "match": "test.invalid", "name": "" }
874                    ]
875                }]),
876                "mapping num 1: name is required",
877            ),
878            // Match compilation / type validation.
879            (
880                "wildcard match with disallowed characters",
881                mapper_profiles!([{ "name": "test", "prefix": "test.", "mappings": [{ "match": "test.[]duration.*.*", "name": "test.job.duration" }] }]),
882                "does not match allowed match regex",
883            ),
884            (
885                "wildcard match anchored with a caret",
886                mapper_profiles!([{ "name": "test", "prefix": "test.", "mappings": [{ "match": "^test.invalid.duration.*.*", "name": "test.job.duration" }] }]),
887                "does not match allowed match regex",
888            ),
889            (
890                "wildcard match with consecutive wildcards",
891                mapper_profiles!([{ "name": "test", "prefix": "test.", "mappings": [{ "match": "test.invalid.duration.**", "name": "test.job.duration" }] }]),
892                "consecutive",
893            ),
894            (
895                "unknown match type",
896                mapper_profiles!([{ "name": "test", "prefix": "test.", "mappings": [{ "match": "test.invalid.duration", "match_type": "invalid", "name": "test.job.duration" }] }]),
897                "invalid match type",
898            ),
899        ];
900
901        for (description, config, expected_substring) in cases {
902            let config =
903                DogStatsDMapperConfiguration::new(NonZeroUsize::new(64 * 1024).expect("not zero"), 1000, config);
904            let err = config
905                .compile_profiles()
906                .err()
907                .unwrap_or_else(|| panic!("[{description}] configuration should be rejected"));
908            let message = err.to_string();
909            assert!(
910                message.contains(expected_substring),
911                "[{description}] error {message:?} should contain {expected_substring:?}"
912            );
913        }
914    }
915
916    #[tokio::test]
917    async fn invalid_mapper_configuration_disables_mapping_instead_of_failing() {
918        // Like the Datadog Agent, one invalid mapping disables metric mapping entirely, rather than failing DogStatsD or
919        // applying only the valid mappings: here, the valid first mapping doesn't apply either.
920        let config = mapper_profiles!([{
921            "name": "test",
922            "prefix": "test.",
923            "mappings": [
924                { "match": "test.valid", "name": "mapped" },
925                { "match": "test.invalid.**", "name": "invalid" }
926            ]
927        }]);
928        let mut mapper = mapper(config).expect("an invalid mapping should not fail the mapper build");
929
930        let metric = counter_metric("test.valid", &[]);
931        assert!(mapper.try_map(metric.context()).is_none(), "no mapping should apply");
932    }
933
934    #[tokio::test]
935    async fn transform_buffer_remaps_matching_metrics_and_passes_others_through() {
936        // Drives the public `SynchronousTransform::transform_buffer` entry point (every other test exercises the
937        // internal `try_map`). Matching metrics are remapped in place; non-matching metrics pass through untouched.
938        let mut transform = DogStatsDMapper {
939            metric_mapper: mapper(simple_mapping_profile()).expect("config should parse and build"),
940        };
941
942        let mut events = EventsBuffer::default();
943        assert!(events
944            .try_push(Event::Metric(counter_metric("test.job.duration.my_type.my_name", &[])))
945            .is_none());
946        assert!(events
947            .try_push(Event::Metric(counter_metric("unrelated.metric", &["keep:me"])))
948            .is_none());
949
950        transform.transform_buffer(&mut events);
951
952        let metrics: Vec<Metric> = events.into_iter().filter_map(Event::try_into_metric).collect();
953        assert_eq!(metrics.len(), 2);
954
955        // The matching metric is remapped in place (order is preserved).
956        assert_eq!(metrics[0].context().name(), "test.job.duration");
957        assert_tags(metrics[0].context(), &["job_type:my_type", "job_name:my_name"]);
958
959        // The non-matching metric is left untouched.
960        assert_eq!(metrics[1].context().name(), "unrelated.metric");
961        assert_tags(metrics[1].context(), &["keep:me"]);
962    }
963
964    #[tokio::test]
965    async fn mapper_preserves_host_context_dimension() {
966        let profiles = mapper_profiles!([{
967          "name": "test",
968          "prefix": "test.",
969          "mappings": [
970            {
971              "match": "test.job.duration.*",
972              "name": "test.job.duration",
973              "tags": {
974                "job_name": "$1"
975              }
976            }
977          ]
978        }]);
979
980        let mut resolver = ContextResolverBuilder::for_tests().build();
981        let context_a = resolver
982            .resolve_with_host("test.job.duration.worker", "host-a", &[] as &[&str], None)
983            .expect("context should resolve");
984        let context_b = resolver
985            .resolve_with_host("test.job.duration.worker", "host-b", &[] as &[&str], None)
986            .expect("context should resolve");
987
988        let mut mapper = mapper(profiles).expect("should have built mapper");
989        let mapped_a = mapper.try_map(&context_a).expect("should have remapped");
990        let mapped_b = mapper.try_map(&context_b).expect("should have remapped");
991
992        assert_ne!(mapped_a, mapped_b);
993        assert_eq!(mapped_a.host(), Some("host-a"));
994        assert_eq!(mapped_b.host(), Some("host-b"));
995        assert_eq!(mapped_a.name(), "test.job.duration");
996        assert_tags(&mapped_a, &["job_name:worker"]);
997        assert_tags(&mapped_b, &["job_name:worker"]);
998    }
999
1000    #[tokio::test]
1001    async fn cache_hit_returns_same_result_as_miss() {
1002        let mut mapper = mapper_with_cache(simple_mapping_profile(), 1000).expect("should have parsed mapping config");
1003        assert_eq!(mapper.cache_len(), Some(0));
1004
1005        let metric = counter_metric("test.job.duration.my_type.my_name", &[]);
1006        let first = mapper.try_map(metric.context()).expect("should have remapped");
1007        assert_eq!(mapper.cache_len(), Some(1));
1008
1009        let metric = counter_metric("test.job.duration.my_type.my_name", &[]);
1010        let second = mapper.try_map(metric.context()).expect("should have remapped");
1011        assert_eq!(mapper.cache_len(), Some(1));
1012
1013        assert_eq!(first.name(), second.name());
1014        assert_eq!(first.name(), "test.job.duration");
1015        assert_tags(&first, &["job_type:my_type", "job_name:my_name"]);
1016        assert_tags(&second, &["job_type:my_type", "job_name:my_name"]);
1017    }
1018
1019    #[tokio::test]
1020    async fn negative_results_are_cached() {
1021        let mut mapper = mapper_with_cache(simple_mapping_profile(), 1000).expect("should have parsed mapping config");
1022
1023        let metric = counter_metric("unrelated.metric.name", &[]);
1024        assert!(mapper.try_map(metric.context()).is_none());
1025        assert_eq!(mapper.cache_len(), Some(1));
1026
1027        let metric = counter_metric("unrelated.metric.name", &[]);
1028        assert!(mapper.try_map(metric.context()).is_none());
1029        assert_eq!(mapper.cache_len(), Some(1));
1030    }
1031
1032    #[tokio::test]
1033    async fn cache_disabled_when_size_is_zero() {
1034        let mut mapper = mapper_with_cache(simple_mapping_profile(), 0).expect("should have parsed mapping config");
1035        assert_eq!(mapper.cache_len(), None);
1036
1037        let metric = counter_metric("test.job.duration.my_type.my_name", &[]);
1038        let context = mapper.try_map(metric.context()).expect("should have remapped");
1039        assert_eq!(context.name(), "test.job.duration");
1040        assert_tags(&context, &["job_type:my_type", "job_name:my_name"]);
1041
1042        assert!(mapper
1043            .try_map(counter_metric("unrelated.metric", &[]).context())
1044            .is_none());
1045        assert_eq!(mapper.cache_len(), None);
1046    }
1047
1048    #[tokio::test]
1049    async fn cache_evicts_older_entry_and_retains_newest_within_capacity() {
1050        let mut mapper = mapper_with_cache(simple_mapping_profile(), 2).expect("should have parsed mapping config");
1051
1052        // Insert three distinct metric names into a capacity-2 result cache, in order a, b, then c.
1053        for suffix in ["a", "b", "c"] {
1054            let name = format!("test.job.duration.t.{}", suffix);
1055            let metric = counter_metric(Box::leak(name.into_boxed_str()), &[]);
1056            mapper.try_map(metric.context()).expect("should have remapped");
1057        }
1058
1059        let a = mapper.cache_contains("test.job.duration.t.a");
1060        let b = mapper.cache_contains("test.job.duration.t.b");
1061        let c = mapper.cache_contains("test.job.duration.t.c");
1062
1063        // The cache must respect its configured capacity...
1064        assert!(
1065            mapper.cache_len().unwrap() <= 2,
1066            "cache should not exceed configured capacity (got {})",
1067            mapper.cache_len().unwrap()
1068        );
1069        // ...eviction must actually have happened (three distinct names cannot all fit in a capacity-2 cache)...
1070        assert!(!(a && b && c), "at least one older entry must have been evicted");
1071        // ...the most-recently-inserted name ("c") must be the entry that survives eviction...
1072        assert!(c, "the most-recently-inserted metric name should survive eviction");
1073        // ...and with "c" retained at capacity 2, at most one of the two older names may remain.
1074        assert!(
1075            !(a && b),
1076            "only one older entry may coexist with the newest entry at capacity 2"
1077        );
1078    }
1079
1080    #[tokio::test]
1081    async fn flood_of_identical_names_populates_single_cache_entry() {
1082        // Many profiles, only the last one matches the test metric. A flood of identical
1083        // names should be served from the cache after the first call.
1084        let mut profiles: Vec<DogStatsDMapperProfile> = (0..50)
1085            .map(|i| DogStatsDMapperProfile {
1086                name: format!("noise-{i}"),
1087                prefix: format!("noise{i}."),
1088                mappings: vec![DogStatsDMetricMapping {
1089                    metric_match: format!("noise{i}.*"),
1090                    match_type: String::new(),
1091                    name: "noise.mapped".to_string(),
1092                    tags: HashMap::new(),
1093                }],
1094            })
1095            .collect();
1096        profiles.push(DogStatsDMapperProfile {
1097            name: "real".to_string(),
1098            prefix: "real.".to_string(),
1099            mappings: vec![DogStatsDMetricMapping {
1100                metric_match: "real.metric.*".to_string(),
1101                match_type: String::new(),
1102                name: "real.mapped".to_string(),
1103                tags: [("x".to_string(), "$1".to_string())].into(),
1104            }],
1105        });
1106
1107        let mut mapper = mapper_with_cache(profiles, 16).expect("should have built mapper");
1108
1109        for _ in 0..10_000 {
1110            let metric = counter_metric("real.metric.flood", &[]);
1111            let context = mapper.try_map(metric.context()).expect("should have remapped");
1112            assert_eq!(context.name(), "real.mapped");
1113        }
1114
1115        assert_eq!(
1116            mapper.cache_len(),
1117            Some(1),
1118            "flood of identical names should populate exactly one cache entry"
1119        );
1120    }
1121}