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::ops::{Deref, DerefMut};

use relay_base_schema::metrics::MetricUnit;
use relay_protocol::{Annotated, Empty, Error, FromValue, IntoValue, Object, Value};

use crate::processor::ProcessValue;

/// An individual observed measurement.
#[derive(Clone, Debug, Default, PartialEq, Empty, FromValue, IntoValue, ProcessValue)]
pub struct Measurement {
    /// Value of observed measurement value.
    #[metastructure(required = "true", skip_serialization = "never")]
    pub value: Annotated<f64>,

    /// The unit of this measurement, defaulting to no unit.
    pub unit: Annotated<MetricUnit>,
}

/// A map of observed measurement values.
///
/// They contain measurement values of observed values such as Largest Contentful Paint (LCP).
#[derive(Clone, Debug, Default, PartialEq, Empty, IntoValue, ProcessValue)]
pub struct Measurements(pub Object<Measurement>);

impl Measurements {
    /// Returns the underlying object of measurements.
    pub fn into_inner(self) -> Object<Measurement> {
        self.0
    }

    /// Return the value of the measurement with the given name, if it exists.
    pub fn get_value(&self, key: &str) -> Option<f64> {
        self.get(key)
            .and_then(Annotated::value)
            .and_then(|x| x.value.value())
            .copied()
    }
}

impl FromValue for Measurements {
    fn from_value(value: Annotated<Value>) -> Annotated<Self> {
        let mut processing_errors = Vec::new();

        let mut measurements = Object::from_value(value).map_value(|measurements| {
            let measurements = measurements
                .into_iter()
                .filter_map(|(name, object)| {
                    let name = name.trim();

                    if name.is_empty() {
                        processing_errors.push(Error::invalid(format!(
                            "measurement name '{name}' cannot be empty"
                        )));
                    } else if is_valid_measurement_name(name) {
                        return Some((name.to_lowercase(), object));
                    } else {
                        processing_errors.push(Error::invalid(format!(
                            "measurement name '{name}' can contain only characters a-z0-9._"
                        )));
                    }

                    None
                })
                .collect();

            Self(measurements)
        });

        for error in processing_errors {
            measurements.meta_mut().add_error(error);
        }

        measurements
    }
}

impl Deref for Measurements {
    type Target = Object<Measurement>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for Measurements {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

fn is_valid_measurement_name(name: &str) -> bool {
    name.starts_with(|c: char| c.is_ascii_alphabetic())
        && name
            .chars()
            .all(|c| matches!(c, 'a'..='z' | 'A'..='Z' | '0'..='9' | '_' | '.'))
}

#[cfg(test)]
mod tests {
    use relay_base_schema::metrics::DurationUnit;
    use similar_asserts::assert_eq;

    use super::*;
    use crate::protocol::Event;

    #[test]
    fn test_measurements_serialization() {
        let input = r#"{
    "measurements": {
        "LCP": {"value": 420.69, "unit": "millisecond"},
        "   lcp_final.element-Size123  ": {"value": 1},
        "fid": {"value": 2020},
        "inp": {"value": 100.14},
        "cls": {"value": null},
        "fp": {"value": "im a first paint"},
        "Total Blocking Time": {"value": 3.14159},
        "missing_value": "string",
        "": {"value": 2.71828}
    }
}"#;

        let output = r#"{
  "measurements": {
    "cls": {
      "value": null
    },
    "fid": {
      "value": 2020.0
    },
    "fp": {
      "value": null
    },
    "inp": {
      "value": 100.14
    },
    "lcp": {
      "value": 420.69,
      "unit": "millisecond"
    },
    "missing_value": null
  },
  "_meta": {
    "measurements": {
      "": {
        "err": [
          [
            "invalid_data",
            {
              "reason": "measurement name '' cannot be empty"
            }
          ],
          [
            "invalid_data",
            {
              "reason": "measurement name 'lcp_final.element-Size123' can contain only characters a-z0-9._"
            }
          ],
          [
            "invalid_data",
            {
              "reason": "measurement name 'Total Blocking Time' can contain only characters a-z0-9._"
            }
          ]
        ]
      },
      "fp": {
        "value": {
          "": {
            "err": [
              [
                "invalid_data",
                {
                  "reason": "expected a floating point number"
                }
              ]
            ],
            "val": "im a first paint"
          }
        }
      },
      "missing_value": {
        "": {
          "err": [
            [
              "invalid_data",
              {
                "reason": "expected measurement"
              }
            ]
          ],
          "val": "string"
        }
      }
    }
  }
}"#;

        let mut measurements = Annotated::new(Measurements({
            let mut measurements = Object::new();
            measurements.insert(
                "cls".to_owned(),
                Annotated::new(Measurement {
                    value: Annotated::empty(),
                    unit: Annotated::empty(),
                }),
            );
            measurements.insert(
                "lcp".to_owned(),
                Annotated::new(Measurement {
                    value: Annotated::new(420.69),
                    unit: Annotated::new(MetricUnit::Duration(DurationUnit::MilliSecond)),
                }),
            );
            measurements.insert(
                "fid".to_owned(),
                Annotated::new(Measurement {
                    value: Annotated::new(2020f64),
                    unit: Annotated::empty(),
                }),
            );
            measurements.insert(
                "inp".to_owned(),
                Annotated::new(Measurement {
                    value: Annotated::new(100.14),
                    unit: Annotated::empty(),
                }),
            );
            measurements.insert(
                "fp".to_owned(),
                Annotated::new(Measurement {
                    value: Annotated::from_error(
                        Error::expected("a floating point number"),
                        Some("im a first paint".into()),
                    ),
                    unit: Annotated::empty(),
                }),
            );

            measurements.insert(
                "missing_value".to_owned(),
                Annotated::from_error(Error::expected("measurement"), Some("string".into())),
            );

            measurements
        }));

        let measurements_meta = measurements.meta_mut();

        measurements_meta.add_error(Error::invalid("measurement name '' cannot be empty"));

        measurements_meta.add_error(Error::invalid(
            "measurement name 'lcp_final.element-Size123' can contain only characters a-z0-9._",
        ));

        measurements_meta.add_error(Error::invalid(
            "measurement name 'Total Blocking Time' can contain only characters a-z0-9._",
        ));

        let event = Annotated::new(Event {
            measurements,
            ..Default::default()
        });

        assert_eq!(event, Annotated::from_json(input).unwrap());
        assert_eq!(event.to_json_pretty().unwrap(), output);
    }
}