Skip to main content

relay_event_schema/protocol/trace_metric/
mod.rs

1use relay_protocol::{
2    Annotated, Empty, FromValue, Getter, IntoValue, Object, SkipSerialization, Value,
3};
4use std::collections::BTreeMap;
5use std::fmt::{self, Display};
6
7use relay_base_schema::metrics::MetricUnit;
8use serde::{Deserialize, Serialize, Serializer};
9
10use crate::processor::ProcessValue;
11use crate::protocol::{Attributes, SpanId, Timestamp, TraceId};
12
13pub mod container;
14
15#[derive(Clone, Debug, Default, PartialEq, Empty, FromValue, IntoValue, ProcessValue)]
16#[metastructure(process_func = "process_trace_metric", value_type = "TraceMetric")]
17pub struct TraceMetric {
18    /// Timestamp when the metric was created.
19    #[metastructure(required = true)]
20    pub timestamp: Annotated<Timestamp>,
21
22    /// The ID of the trace the metric belongs to.
23    #[metastructure(required = true, trim = false)]
24    pub trace_id: Annotated<TraceId>,
25
26    /// The Span this metric belongs to.
27    #[metastructure(required = false, trim = false)]
28    pub span_id: Annotated<SpanId>,
29
30    /// The metric name.
31    #[metastructure(required = true, trim = false)]
32    pub name: Annotated<String>,
33
34    /// The metric type.
35    #[metastructure(required = true, field = "type")]
36    pub ty: Annotated<MetricType>,
37
38    /// The metric unit.
39    #[metastructure(required = false)]
40    pub unit: Annotated<MetricUnit>,
41
42    /// The metric value.
43    ///
44    /// Should be constrained to a number.
45    #[metastructure(pii = "maybe", required = true, trim = false)]
46    pub value: Annotated<Value>,
47
48    /// Arbitrary attributes on a metric.
49    #[metastructure(pii = "maybe", trim = false)]
50    pub attributes: Annotated<Attributes>,
51
52    /// Additional arbitrary fields for forwards compatibility.
53    #[metastructure(additional_properties, retain = false)]
54    pub other: Object<Value>,
55}
56
57/// Relay specific metadata embedded into the trace metric item.
58///
59/// This metadata is purely an internal protocol extension used by Relay,
60/// no one except Relay should be sending this data, nor should anyone except Relay rely on it.
61#[derive(Clone, Debug, Default, Serialize, Deserialize)]
62pub struct TraceMetricHeader {
63    /// Original (calculated) size of the trace metric item when it was first received by a Relay.
64    ///
65    /// If this value exists, Relay uses it as quantity for all outcomes emitted to the
66    /// trace metric byte data category.
67    pub byte_size: Option<u64>,
68
69    /// Forward compatibility for additional headers.
70    #[serde(flatten)]
71    pub other: BTreeMap<String, Value>,
72}
73
74impl Getter for TraceMetric {
75    fn get_value(&self, path: &str) -> Option<relay_protocol::Val<'_>> {
76        Some(match path.strip_prefix("trace_metric.")? {
77            "name" => self.name.as_str()?.into(),
78            path => {
79                if let Some(key) = path.strip_prefix("attributes.") {
80                    let key = key.strip_suffix(".value")?;
81                    self.attributes.value()?.get_value(key)?.into()
82                } else {
83                    return None;
84                }
85            }
86        })
87    }
88}
89
90#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
91pub enum MetricType {
92    /// A gauge metric represents a single numerical value that can arbitrarily go up and down.
93    Gauge,
94    /// A distribution metric represents a collection of values that can be aggregated.
95    Distribution,
96    /// A counter metric represents a single numerical value.
97    Counter,
98    /// Unknown type, for forward compatibility.
99    Unknown(String),
100}
101
102impl MetricType {
103    fn as_str(&self) -> &str {
104        match self {
105            MetricType::Gauge => "gauge",
106            MetricType::Distribution => "distribution",
107            MetricType::Counter => "counter",
108            MetricType::Unknown(s) => s.as_str(),
109        }
110    }
111}
112
113impl Display for MetricType {
114    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115        write!(f, "{}", self.as_str())
116    }
117}
118
119impl From<String> for MetricType {
120    fn from(value: String) -> Self {
121        match value.as_str() {
122            "gauge" => MetricType::Gauge,
123            "distribution" => MetricType::Distribution,
124            "counter" => MetricType::Counter,
125            _ => MetricType::Unknown(value),
126        }
127    }
128}
129
130impl FromValue for MetricType {
131    fn from_value(value: Annotated<Value>) -> Annotated<Self> {
132        match String::from_value(value) {
133            Annotated(Some(value), meta) => Annotated(Some(value.into()), meta),
134            Annotated(None, meta) => Annotated(None, meta),
135        }
136    }
137}
138
139impl IntoValue for MetricType {
140    fn into_value(self) -> Value {
141        Value::String(self.to_string())
142    }
143
144    fn serialize_payload<S>(&self, s: S, _behavior: SkipSerialization) -> Result<S::Ok, S::Error>
145    where
146        Self: Sized,
147        S: Serializer,
148    {
149        Serialize::serialize(self.as_str(), s)
150    }
151}
152
153impl ProcessValue for MetricType {}
154
155impl Empty for MetricType {
156    #[inline]
157    fn is_empty(&self) -> bool {
158        false
159    }
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165    use relay_protocol::SerializableAnnotated;
166
167    #[test]
168    fn test_trace_metric_serialization() {
169        let json = r#"{
170            "timestamp": 1544719860.0,
171            "trace_id": "5b8efff798038103d269b633813fc60c",
172            "span_id": "eee19b7ec3c1b174",
173            "name": "http.request.duration",
174            "type": "distribution",
175            "value": 123.45,
176            "attributes": {
177                "http.method": {
178                    "value": "GET",
179                    "type": "string"
180                },
181                "http.status_code": {
182                    "value": "200",
183                    "type": "integer"
184                }
185            }
186        }"#;
187
188        let data = Annotated::<TraceMetric>::from_json(json).unwrap();
189
190        insta::assert_json_snapshot!(SerializableAnnotated(&data), @r###"
191        {
192          "timestamp": 1544719860.0,
193          "trace_id": "5b8efff798038103d269b633813fc60c",
194          "span_id": "eee19b7ec3c1b174",
195          "name": "http.request.duration",
196          "type": "distribution",
197          "value": 123.45,
198          "attributes": {
199            "http.method": {
200              "type": "string",
201              "value": "GET"
202            },
203            "http.status_code": {
204              "type": "integer",
205              "value": "200"
206            }
207          }
208        }
209        "###);
210    }
211
212    #[test]
213    fn test_trace_metric_with_custom_unit_preserved() {
214        let json = r#"{
215            "timestamp": 1544719860.0,
216            "trace_id": "5b8efff798038103d269b633813fc60c",
217            "name": "custom.metric",
218            "type": "counter",
219            "value": 42,
220            "unit": "customunit"
221        }"#;
222
223        let data = Annotated::<TraceMetric>::from_json(json).unwrap();
224        let trace_metric = data.value().unwrap();
225
226        assert_eq!(
227            trace_metric.unit.value(),
228            Some(&MetricUnit::Custom("customunit".parse().unwrap()))
229        );
230    }
231}