relay_server/utils/
statsd.rs

1use relay_base_schema::events::EventType;
2use relay_event_normalization::utils::extract_http_status_code;
3use relay_event_schema::protocol::{Event, TransactionSource};
4use relay_protocol::{Annotated, RemarkType};
5
6use crate::statsd::RelayCounters;
7
8/// Maps the event's transaction source to a low-cardinality statsd tag.
9pub fn transaction_source_tag(event: &Event) -> &str {
10    let source = event
11        .transaction_info
12        .value()
13        .and_then(|i| i.source.value());
14    match source {
15        None => "none",
16        Some(TransactionSource::Other(_)) => "other",
17        Some(source) => source.as_str(),
18    }
19}
20
21/// Log statsd metrics about transaction name modifications.
22///
23/// We have to look at event & meta before and after the modification is made,
24/// so we delegate to `f` in the middle of the function.
25pub fn log_transaction_name_metrics<F, R>(event: &mut Annotated<Event>, mut f: F) -> R
26where
27    F: FnMut(&mut Annotated<Event>) -> R,
28{
29    let Some(inner) = event.value() else {
30        return f(event);
31    };
32
33    if inner.ty.value() != Some(&EventType::Transaction) {
34        return f(event);
35    }
36
37    let old_source = transaction_source_tag(inner).to_string();
38    let old_remarks = inner.transaction.meta().iter_remarks().count();
39
40    let res = f(event);
41
42    // Need to reborrow event so the reference's lifetime does not overlap with `f`:
43    let Some(inner) = event.value() else {
44        return res;
45    };
46
47    let mut pattern_based_changes = false;
48    let mut rule_based_changes = false;
49    let remarks = inner.transaction.meta().iter_remarks().skip(old_remarks);
50    for remark in remarks {
51        if remark.ty() == RemarkType::Substituted {
52            if remark.range().is_some() {
53                pattern_based_changes = true;
54            } else {
55                rule_based_changes = true;
56            }
57        }
58    }
59
60    let changes = match (pattern_based_changes, rule_based_changes) {
61        (true, true) => "both",
62        (true, false) => "pattern",
63        (false, true) => "rule",
64        (false, false) => "none",
65    };
66
67    let new_source = transaction_source_tag(inner);
68    let is_404 = extract_http_status_code(inner).is_some_and(|s| s == "404");
69
70    relay_statsd::metric!(
71        counter(RelayCounters::TransactionNameChanges) += 1,
72        source_in = old_source.as_str(),
73        changes = changes,
74        source_out = new_source,
75        is_404 = if is_404 { "true" } else { "false" },
76    );
77
78    res
79}