relay_server/metrics_extraction/transactions/
types.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
use std::borrow::Cow;
use std::collections::BTreeMap;
use std::fmt::Display;

use relay_base_schema::project::ProjectId;
use relay_common::time::UnixTimestamp;
use relay_metrics::{
    Bucket, BucketMetadata, BucketValue, DistributionType, DurationUnit, MetricNamespace,
    MetricResourceIdentifier, MetricUnit,
};

use crate::metrics_extraction::IntoMetric;

/// Enumerates the metrics extracted from transaction payloads.
#[derive(Clone, Debug, PartialEq)]
pub enum TransactionMetric {
    /// A set metric counting unique users.
    User { value: String, tags: CommonTags },
    /// A distribution metric for the transaction duration.
    ///
    /// Also used to count transactions, as any distribution metric features a counter.
    Duration {
        unit: DurationUnit,
        value: DistributionType,
        tags: CommonTags,
    },
    /// A distribution metric for the transaction duration with limited tags.
    DurationLight {
        unit: DurationUnit,
        value: DistributionType,
        tags: LightTransactionTags,
    },
    /// An internal counter metric that tracks transaction usage.
    ///
    /// This metric does not have any of the common tags for the performance product, but instead
    /// carries internal information for accounting purposes.
    Usage,
    /// An internal counter metric used to compute dynamic sampling biases.
    ///
    /// See '<https://github.com/getsentry/sentry/blob/d3d9ed6cfa6e06aa402ab1d496dedbb22b3eabd7/src/sentry/dynamic_sampling/prioritise_projects.py#L40>'.
    CountPerRootProject { tags: TransactionCPRTags },
    /// A metric created from [`relay_event_schema::protocol::Breakdowns`].
    Breakdown {
        name: String,
        value: DistributionType,
        tags: CommonTags,
    },
    /// A metric created from a [`relay_event_schema::protocol::Measurement`].
    Measurement {
        name: String,
        value: DistributionType,
        unit: MetricUnit,
        tags: TransactionMeasurementTags,
    },
}

impl IntoMetric for TransactionMetric {
    fn into_metric(self, timestamp: UnixTimestamp) -> Bucket {
        let namespace = MetricNamespace::Transactions;

        let (name, value, unit, tags) = match self {
            Self::User { value, tags } => (
                Cow::Borrowed("user"),
                BucketValue::set_from_str(&value),
                MetricUnit::None,
                tags.into(),
            ),
            Self::Duration { unit, value, tags } => (
                Cow::Borrowed("duration"),
                BucketValue::distribution(value),
                MetricUnit::Duration(unit),
                tags.into(),
            ),
            Self::DurationLight { unit, value, tags } => (
                Cow::Borrowed("duration_light"),
                BucketValue::distribution(value),
                MetricUnit::Duration(unit),
                tags.into(),
            ),
            Self::Usage => (
                Cow::Borrowed("usage"),
                BucketValue::counter(1.into()),
                MetricUnit::None,
                Default::default(),
            ),
            Self::CountPerRootProject { tags } => (
                Cow::Borrowed("count_per_root_project"),
                BucketValue::counter(1.into()),
                MetricUnit::None,
                tags.into(),
            ),
            Self::Breakdown { name, value, tags } => (
                Cow::Owned(format!("breakdowns.{name}")),
                BucketValue::distribution(value),
                MetricUnit::Duration(DurationUnit::MilliSecond),
                tags.into(),
            ),
            Self::Measurement {
                name,
                value,
                unit,
                tags,
            } => (
                Cow::Owned(format!("measurements.{name}")),
                BucketValue::distribution(value),
                unit,
                tags.into(),
            ),
        };

        let mri = MetricResourceIdentifier {
            ty: value.ty(),
            namespace,
            name,
            unit,
        };

        // For extracted metrics we assume the `received_at` timestamp is equivalent to the time
        // in which the metric is extracted.
        let received_at = if cfg!(not(test)) {
            UnixTimestamp::now()
        } else {
            UnixTimestamp::from_secs(0)
        };

        Bucket {
            timestamp,
            width: 0,
            name: mri.to_string().into(),
            value,
            tags,
            metadata: BucketMetadata::new(received_at),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Ord, PartialOrd)]
pub struct LightTransactionTags {
    pub transaction_op: Option<String>,
    pub transaction: Option<String>,
}

impl From<LightTransactionTags> for BTreeMap<String, String> {
    fn from(tags: LightTransactionTags) -> Self {
        let mut map = BTreeMap::new();
        if let Some(transaction_op) = tags.transaction_op {
            map.insert(CommonTag::TransactionOp.to_string(), transaction_op);
        }
        if let Some(transaction) = tags.transaction {
            map.insert(CommonTag::Transaction.to_string(), transaction);
        }
        map
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Ord, PartialOrd)]
pub struct TransactionMeasurementTags {
    pub measurement_rating: Option<String>,
    pub score_profile_version: Option<String>,
    pub universal_tags: CommonTags,
}

impl From<TransactionMeasurementTags> for BTreeMap<String, String> {
    fn from(value: TransactionMeasurementTags) -> Self {
        let mut map: BTreeMap<String, String> = value.universal_tags.into();
        if let Some(decision) = value.measurement_rating {
            map.insert("measurement_rating".to_owned(), decision);
        }
        if let Some(score_profile_version) = value.score_profile_version {
            map.insert(
                "sentry.score_profile_version".to_owned(),
                score_profile_version,
            );
        }
        map
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TransactionCPRTags {
    pub decision: String,
    pub target_project_id: ProjectId,
    pub universal_tags: CommonTags,
}

impl From<TransactionCPRTags> for BTreeMap<String, String> {
    fn from(value: TransactionCPRTags) -> Self {
        let mut map: BTreeMap<String, String> = value.universal_tags.into();
        map.insert("decision".to_string(), value.decision);
        map.insert(
            "target_project_id".to_string(),
            value.target_project_id.to_string(),
        );
        map
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Ord, PartialOrd)]
pub struct CommonTags(pub BTreeMap<CommonTag, String>);

impl From<CommonTags> for BTreeMap<String, String> {
    fn from(value: CommonTags) -> Self {
        value
            .0
            .into_iter()
            .map(|(k, v)| (k.to_string(), v))
            .collect()
    }
}

/// The most common tags for transaction metrics.
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum CommonTag {
    Release,
    Dist,
    Environment,
    Transaction,
    Platform,
    TransactionStatus,
    TransactionOp,
    HttpMethod,
    HttpStatusCode,
    BrowserName,
    OsName,
    GeoCountryCode,
    UserSubregion,
    DeviceClass,
    Custom(String),
}

impl Display for CommonTag {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let name = match self {
            CommonTag::Release => "release",
            CommonTag::Dist => "dist",
            CommonTag::Environment => "environment",
            CommonTag::Transaction => "transaction",
            CommonTag::Platform => "platform",
            CommonTag::TransactionStatus => "transaction.status",
            CommonTag::TransactionOp => "transaction.op",
            CommonTag::HttpMethod => "http.method",
            CommonTag::HttpStatusCode => "http.status_code",
            CommonTag::BrowserName => "browser.name",
            CommonTag::OsName => "os.name",
            CommonTag::GeoCountryCode => "geo.country_code",
            CommonTag::UserSubregion => "user.geo.subregion",
            CommonTag::DeviceClass => "device.class",
            CommonTag::Custom(s) => s,
        };
        write!(f, "{name}")
    }
}

/// Error returned from transaction metrics extraction.
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
pub enum ExtractMetricsError {
    /// The start or end timestamps are missing from the event payload.
    #[error("no valid timestamp could be found in the event")]
    MissingTimestamp,
    /// The event timestamp is outside the supported range.
    ///
    /// The supported range is derived from the
    /// [`max_secs_in_past`](relay_metrics::aggregator::AggregatorConfig::max_secs_in_past) and
    /// [`max_secs_in_future`](relay_metrics::aggregator::AggregatorConfig::max_secs_in_future) configuration options.
    #[error("timestamp too old or too far in the future")]
    InvalidTimestamp,
}