relay_event_schema/protocol/trace_metric/
mod.rs1use 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 #[metastructure(required = true)]
20 pub timestamp: Annotated<Timestamp>,
21
22 #[metastructure(required = true, trim = false)]
24 pub trace_id: Annotated<TraceId>,
25
26 #[metastructure(required = false, trim = false)]
28 pub span_id: Annotated<SpanId>,
29
30 #[metastructure(required = true, trim = false)]
32 pub name: Annotated<String>,
33
34 #[metastructure(required = true, field = "type")]
36 pub ty: Annotated<MetricType>,
37
38 #[metastructure(required = false)]
40 pub unit: Annotated<MetricUnit>,
41
42 #[metastructure(pii = "maybe", required = true, trim = false)]
46 pub value: Annotated<Value>,
47
48 #[metastructure(pii = "maybe", trim = false)]
50 pub attributes: Annotated<Attributes>,
51
52 #[metastructure(additional_properties, retain = false)]
54 pub other: Object<Value>,
55}
56
57#[derive(Clone, Debug, Default, Serialize, Deserialize)]
62pub struct TraceMetricHeader {
63 pub byte_size: Option<u64>,
68
69 #[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 Gauge,
94 Distribution,
96 Counter,
98 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}