1use stringtheory::MetaString;
9
10use crate::data_model::{event::metric::context::Context, tags::TagSet};
11
12#[derive(Clone)]
19pub struct RemapperRule {
20 existing_name: &'static str,
21 existing_tags: &'static [&'static str],
22 required_tag_keys: Vec<&'static str>,
23 rejected_tags: Vec<&'static str>,
24 new_name: &'static str,
25 remapped_tags: Vec<(&'static str, &'static str)>,
26 additional_tags: Vec<MetaString>,
27 all_original_tags_except: Option<Vec<&'static str>>,
28 continue_matching: bool,
29 sum_gauges: bool,
30 help_text: Option<&'static str>,
31}
32
33impl RemapperRule {
34 pub fn by_name(existing_name: &'static str, new_name: &'static str) -> Self {
36 Self {
37 existing_name,
38 existing_tags: &[],
39 required_tag_keys: Vec::new(),
40 rejected_tags: Vec::new(),
41 new_name,
42 remapped_tags: Vec::new(),
43 additional_tags: Vec::new(),
44 all_original_tags_except: None,
45 continue_matching: false,
46 sum_gauges: false,
47 help_text: None,
48 }
49 }
50
51 pub fn by_name_and_tags(
53 existing_name: &'static str, existing_tags: &'static [&'static str], new_name: &'static str,
54 ) -> Self {
55 Self {
56 existing_name,
57 existing_tags,
58 required_tag_keys: Vec::new(),
59 rejected_tags: Vec::new(),
60 new_name,
61 remapped_tags: Vec::new(),
62 additional_tags: Vec::new(),
63 all_original_tags_except: None,
64 continue_matching: false,
65 sum_gauges: false,
66 help_text: None,
67 }
68 }
69
70 pub fn with_required_tag_keys<I>(mut self, required_tag_keys: I) -> Self
77 where
78 I: IntoIterator<Item = &'static str>,
79 {
80 self.required_tag_keys.extend(required_tag_keys);
81 self
82 }
83
84 pub fn rejecting_tags<I>(mut self, rejected_tags: I) -> Self
98 where
99 I: IntoIterator<Item = &'static str>,
100 {
101 self.rejected_tags.extend(rejected_tags);
102 self
103 }
104
105 pub fn with_remapped_tags<I>(mut self, remapped_tags: I) -> Self
114 where
115 I: IntoIterator<Item = (&'static str, &'static str)>,
116 {
117 self.remapped_tags.extend(remapped_tags);
118 self
119 }
120
121 pub fn with_original_tags<I>(mut self, original_tags: I) -> Self
130 where
131 I: IntoIterator<Item = &'static str>,
132 {
133 self.remapped_tags
134 .extend(original_tags.into_iter().map(|tag| (tag, tag)));
135 self
136 }
137
138 pub fn with_additional_tags<I>(mut self, additional_tags: I) -> Self
144 where
145 I: IntoIterator<Item = &'static str>,
146 {
147 self.additional_tags
148 .extend(additional_tags.into_iter().map(MetaString::from_static));
149 self
150 }
151
152 pub fn with_all_original_tags_except<I>(mut self, excluded_tags: I) -> Self
165 where
166 I: IntoIterator<Item = &'static str>,
167 {
168 self.all_original_tags_except = Some(excluded_tags.into_iter().collect());
169 self
170 }
171
172 pub fn with_continued_matching(mut self) -> Self {
174 self.continue_matching = true;
175 self
176 }
177
178 pub fn with_summed_gauges(mut self) -> Self {
184 self.sum_gauges = true;
185 self
186 }
187
188 pub fn with_help_text(mut self, help_text: &'static str) -> Self {
194 self.help_text = Some(help_text);
195 self
196 }
197
198 pub const fn should_continue_matching(&self) -> bool {
200 self.continue_matching
201 }
202
203 pub const fn sums_gauges(&self) -> bool {
205 self.sum_gauges
206 }
207
208 pub const fn remapped_name(&self) -> &'static str {
210 self.new_name
211 }
212
213 pub const fn help_text(&self) -> Option<&'static str> {
215 self.help_text
216 }
217
218 pub fn try_match_no_context(&self, context: &Context) -> Option<RemappedMetric> {
222 if context.name() != self.existing_name {
223 return None;
224 }
225
226 let metric_tags = context.tags();
227 for existing_tag in self.existing_tags {
228 if !metric_tags.has_tag(existing_tag) {
229 return None;
230 }
231 }
232
233 if self
234 .rejected_tags
235 .iter()
236 .any(|rejected_tag| metric_tags.has_tag(rejected_tag))
237 {
238 return None;
239 }
240
241 if self
242 .required_tag_keys
243 .iter()
244 .any(|required_tag_key| metric_tags.get_single_tag(required_tag_key).is_none())
245 {
246 return None;
247 }
248
249 let tags = self.build_remapped_tags(metric_tags);
250 Some(RemappedMetric {
251 name: self.new_name,
252 tags,
253 })
254 }
255
256 fn build_remapped_tags(&self, metric_tags: &TagSet) -> Vec<MetaString> {
258 let mut new_tags = vec![];
259
260 for (original_tag_name, new_tag_name) in &self.remapped_tags {
261 if let Some(tag) = metric_tags.get_single_tag(original_tag_name) {
262 if original_tag_name == new_tag_name {
263 new_tags.push(tag.clone().into_inner());
265 } else {
266 match tag.value() {
268 Some(value) => {
269 new_tags.push(MetaString::from(format!("{}:{}", new_tag_name, value)));
270 }
271 None => {
272 new_tags.push(MetaString::from(*new_tag_name));
273 }
274 }
275 }
276 }
277 }
278
279 if let Some(excluded_tags) = &self.all_original_tags_except {
280 let mut copied_names = Vec::new();
281 for tag in metric_tags {
282 let name = tag.name();
283 if excluded_tags.contains(&name)
284 || copied_names.contains(&name)
285 || self
286 .remapped_tags
287 .iter()
288 .any(|(source, destination)| *source == name || *destination == name)
289 || self
290 .additional_tags
291 .iter()
292 .any(|additional| additional.split_once(':').map_or(&**additional, |(n, _)| n) == name)
293 {
294 continue;
295 }
296 copied_names.push(name);
297 new_tags.push(tag.clone().into_inner());
298 }
299 }
300
301 for additional_tag in &self.additional_tags {
302 new_tags.push(additional_tag.clone());
303 }
304
305 new_tags
306 }
307}
308
309pub struct RemappedMetric {
311 pub name: &'static str,
313
314 pub tags: Vec<MetaString>,
316}
317
318#[cfg(test)]
319mod tests {
320 use super::*;
321 use crate::data_model::event::metric::context::Context;
322
323 struct MatchCase {
324 description: &'static str,
325 rule: RemapperRule,
326 context: Context,
327 expected_name: Option<&'static str>,
328 }
329
330 #[test]
331 fn matches_by_name_and_required_tags() {
332 let cases = [
333 MatchCase {
334 description: "by_name matches on the metric name alone",
335 rule: RemapperRule::by_name("src.metric", "dst.metric"),
336 context: Context::from_static_parts("src.metric", &["env:prod"]),
337 expected_name: Some("dst.metric"),
338 },
339 MatchCase {
340 description: "by_name rejects a different metric name",
341 rule: RemapperRule::by_name("src.metric", "dst.metric"),
342 context: Context::from_static_parts("other.metric", &["env:prod"]),
343 expected_name: None,
344 },
345 MatchCase {
346 description: "by_name_and_tags matches when every required tag is present",
347 rule: RemapperRule::by_name_and_tags("src.metric", &["env:prod", "role:api"], "dst.metric"),
348 context: Context::from_static_parts("src.metric", &["env:prod", "role:api", "extra:1"]),
349 expected_name: Some("dst.metric"),
350 },
351 MatchCase {
352 description: "by_name_and_tags rejects when a required tag has a different value",
353 rule: RemapperRule::by_name_and_tags("src.metric", &["env:prod"], "dst.metric"),
354 context: Context::from_static_parts("src.metric", &["env:dev"]),
355 expected_name: None,
356 },
357 MatchCase {
358 description: "by_name_and_tags rejects when only one of several required tags is present",
359 rule: RemapperRule::by_name_and_tags("src.metric", &["env:prod", "role:api"], "dst.metric"),
360 context: Context::from_static_parts("src.metric", &["env:prod"]),
361 expected_name: None,
362 },
363 MatchCase {
364 description: "with_required_tag_keys matches when the tag key is present with any value",
365 rule: RemapperRule::by_name("src.metric", "dst.metric").with_required_tag_keys(["domain"]),
366 context: Context::from_static_parts("src.metric", &["domain:example.com"]),
367 expected_name: Some("dst.metric"),
368 },
369 MatchCase {
370 description: "with_required_tag_keys rejects when the tag key is absent",
371 rule: RemapperRule::by_name("src.metric", "dst.metric").with_required_tag_keys(["domain"]),
372 context: Context::from_static_parts("src.metric", &["component_id:forwarder"]),
373 expected_name: None,
374 },
375 MatchCase {
376 description: "rejecting_tags rejects a metric that carries a rejected tag",
377 rule: RemapperRule::by_name("src.metric", "dst.metric").rejecting_tags(["purpose:validation"]),
378 context: Context::from_static_parts("src.metric", &["domain:example.com", "purpose:validation"]),
379 expected_name: None,
380 },
381 MatchCase {
382 description: "rejecting_tags matches when the rejected tag is absent",
383 rule: RemapperRule::by_name("src.metric", "dst.metric").rejecting_tags(["purpose:validation"]),
384 context: Context::from_static_parts("src.metric", &["domain:example.com"]),
385 expected_name: Some("dst.metric"),
386 },
387 MatchCase {
388 description: "rejecting_tags only rejects the exact rejected tag value",
389 rule: RemapperRule::by_name("src.metric", "dst.metric").rejecting_tags(["purpose:validation"]),
390 context: Context::from_static_parts("src.metric", &["purpose:other"]),
391 expected_name: Some("dst.metric"),
392 },
393 MatchCase {
394 description: "rejecting_tags rejects when any of several rejected tags is present",
395 rule: RemapperRule::by_name("src.metric", "dst.metric")
396 .rejecting_tags(["purpose:validation"])
397 .rejecting_tags(["purpose:probe"]),
398 context: Context::from_static_parts("src.metric", &["purpose:probe"]),
399 expected_name: None,
400 },
401 ];
402
403 for case in cases {
404 let actual = case
405 .rule
406 .try_match_no_context(&case.context)
407 .map(|remapped| remapped.name);
408 assert_eq!(actual, case.expected_name, "case: {}", case.description);
409 }
410 }
411
412 fn remapped_tags(rule: &RemapperRule, context: &Context) -> Vec<String> {
413 rule.try_match_no_context(context)
414 .expect("rule should match")
415 .tags
416 .iter()
417 .map(|tag| tag.as_ref().to_string())
418 .collect()
419 }
420
421 #[test]
422 fn copies_original_tags_and_renames_remapped_tags() {
423 let rule = RemapperRule::by_name("src.metric", "dst.metric")
426 .with_original_tags(["region"])
427 .with_remapped_tags([("host", "hostname")]);
428 let context = Context::from_static_parts("src.metric", &["region:us-east-1", "host:web01"]);
429
430 assert_eq!(remapped_tags(&rule, &context), ["region:us-east-1", "hostname:web01"]);
431 }
432
433 #[test]
434 fn copies_dynamic_original_tags_excluding_component_tags() {
435 let rule = RemapperRule::by_name_and_tags("src.metric", &["component_id:dsd_agg"], "dst.metric")
436 .with_all_original_tags_except(["component_id"]);
437 let context = Context::from_static_parts(
438 "src.metric",
439 &["component_id:dsd_agg", "pod_name:pod-1", "kube_namespace:default"],
440 );
441
442 let tags = remapped_tags(&rule, &context);
443 assert_eq!(tags.len(), 2);
444 assert!(tags.contains(&"pod_name:pod-1".to_string()));
445 assert!(tags.contains(&"kube_namespace:default".to_string()));
446 }
447
448 #[test]
449 fn copied_dynamic_tags_never_duplicate_output_tag_names() {
450 let rule = RemapperRule::by_name("src.metric", "dst.metric")
451 .with_remapped_tags([("source", "renamed")])
452 .with_additional_tags(["fixed:value"])
453 .with_all_original_tags_except(["component_id"]);
454 let context = Context::from_static_parts(
455 "src.metric",
456 &["source:a", "renamed:b", "fixed:c", "multi:x", "multi:y", "kept:z"],
457 );
458
459 let tags = remapped_tags(&rule, &context);
460 let mut names: Vec<_> = tags.iter().map(|tag| tag.split_once(':').unwrap().0).collect();
461 names.sort_unstable();
462 assert_eq!(names, ["fixed", "kept", "multi", "renamed"]);
463 assert!(tags.contains(&"renamed:a".to_string()));
464 assert!(tags.contains(&"fixed:value".to_string()));
465 }
466
467 #[test]
468 fn appends_additional_fixed_tags_after_copied_tags() {
469 let rule = RemapperRule::by_name("src.metric", "dst.metric")
470 .with_original_tags(["region"])
471 .with_additional_tags(["source:internal"]);
472 let context = Context::from_static_parts("src.metric", &["region:us-east-1"]);
473
474 assert_eq!(remapped_tags(&rule, &context), ["region:us-east-1", "source:internal"]);
475 }
476
477 #[test]
478 fn skips_remapped_tags_absent_from_the_source_metric() {
479 let rule = RemapperRule::by_name("src.metric", "dst.metric").with_remapped_tags([("host", "hostname")]);
481 let context = Context::from_static_parts("src.metric", &["region:us-east-1"]);
482
483 assert!(remapped_tags(&rule, &context).is_empty());
484 }
485
486 #[test]
487 fn exposes_continue_matching_and_help_text_accessors() {
488 let rule = RemapperRule::by_name("src.metric", "dst.metric");
489 assert_eq!(rule.remapped_name(), "dst.metric");
490 assert!(!rule.should_continue_matching());
491 assert_eq!(rule.help_text(), None);
492
493 let rule = rule.with_continued_matching().with_help_text("some help text");
494 assert!(rule.should_continue_matching());
495 assert_eq!(rule.help_text(), Some("some help text"));
496 }
497}