relay_server/metrics/
minimal.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
use relay_metrics::{
    BucketMetadata, CounterType, MetricName, MetricNamespace, MetricResourceIdentifier, MetricType,
};
use serde::de::IgnoredAny;
use serde::Deserialize;

use crate::metrics::{BucketSummary, TrackableBucket};

/// Bucket which parses only the minimally required information to implement [`TrackableBucket`].
///
/// Note: this can not be used to parse untrusted buckets, there is no normalization of data
/// happening, e.g. a missing namespace will not turn the bucket into a custom metric bucket.
#[derive(Deserialize)]
pub struct MinimalTrackableBucket {
    name: MetricName,
    #[serde(flatten)]
    value: MinimalValue,
    #[serde(default)]
    metadata: BucketMetadata,
}

impl TrackableBucket for MinimalTrackableBucket {
    fn name(&self) -> &relay_metrics::MetricName {
        &self.name
    }

    fn ty(&self) -> relay_metrics::MetricType {
        self.value.ty()
    }

    fn summary(&self) -> BucketSummary {
        let mri = match MetricResourceIdentifier::parse(self.name()) {
            Ok(mri) => mri,
            Err(_) => return BucketSummary::default(),
        };

        match mri.namespace {
            MetricNamespace::Transactions => {
                let count = match self.value {
                    MinimalValue::Counter(c) if mri.name == "usage" => c.to_f64() as usize,
                    _ => 0,
                };
                BucketSummary::Transactions(count)
            }
            MetricNamespace::Spans => BucketSummary::Spans(match self.value {
                MinimalValue::Counter(c) if mri.name == "usage" => c.to_f64() as usize,
                _ => 0,
            }),
            _ => BucketSummary::default(),
        }
    }

    fn metadata(&self) -> BucketMetadata {
        self.metadata
    }
}

#[derive(Clone, Copy, Debug, Deserialize)]
#[serde(tag = "type", content = "value")]
enum MinimalValue {
    #[serde(rename = "c")]
    Counter(CounterType),
    #[serde(rename = "d")]
    Distribution(IgnoredAny),
    #[serde(rename = "s")]
    Set(IgnoredAny),
    #[serde(rename = "g")]
    Gauge(IgnoredAny),
}

impl MinimalValue {
    fn ty(self) -> MetricType {
        match self {
            MinimalValue::Counter(_) => MetricType::Counter,
            MinimalValue::Distribution(_) => MetricType::Distribution,
            MinimalValue::Set(_) => MetricType::Set,
            MinimalValue::Gauge(_) => MetricType::Gauge,
        }
    }
}

#[cfg(test)]
mod tests {
    use insta::assert_debug_snapshot;
    use relay_metrics::Bucket;

    use super::*;

    #[test]
    fn test_buckets() {
        let json = r#"[
  {
    "timestamp": 1615889440,
    "width": 10,
    "name": "d:transactions/duration@none",
    "type": "d",
    "value": [
      36.0,
      49.0,
      57.0,
      68.0
    ],
    "tags": {
      "has_profile": "true"
    }
  },
  {
    "timestamp": 1615889440,
    "width": 10,
    "name": "c:transactions/usage@none",
    "type": "c",
    "value": 3.0,
    "tags": {
      "route": "user_index"
    }
  },
  {
    "timestamp": 1615889440,
    "width": 10,
    "name": "c:spans/usage@none",
    "type": "c",
    "value": 3.0,
    "tags": {
    }
  },
  {
    "timestamp": 1615889440,
    "width": 10,
    "name": "g:custom/unrelated@none",
    "type": "g",
    "value": {
      "last": 25.0,
      "min": 17.0,
      "max": 42.0,
      "sum": 2210.0,
      "count": 85
    }
  },
  {
    "timestamp": 1615889440,
    "width": 10,
    "name": "s:custom/endpoint.users@none",
    "type": "s",
    "value": [
      3182887624,
      4267882815
    ],
    "tags": {
      "route": "user_index"
    }
  }
]"#;
        let buckets: Vec<Bucket> = serde_json::from_str(json).unwrap();
        let min_buckets: Vec<MinimalTrackableBucket> = serde_json::from_str(json).unwrap();

        for (b, mb) in buckets.iter().zip(min_buckets.iter()) {
            assert_eq!(b.name(), mb.name());
            assert_eq!(b.summary(), mb.summary());
            assert_eq!(b.metadata, mb.metadata);
        }

        let summary = min_buckets.iter().map(|b| b.summary()).collect::<Vec<_>>();
        assert_debug_snapshot!(summary, @r###"
        [
            Transactions(
                0,
            ),
            Transactions(
                3,
            ),
            Spans(
                3,
            ),
            None,
            None,
        ]
        "###);
    }
}