Skip to main content

relay_event_normalization/normalize/
mod.rs

1use std::hash::Hash;
2use std::{collections::HashMap, sync::LazyLock};
3
4use regex::Regex;
5use relay_base_schema::metrics::MetricUnit;
6use relay_event_schema::protocol::VALID_PLATFORMS;
7use relay_pattern::{Gas, Pattern};
8use relay_protocol::{FiniteF64, RuleCondition};
9use serde::{Deserialize, Serialize};
10
11pub mod breakdowns;
12pub mod contexts;
13pub mod nel;
14pub mod request;
15pub mod span;
16pub mod user_agent;
17pub mod utils;
18
19/// Defines a builtin measurement.
20#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Hash, Eq)]
21#[serde(default, rename_all = "camelCase")]
22pub struct BuiltinMeasurementKey {
23    name: String,
24    unit: MetricUnit,
25    #[serde(skip_serializing_if = "is_false")]
26    allow_negative: bool,
27}
28
29fn is_false(b: &bool) -> bool {
30    !b
31}
32
33impl BuiltinMeasurementKey {
34    /// Creates a new [`BuiltinMeasurementKey`].
35    pub fn new(name: impl Into<String>, unit: MetricUnit) -> Self {
36        Self {
37            name: name.into(),
38            unit,
39            allow_negative: false,
40        }
41    }
42
43    /// Returns the name of the built in measurement key.
44    pub fn name(&self) -> &str {
45        &self.name
46    }
47
48    /// Returns the unit of the built in measurement key.
49    pub fn unit(&self) -> &MetricUnit {
50        &self.unit
51    }
52
53    /// Return true if the built in measurement key allows negative values.
54    pub fn allow_negative(&self) -> &bool {
55        &self.allow_negative
56    }
57}
58
59/// Configuration for measurements normalization.
60#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Hash)]
61#[serde(default, rename_all = "camelCase")]
62pub struct MeasurementsConfig {
63    /// A list of measurements that are built-in and are not subject to custom measurement limits.
64    #[serde(default, skip_serializing_if = "Vec::is_empty")]
65    pub builtin_measurements: Vec<BuiltinMeasurementKey>,
66
67    /// The maximum number of measurements allowed per event that are not known measurements.
68    pub max_custom_measurements: usize,
69}
70
71impl MeasurementsConfig {
72    /// The length of a full measurement MRI, minus the name and the unit. This length is the same
73    /// for every measurement-mri.
74    pub const MEASUREMENT_MRI_OVERHEAD: usize = 29;
75}
76
77/// Returns `true` if the given platform string is a known platform identifier.
78///
79/// See [`VALID_PLATFORMS`] for a list of all known platforms.
80pub fn is_valid_platform(platform: &str) -> bool {
81    VALID_PLATFORMS.contains(&platform)
82}
83
84/// Container for global and project level [`MeasurementsConfig`]. The purpose is to handle
85/// the merging logic.
86#[derive(Copy, Clone, Debug)]
87pub struct CombinedMeasurementsConfig<'a> {
88    project: Option<&'a MeasurementsConfig>,
89    global: Option<&'a MeasurementsConfig>,
90}
91
92impl<'a> CombinedMeasurementsConfig<'a> {
93    /// Constructor for [`CombinedMeasurementsConfig`].
94    pub fn new(
95        project: Option<&'a MeasurementsConfig>,
96        global: Option<&'a MeasurementsConfig>,
97    ) -> Self {
98        CombinedMeasurementsConfig { project, global }
99    }
100
101    /// Returns an iterator over the merged builtin measurement keys.
102    ///
103    /// Items from the project config are prioritized over global config, and
104    /// there are no duplicates.
105    pub fn builtin_measurement_keys(
106        &'a self,
107    ) -> impl Iterator<Item = &'a BuiltinMeasurementKey> + 'a {
108        let project = self
109            .project
110            .map(|p| p.builtin_measurements.as_slice())
111            .unwrap_or_default();
112
113        let global = self
114            .global
115            .map(|g| g.builtin_measurements.as_slice())
116            .unwrap_or_default();
117
118        project
119            .iter()
120            .chain(global.iter().filter(|key| !project.contains(key)))
121    }
122
123    /// Gets the max custom measurements value from the [`MeasurementsConfig`] from project level or
124    /// global level. If both of them are available, it will choose the most restrictive.
125    pub fn max_custom_measurements(&'a self) -> Option<usize> {
126        match (&self.project, &self.global) {
127            (None, None) => None,
128            (None, Some(global)) => Some(global.max_custom_measurements),
129            (Some(project), None) => Some(project.max_custom_measurements),
130            (Some(project), Some(global)) => Some(std::cmp::min(
131                project.max_custom_measurements,
132                global.max_custom_measurements,
133            )),
134        }
135    }
136}
137
138/// Defines a weighted component for a performance score.
139///
140/// Weight is the % of score it can take up (eg. LCP is a max of 35% weight for desktops)
141/// Currently also contains (p10, p50) which are used for log CDF normalization of the weight score
142#[derive(Debug, Default, Clone, Serialize, Deserialize)]
143pub struct PerformanceScoreWeightedComponent {
144    /// Measurement (eg. measurements.lcp) to be matched against. If this measurement is missing the entire
145    /// profile will be discarded.
146    pub measurement: String,
147    /// Weight [0,1.0] of this component in the performance score
148    pub weight: FiniteF64,
149    /// p10 used to define the log-normal for calculation
150    pub p10: FiniteF64,
151    /// Median used to define the log-normal for calculation
152    pub p50: FiniteF64,
153    /// Whether the measurement is optional. If the measurement is missing, performance score processing
154    /// may still continue, and the weight will be 0.
155    #[serde(default)]
156    pub optional: bool,
157}
158
159/// Defines a profile for performance score.
160///
161/// A profile contains weights for a score of 100% and match against an event using a condition.
162/// eg. Desktop vs. Mobile(web) profiles for better web vital score calculation.
163#[derive(Debug, Default, Clone, Serialize, Deserialize)]
164#[serde(rename_all = "camelCase")]
165pub struct PerformanceScoreProfile {
166    /// Name of the profile, used for debugging and faceting multiple profiles
167    pub name: Option<String>,
168    /// Score components
169    #[serde(default, skip_serializing_if = "Vec::is_empty")]
170    pub score_components: Vec<PerformanceScoreWeightedComponent>,
171    /// See [`RuleCondition`] for all available options to specify and combine conditions.
172    pub condition: Option<RuleCondition>,
173    /// The version of the profile, used to isolate changes to score calculations.
174    #[serde(skip_serializing_if = "Option::is_none")]
175    pub version: Option<String>,
176}
177
178/// Defines the performance configuration for the project.
179///
180/// Includes profiles matching different behaviour (desktop / mobile) and weights matching those
181/// specific conditions.
182#[derive(Debug, Default, Clone, Serialize, Deserialize)]
183pub struct PerformanceScoreConfig {
184    /// List of performance profiles, only the first with matching conditions will be applied.
185    #[serde(default, skip_serializing_if = "Vec::is_empty")]
186    pub profiles: Vec<PerformanceScoreProfile>,
187}
188
189/// Regex that matches version and/or date patterns at the end of a model name.
190///
191/// Examples matched:
192/// - "-20250805-v1:0" in "claude-opus-4-1-20250805-v1:0" (both)
193/// - "-20250514-v1:0" in "claude-sonnet-4-20250514-v1:0" (both)
194/// - "_v2" in "model_v2" (version only)
195/// - "-v1.0" in "gpt-4-v1.0" (version only)
196/// - "-20250522" in "claude-4-sonnet-20250522" (date only)
197/// - "-2025-06-10" in "o3-pro-2025-06-10" (date only)
198/// - "@20241022" in "claude-3-5-haiku@20241022" (date only)
199static VERSION_AND_DATE_REGEX: LazyLock<Regex> = LazyLock::new(|| {
200    Regex::new(
201        r"(?x)
202        (
203            ([-_@])                                    # Required separator before date (-, _, or @)
204            (\d{4}[-/.]\d{2}[-/.]\d{2}|\d{8})          # Date: YYYY-MM-DD/YYYY/MM/DD/YYYY.MM.DD or YYYYMMDD
205        )?                                              # Date is optional
206        (
207            [-_]                                        # Required separator before version (- or _)
208            v\d+[:.]?\d*                                # Version: v1, v1.0, v1:0
209            ([-:].*)?                                   # Optional trailing content
210        )?                                              # Version is optional
211        $  # Must be at the end of the string
212        ",
213    )
214    .unwrap()
215});
216
217/// Normalizes an AI model name by stripping date and version patterns.
218///
219/// This function converts specific model versions into normalized names suitable for matching
220/// against cost configurations, ensuring that different versions of the same model can share
221/// cost information.
222///
223/// The normalization strips version and/or date patterns from the end of the string in a single pass.
224///
225/// Examples:
226/// - "claude-4-sonnet-20250522" -> "claude-4-sonnet"
227/// - "o3-pro-2025-06-10" -> "o3-pro"
228/// - "claude-3-5-haiku@20241022" -> "claude-3-5-haiku"
229/// - "claude-opus-4-1-20250805-v1:0" -> "claude-opus-4-1"
230/// - "us.anthropic.claude-sonnet-4-20250514-v1:0" -> "us.anthropic.claude-sonnet-4"
231/// - "gpt-4-v1.0" -> "gpt-4"
232/// - "gpt-4-v1:0" -> "gpt-4"
233/// - "model_v2" -> "model"
234///
235/// Version patterns:
236/// - Must start with 'v': v1, v1.0, v1:0 (requires -, _ separator)
237///
238/// Date patterns:
239/// - YYYYMMDD: 20250522
240/// - YYYY-MM-DD, YYYY/MM/DD, YYYY.MM.DD: 2025-06-10
241///
242/// Args:
243///     model_id: The original model ID
244///
245/// Returns:
246///     The normalized model name without date and version patterns
247fn normalize_ai_model_name(model_id: &str) -> &str {
248    if let Some(captures) = VERSION_AND_DATE_REGEX.captures(model_id) {
249        let match_idx = captures.get(0).map(|m| m.start()).unwrap_or(model_id.len());
250        &model_id[..match_idx]
251    } else {
252        model_id
253    }
254}
255
256/// Version 2 of a mapping of AI model types (like GPT-4) to their respective costs.
257#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq)]
258#[serde(rename_all = "camelCase")]
259pub struct ModelCostV2 {
260    /// The cost per input token
261    pub input_per_token: f64,
262    /// The cost per output token
263    pub output_per_token: f64,
264    /// The cost per output reasoning token
265    pub output_reasoning_per_token: f64,
266    /// The cost per input cached token
267    pub input_cached_per_token: f64,
268    /// The cost per input cache write token
269    pub input_cache_write_per_token: f64,
270}
271
272/// Metadata for AI models including costs and context size.
273///
274/// Example JSON:
275/// ```json
276/// {
277///   "version": 1,
278///   "models": {
279///     "gpt-4": {
280///       "costs": {
281///         "inputPerToken": 0.0000003,
282///         "outputPerToken": 0.00000165,
283///         "outputReasoningPerToken": 0.0,
284///         "inputCachedPerToken": 0.0000015,
285///         "inputCacheWritePerToken": 0.00001875
286///       },
287///       "contextSize": 1000000
288///     }
289///   }
290/// }
291/// ```
292#[derive(Clone, Default, Debug, Serialize, Deserialize)]
293#[serde(rename_all = "camelCase")]
294pub struct ModelMetadata {
295    /// The version of the model metadata struct.
296    pub version: u16,
297
298    /// The mappings of model ID => metadata as a dictionary.
299    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
300    pub models: HashMap<ModelPattern, ModelMetadataEntry>,
301}
302
303impl ModelMetadata {
304    const SUPPORTED_VERSION: u16 = 1;
305
306    /// `true` if the model metadata is empty or the version is unsupported.
307    pub fn is_empty(&self) -> bool {
308        self.models.is_empty() || !self.is_enabled()
309    }
310
311    /// `false` if the version is unsupported.
312    pub fn is_enabled(&self) -> bool {
313        self.version == Self::SUPPORTED_VERSION
314    }
315
316    /// Gets the cost per token for a given model, if defined.
317    pub fn cost_per_token(&self, model_id: &str) -> Option<&ModelCostV2> {
318        self.get(model_id).and_then(|entry| entry.costs.as_ref())
319    }
320
321    /// Gets the context window size for a given model, if defined.
322    ///
323    /// Returns `None` for a zero context size, as it is not a meaningful value.
324    pub fn context_size(&self, model_id: &str) -> Option<u64> {
325        self.get(model_id)
326            .and_then(|entry| entry.context_size)
327            .filter(|&size| size > 0)
328    }
329
330    /// Gets the metadata for a given model, if defined.
331    pub fn get(&self, model_id: &str) -> Option<&ModelMetadataEntry> {
332        if !self.is_enabled() {
333            return None;
334        }
335
336        let normalized_model_id = normalize_ai_model_name(model_id);
337
338        // First try exact match.
339        if let Some(value) = self.models.get(normalized_model_id) {
340            return Some(value);
341        }
342
343        // Fall back to glob matching.
344        self.models.iter().find_map(|(key, value)| {
345            if key.is_match(normalized_model_id) {
346                Some(value)
347            } else {
348                None
349            }
350        })
351    }
352}
353
354/// A [`Pattern`] which remembers its original pattern and can be stored in a hash-map.
355#[derive(Debug, Clone)]
356pub struct ModelPattern {
357    original: Box<str>,
358    pattern: Pattern,
359}
360
361impl ModelPattern {
362    /// Returns `true` if the pattern matches the passed string.
363    pub fn is_match(&self, haystack: &str) -> bool {
364        // Patterns are expected to be safe and not user controlled.
365        self.pattern.is_match(haystack, Gas::MAX).unwrap_or(false)
366    }
367}
368
369impl std::cmp::PartialEq for ModelPattern {
370    fn eq(&self, other: &Self) -> bool {
371        self.original == other.original
372    }
373}
374
375impl std::cmp::Eq for ModelPattern {}
376
377impl std::hash::Hash for ModelPattern {
378    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
379        self.original.hash(state);
380    }
381}
382
383impl std::borrow::Borrow<str> for ModelPattern {
384    fn borrow(&self) -> &str {
385        &self.original
386    }
387}
388
389impl std::str::FromStr for ModelPattern {
390    type Err = relay_pattern::Error;
391
392    fn from_str(s: &str) -> Result<Self, Self::Err> {
393        Ok(Self {
394            original: s.into(),
395            pattern: Pattern::new(s)?,
396        })
397    }
398}
399
400impl<'de> serde::de::Deserialize<'de> for ModelPattern {
401    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
402    where
403        D: serde::Deserializer<'de>,
404    {
405        let original = Box::<str>::deserialize(deserializer)?;
406        let pattern = Pattern::new(&original).map_err(serde::de::Error::custom)?;
407
408        Ok(Self { original, pattern })
409    }
410}
411
412impl serde::ser::Serialize for ModelPattern {
413    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
414    where
415        S: serde::Serializer,
416    {
417        serializer.serialize_str(&self.original)
418    }
419}
420
421/// Metadata for a single AI model.
422#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq)]
423#[serde(rename_all = "camelCase")]
424pub struct ModelMetadataEntry {
425    /// Token costs for this model.
426    #[serde(default, skip_serializing_if = "Option::is_none")]
427    pub costs: Option<ModelCostV2>,
428
429    /// The context window size in tokens.
430    #[serde(default, skip_serializing_if = "Option::is_none")]
431    pub context_size: Option<u64>,
432}
433
434#[cfg(test)]
435mod tests {
436    use chrono::{TimeZone, Utc};
437    use insta::{assert_debug_snapshot, assert_json_snapshot};
438    use itertools::Itertools;
439    use relay_base_schema::events::EventType;
440    use relay_base_schema::metrics::DurationUnit;
441    use relay_base_schema::spans::SpanStatus;
442    use relay_event_schema::protocol::{
443        ClientSdkInfo, Context, ContextInner, Contexts, DebugImage, DebugMeta, Event, EventId,
444        Exception, Frame, Geo, IpAddr, LenientString, Level, LogEntry, PairList, RawStacktrace,
445        ReplayContext, Request, Span, Stacktrace, TagEntry, Tags, TraceContext, User, Values,
446    };
447    use relay_protocol::{
448        Annotated, Error, ErrorKind, FromValue, Object, SerializableAnnotated, Value,
449        assert_annotated_snapshot, get_path, get_value,
450    };
451    use serde_json::json;
452    use similar_asserts::assert_eq;
453    use uuid::Uuid;
454
455    use crate::stacktrace::normalize_non_raw_frame;
456    use crate::validation::validate_event;
457    use crate::{EventValidationConfig, GeoIpLookup, NormalizationConfig, normalize_event};
458
459    use super::*;
460
461    #[test]
462    fn test_normalize_ai_model_name() {
463        // Test date patterns
464        assert_eq!(
465            normalize_ai_model_name("claude-4-sonnet-20250522"),
466            "claude-4-sonnet"
467        );
468        assert_eq!(normalize_ai_model_name("o3-pro-2025-06-10"), "o3-pro");
469        assert_eq!(
470            normalize_ai_model_name("claude-3-5-haiku@20241022"),
471            "claude-3-5-haiku"
472        );
473
474        // Test date with version patterns
475        assert_eq!(
476            normalize_ai_model_name("claude-opus-4-1-20250805-v1:0"),
477            "claude-opus-4-1"
478        );
479        assert_eq!(
480            normalize_ai_model_name("us.anthropic.claude-sonnet-4-20250514-v1:0"),
481            "us.anthropic.claude-sonnet-4"
482        );
483
484        // Test standalone version patterns with 'v' prefix
485        assert_eq!(normalize_ai_model_name("gpt-4-v1.0"), "gpt-4");
486        assert_eq!(normalize_ai_model_name("gpt-4-v1:0"), "gpt-4");
487        assert_eq!(normalize_ai_model_name("gpt-4-v1"), "gpt-4");
488        assert_eq!(normalize_ai_model_name("model_v2"), "model");
489
490        // Test that version patterns WITHOUT 'v' prefix are NOT stripped
491        assert_eq!(normalize_ai_model_name("gpt-4.5"), "gpt-4.5");
492
493        // Test that if version without 'v' comes after date, nothing is stripped
494        // (date regex requires end of string, so date won't match if followed by version)
495        assert_eq!(
496            normalize_ai_model_name("anthropic.claude-3-5-sonnet-20241022-v2:0"),
497            "anthropic.claude-3-5-sonnet"
498        );
499
500        // Test no pattern (should return original)
501        assert_eq!(normalize_ai_model_name("gpt-4"), "gpt-4");
502        assert_eq!(normalize_ai_model_name("claude-3-opus"), "claude-3-opus");
503    }
504
505    #[test]
506    fn test_merge_builtin_measurement_keys() {
507        let foo = BuiltinMeasurementKey::new("foo", MetricUnit::Duration(DurationUnit::Hour));
508        let bar = BuiltinMeasurementKey::new("bar", MetricUnit::Duration(DurationUnit::Day));
509        let baz = BuiltinMeasurementKey::new("baz", MetricUnit::Duration(DurationUnit::Week));
510
511        let proj = MeasurementsConfig {
512            builtin_measurements: vec![foo.clone(), bar.clone()],
513            max_custom_measurements: 4,
514        };
515
516        let glob = MeasurementsConfig {
517            // The 'bar' here will be ignored since it's a duplicate from the project level.
518            builtin_measurements: vec![baz.clone(), bar.clone()],
519            max_custom_measurements: 4,
520        };
521        let dynamic_config = CombinedMeasurementsConfig::new(Some(&proj), Some(&glob));
522
523        let keys = dynamic_config.builtin_measurement_keys().collect_vec();
524
525        assert_eq!(keys, vec![&foo, &bar, &baz]);
526    }
527
528    #[test]
529    fn test_max_custom_measurement() {
530        // Empty configs will return a None value for max measurements.
531        let dynamic_config = CombinedMeasurementsConfig::new(None, None);
532        assert!(dynamic_config.max_custom_measurements().is_none());
533
534        let proj = MeasurementsConfig {
535            builtin_measurements: vec![],
536            max_custom_measurements: 3,
537        };
538
539        let glob = MeasurementsConfig {
540            builtin_measurements: vec![],
541            max_custom_measurements: 4,
542        };
543
544        // If only project level measurement config is there, return its max custom measurement variable.
545        let dynamic_config = CombinedMeasurementsConfig::new(Some(&proj), None);
546        assert_eq!(dynamic_config.max_custom_measurements().unwrap(), 3);
547
548        // Same logic for when only global level measurement config exists.
549        let dynamic_config = CombinedMeasurementsConfig::new(None, Some(&glob));
550        assert_eq!(dynamic_config.max_custom_measurements().unwrap(), 4);
551
552        // If both is available, pick the smallest number.
553        let dynamic_config = CombinedMeasurementsConfig::new(Some(&proj), Some(&glob));
554        assert_eq!(dynamic_config.max_custom_measurements().unwrap(), 3);
555    }
556
557    #[test]
558    fn test_geo_from_ip_address() {
559        let lookup = GeoIpLookup::open("tests/fixtures/GeoIP2-Enterprise-Test.mmdb").unwrap();
560
561        let json = r#"{
562            "user": {
563                "ip_address": "2.125.160.216"
564            }
565        }"#;
566        let mut event = Annotated::<Event>::from_json(json).unwrap();
567
568        normalize_event(
569            &mut event,
570            &NormalizationConfig {
571                geoip_lookup: Some(&lookup),
572                ..Default::default()
573            },
574        );
575
576        let expected = Annotated::new(Geo {
577            country_code: Annotated::new("GB".to_owned()),
578            city: Annotated::new("Boxford".to_owned()),
579            subdivision: Annotated::new("England".to_owned()),
580            region: Annotated::new("United Kingdom".to_owned()),
581            ..Geo::default()
582        });
583        assert_eq!(get_value!(event.user!).geo, expected);
584    }
585
586    #[test]
587    fn test_user_ip_from_remote_addr() {
588        let mut event = Annotated::new(Event {
589            request: Annotated::from(Request {
590                env: Annotated::new({
591                    let mut map = Object::new();
592                    map.insert(
593                        "REMOTE_ADDR".to_owned(),
594                        Annotated::new(Value::String("2.125.160.216".to_owned())),
595                    );
596                    map
597                }),
598                ..Request::default()
599            }),
600            platform: Annotated::new("javascript".to_owned()),
601            ..Event::default()
602        });
603
604        normalize_event(&mut event, &NormalizationConfig::default());
605
606        let ip_addr = get_value!(event.user.ip_address!);
607        assert_eq!(ip_addr, &IpAddr("2.125.160.216".to_owned()));
608    }
609
610    #[test]
611    fn test_user_ip_and_span_tags_with_auto_ip() {
612        let client_ip = IpAddr::parse("203.0.113.1").unwrap();
613        let remote_ip = "2001:db8::1";
614        for (remote, client, infer_ip, expected) in [
615            // A concrete REMOTE_ADDR takes precedence over the connection IP.
616            (remote_ip, Some(&client_ip), "auto", Some(remote_ip)),
617            // An explicit placeholder opts into inference even in legacy mode.
618            (
619                "{{auto}}",
620                Some(&client_ip),
621                "legacy",
622                Some(client_ip.as_str()),
623            ),
624            // Inference is enabled, but there is no address to use.
625            ("{{auto}}", None, "auto", None),
626            // The SDK disables inference even though a connection IP is available.
627            ("{{auto}}", Some(&client_ip), "never", None),
628        ] {
629            let payload = json!({
630                "type": "transaction",
631                "start_timestamp": 1700000000,
632                "timestamp": 1700000001,
633                "contexts": {"trace": {
634                    "trace_id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
635                    "span_id": "bbbbbbbbbbbbbbbb"
636                }},
637                "sdk": {"settings": {"infer_ip": infer_ip}},
638                "request": {"env": {"REMOTE_ADDR": remote}},
639                "user": {"ip_address": "{{auto}}"},
640                "spans": [{
641                    "trace_id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
642                    "span_id": "cccccccccccccccc",
643                    "parent_span_id": "bbbbbbbbbbbbbbbb",
644                    "start_timestamp": 1700000000,
645                    "timestamp": 1700000001
646                }]
647            });
648            let mut event = Annotated::<Event>::from_json(&payload.to_string()).unwrap();
649            normalize_event(
650                &mut event,
651                &NormalizationConfig {
652                    client_ip: client,
653                    enrich_spans: true,
654                    ..Default::default()
655                },
656            );
657
658            let env = get_value!(event.request.env!);
659            assert_eq!(
660                env.get("REMOTE_ADDR").map(|v| v.as_str().unwrap()),
661                expected
662            );
663            assert_eq!(
664                get_value!(event.user.ip_address).map(IpAddr::as_str),
665                expected
666            );
667            let tags = get_value!(event.spans[0].sentry_tags!);
668            assert_eq!(tags.user_ip.as_str(), expected);
669            assert_eq!(
670                tags.user.value(),
671                expected.map(|ip| format!("ip:{ip}")).as_ref()
672            );
673        }
674    }
675
676    #[test]
677    fn test_user_ip_from_invalid_remote_addr() {
678        let mut event = Annotated::new(Event {
679            request: Annotated::from(Request {
680                env: Annotated::new({
681                    let mut map = Object::new();
682                    map.insert(
683                        "REMOTE_ADDR".to_owned(),
684                        Annotated::new(Value::String("whoops".to_owned())),
685                    );
686                    map
687                }),
688                ..Request::default()
689            }),
690            platform: Annotated::new("javascript".to_owned()),
691            ..Event::default()
692        });
693
694        normalize_event(&mut event, &NormalizationConfig::default());
695
696        assert_eq!(Annotated::empty(), event.value().unwrap().user);
697    }
698
699    #[test]
700    fn test_user_ip_from_client_ip_without_auto() {
701        let mut event = Annotated::new(Event {
702            platform: Annotated::new("javascript".to_owned()),
703            ..Default::default()
704        });
705
706        let ip_address = IpAddr::parse("2.125.160.216").unwrap();
707
708        normalize_event(
709            &mut event,
710            &NormalizationConfig {
711                client_ip: Some(&ip_address),
712                infer_ip_address: true,
713                ..Default::default()
714            },
715        );
716
717        let ip_addr = get_value!(event.user.ip_address!);
718        assert_eq!(ip_addr, &IpAddr("2.125.160.216".to_owned()));
719    }
720
721    #[test]
722    fn test_user_ip_from_client_ip_with_auto() {
723        let mut event = Annotated::new(Event {
724            user: Annotated::new(User {
725                ip_address: Annotated::new(IpAddr::auto()),
726                ..Default::default()
727            }),
728            ..Default::default()
729        });
730
731        let ip_address = IpAddr::parse("2.125.160.216").unwrap();
732
733        let geo = GeoIpLookup::open("tests/fixtures/GeoIP2-Enterprise-Test.mmdb").unwrap();
734        normalize_event(
735            &mut event,
736            &NormalizationConfig {
737                client_ip: Some(&ip_address),
738                geoip_lookup: Some(&geo),
739                infer_ip_address: true,
740                ..Default::default()
741            },
742        );
743
744        let user = get_value!(event.user!);
745        let ip_addr = user.ip_address.value().expect("ip address missing");
746
747        assert_eq!(ip_addr, &IpAddr("2.125.160.216".to_owned()));
748        assert!(user.geo.value().is_some());
749    }
750
751    #[test]
752    fn test_user_ip_from_client_ip_without_appropriate_platform() {
753        let mut event = Annotated::new(Event::default());
754
755        let ip_address = IpAddr::parse("2.125.160.216").unwrap();
756        let geo = GeoIpLookup::open("tests/fixtures/GeoIP2-Enterprise-Test.mmdb").unwrap();
757        normalize_event(
758            &mut event,
759            &NormalizationConfig {
760                client_ip: Some(&ip_address),
761                geoip_lookup: Some(&geo),
762                ..Default::default()
763            },
764        );
765
766        let user = get_value!(event.user!);
767        assert!(user.ip_address.value().is_none());
768        assert!(user.geo.value().is_some());
769    }
770
771    #[test]
772    fn test_geo_present_if_ip_inferring_disabled() {
773        let mut event = Annotated::new(Event {
774            user: Annotated::new(User {
775                ip_address: Annotated::new(IpAddr::auto()),
776                ..Default::default()
777            }),
778            ..Default::default()
779        });
780
781        let ip_address = IpAddr::parse("2.125.160.216").unwrap();
782        let geo = GeoIpLookup::open("tests/fixtures/GeoIP2-Enterprise-Test.mmdb").unwrap();
783
784        normalize_event(
785            &mut event,
786            &NormalizationConfig {
787                client_ip: Some(&ip_address),
788                geoip_lookup: Some(&geo),
789                infer_ip_address: false,
790                ..Default::default()
791            },
792        );
793
794        let user = get_value!(event.user!);
795        assert!(user.ip_address.value().is_none());
796        assert!(user.geo.value().is_some());
797    }
798
799    #[test]
800    fn test_geo_and_ip_present_if_ip_inferring_enabled() {
801        let mut event = Annotated::new(Event {
802            user: Annotated::new(User {
803                ip_address: Annotated::new(IpAddr::auto()),
804                ..Default::default()
805            }),
806            ..Default::default()
807        });
808
809        let ip_address = IpAddr::parse("2.125.160.216").unwrap();
810        let geo = GeoIpLookup::open("tests/fixtures/GeoIP2-Enterprise-Test.mmdb").unwrap();
811
812        normalize_event(
813            &mut event,
814            &NormalizationConfig {
815                client_ip: Some(&ip_address),
816                geoip_lookup: Some(&geo),
817                infer_ip_address: true,
818                ..Default::default()
819            },
820        );
821
822        let user = get_value!(event.user!);
823        assert_eq!(
824            user.ip_address.value(),
825            Some(&IpAddr::parse("2.125.160.216").unwrap())
826        );
827        assert!(user.geo.value().is_some());
828    }
829
830    #[test]
831    fn test_event_level_defaulted() {
832        let mut event = Annotated::new(Event::default());
833        normalize_event(&mut event, &NormalizationConfig::default());
834        assert_eq!(get_value!(event.level), Some(&Level::Error));
835    }
836
837    #[test]
838    fn test_transaction_level_untouched() {
839        let mut event = Annotated::new(Event {
840            ty: Annotated::new(EventType::Transaction),
841            timestamp: Annotated::new(Utc.with_ymd_and_hms(1987, 6, 5, 4, 3, 2).unwrap().into()),
842            start_timestamp: Annotated::new(
843                Utc.with_ymd_and_hms(1987, 6, 5, 4, 3, 2).unwrap().into(),
844            ),
845            contexts: {
846                let mut contexts = Contexts::new();
847                contexts.add(TraceContext {
848                    trace_id: Annotated::new("4c79f60c11214eb38604f4ae0781bfb2".parse().unwrap()),
849                    span_id: Annotated::new("fa90fdead5f74053".parse().unwrap()),
850                    op: Annotated::new("http.server".to_owned()),
851                    ..Default::default()
852                });
853                Annotated::new(contexts)
854            },
855            ..Event::default()
856        });
857        normalize_event(&mut event, &NormalizationConfig::default());
858        assert_eq!(get_value!(event.level), Some(&Level::Info));
859    }
860
861    #[test]
862    fn test_environment_tag_is_moved() {
863        let mut event = Annotated::new(Event {
864            tags: Annotated::new(Tags(PairList(vec![Annotated::new(TagEntry(
865                Annotated::new("environment".to_owned()),
866                Annotated::new("despacito".to_owned()),
867            ))]))),
868            ..Event::default()
869        });
870
871        normalize_event(&mut event, &NormalizationConfig::default());
872
873        let event = event.value().unwrap();
874
875        assert_eq!(event.environment.as_str(), Some("despacito"));
876        assert_eq!(event.tags.value(), Some(&Tags(vec![].into())));
877    }
878
879    #[test]
880    fn test_empty_environment_is_removed_and_overwritten_with_tag() {
881        let mut event = Annotated::new(Event {
882            tags: Annotated::new(Tags(PairList(vec![Annotated::new(TagEntry(
883                Annotated::new("environment".to_owned()),
884                Annotated::new("despacito".to_owned()),
885            ))]))),
886            environment: Annotated::new("".to_owned()),
887            ..Event::default()
888        });
889
890        normalize_event(&mut event, &NormalizationConfig::default());
891
892        let event = event.value().unwrap();
893
894        assert_eq!(event.environment.as_str(), Some("despacito"));
895        assert_eq!(event.tags.value(), Some(&Tags(vec![].into())));
896    }
897
898    #[test]
899    fn test_empty_environment_is_removed() {
900        let mut event = Annotated::new(Event {
901            environment: Annotated::new("".to_owned()),
902            ..Event::default()
903        });
904
905        normalize_event(&mut event, &NormalizationConfig::default());
906        assert_eq!(get_value!(event.environment), None);
907    }
908    #[test]
909    fn test_replay_id_added_from_dsc() {
910        let replay_id = Uuid::new_v4();
911        let mut event = Annotated::new(Event {
912            contexts: Annotated::new(Contexts(Object::new())),
913            ..Event::default()
914        });
915        normalize_event(
916            &mut event,
917            &NormalizationConfig {
918                replay_id: Some(replay_id),
919                ..Default::default()
920            },
921        );
922
923        let event = event.value().unwrap();
924
925        assert_eq!(event.contexts, {
926            let mut contexts = Contexts::new();
927            contexts.add(ReplayContext {
928                replay_id: Annotated::new(EventId(replay_id)),
929                other: Object::default(),
930            });
931            Annotated::new(contexts)
932        })
933    }
934
935    #[test]
936    fn test_none_environment_errors() {
937        let mut event = Annotated::new(Event {
938            environment: Annotated::new("none".to_owned()),
939            ..Event::default()
940        });
941
942        normalize_event(&mut event, &NormalizationConfig::default());
943
944        let environment = get_path!(event.environment!);
945        let expected_original = &Value::String("none".to_owned());
946
947        assert_eq!(
948            environment.meta().iter_errors().collect::<Vec<&Error>>(),
949            vec![&Error::new(ErrorKind::InvalidData)],
950        );
951        assert_eq!(
952            environment.meta().original_value().unwrap(),
953            expected_original
954        );
955        assert_eq!(environment.value(), None);
956    }
957
958    #[test]
959    fn test_invalid_release_removed() {
960        let mut event = Annotated::new(Event {
961            release: Annotated::new(LenientString("Latest".to_owned())),
962            ..Event::default()
963        });
964
965        normalize_event(&mut event, &NormalizationConfig::default());
966
967        let release = get_path!(event.release!);
968        let expected_original = &Value::String("Latest".to_owned());
969
970        assert_eq!(
971            release.meta().iter_errors().collect::<Vec<&Error>>(),
972            vec![&Error::new(ErrorKind::InvalidData)],
973        );
974        assert_eq!(release.meta().original_value().unwrap(), expected_original);
975        assert_eq!(release.value(), None);
976    }
977
978    #[test]
979    fn test_top_level_keys_moved_into_tags() {
980        let mut event = Annotated::new(Event {
981            server_name: Annotated::new("foo".to_owned()),
982            site: Annotated::new("foo".to_owned()),
983            tags: Annotated::new(Tags(PairList(vec![
984                Annotated::new(TagEntry(
985                    Annotated::new("site".to_owned()),
986                    Annotated::new("old".to_owned()),
987                )),
988                Annotated::new(TagEntry(
989                    Annotated::new("server_name".to_owned()),
990                    Annotated::new("old".to_owned()),
991                )),
992            ]))),
993            ..Event::default()
994        });
995
996        normalize_event(&mut event, &NormalizationConfig::default());
997
998        assert_eq!(get_value!(event.site), None);
999        assert_eq!(get_value!(event.server_name), None);
1000
1001        assert_eq!(
1002            get_value!(event.tags!),
1003            &Tags(PairList(vec![
1004                Annotated::new(TagEntry(
1005                    Annotated::new("site".to_owned()),
1006                    Annotated::new("foo".to_owned()),
1007                )),
1008                Annotated::new(TagEntry(
1009                    Annotated::new("server_name".to_owned()),
1010                    Annotated::new("foo".to_owned()),
1011                )),
1012            ]))
1013        );
1014    }
1015
1016    #[test]
1017    fn test_internal_tags_removed() {
1018        let mut event = Annotated::new(Event {
1019            tags: Annotated::new(Tags(PairList(vec![
1020                Annotated::new(TagEntry(
1021                    Annotated::new("release".to_owned()),
1022                    Annotated::new("foo".to_owned()),
1023                )),
1024                Annotated::new(TagEntry(
1025                    Annotated::new("dist".to_owned()),
1026                    Annotated::new("foo".to_owned()),
1027                )),
1028                Annotated::new(TagEntry(
1029                    Annotated::new("user".to_owned()),
1030                    Annotated::new("foo".to_owned()),
1031                )),
1032                Annotated::new(TagEntry(
1033                    Annotated::new("filename".to_owned()),
1034                    Annotated::new("foo".to_owned()),
1035                )),
1036                Annotated::new(TagEntry(
1037                    Annotated::new("function".to_owned()),
1038                    Annotated::new("foo".to_owned()),
1039                )),
1040                Annotated::new(TagEntry(
1041                    Annotated::new("something".to_owned()),
1042                    Annotated::new("else".to_owned()),
1043                )),
1044            ]))),
1045            ..Event::default()
1046        });
1047
1048        normalize_event(&mut event, &NormalizationConfig::default());
1049
1050        assert_eq!(get_value!(event.tags!).len(), 1);
1051    }
1052
1053    #[test]
1054    fn test_empty_tags_removed() {
1055        let mut event = Annotated::new(Event {
1056            tags: Annotated::new(Tags(PairList(vec![
1057                Annotated::new(TagEntry(
1058                    Annotated::new("".to_owned()),
1059                    Annotated::new("foo".to_owned()),
1060                )),
1061                Annotated::new(TagEntry(
1062                    Annotated::new("foo".to_owned()),
1063                    Annotated::new("".to_owned()),
1064                )),
1065                Annotated::new(TagEntry(
1066                    Annotated::new("something".to_owned()),
1067                    Annotated::new("else".to_owned()),
1068                )),
1069            ]))),
1070            ..Event::default()
1071        });
1072
1073        normalize_event(&mut event, &NormalizationConfig::default());
1074
1075        assert_eq!(
1076            get_value!(event.tags!),
1077            &Tags(PairList(vec![
1078                Annotated::new(TagEntry(
1079                    Annotated::from_error(Error::nonempty(), None),
1080                    Annotated::new("foo".to_owned()),
1081                )),
1082                Annotated::new(TagEntry(
1083                    Annotated::new("foo".to_owned()),
1084                    Annotated::from_error(Error::nonempty(), None),
1085                )),
1086                Annotated::new(TagEntry(
1087                    Annotated::new("something".to_owned()),
1088                    Annotated::new("else".to_owned()),
1089                )),
1090            ]))
1091        );
1092    }
1093
1094    #[test]
1095    fn test_tags_deduplicated() {
1096        let mut event = Annotated::new(Event {
1097            tags: Annotated::new(Tags(PairList(vec![
1098                Annotated::new(TagEntry(
1099                    Annotated::new("foo".to_owned()),
1100                    Annotated::new("1".to_owned()),
1101                )),
1102                Annotated::new(TagEntry(
1103                    Annotated::new("bar".to_owned()),
1104                    Annotated::new("1".to_owned()),
1105                )),
1106                Annotated::new(TagEntry(
1107                    Annotated::new("foo".to_owned()),
1108                    Annotated::new("2".to_owned()),
1109                )),
1110                Annotated::new(TagEntry(
1111                    Annotated::new("bar".to_owned()),
1112                    Annotated::new("2".to_owned()),
1113                )),
1114                Annotated::new(TagEntry(
1115                    Annotated::new("foo".to_owned()),
1116                    Annotated::new("3".to_owned()),
1117                )),
1118            ]))),
1119            ..Event::default()
1120        });
1121
1122        normalize_event(&mut event, &NormalizationConfig::default());
1123
1124        // should keep the first occurrence of every tag
1125        assert_eq!(
1126            get_value!(event.tags!),
1127            &Tags(PairList(vec![
1128                Annotated::new(TagEntry(
1129                    Annotated::new("foo".to_owned()),
1130                    Annotated::new("1".to_owned()),
1131                )),
1132                Annotated::new(TagEntry(
1133                    Annotated::new("bar".to_owned()),
1134                    Annotated::new("1".to_owned()),
1135                )),
1136            ]))
1137        );
1138    }
1139
1140    #[test]
1141    fn test_transaction_status_defaulted_to_unknown() {
1142        let mut object = Object::new();
1143        let trace_context = TraceContext {
1144            // We assume the status to be null.
1145            status: Annotated::empty(),
1146            ..TraceContext::default()
1147        };
1148        object.insert(
1149            "trace".to_owned(),
1150            Annotated::new(ContextInner(Context::Trace(Box::new(trace_context)))),
1151        );
1152
1153        let mut event = Annotated::new(Event {
1154            contexts: Annotated::new(Contexts(object)),
1155            ..Event::default()
1156        });
1157        normalize_event(&mut event, &NormalizationConfig::default());
1158
1159        let event = event.value().unwrap();
1160
1161        let event_trace_context = event.context::<TraceContext>().unwrap();
1162        assert_eq!(
1163            event_trace_context.status,
1164            Annotated::new(SpanStatus::Unknown)
1165        )
1166    }
1167
1168    #[test]
1169    fn test_unknown_debug_image() {
1170        let mut event = Annotated::new(Event {
1171            debug_meta: Annotated::new(DebugMeta {
1172                images: Annotated::new(vec![Annotated::new(DebugImage::Other(Object::default()))]),
1173                ..DebugMeta::default()
1174            }),
1175            ..Event::default()
1176        });
1177
1178        normalize_event(&mut event, &NormalizationConfig::default());
1179
1180        assert_eq!(
1181            get_path!(event.debug_meta!),
1182            &Annotated::new(DebugMeta {
1183                images: Annotated::new(vec![Annotated::from_error(
1184                    Error::invalid("unsupported debug image type"),
1185                    Some(Value::Object(Object::default())),
1186                )]),
1187                ..DebugMeta::default()
1188            })
1189        );
1190    }
1191
1192    #[test]
1193    fn test_context_line_default() {
1194        let mut frame = Annotated::new(Frame {
1195            pre_context: Annotated::new(vec![Annotated::default(), Annotated::new("".to_owned())]),
1196            post_context: Annotated::new(vec![Annotated::new("".to_owned()), Annotated::default()]),
1197            ..Frame::default()
1198        });
1199
1200        normalize_non_raw_frame(&mut frame);
1201
1202        let frame = frame.value().unwrap();
1203        assert_eq!(frame.context_line.as_str(), Some(""));
1204    }
1205
1206    #[test]
1207    fn test_context_line_retain() {
1208        let mut frame = Annotated::new(Frame {
1209            pre_context: Annotated::new(vec![Annotated::default(), Annotated::new("".to_owned())]),
1210            post_context: Annotated::new(vec![Annotated::new("".to_owned()), Annotated::default()]),
1211            context_line: Annotated::new("some line".to_owned()),
1212            ..Frame::default()
1213        });
1214
1215        normalize_non_raw_frame(&mut frame);
1216
1217        let frame = frame.value().unwrap();
1218        assert_eq!(frame.context_line.as_str(), Some("some line"));
1219    }
1220
1221    #[test]
1222    fn test_frame_null_context_lines() {
1223        let mut frame = Annotated::new(Frame {
1224            pre_context: Annotated::new(vec![Annotated::default(), Annotated::new("".to_owned())]),
1225            post_context: Annotated::new(vec![Annotated::new("".to_owned()), Annotated::default()]),
1226            ..Frame::default()
1227        });
1228
1229        normalize_non_raw_frame(&mut frame);
1230
1231        assert_eq!(
1232            *get_value!(frame.pre_context!),
1233            vec![Annotated::new("".to_owned()), Annotated::new("".to_owned())],
1234        );
1235        assert_eq!(
1236            *get_value!(frame.post_context!),
1237            vec![Annotated::new("".to_owned()), Annotated::new("".to_owned())],
1238        );
1239    }
1240
1241    #[test]
1242    fn test_too_long_distribution() {
1243        let json = r#"{
1244  "event_id": "52df9022835246eeb317dbd739ccd059",
1245  "fingerprint": [
1246    "{{ default }}"
1247  ],
1248  "platform": "other",
1249  "dist": "52df9022835246eeb317dbd739ccd059-52df9022835246eeb317dbd739ccd059-52df9022835246eeb317dbd739ccd059"
1250}"#;
1251
1252        let mut event = Annotated::<Event>::from_json(json).unwrap();
1253
1254        normalize_event(&mut event, &NormalizationConfig::default());
1255
1256        let dist = &event.value().unwrap().dist;
1257        let result = &Annotated::<String>::from_error(
1258            Error::new(ErrorKind::ValueTooLong),
1259            Some(Value::String("52df9022835246eeb317dbd739ccd059-52df9022835246eeb317dbd739ccd059-52df9022835246eeb317dbd739ccd059".to_owned()))
1260        );
1261        assert_eq!(dist, result);
1262    }
1263
1264    #[test]
1265    fn test_regression_backfills_abs_path_even_when_moving_stacktrace() {
1266        let mut event = Annotated::new(Event {
1267            exceptions: Annotated::new(Values::new(vec![Annotated::new(Exception {
1268                ty: Annotated::new("FooDivisionError".to_owned()),
1269                value: Annotated::new("hi".to_owned().into()),
1270                ..Exception::default()
1271            })])),
1272            stacktrace: Annotated::new(
1273                RawStacktrace {
1274                    frames: Annotated::new(vec![Annotated::new(Frame {
1275                        module: Annotated::new("MyModule".to_owned()),
1276                        filename: Annotated::new("MyFilename".into()),
1277                        function: Annotated::new("Void FooBar()".to_owned()),
1278                        ..Frame::default()
1279                    })]),
1280                    ..RawStacktrace::default()
1281                }
1282                .into(),
1283            ),
1284            ..Event::default()
1285        });
1286
1287        normalize_event(&mut event, &NormalizationConfig::default());
1288
1289        assert_eq!(
1290            get_value!(event.exceptions.values[0].stacktrace!),
1291            &Stacktrace(RawStacktrace {
1292                frames: Annotated::new(vec![Annotated::new(Frame {
1293                    module: Annotated::new("MyModule".to_owned()),
1294                    filename: Annotated::new("MyFilename".into()),
1295                    abs_path: Annotated::new("MyFilename".into()),
1296                    function: Annotated::new("Void FooBar()".to_owned()),
1297                    ..Frame::default()
1298                })]),
1299                ..RawStacktrace::default()
1300            })
1301        );
1302    }
1303
1304    #[test]
1305    fn test_parses_sdk_info_from_header() {
1306        let mut event = Annotated::new(Event::default());
1307
1308        normalize_event(
1309            &mut event,
1310            &NormalizationConfig {
1311                client: Some("_fooBar/0.0.0".to_owned()),
1312                ..Default::default()
1313            },
1314        );
1315
1316        assert_eq!(
1317            get_path!(event.client_sdk!),
1318            &Annotated::new(ClientSdkInfo {
1319                name: Annotated::new("_fooBar".to_owned()),
1320                version: Annotated::new("0.0.0".to_owned()),
1321                ..ClientSdkInfo::default()
1322            })
1323        );
1324    }
1325
1326    #[test]
1327    fn test_discards_received() {
1328        let mut event = Annotated::new(Event {
1329            received: FromValue::from_value(Annotated::new(Value::U64(696_969_696_969))),
1330            ..Default::default()
1331        });
1332
1333        validate_event(&mut event, &EventValidationConfig::default()).unwrap();
1334        normalize_event(&mut event, &NormalizationConfig::default());
1335
1336        assert_eq!(get_value!(event.received!), get_value!(event.timestamp!));
1337    }
1338
1339    #[test]
1340    fn test_grouping_config() {
1341        let mut event = Annotated::new(Event {
1342            logentry: Annotated::from(LogEntry {
1343                message: Annotated::new("Hello World!".to_owned().into()),
1344                ..Default::default()
1345            }),
1346            ..Default::default()
1347        });
1348
1349        validate_event(&mut event, &EventValidationConfig::default()).unwrap();
1350        normalize_event(
1351            &mut event,
1352            &NormalizationConfig {
1353                grouping_config: Some(json!({
1354                    "id": "legacy:1234-12-12".to_owned(),
1355                })),
1356                ..Default::default()
1357            },
1358        );
1359
1360        insta::assert_ron_snapshot!(SerializableAnnotated(&event), {
1361            ".event_id" => "[event-id]",
1362            ".received" => "[received]",
1363            ".timestamp" => "[timestamp]"
1364        }, @r###"
1365        {
1366          "event_id": "[event-id]",
1367          "level": "error",
1368          "type": "default",
1369          "logentry": {
1370            "formatted": "Hello World!",
1371          },
1372          "logger": "",
1373          "platform": "other",
1374          "timestamp": "[timestamp]",
1375          "received": "[received]",
1376          "grouping_config": {
1377            "id": "legacy:1234-12-12",
1378          },
1379        }
1380        "###);
1381    }
1382
1383    #[test]
1384    fn test_logentry_error() {
1385        let json = r#"
1386{
1387    "event_id": "74ad1301f4df489ead37d757295442b1",
1388    "timestamp": 1668148328.308933,
1389    "received": 1668148328.308933,
1390    "level": "error",
1391    "platform": "python",
1392    "logentry": {
1393        "params": [
1394            "bogus"
1395        ],
1396        "formatted": 42
1397    }
1398}
1399"#;
1400        let mut event = Annotated::<Event>::from_json(json).unwrap();
1401
1402        normalize_event(&mut event, &NormalizationConfig::default());
1403
1404        assert_json_snapshot!(SerializableAnnotated(&event), {".received" => "[received]"}, @r###"
1405        {
1406          "event_id": "74ad1301f4df489ead37d757295442b1",
1407          "level": "error",
1408          "type": "default",
1409          "logentry": null,
1410          "logger": "",
1411          "platform": "python",
1412          "timestamp": 1668148328.308933,
1413          "received": "[received]",
1414          "_meta": {
1415            "logentry": {
1416              "": {
1417                "err": [
1418                  [
1419                    "invalid_data",
1420                    {
1421                      "reason": "no message present"
1422                    }
1423                  ]
1424                ],
1425                "val": {
1426                  "formatted": null,
1427                  "message": null,
1428                  "params": [
1429                    "bogus"
1430                  ]
1431                }
1432              }
1433            }
1434          }
1435        }
1436        "###);
1437    }
1438
1439    #[test]
1440    fn test_future_timestamp() {
1441        let mut event = Annotated::new(Event {
1442            timestamp: Annotated::new(Utc.with_ymd_and_hms(2000, 1, 3, 0, 2, 0).unwrap().into()),
1443            ..Default::default()
1444        });
1445
1446        let received_at = Some(Utc.with_ymd_and_hms(2000, 1, 3, 0, 0, 0).unwrap());
1447        let max_secs_in_past = Some(30 * 24 * 3600);
1448        let max_secs_in_future = Some(60);
1449
1450        validate_event(
1451            &mut event,
1452            &EventValidationConfig {
1453                received_at,
1454                max_secs_in_past,
1455                max_secs_in_future,
1456                is_validated: false,
1457                ..Default::default()
1458            },
1459        )
1460        .unwrap();
1461        normalize_event(&mut event, &NormalizationConfig::default());
1462
1463        insta::assert_ron_snapshot!(SerializableAnnotated(&event), {
1464        ".event_id" => "[event-id]",
1465    }, @r###"
1466        {
1467          "event_id": "[event-id]",
1468          "level": "error",
1469          "type": "default",
1470          "logger": "",
1471          "platform": "other",
1472          "timestamp": 946857600.0,
1473          "received": 946857600.0,
1474          "_meta": {
1475            "timestamp": {
1476              "": Meta(Some(MetaInner(
1477                err: [
1478                  [
1479                    "future_timestamp",
1480                    {
1481                      "sdk_time": "2000-01-03T00:02:00+00:00",
1482                      "server_time": "2000-01-03T00:00:00+00:00",
1483                    },
1484                  ],
1485                ],
1486              ))),
1487            },
1488          },
1489        }
1490        "###);
1491    }
1492
1493    #[test]
1494    fn test_past_timestamp() {
1495        let mut event = Annotated::new(Event {
1496            timestamp: Annotated::new(Utc.with_ymd_and_hms(2000, 1, 3, 0, 0, 0).unwrap().into()),
1497            ..Default::default()
1498        });
1499
1500        let received_at = Some(Utc.with_ymd_and_hms(2000, 3, 3, 0, 0, 0).unwrap());
1501        let max_secs_in_past = Some(30 * 24 * 3600);
1502        let max_secs_in_future = Some(60);
1503
1504        validate_event(
1505            &mut event,
1506            &EventValidationConfig {
1507                received_at,
1508                max_secs_in_past,
1509                max_secs_in_future,
1510                is_validated: false,
1511                ..Default::default()
1512            },
1513        )
1514        .unwrap();
1515        normalize_event(&mut event, &NormalizationConfig::default());
1516
1517        insta::assert_ron_snapshot!(SerializableAnnotated(&event), {
1518        ".event_id" => "[event-id]",
1519    }, @r###"
1520        {
1521          "event_id": "[event-id]",
1522          "level": "error",
1523          "type": "default",
1524          "logger": "",
1525          "platform": "other",
1526          "timestamp": 952041600.0,
1527          "received": 952041600.0,
1528          "_meta": {
1529            "timestamp": {
1530              "": Meta(Some(MetaInner(
1531                err: [
1532                  [
1533                    "past_timestamp",
1534                    {
1535                      "sdk_time": "2000-01-03T00:00:00+00:00",
1536                      "server_time": "2000-03-03T00:00:00+00:00",
1537                    },
1538                  ],
1539                ],
1540              ))),
1541            },
1542          },
1543        }
1544        "###);
1545    }
1546
1547    #[test]
1548    fn test_normalize_logger_empty() {
1549        let mut event = Event::from_value(
1550            serde_json::json!({
1551                "event_id": "7637af36578e4e4592692e28a1d6e2ca",
1552                "platform": "java",
1553                "logger": "",
1554            })
1555            .into(),
1556        );
1557
1558        normalize_event(&mut event, &NormalizationConfig::default());
1559        assert_annotated_snapshot!(event);
1560    }
1561
1562    #[test]
1563    fn test_normalize_logger_trimmed() {
1564        let mut event = Event::from_value(
1565            serde_json::json!({
1566                "event_id": "7637af36578e4e4592692e28a1d6e2ca",
1567                "platform": "java",
1568                "logger": " \t  \t   ",
1569            })
1570            .into(),
1571        );
1572
1573        normalize_event(&mut event, &NormalizationConfig::default());
1574        assert_annotated_snapshot!(event);
1575    }
1576
1577    #[test]
1578    fn test_normalize_logger_short_no_trimming() {
1579        let mut event = Event::from_value(
1580            serde_json::json!({
1581                "event_id": "7637af36578e4e4592692e28a1d6e2ca",
1582                "platform": "java",
1583                "logger": "my.short-logger.isnt_trimmed",
1584            })
1585            .into(),
1586        );
1587
1588        normalize_event(&mut event, &NormalizationConfig::default());
1589        assert_annotated_snapshot!(event);
1590    }
1591
1592    #[test]
1593    fn test_normalize_logger_exact_length() {
1594        let mut event = Event::from_value(
1595            serde_json::json!({
1596                "event_id": "7637af36578e4e4592692e28a1d6e2ca",
1597                "platform": "java",
1598                "logger": "this_is-exactly-the_max_len.012345678901234567890123456789012345",
1599            })
1600            .into(),
1601        );
1602
1603        normalize_event(&mut event, &NormalizationConfig::default());
1604        assert_annotated_snapshot!(event);
1605    }
1606
1607    #[test]
1608    fn test_normalize_logger_too_long_single_word() {
1609        let mut event = Event::from_value(
1610            serde_json::json!({
1611                "event_id": "7637af36578e4e4592692e28a1d6e2ca",
1612                "platform": "java",
1613                "logger": "this_is-way_too_long-and_we_only_have_one_word-so_we_cant_smart_trim",
1614            })
1615            .into(),
1616        );
1617
1618        normalize_event(&mut event, &NormalizationConfig::default());
1619        assert_annotated_snapshot!(event);
1620    }
1621
1622    #[test]
1623    fn test_normalize_logger_word_trimmed_at_max() {
1624        let mut event = Event::from_value(
1625            serde_json::json!({
1626                "event_id": "7637af36578e4e4592692e28a1d6e2ca",
1627                "platform": "java",
1628                "logger": "already_out.out.in.this_part-is-kept.this_right_here-is_an-extremely_long_word",
1629            })
1630            .into(),
1631        );
1632
1633        normalize_event(&mut event, &NormalizationConfig::default());
1634        assert_annotated_snapshot!(event);
1635    }
1636
1637    #[test]
1638    fn test_normalize_logger_word_trimmed_before_max() {
1639        // This test verifies the "smart" trimming on words -- the logger name
1640        // should be cut before the max limit, removing entire words.
1641        let mut event = Event::from_value(
1642            serde_json::json!({
1643                "event_id": "7637af36578e4e4592692e28a1d6e2ca",
1644                "platform": "java",
1645                "logger": "super_out.this_is_already_out_too.this_part-is-kept.this_right_here-is_a-very_long_word",
1646            })
1647            .into(),
1648        );
1649
1650        normalize_event(&mut event, &NormalizationConfig::default());
1651        assert_annotated_snapshot!(event);
1652    }
1653
1654    #[test]
1655    fn test_normalize_logger_word_leading_dots() {
1656        let mut event = Event::from_value(
1657            serde_json::json!({
1658                "event_id": "7637af36578e4e4592692e28a1d6e2ca",
1659                "platform": "java",
1660                "logger": "io.this-tests-the-smart-trimming-and-word-removal-around-dot.words",
1661            })
1662            .into(),
1663        );
1664
1665        normalize_event(&mut event, &NormalizationConfig::default());
1666        assert_annotated_snapshot!(event);
1667    }
1668
1669    #[test]
1670    fn test_normalization_is_idempotent() {
1671        // get an event, normalize it. the result of that must be the same as normalizing it once more
1672        let start = Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap();
1673        let end = Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 10).unwrap();
1674        let mut event = Annotated::new(Event {
1675            ty: Annotated::new(EventType::Transaction),
1676            transaction: Annotated::new("/".to_owned()),
1677            timestamp: Annotated::new(end.into()),
1678            start_timestamp: Annotated::new(start.into()),
1679            contexts: {
1680                let mut contexts = Contexts::new();
1681                contexts.add(TraceContext {
1682                    trace_id: Annotated::new("4c79f60c11214eb38604f4ae0781bfb2".parse().unwrap()),
1683                    span_id: Annotated::new("fa90fdead5f74053".parse().unwrap()),
1684                    op: Annotated::new("http.server".to_owned()),
1685                    ..Default::default()
1686                });
1687                Annotated::new(contexts)
1688            },
1689            spans: Annotated::new(vec![Annotated::new(Span {
1690                timestamp: Annotated::new(
1691                    Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 10).unwrap().into(),
1692                ),
1693                start_timestamp: Annotated::new(
1694                    Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap().into(),
1695                ),
1696                trace_id: Annotated::new("4c79f60c11214eb38604f4ae0781bfb2".parse().unwrap()),
1697                span_id: Annotated::new("fa90fdead5f74053".parse().unwrap()),
1698
1699                ..Default::default()
1700            })]),
1701            ..Default::default()
1702        });
1703
1704        fn remove_received_from_event(event: &mut Annotated<Event>) -> &mut Annotated<Event> {
1705            relay_event_schema::processor::apply(event, |e, _m| {
1706                e.received = Annotated::empty();
1707                Ok(())
1708            })
1709            .unwrap();
1710            event
1711        }
1712
1713        normalize_event(&mut event, &NormalizationConfig::default());
1714        let first = remove_received_from_event(&mut event.clone())
1715            .to_json()
1716            .unwrap();
1717        // Expected some fields (such as timestamps) exist after first normalization.
1718
1719        normalize_event(&mut event, &NormalizationConfig::default());
1720        let second = remove_received_from_event(&mut event.clone())
1721            .to_json()
1722            .unwrap();
1723        assert_eq!(&first, &second, "idempotency check failed");
1724
1725        normalize_event(&mut event, &NormalizationConfig::default());
1726        let third = remove_received_from_event(&mut event.clone())
1727            .to_json()
1728            .unwrap();
1729        assert_eq!(&second, &third, "idempotency check failed");
1730    }
1731
1732    /// Validate full normalization is idempotent.
1733    ///
1734    /// Both PoPs and processing relays will temporarily run full normalization
1735    /// in events, during the rollout of running normalization once in internal
1736    /// relays.
1737    // TODO(iker): remove this test after the rollout is done.
1738    #[test]
1739    fn test_full_normalization_is_idempotent() {
1740        let start = Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap();
1741        let end = Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 10).unwrap();
1742        let mut event = Annotated::new(Event {
1743            ty: Annotated::new(EventType::Transaction),
1744            transaction: Annotated::new("/".to_owned()),
1745            timestamp: Annotated::new(end.into()),
1746            start_timestamp: Annotated::new(start.into()),
1747            contexts: {
1748                let mut contexts = Contexts::new();
1749                contexts.add(TraceContext {
1750                    trace_id: Annotated::new("4c79f60c11214eb38604f4ae0781bfb2".parse().unwrap()),
1751                    span_id: Annotated::new("fa90fdead5f74053".parse().unwrap()),
1752                    op: Annotated::new("http.server".to_owned()),
1753                    ..Default::default()
1754                });
1755                Annotated::new(contexts)
1756            },
1757            spans: Annotated::new(vec![Annotated::new(Span {
1758                timestamp: Annotated::new(
1759                    Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 10).unwrap().into(),
1760                ),
1761                start_timestamp: Annotated::new(
1762                    Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap().into(),
1763                ),
1764                trace_id: Annotated::new("4c79f60c11214eb38604f4ae0781bfb2".parse().unwrap()),
1765                span_id: Annotated::new("fa90fdead5f74053".parse().unwrap()),
1766
1767                ..Default::default()
1768            })]),
1769            ..Default::default()
1770        });
1771
1772        fn remove_received_from_event(event: &mut Annotated<Event>) -> &mut Annotated<Event> {
1773            relay_event_schema::processor::apply(event, |e, _m| {
1774                e.received = Annotated::empty();
1775                Ok(())
1776            })
1777            .unwrap();
1778            event
1779        }
1780
1781        let full_normalization_config = NormalizationConfig {
1782            is_renormalize: false,
1783            enable_trimming: true,
1784            remove_other: true,
1785            emit_event_errors: true,
1786            ..Default::default()
1787        };
1788
1789        normalize_event(&mut event, &full_normalization_config);
1790        let first = remove_received_from_event(&mut event.clone())
1791            .to_json()
1792            .unwrap();
1793        // Expected some fields (such as timestamps) exist after first normalization.
1794
1795        normalize_event(&mut event, &full_normalization_config);
1796        let second = remove_received_from_event(&mut event.clone())
1797            .to_json()
1798            .unwrap();
1799        assert_eq!(&first, &second, "idempotency check failed");
1800
1801        normalize_event(&mut event, &full_normalization_config);
1802        let third = remove_received_from_event(&mut event.clone())
1803            .to_json()
1804            .unwrap();
1805        assert_eq!(&second, &third, "idempotency check failed");
1806    }
1807
1808    #[test]
1809    fn test_normalize_validates_spans() {
1810        let event = Annotated::<Event>::from_json(
1811            r#"
1812            {
1813                "type": "transaction",
1814                "transaction": "/",
1815                "timestamp": 946684810.0,
1816                "start_timestamp": 946684800.0,
1817                "contexts": {
1818                    "trace": {
1819                    "trace_id": "4c79f60c11214eb38604f4ae0781bfb2",
1820                    "span_id": "fa90fdead5f74053",
1821                    "op": "http.server",
1822                    "type": "trace"
1823                    }
1824                },
1825                "spans": []
1826            }
1827            "#,
1828        )
1829        .unwrap();
1830
1831        // All incomplete spans should be caught by normalization:
1832        for span in [
1833            r#"null"#,
1834            r#"{
1835              "timestamp": 946684810.0,
1836              "start_timestamp": 946684900.0,
1837              "span_id": "fa90fdead5f74053",
1838              "trace_id": "4c79f60c11214eb38604f4ae0781bfb2"
1839            }"#,
1840            r#"{
1841              "timestamp": 946684810.0,
1842              "span_id": "fa90fdead5f74053",
1843              "trace_id": "4c79f60c11214eb38604f4ae0781bfb2"
1844            }"#,
1845            r#"{
1846              "timestamp": 946684810.0,
1847              "start_timestamp": 946684800.0,
1848              "trace_id": "4c79f60c11214eb38604f4ae0781bfb2"
1849            }"#,
1850            r#"{
1851              "timestamp": 946684810.0,
1852              "start_timestamp": 946684800.0,
1853              "span_id": "fa90fdead5f74053"
1854            }"#,
1855        ] {
1856            let mut modified_event = event.clone();
1857            let event_ref = modified_event.value_mut().as_mut().unwrap();
1858            event_ref
1859                .spans
1860                .set_value(Some(vec![Annotated::<Span>::from_json(span).unwrap()]));
1861
1862            let res = validate_event(&mut modified_event, &EventValidationConfig::default());
1863
1864            assert!(res.is_err(), "{span:?}");
1865        }
1866    }
1867
1868    #[test]
1869    fn test_normalization_respects_is_renormalize() {
1870        let mut event = Annotated::<Event>::from_json(
1871            r#"
1872            {
1873                "type": "default",
1874                "tags": [["environment", "some_environment"]]
1875            }
1876            "#,
1877        )
1878        .unwrap();
1879
1880        normalize_event(
1881            &mut event,
1882            &NormalizationConfig {
1883                is_renormalize: true,
1884                ..Default::default()
1885            },
1886        );
1887
1888        assert_debug_snapshot!(event.value().unwrap().tags, @r###"
1889        Tags(
1890            PairList(
1891                [
1892                    TagEntry(
1893                        "environment",
1894                        "some_environment",
1895                    ),
1896                ],
1897            ),
1898        )
1899        "###);
1900    }
1901
1902    #[test]
1903    fn test_geo_in_normalize() {
1904        let mut event = Annotated::<Event>::from_json(
1905            r#"
1906            {
1907                "type": "transaction",
1908                "transaction": "/foo/",
1909                "timestamp": 946684810.0,
1910                "start_timestamp": 946684800.0,
1911                "contexts": {
1912                    "trace": {
1913                        "trace_id": "4c79f60c11214eb38604f4ae0781bfb2",
1914                        "span_id": "fa90fdead5f74053",
1915                        "op": "http.server",
1916                        "type": "trace"
1917                    }
1918                },
1919                "transaction_info": {
1920                    "source": "url"
1921                },
1922                "user": {
1923                    "ip_address": "2.125.160.216"
1924                }
1925            }
1926            "#,
1927        )
1928        .unwrap();
1929
1930        let lookup = GeoIpLookup::open("tests/fixtures/GeoIP2-Enterprise-Test.mmdb").unwrap();
1931
1932        // Extract user's geo information before normalization.
1933        let user_geo = event.value().unwrap().user.value().unwrap().geo.value();
1934        assert!(user_geo.is_none());
1935
1936        normalize_event(
1937            &mut event,
1938            &NormalizationConfig {
1939                geoip_lookup: Some(&lookup),
1940                ..Default::default()
1941            },
1942        );
1943
1944        // Extract user's geo information after normalization.
1945        let user_geo = event
1946            .value()
1947            .unwrap()
1948            .user
1949            .value()
1950            .unwrap()
1951            .geo
1952            .value()
1953            .unwrap();
1954
1955        assert_eq!(user_geo.country_code.value().unwrap(), "GB");
1956        assert_eq!(user_geo.city.value().unwrap(), "Boxford");
1957    }
1958
1959    #[test]
1960    fn test_normalize_app_start_spans_only_for_react_native_3_to_4_4() {
1961        let mut event = Event {
1962            spans: Annotated::new(vec![Annotated::new(Span {
1963                op: Annotated::new("app_start_cold".to_owned()),
1964                ..Default::default()
1965            })]),
1966            client_sdk: Annotated::new(ClientSdkInfo {
1967                name: Annotated::new("sentry.javascript.react-native".to_owned()),
1968                version: Annotated::new("4.5.0".to_owned()),
1969                ..Default::default()
1970            }),
1971            ..Default::default()
1972        };
1973        span::normalize_app_start_spans(&mut event);
1974        assert_debug_snapshot!(event.spans, @r#"
1975        [
1976            Span {
1977                timestamp: ~,
1978                start_timestamp: ~,
1979                exclusive_time: ~,
1980                op: "app_start_cold",
1981                span_id: ~,
1982                parent_span_id: ~,
1983                trace_id: ~,
1984                segment_id: ~,
1985                is_segment: ~,
1986                is_remote: ~,
1987                status: ~,
1988                description: ~,
1989                tags: ~,
1990                origin: ~,
1991                profile_id: ~,
1992                data: ~,
1993                links: ~,
1994                sentry_tags: ~,
1995                received: ~,
1996                measurements: ~,
1997                platform: ~,
1998                was_transaction: ~,
1999                kind: ~,
2000                other: {},
2001            },
2002        ]
2003        "#);
2004    }
2005
2006    #[test]
2007    fn test_normalize_app_start_cold_spans_for_react_native() {
2008        let mut event = Event {
2009            spans: Annotated::new(vec![Annotated::new(Span {
2010                op: Annotated::new("app_start_cold".to_owned()),
2011                ..Default::default()
2012            })]),
2013            client_sdk: Annotated::new(ClientSdkInfo {
2014                name: Annotated::new("sentry.javascript.react-native".to_owned()),
2015                version: Annotated::new("4.4.0".to_owned()),
2016                ..Default::default()
2017            }),
2018            ..Default::default()
2019        };
2020        span::normalize_app_start_spans(&mut event);
2021        assert_debug_snapshot!(event.spans, @r#"
2022        [
2023            Span {
2024                timestamp: ~,
2025                start_timestamp: ~,
2026                exclusive_time: ~,
2027                op: "app.start.cold",
2028                span_id: ~,
2029                parent_span_id: ~,
2030                trace_id: ~,
2031                segment_id: ~,
2032                is_segment: ~,
2033                is_remote: ~,
2034                status: ~,
2035                description: ~,
2036                tags: ~,
2037                origin: ~,
2038                profile_id: ~,
2039                data: ~,
2040                links: ~,
2041                sentry_tags: ~,
2042                received: ~,
2043                measurements: ~,
2044                platform: ~,
2045                was_transaction: ~,
2046                kind: ~,
2047                other: {},
2048            },
2049        ]
2050        "#);
2051    }
2052
2053    #[test]
2054    fn test_normalize_app_start_warm_spans_for_react_native() {
2055        let mut event = Event {
2056            spans: Annotated::new(vec![Annotated::new(Span {
2057                op: Annotated::new("app_start_warm".to_owned()),
2058                ..Default::default()
2059            })]),
2060            client_sdk: Annotated::new(ClientSdkInfo {
2061                name: Annotated::new("sentry.javascript.react-native".to_owned()),
2062                version: Annotated::new("4.4.0".to_owned()),
2063                ..Default::default()
2064            }),
2065            ..Default::default()
2066        };
2067        span::normalize_app_start_spans(&mut event);
2068        assert_debug_snapshot!(event.spans, @r#"
2069        [
2070            Span {
2071                timestamp: ~,
2072                start_timestamp: ~,
2073                exclusive_time: ~,
2074                op: "app.start.warm",
2075                span_id: ~,
2076                parent_span_id: ~,
2077                trace_id: ~,
2078                segment_id: ~,
2079                is_segment: ~,
2080                is_remote: ~,
2081                status: ~,
2082                description: ~,
2083                tags: ~,
2084                origin: ~,
2085                profile_id: ~,
2086                data: ~,
2087                links: ~,
2088                sentry_tags: ~,
2089                received: ~,
2090                measurements: ~,
2091                platform: ~,
2092                was_transaction: ~,
2093                kind: ~,
2094                other: {},
2095            },
2096        ]
2097        "#);
2098    }
2099}