Skip to main content

relay_event_normalization/eap/
mod.rs

1//! Event normalization and processing for attribute (EAP) based payloads.
2//!
3//! A central place for all modifications/normalizations for attributes.
4
5use std::borrow::Cow;
6use std::fmt;
7use std::net::IpAddr;
8
9use chrono::{DateTime, Utc};
10use relay_common::time::UnixTimestamp;
11use relay_conventions::attributes::*;
12use relay_conventions::{AttributeInfo, ReplacementName, WriteBehavior};
13use relay_event_schema::protocol::{
14    Attribute, AttributeType, Attributes, Geo, SpanV2, SpanV2Status,
15};
16use relay_protocol::{Annotated, Empty, Error, ErrorKind, Meta, Object, Remark, RemarkType, Value};
17use relay_sampling::DynamicSamplingContext;
18use relay_spans::{derive_description_for_v2_span, derive_op_for_v2_span};
19use smallvec::SmallVec;
20
21use crate::span::TABLE_NAME_REGEX;
22use crate::span::country_subregion::Subregion;
23use crate::span::description::{scrub_db_query, scrub_http};
24use crate::span::tag_extraction::{
25    domain_from_scrubbed_http, domain_from_server_address, span_op_to_category,
26    sql_action_from_query, sql_tables_from_query,
27};
28use crate::utils::format_user_tag;
29use crate::{TransactionNameRule, normalize_transaction_name};
30
31mod ai;
32mod attribute_like;
33mod mobile;
34pub mod time;
35pub mod trace_metric;
36mod trimming;
37mod user_agent;
38
39pub use self::ai::normalize_ai;
40pub use self::attribute_like::AttributesLike;
41pub use self::mobile::{normalize_mobile_attributes, normalize_mobile_measurements};
42pub use self::trimming::TrimmingProcessor;
43pub use self::user_agent::UserAgentNormalizer;
44
45/// How an EAP item entered Relay.
46#[derive(Debug, Clone)]
47pub enum Ingress {
48    /// The item comes from an integration (e.g. OTEL, Vercel).
49    Integration,
50    /// The item comes from an item container.
51    Container,
52    /// The item was converted from a legacy item type.
53    Legacy,
54}
55
56impl fmt::Display for Ingress {
57    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58        match self {
59            Ingress::Integration => f.write_str("integration"),
60            Ingress::Container => f.write_str("container"),
61            Ingress::Legacy => f.write_str("legacy"),
62        }
63    }
64}
65
66/// The pipeline through which an item went in Relay.
67#[derive(Debug, Clone)]
68pub enum Pipeline {
69    /// The legacy standalone span pipeline.
70    SpanLegacy,
71    /// The legacy transaction pipeline.
72    Transaction,
73    /// The V2 span pipeline.
74    SpanV2,
75}
76
77impl fmt::Display for Pipeline {
78    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79        match self {
80            Pipeline::SpanLegacy => f.write_str("span_legacy"),
81            Pipeline::Transaction => f.write_str("transaction"),
82            Pipeline::SpanV2 => f.write_str("span_v2"),
83        }
84    }
85}
86
87/// Writes `ingress` and `pipeline` into [`SENTRY__RELAY__INGRESS`] and
88/// [`SENTRY__RELAY__PIPELINE`], respectively.
89pub fn normalize_pipeline_attributes(
90    attributes: &mut Annotated<Attributes>,
91    ingress: Option<&Ingress>,
92    pipeline: Option<&Pipeline>,
93) {
94    let attributes = attributes.get_or_insert_with(Default::default);
95
96    if let Some(ingress) = ingress {
97        attributes.insert_if_missing(SENTRY__RELAY__INGRESS, || ingress.to_string());
98    }
99
100    if let Some(pipeline) = pipeline {
101        attributes.insert_if_missing(SENTRY__RELAY__PIPELINE, || pipeline.to_string());
102    }
103}
104
105/// Infers the sentry.op attribute and inserts it into [`Attributes`] if not already set.
106pub fn normalize_sentry_op(attributes: &mut Annotated<Attributes>) {
107    if attributes
108        .value()
109        .is_some_and(|attrs| attrs.contains_key(SENTRY__OP))
110    {
111        return;
112    }
113    let inferred_op = derive_op_for_v2_span(attributes);
114    let attrs = attributes.get_or_insert_with(Default::default);
115    attrs.insert_if_missing(SENTRY__OP, || inferred_op);
116}
117
118/// Normalizes a V2 span's [`SENTRY__DESCRIPTION`] attribute.
119///
120/// If the span has no description, this will attempt to synthesize one from its
121/// attributes using [derive_description_for_v2_span].
122pub fn normalize_sentry_description(
123    attributes: &mut Annotated<Attributes>,
124    name: &Annotated<String>,
125) {
126    let Some(attributes) = attributes.value_mut() else {
127        return;
128    };
129
130    let description = attributes.get_annotated_value(SENTRY__DESCRIPTION);
131
132    if description.is_some_and(|d| !d.is_empty()) {
133        return;
134    }
135
136    if let Some(description) = derive_description_for_v2_span(attributes, name) {
137        attributes.insert(SENTRY__DESCRIPTION, description);
138    }
139}
140
141/// Normalizes a V2 span's name.
142///
143/// If the span has no name, this will attempt to synthesize one from its
144/// attributes using [relay_spans::name_for_attributes].
145///
146/// This is only relevant for spans converted from V1. Spans that were sent
147/// as V2 should always have a name.
148pub fn normalize_span_name(span: &mut SpanV2) {
149    if span.name.value().is_some() {
150        return;
151    }
152
153    let Some(attributes) = span.attributes.value() else {
154        return;
155    };
156
157    if let Some(name) = relay_spans::name_for_attributes(attributes) {
158        span.name = name.into();
159    }
160}
161
162/// Infers the sentry.category attribute and inserts it into `attributes` if not
163/// already set.  The category is derived from the span operation or other span
164/// attributes.
165pub fn normalize_span_category(attributes: &mut Annotated<Attributes>) {
166    let Some(attributes_val) = attributes.value() else {
167        return;
168    };
169
170    // Clients can explicitly set the category.
171    if attribute_is_nonempty_string(attributes_val, SENTRY__CATEGORY) {
172        return;
173    }
174
175    // Try to derive category from sentry.op.
176    if let Some(op_value) = attributes_val.get_value(SENTRY__OP)
177        && let Some(op_str) = op_value.as_str()
178    {
179        let op_lowercase = op_str.to_lowercase();
180        if let Some(category) = span_op_to_category(&op_lowercase) {
181            let attrs = attributes.get_or_insert_with(Default::default);
182            attrs.insert(SENTRY__CATEGORY, category.to_owned());
183            return;
184        }
185    }
186
187    // Without an op, rely on attributes typically found only on spans of the given category.
188    let category = if attribute_is_nonempty_string(attributes_val, DB__SYSTEM__NAME) {
189        Some("db")
190    } else if attribute_is_nonempty_string(attributes_val, HTTP__REQUEST__METHOD) {
191        Some("http")
192    } else if attribute_is_nonempty_string(attributes_val, UI__COMPONENT_NAME) {
193        Some("ui")
194    } else if attribute_is_nonempty_string(attributes_val, RESOURCE__RENDER_BLOCKING_STATUS) {
195        Some("resource")
196    } else if attributes_val
197        .get_value(SENTRY__ORIGIN)
198        .and_then(|v| v.as_str())
199        .is_some_and(|v| v == "auto.ui.browser.metrics")
200    {
201        Some("browser")
202    } else {
203        None
204    };
205
206    // Write the derived category to attributes
207    if let Some(category) = category {
208        let attrs = attributes.get_or_insert_with(Default::default);
209        attrs.insert(SENTRY__CATEGORY, category.to_owned());
210    }
211}
212
213fn attribute_is_nonempty_string(attributes: &Attributes, key: &str) -> bool {
214    attributes
215        .get_value(key)
216        .and_then(|v| v.as_str())
217        .is_some_and(|s| !s.is_empty())
218}
219
220/// Normalizes/validates all attribute types.
221///
222/// Removes and marks all attributes with an error for which the specified [`AttributeType`]
223/// does not match the value.
224pub fn normalize_attribute_types(attributes: &mut Annotated<Attributes>) {
225    let Some(attributes) = attributes.value_mut() else {
226        return;
227    };
228
229    let attributes = attributes.0.values_mut();
230    for attribute in attributes {
231        use AttributeType::*;
232
233        let Some(inner) = attribute.value_mut() else {
234            continue;
235        };
236
237        match (&mut inner.value.ty, &mut inner.value.value) {
238            (Annotated(Some(Boolean), _), Annotated(Some(Value::Bool(_)), _)) => (),
239            (Annotated(Some(Integer), _), Annotated(Some(Value::I64(_)), _)) => (),
240            (Annotated(Some(Integer), _), Annotated(Some(Value::U64(u)), _))
241                if i64::try_from(*u).is_ok() => {}
242            (Annotated(Some(Double), _), Annotated(Some(Value::I64(_)), _)) => (),
243            (Annotated(Some(Double), _), Annotated(Some(Value::U64(_)), _)) => (),
244            (Annotated(Some(Double), _), Annotated(Some(Value::F64(_)), _)) => (),
245            (Annotated(Some(String), _), Annotated(Some(Value::String(_)), _)) => (),
246            (Annotated(Some(Array), _), Annotated(Some(Value::Array(arr)), _)) => {
247                if !is_supported_array(arr) {
248                    let _ = attribute.value_mut().take();
249                    attribute.meta_mut().add_error(ErrorKind::InvalidData);
250                }
251            }
252            // Note: currently the mapping to Kafka requires that invalid or unknown combinations
253            // of types and values are removed from the mapping.
254            //
255            // Usually Relay would only modify the offending values, but for now, until there
256            // is better support in the pipeline here, we need to remove the entire attribute.
257            (Annotated(Some(Unknown(_)), _), _) => {
258                let original = attribute.value_mut().take();
259                attribute.meta_mut().add_error(ErrorKind::InvalidData);
260                attribute.meta_mut().set_original_value(original);
261            }
262            (Annotated(Some(_), _), Annotated(Some(_), _)) => {
263                let original = attribute.value_mut().take();
264                attribute.meta_mut().add_error(ErrorKind::InvalidData);
265                attribute.meta_mut().set_original_value(original);
266            }
267            (Annotated(None, _), _) | (_, Annotated(None, _)) => {
268                let original = attribute.value_mut().take();
269                attribute.meta_mut().add_error(ErrorKind::MissingAttribute);
270                attribute.meta_mut().set_original_value(original);
271            }
272        }
273    }
274}
275
276/// Returns `true` if the passed array is an array we currently support.
277///
278/// Currently all arrays must be homogeneous types.
279fn is_supported_array(arr: &[Annotated<Value>]) -> bool {
280    let mut iter = arr.iter();
281
282    let Some(first) = iter.next() else {
283        // Empty arrays are supported.
284        return true;
285    };
286
287    let item = iter.try_fold(first, |prev, current| {
288        let r = match (prev.value(), current.value()) {
289            (None, None) => prev,
290            (None, Some(_)) => current,
291            (Some(_), None) => prev,
292            (Some(Value::String(_)), Some(Value::String(_))) => prev,
293            (Some(Value::Bool(_)), Some(Value::Bool(_))) => prev,
294            (
295                // We allow mixing different numeric types because they are all the same in JSON.
296                Some(Value::I64(_) | Value::U64(_) | Value::F64(_)),
297                Some(Value::I64(_) | Value::U64(_) | Value::F64(_)),
298            ) => prev,
299            // Everything else is unsupported.
300            //
301            // This includes nested arrays, nested objects and mixed arrays for now.
302            (Some(_), Some(_)) => return None,
303        };
304
305        Some(r)
306    });
307
308    let Some(item) = item else {
309        // Unsupported combination of types.
310        return false;
311    };
312
313    matches!(
314        item.value(),
315        // `None` -> `[null, null]` is allowed, as the `Annotated` may carry information.
316        // `Some` -> must be a currently supported type.
317        None | Some(
318            Value::String(_) | Value::Bool(_) | Value::I64(_) | Value::U64(_) | Value::F64(_)
319        )
320    )
321}
322
323/// Adds the `received` time to the attributes.
324pub fn normalize_received(attributes: &mut Annotated<Attributes>, received: DateTime<Utc>) {
325    attributes
326        .get_or_insert_with(Default::default)
327        .insert_if_missing(SENTRY__OBSERVED_TIMESTAMP_NANOS, || {
328            received
329                .timestamp_nanos_opt()
330                .unwrap_or_else(|| UnixTimestamp::now().as_nanos() as i64)
331                .to_string()
332        });
333}
334
335/// Normalizes the client address and the user IP address into [`Attributes`].
336///
337/// Infers the client ip from the client information which was provided to Relay, if the SDK
338/// indicates the client ip should be inferred by setting [`CLIENT__ADDRESS`] or
339/// [`USER__IP_ADDRESS`] to `{{auto}}`.
340///
341/// This requires cooperation from SDKs as inferring a client ip only works in non-server
342/// environments, where the user/client device is also the device sending the item.
343pub fn normalize_client_address(attributes: &mut Annotated<Attributes>, client_ip: Option<IpAddr>) {
344    let Some(attributes) = attributes.value_mut() else {
345        return;
346    };
347
348    for key in [CLIENT__ADDRESS, USER__IP_ADDRESS] {
349        if attributes.get_value(key).and_then(|v| v.as_str()) == Some("{{auto}}") {
350            match client_ip {
351                Some(client_ip) => attributes.insert(key, client_ip.to_string()),
352                None => drop(attributes.remove(key)),
353            }
354        }
355    }
356}
357
358/// Injects a client ip address into [`Attributes`].
359///
360/// Unlike [`normalize_client_address`], this always injects the passed client ip into `attributes`.
361pub fn normalize_inject_client_address(
362    attributes: &mut Annotated<Attributes>,
363    client_ip: Option<IpAddr>,
364) {
365    let Some(client_ip) = client_ip else {
366        return;
367    };
368
369    let attributes = attributes.get_or_insert_with(Default::default);
370    attributes.insert_if_missing(CLIENT__ADDRESS, || client_ip.to_string());
371}
372
373/// Normalizes the user's geographical information into [`Attributes`].
374///
375/// Does not modify the attributes if there is already user geo information present,
376/// to preserve original values.
377///
378/// This uses the [`CLIENT__ADDRESS`] attribute to infer the client IP address, you may want to run
379/// [`normalize_client_address`] before [`normalize_user_geo`].
380pub fn normalize_user_geo(
381    attributes: &mut Annotated<Attributes>,
382    info: impl FnOnce(IpAddr) -> Option<Geo>,
383) {
384    let Some(attributes) = attributes.value_mut() else {
385        return;
386    };
387
388    if [
389        USER__GEO__COUNTRY_CODE,
390        USER__GEO__CITY,
391        USER__GEO__SUBDIVISION,
392        USER__GEO__REGION,
393    ]
394    .into_iter()
395    .any(|a| attributes.contains_key(a))
396    {
397        return;
398    }
399
400    let client_address = attributes
401        .get_value(CLIENT__ADDRESS)
402        .and_then(|v| v.as_str())
403        .and_then(|v| v.parse().ok());
404
405    let Some(geo) = client_address.and_then(info) else {
406        return;
407    };
408
409    let subregion = geo
410        .country_code
411        .value()
412        .and_then(|cc| Subregion::from_iso2(cc));
413
414    attributes.insert_if_missing(USER__GEO__COUNTRY_CODE, || geo.country_code);
415    attributes.insert_if_missing(USER__GEO__CITY, || geo.city);
416    attributes.insert_if_missing(USER__GEO__SUBDIVISION, || geo.subdivision);
417    attributes.insert_if_missing(USER__GEO__REGION, || geo.region);
418    if let Some(subregion) = subregion {
419        attributes.insert_if_missing(USER__GEO__SUBREGION, || (subregion as u8).to_string());
420    }
421}
422
423/// Derives the [`SENTRY__USER`] attribute from the user attributes.
424///
425/// Uses the first of [`USER__ID`], [`USER__NAME`], [`USER__EMAIL`] and [`USER__IP_ADDRESS`], with the
426/// same format as the `user` tag on transactions. Values removed, replaced or masked by PII scrubbing
427/// are skipped, since they do not identify a user. Pseudonymized (hashed) values are kept.
428///
429/// Does not modify the attributes if [`SENTRY__USER`] is already present. This must run after PII
430/// scrubbing, so that scrubbed user attributes can be skipped.
431pub fn normalize_sentry_user(attributes: &mut Annotated<Attributes>) {
432    let Some(attributes) = attributes.value_mut() else {
433        return;
434    };
435
436    if attributes.contains_key(SENTRY__USER) {
437        return;
438    }
439
440    let get = |key| {
441        let value = attributes.get_annotated_value(key)?;
442        if value
443            .meta()
444            .iter_remarks()
445            .any(|r| r.ty != RemarkType::Pseudonymized)
446        {
447            return None;
448        }
449        match value.value()? {
450            Value::String(s) => Some(Cow::Borrowed(s.as_str())),
451            Value::I64(i) => Some(Cow::Owned(i.to_string())),
452            Value::U64(u) => Some(Cow::Owned(u.to_string())),
453            _ => None,
454        }
455    };
456
457    let user = format_user_tag(
458        get(USER__ID).as_deref(),
459        get(USER__NAME).as_deref(),
460        get(USER__EMAIL).as_deref(),
461        get(USER__IP_ADDRESS).as_deref(),
462    );
463
464    if let Some(user) = user {
465        attributes.insert(SENTRY__USER, user);
466    }
467}
468
469/// Normalizes the dynamic sampling context into [`Attributes`].
470///
471/// If `is_segment` is set to `false`, the function will only add select attributes that are
472/// necessary on every span - both segment and non-segment - for dynamic sampling to work. More
473/// attributes are added when `is_segment` is set to `true`.
474pub fn normalize_dsc(
475    attributes: &mut Annotated<Attributes>,
476    is_segment: &Annotated<bool>,
477    dsc: Option<&DynamicSamplingContext>,
478) {
479    let Some(dsc) = dsc else {
480        return;
481    };
482
483    let attributes = attributes.get_or_insert_with(Default::default);
484
485    attributes.insert(SENTRY__DSC__TRACE_ID, dsc.trace_id.to_string());
486
487    match &dsc.transaction {
488        Some(transaction) => attributes.insert(SENTRY__DSC__TRANSACTION, transaction.clone()),
489        None => drop(attributes.remove(SENTRY__DSC__TRANSACTION)),
490    }
491
492    if let Some(project_id) = &dsc.project_id {
493        attributes.insert(SENTRY__DSC__PROJECT_ID, project_id.to_string());
494    }
495
496    if is_segment.value().is_some_and(|is_segment| *is_segment) {
497        attributes.insert(SENTRY__DSC__PUBLIC_KEY, dsc.public_key.to_string());
498        if let Some(release) = &dsc.release {
499            attributes.insert(SENTRY__DSC__RELEASE, release.clone());
500        }
501        if let Some(environment) = &dsc.environment {
502            attributes.insert(SENTRY__DSC__ENVIRONMENT, environment.clone());
503        }
504        if let Some(sample_rate) = dsc.sample_rate {
505            attributes.insert(SENTRY__DSC__SAMPLE_RATE, sample_rate);
506        }
507        if let Some(sampled) = dsc.sampled {
508            attributes.insert(SENTRY__DSC__SAMPLED, sampled);
509        }
510    }
511}
512
513/// Sets the `sentry.trace.status` attribute on segment spans.
514///
515/// The value is derived from the `sentry.status` attribute if present, falling back to the span's
516/// top-level `status` field.
517pub fn normalize_trace_status(
518    attributes: &mut Annotated<Attributes>,
519    is_segment: &Annotated<bool>,
520    status: &Annotated<SpanV2Status>,
521) {
522    if is_segment.value().is_none_or(|is_segment| !*is_segment) {
523        return;
524    }
525
526    let attributes = attributes.get_or_insert_with(Default::default);
527    if attributes.contains_key(SENTRY__TRACE__STATUS) {
528        return;
529    }
530
531    let trace_status = attributes
532        .get_value(SENTRY__STATUS)
533        .and_then(|v| v.as_str())
534        .map(|s| s.to_owned())
535        .or_else(|| status.value().map(|s| s.to_string()));
536
537    if let Some(trace_status) = trace_status {
538        attributes.insert(SENTRY__TRACE__STATUS, trace_status);
539    }
540}
541
542/// Normalizes the client sample rate attribute to be in the range `(0, 1]`.
543///
544/// If the attribute is missing, it is created from the DSC sample rate, falling back to `1.0`. The
545/// resulting value is validated the same way as a client supplied one.
546///
547/// This is only relevant for spans as other eap types re not sampled.
548pub fn normalize_client_sample_rate(
549    attributes: &mut Annotated<Attributes>,
550    dsc_sample_rate: Option<f64>,
551) {
552    let attributes = attributes.get_or_insert_with(Default::default);
553
554    if attributes.get_value(SENTRY__CLIENT_SAMPLE_RATE).is_none() {
555        attributes.insert(SENTRY__CLIENT_SAMPLE_RATE, dsc_sample_rate.unwrap_or(1.0));
556    }
557
558    // This is fine if normalizations like this stay one-offs. If at some point we end up with more
559    // of these structural validations or normalizations based on attributes, they should be
560    // outsourced to conventions and enforced with a dedicated processor.
561    fn normalize_sample_rate(sr: &Annotated<Attribute>) -> Option<Annotated<Attribute>> {
562        match sr.value()?.value.value.value()?.as_f64() {
563            Some(v) if v > 0.0 && v <= 1.0 => None,
564            // This is an invalid sample rate, either by type or value.
565            _ => Some(Annotated::from_error(
566                Error::expected("sample rate > 0.0, <= 1.0"),
567                None,
568            )),
569        }
570    }
571
572    if let Some(sr) = attributes.0.get_mut(SENTRY__CLIENT_SAMPLE_RATE)
573        && let Some(new_sr) = normalize_sample_rate(sr)
574    {
575        *sr = new_sr;
576    }
577}
578
579/// Validates the [`SENTRY__RELEASE`] attribute.
580///
581/// Invalid releases are removed and marked with an error, the same way releases are validated on
582/// events.
583pub fn normalize_release(attributes: &mut Annotated<Attributes>) {
584    let Some(release) = attributes
585        .value_mut()
586        .as_mut()
587        .and_then(|attributes| attributes.0.get_mut(SENTRY__RELEASE))
588    else {
589        return;
590    };
591
592    if let Some(Value::String(value)) = release.value().and_then(|r| r.value.value.value())
593        && crate::validate_release(value).is_err()
594    {
595        let original = release.value_mut().take();
596        release.meta_mut().add_error(ErrorKind::InvalidData);
597        release.meta_mut().set_original_value(original);
598    }
599}
600
601/// Normalizes deprecated attributes according to `sentry-conventions`.
602///
603/// Attributes with a status of `"normalize"` will be moved to their replacement name.
604/// If there is already a value present under the replacement name, it will be left alone,
605/// but the deprecated attribute is removed anyway.
606///
607/// Attributes with a status of `"backfill"` will be copied to their replacement name if the
608/// replacement name is not present. In any case, the original name is left alone.
609pub fn normalize_attribute_names(attributes: &mut Annotated<impl AttributesLike>) {
610    let Some(attributes) = attributes.value_mut() else {
611        return;
612    };
613
614    normalize_attribute_names_inner(
615        attributes.as_object_mut(),
616        relay_conventions::attribute_info_with_fragment,
617    )
618}
619
620type AttributeInfoFn = fn(&str) -> Option<(&'static AttributeInfo, Option<&str>)>;
621
622fn normalize_attribute_names_inner<T>(attributes: &mut Object<T>, attribute_info: AttributeInfoFn)
623where
624    T: Clone,
625{
626    // Only keep keys that need rewriting. Current and unknown names stay in place.
627    let mut rewrites = SmallVec::<[_; 4]>::new();
628    for name in attributes.keys() {
629        let Some((info, fragment)) = attribute_info(name) else {
630            continue;
631        };
632        let (target, move_value) = match info.write_behavior {
633            WriteBehavior::CurrentName => continue,
634            WriteBehavior::NewName(target) => (target, true),
635            WriteBehavior::BothNames(target) => (target, false),
636        };
637        let Some(target) = resolve_attribute_name(target, fragment) else {
638            relay_log::error!(
639                attribute = name,
640                ?fragment,
641                "Attribute placeholder mismatch"
642            );
643            continue;
644        };
645        rewrites.push((Box::<str>::from(name.as_str()), target, move_value));
646    }
647
648    for (name, target, move_value) in rewrites {
649        if move_value {
650            let Some(source) = attributes.get_mut(name.as_ref()) else {
651                continue;
652            };
653            let mut meta = Meta::default();
654            // TODO: Possibly add a new RemarkType for "renamed/moved"
655            meta.add_remark(Remark::new(RemarkType::Removed, "attribute.deprecated"));
656            let value = std::mem::replace(source, Annotated(None, meta));
657            if !attributes.contains_key(&*target) {
658                attributes.insert(target.into_owned(), value);
659            }
660        } else if !attributes.contains_key(&*target)
661            && let Some(source) = attributes.get(name.as_ref()).cloned()
662        {
663            attributes.insert(target.into_owned(), source);
664        }
665    }
666}
667
668/// Resolves the name of a replacement attribute for rewriting.
669///
670/// There are two cases to consider:
671/// - `name` is `Static` and `fragment` is `None`: This means that both
672///   the source and target attribute don't have a placeholder.
673/// - `name` is `Dynamic` and `fragment` is `Some`: This means that both the
674///   source and target attribute do have a placeholder.
675fn resolve_attribute_name(
676    name: ReplacementName,
677    fragment: Option<&str>,
678) -> Option<Cow<'static, str>> {
679    match (name, fragment) {
680        // Neither the original nor the replacement attribute contains a placeholder.
681        // Simply use the replacement attribute's static name.
682        (ReplacementName::Static(name), None) => Some(Cow::Borrowed(name)),
683        // Both the original and replacement attribute contain a placeholder.
684        // Use the replacement's interpolation function and the matched fragment
685        // to obtain the new name.
686        (ReplacementName::Dynamic(name_fn), Some(fragment)) => Some(Cow::Owned(name_fn(fragment))),
687        // The other cases would mean that either the original attribute contains a placeholder
688        // and the replacement doesn't, or vice versa. This is ruled out by a compile-time check
689        // in `relay-conventions`.
690        _ => None,
691    }
692}
693
694/// Normalizes the values of a set of attributes if present in the span.
695///
696/// Each span type has a set of important attributes containing the main relevant information displayed
697/// in the product-end. For instance, for DB spans, these attributes are `db.query.text`, `db.operation.name`,
698/// `db.collection.name`. Previously, V1 spans always held these important values in the `description` field,
699/// however, V2 spans now store these values in their respective attributes based on sentry conventions.
700/// This function ports over the SpanV1 normalization logic that was previously in `scrub_span_description`
701/// by creating a set of functions to handle each group of attributes separately.
702pub fn normalize_attribute_values(
703    attributes: &mut Annotated<Attributes>,
704    http_span_allowed_hosts: &[String],
705) {
706    normalize_db_attributes(attributes);
707    normalize_http_attributes(attributes, http_span_allowed_hosts);
708    normalize_mobile_attributes(attributes);
709}
710
711/// Normalizes the following db attributes: `db.query.text`, `db.operation.name`, `db.collection.name`
712/// based on related attributes within DB spans.
713///
714/// This function reads the raw db query from `db.query.text`, scrubs it if possible, and writes
715/// the normalized query to the `sentry.normalized_db_query` attribute. After normalizing the query,
716/// the db operation and collection name are updated if needed.
717///
718/// Note: This function assumes that the sentry.op has already been inferred and set in the attributes.
719fn normalize_db_attributes(annotated_attributes: &mut Annotated<Attributes>) {
720    let Some(attributes) = annotated_attributes.value() else {
721        return;
722    };
723
724    // Skip normalization if the normalized db query attribute is already set.
725    if attributes.get_value(SENTRY__NORMALIZED_DB_QUERY).is_some() {
726        return;
727    }
728
729    let (op, sub_op) = attributes
730        .get_value(SENTRY__OP)
731        .and_then(|v| v.as_str())
732        .map(|op| op.split_once('.').unwrap_or((op, "")))
733        .unwrap_or_default();
734
735    let raw_query = attributes
736        .get_value(DB__QUERY__TEXT)
737        .or_else(|| {
738            if op == "db" {
739                attributes.get_value(SENTRY__DESCRIPTION)
740            } else {
741                None
742            }
743        })
744        .and_then(|v| v.as_str());
745
746    let db_system = attributes
747        .get_value(DB__SYSTEM__NAME)
748        .and_then(|v| v.as_str());
749
750    let db_operation = attributes
751        .get_value(DB__OPERATION__NAME)
752        .and_then(|v| v.as_str());
753
754    let collection_name = attributes
755        .get_value(DB__COLLECTION__NAME)
756        .and_then(|v| v.as_str());
757
758    let span_origin = attributes
759        .get_value(SENTRY__ORIGIN)
760        .and_then(|v| v.as_str());
761
762    let (normalized_db_query, parsed_sql) = if let Some(raw_query) = raw_query {
763        scrub_db_query(
764            raw_query,
765            sub_op,
766            db_system,
767            db_operation,
768            collection_name,
769            span_origin,
770        )
771    } else {
772        (None, None)
773    };
774
775    let db_operation = if db_operation.is_none() {
776        if sub_op == "redis" || db_system == Some("redis") {
777            // This only works as long as redis span descriptions contain the command + " *"
778            if let Some(query) = normalized_db_query.as_ref() {
779                let command = query.replace(" *", "");
780                if command.is_empty() {
781                    None
782                } else {
783                    Some(command)
784                }
785            } else {
786                None
787            }
788        } else if let Some(raw_query) = raw_query {
789            // For other database operations, try to get the operation from data
790            sql_action_from_query(raw_query).map(|a| a.to_uppercase())
791        } else {
792            None
793        }
794    } else {
795        db_operation.map(|db_operation| db_operation.to_uppercase())
796    };
797
798    let db_collection_name: Option<String> = if let Some(name) = collection_name {
799        if db_system == Some("mongodb") {
800            match TABLE_NAME_REGEX.replace_all(name, "{%s}") {
801                Cow::Owned(s) => Some(s),
802                Cow::Borrowed(_) => Some(name.to_owned()),
803            }
804        } else {
805            Some(name.to_owned())
806        }
807    } else if span_origin == Some("auto.db.supabase") {
808        normalized_db_query
809            .as_ref()
810            .and_then(|query| query.strip_prefix("from("))
811            .and_then(|s| s.strip_suffix(")"))
812            .map(String::from)
813    } else if let Some(raw_query) = raw_query {
814        sql_tables_from_query(raw_query, &parsed_sql)
815    } else {
816        None
817    };
818
819    if let Some(attributes) = annotated_attributes.value_mut() {
820        if let Some(normalized_db_query) = normalized_db_query {
821            let mut normalized_db_query_hash = format!("{:x}", md5::compute(&normalized_db_query));
822            normalized_db_query_hash.truncate(16);
823
824            attributes.insert(SENTRY__NORMALIZED_DB_QUERY, normalized_db_query);
825            attributes.insert(SENTRY__NORMALIZED_DB_QUERY__HASH, normalized_db_query_hash);
826        }
827        if let Some(db_operation_name) = db_operation {
828            attributes.insert(DB__OPERATION__NAME, db_operation_name)
829        }
830        if let Some(db_collection_name) = db_collection_name {
831            attributes.insert(DB__COLLECTION__NAME, db_collection_name);
832        }
833    }
834}
835
836/// Normalizes the following http attributes: `http.request.method` and `server.address`.
837///
838/// The normalization process first scrubs the url and extracts the server address from the url.
839/// It also sets 'url.full' to the raw url if it is not already set and can be retrieved from the server address.
840fn normalize_http_attributes(
841    annotated_attributes: &mut Annotated<Attributes>,
842    allowed_hosts: &[String],
843) {
844    let Some(attributes) = annotated_attributes.value() else {
845        return;
846    };
847
848    // Skip normalization if not an http span.
849    if attributes
850        .get_value(SENTRY__CATEGORY)
851        .is_none_or(|category| category.as_str().unwrap_or_default() != "http")
852    {
853        return;
854    }
855
856    let op = attributes.get_value(SENTRY__OP).and_then(|v| v.as_str());
857
858    let (description_method, description_url) = match attributes
859        .get_value(SENTRY__DESCRIPTION)
860        .and_then(|v| v.as_str())
861        .and_then(|description| description.split_once(' '))
862    {
863        Some((method, url)) => (Some(method), Some(url)),
864        _ => (None, None),
865    };
866
867    let method = attributes
868        .get_value(HTTP__REQUEST__METHOD)
869        .and_then(|v| v.as_str())
870        .or(description_method);
871
872    let server_address = attributes
873        .get_value(SERVER__ADDRESS)
874        .and_then(|v| v.as_str());
875
876    let url: Option<&str> = attributes
877        .get_value(URL__FULL)
878        .and_then(|v| v.as_str())
879        .or(description_url);
880    let url_scheme = attributes.get_value(URL__SCHEME).and_then(|v| v.as_str());
881
882    // If the span op is "http.client" and the method and url are present,
883    // extract a normalized domain to be stored in the "server.address" attribute.
884    let (normalized_server_address, raw_url) = if op == Some("http.client") {
885        let domain_from_scrubbed_http = method
886            .zip(url)
887            .and_then(|(method, url)| scrub_http(method, url, allowed_hosts))
888            .and_then(|scrubbed_http| domain_from_scrubbed_http(&scrubbed_http));
889
890        if let Some(domain) = domain_from_scrubbed_http {
891            (Some(domain), url.map(String::from))
892        } else {
893            domain_from_server_address(server_address, url_scheme)
894        }
895    } else {
896        (None, None)
897    };
898
899    let method = method.map(|m| m.to_uppercase());
900
901    if let Some(attributes) = annotated_attributes.value_mut() {
902        if let Some(method) = method {
903            attributes.insert(HTTP__REQUEST__METHOD, method);
904        }
905
906        if let Some(normalized_server_address) = normalized_server_address {
907            attributes.insert(SERVER__ADDRESS, normalized_server_address);
908        }
909
910        if let Some(raw_url) = raw_url {
911            attributes.insert_if_missing(URL__FULL, || raw_url);
912        }
913    }
914}
915
916/// Makes sure web vital spans are not identified with segments.
917///
918/// This was ported from the legacy pipeline for behavior parity.
919/// At some point in the future, web vital spans will become metrics,
920/// and this will become academic.
921pub fn normalize_web_vital_span_segment(span: &mut SpanV2) {
922    let Some(attributes) = span.attributes.value_mut() else {
923        return;
924    };
925
926    if let Some(op) = attributes.get_value(SENTRY__OP)
927        && let Some(op_name) = op.as_str()
928        && (op_name.starts_with("ui.interaction.") || op_name.starts_with("ui.webvital."))
929    {
930        span.is_segment = None.into();
931        span.parent_span_id = None.into();
932        attributes.remove(SENTRY__SEGMENT__ID);
933    }
934}
935
936/// Normalize the [`SENTRY__SEGMENT__NAME`] attribute (aka the transaction)
937/// by running [`normalize_transaction_name`] on it.
938///
939/// This exists for parity with the legacy standalone span pipeline.
940pub fn normalize_segment_name(
941    attributes: &mut Annotated<Attributes>,
942    tx_name_rules: &[TransactionNameRule],
943) {
944    let Some(attributes) = attributes.value_mut() else {
945        return;
946    };
947
948    let Some(attr_value) = attributes.get_annotated_value_mut(SENTRY__SEGMENT__NAME) else {
949        return;
950    };
951
952    let mut segment_name = match &attr_value.0 {
953        Some(Value::String(s)) => Annotated(Some(s.to_owned()), attr_value.1.clone()),
954        _ => return,
955    };
956
957    normalize_transaction_name(&mut segment_name, tx_name_rules);
958
959    *attr_value = segment_name.map_value(Value::String);
960}
961
962/// Double writes sentry conventions attributes into legacy attributes.
963///
964/// This achieves backwards compatibility as it allows products to continue using legacy attributes
965/// while we accumulate spans that conform to sentry conventions.
966///
967/// This function is called after attribute value normalization (`normalize_attribute_values`) as it
968/// clones normalized attributes into legacy attributes.
969pub fn write_legacy_attributes(attributes: &mut Annotated<Attributes>) {
970    let Some(attributes) = attributes.value_mut() else {
971        return;
972    };
973
974    // Map of new sentry conventions attributes to legacy SpanV1 attributes
975    let current_to_legacy_attributes = [
976        // DB attributes
977        (SENTRY__NORMALIZED_DB_QUERY, SENTRY__NORMALIZED_DESCRIPTION),
978        (SENTRY__NORMALIZED_DB_QUERY__HASH, SENTRY__GROUP),
979        (DB__OPERATION__NAME, SENTRY__ACTION),
980        // HTTP attributes
981        (SERVER__ADDRESS, SENTRY__DOMAIN),
982        (HTTP__REQUEST__METHOD, SENTRY__ACTION),
983        (HTTP__RESPONSE__STATUS_CODE, SENTRY__STATUS_CODE),
984    ];
985
986    for (current_attribute, legacy_attribute) in current_to_legacy_attributes {
987        if attributes.contains_key(legacy_attribute) {
988            continue;
989        }
990
991        let Some(attr) = attributes.get_attribute(current_attribute) else {
992            continue;
993        };
994
995        attributes.insert(legacy_attribute, attr.value.clone());
996    }
997
998    if !attributes.contains_key(SENTRY__DOMAIN)
999        && let Some(db_domain) = attributes
1000            .get_value(DB__COLLECTION__NAME)
1001            .and_then(|value| value.as_str())
1002            .map(|collection_name| collection_name.to_owned())
1003    {
1004        // sentry.domain must be wrapped in preceding and trailing commas, for old hacky reasons.
1005        attributes.insert(
1006            SENTRY__DOMAIN,
1007            match (db_domain.starts_with(','), db_domain.ends_with(',')) {
1008                (true, true) => db_domain,
1009                (true, false) => format!("{db_domain},"),
1010                (false, true) => format!(",{db_domain}"),
1011                (false, false) => format!(",{db_domain},"),
1012            },
1013        );
1014    }
1015}
1016
1017#[cfg(test)]
1018mod tests {
1019    use std::time::Duration;
1020
1021    use relay_base_schema::project::ProjectId;
1022    use relay_protocol::{Empty, SerializableAnnotated, assert_annotated_snapshot};
1023    use relay_sampling::DynamicSamplingContext;
1024
1025    use super::*;
1026
1027    fn mock_dsc(transaction: Option<&str>) -> DynamicSamplingContext {
1028        DynamicSamplingContext {
1029            trace_id: "67e5504410b1426f9247bb680e5fe0c8".parse().unwrap(),
1030            public_key: "12345678901234567890123456789012".parse().unwrap(),
1031            project_id: Some(ProjectId::new(42)),
1032            release: None,
1033            environment: None,
1034            transaction: transaction.map(str::to_owned),
1035            sample_rate: None,
1036            user: Default::default(),
1037            replay_id: None,
1038            sampled: None,
1039            other: Default::default(),
1040        }
1041    }
1042
1043    #[test]
1044    fn test_normalize_dsc_child_span_no_dsc() {
1045        let mut attributes = Annotated::empty();
1046        normalize_dsc(&mut attributes, &Annotated::new(false), None);
1047        assert!(attributes.value().is_none());
1048    }
1049
1050    #[test]
1051    fn test_normalize_dsc_child_span_no_transaction() {
1052        let mut attributes = Annotated::empty();
1053        let dsc = &mock_dsc(None);
1054        normalize_dsc(&mut attributes, &Annotated::new(false), Some(dsc));
1055        assert_annotated_snapshot!(attributes, @r#"
1056        {
1057          "sentry.dsc.project_id": {
1058            "type": "string",
1059            "value": "42"
1060          },
1061          "sentry.dsc.trace_id": {
1062            "type": "string",
1063            "value": "67e5504410b1426f9247bb680e5fe0c8"
1064          }
1065        }
1066        "#);
1067    }
1068
1069    #[test]
1070    fn test_normalize_dsc_child_span() {
1071        let mut attributes = Annotated::empty();
1072        let dsc = &mock_dsc(Some("/some/endpoint"));
1073        normalize_dsc(&mut attributes, &Annotated::new(false), Some(dsc));
1074        assert_annotated_snapshot!(attributes, @r#"
1075        {
1076          "sentry.dsc.project_id": {
1077            "type": "string",
1078            "value": "42"
1079          },
1080          "sentry.dsc.trace_id": {
1081            "type": "string",
1082            "value": "67e5504410b1426f9247bb680e5fe0c8"
1083          },
1084          "sentry.dsc.transaction": {
1085            "type": "string",
1086            "value": "/some/endpoint"
1087          }
1088        }
1089        "#);
1090    }
1091
1092    #[test]
1093    fn test_normalize_dsc_segment() {
1094        let mut attributes = Annotated::empty();
1095        let dsc = &mock_dsc(Some("/some/endpoint"));
1096        normalize_dsc(&mut attributes, &Annotated::new(true), Some(dsc));
1097        assert_annotated_snapshot!(attributes, @r#"
1098        {
1099          "sentry.dsc.project_id": {
1100            "type": "string",
1101            "value": "42"
1102          },
1103          "sentry.dsc.public_key": {
1104            "type": "string",
1105            "value": "12345678901234567890123456789012"
1106          },
1107          "sentry.dsc.trace_id": {
1108            "type": "string",
1109            "value": "67e5504410b1426f9247bb680e5fe0c8"
1110          },
1111          "sentry.dsc.transaction": {
1112            "type": "string",
1113            "value": "/some/endpoint"
1114          }
1115        }
1116        "#);
1117    }
1118
1119    #[test]
1120    fn test_normalize_trace_status_not_segment() {
1121        let mut attributes = Annotated::empty();
1122        normalize_trace_status(
1123            &mut attributes,
1124            &Annotated::new(false),
1125            &Annotated::new(SpanV2Status::Ok),
1126        );
1127        assert!(attributes.value().is_none());
1128    }
1129
1130    #[test]
1131    fn test_normalize_trace_status_already_set() {
1132        let mut attributes = Annotated::from_json(
1133            r#"{"sentry.trace.status": {"type": "string", "value": "internal_error"}}"#,
1134        )
1135        .unwrap();
1136        normalize_trace_status(
1137            &mut attributes,
1138            &Annotated::new(true),
1139            &Annotated::new(SpanV2Status::Error),
1140        );
1141        assert_eq!(
1142            attributes
1143                .value()
1144                .unwrap()
1145                .get_value("sentry.trace.status")
1146                .and_then(|v| v.as_str()),
1147            Some("internal_error"),
1148        );
1149    }
1150
1151    #[test]
1152    fn test_normalize_trace_status_from_sentry_status_attribute() {
1153        let mut attributes = Annotated::from_json(
1154            r#"{"sentry.status": {"type": "string", "value": "internal_error"}}"#,
1155        )
1156        .unwrap();
1157        normalize_trace_status(
1158            &mut attributes,
1159            &Annotated::new(true),
1160            &Annotated::new(SpanV2Status::Error),
1161        );
1162        assert_eq!(
1163            attributes
1164                .value()
1165                .unwrap()
1166                .get_value("sentry.trace.status")
1167                .and_then(|v| v.as_str()),
1168            Some("internal_error"),
1169        );
1170    }
1171
1172    #[test]
1173    fn test_normalize_trace_status_from_span_status() {
1174        let mut attributes = Annotated::empty();
1175        normalize_trace_status(
1176            &mut attributes,
1177            &Annotated::new(true),
1178            &Annotated::new(SpanV2Status::Error),
1179        );
1180        assert_eq!(
1181            attributes
1182                .value()
1183                .unwrap()
1184                .get_value("sentry.trace.status")
1185                .and_then(|v| v.as_str()),
1186            Some("error"),
1187        );
1188    }
1189
1190    #[test]
1191    fn test_normalize_trace_status_no_status() {
1192        let mut attributes = Annotated::empty();
1193        normalize_trace_status(&mut attributes, &Annotated::new(true), &Annotated::empty());
1194        assert!(
1195            attributes
1196                .value()
1197                .unwrap()
1198                .get_value("sentry.trace.status")
1199                .is_none(),
1200        );
1201    }
1202
1203    #[test]
1204    fn test_normalize_received_none() {
1205        let mut attributes = Default::default();
1206
1207        normalize_received(
1208            &mut attributes,
1209            DateTime::from_timestamp_nanos(1_234_201_337),
1210        );
1211
1212        assert_annotated_snapshot!(attributes, @r#"
1213        {
1214          "sentry.observed_timestamp_nanos": {
1215            "type": "string",
1216            "value": "1234201337"
1217          }
1218        }
1219        "#);
1220    }
1221
1222    #[test]
1223    fn test_normalize_received_existing() {
1224        let mut attributes = Annotated::from_json(
1225            r#"{
1226          "sentry.observed_timestamp_nanos": {
1227            "type": "string",
1228            "value": "111222333"
1229          }
1230        }"#,
1231        )
1232        .unwrap();
1233
1234        normalize_received(
1235            &mut attributes,
1236            DateTime::from_timestamp_nanos(1_234_201_337),
1237        );
1238
1239        assert_annotated_snapshot!(attributes, @r###"
1240        {
1241          "sentry.observed_timestamp_nanos": {
1242            "type": "string",
1243            "value": "111222333"
1244          }
1245        }
1246        "###);
1247    }
1248
1249    #[test]
1250    fn test_process_attribute_types() {
1251        let json = r#"{
1252            "valid_bool": {
1253                "type": "boolean",
1254                "value": true
1255            },
1256            "valid_int_i64": {
1257                "type": "integer",
1258                "value": -42
1259            },
1260            "valid_int_u64": {
1261                "type": "integer",
1262                "value": 42
1263            },
1264            "valid_int_from_string": {
1265                "type": "integer",
1266                "value": "42"
1267            },
1268            "valid_double": {
1269                "type": "double",
1270                "value": 42.5
1271            },
1272            "double_with_i64": {
1273                "type": "double",
1274                "value": -42
1275            },
1276            "valid_double_with_u64": {
1277                "type": "double",
1278                "value": 42
1279            },
1280            "valid_string": {
1281                "type": "string",
1282                "value": "test"
1283            },
1284            "valid_string_with_other": {
1285                "type": "string",
1286                "value": "test",
1287                "some_other_field": "some_other_value"
1288            },
1289            "unknown_type": {
1290                "type": "custom",
1291                "value": "test"
1292            },
1293            "invalid_int_from_invalid_string": {
1294                "type": "integer",
1295                "value": "abc"
1296            },
1297            "invalid_int": {
1298                "type": "integer",
1299                "value": 9223372036854775808
1300            },
1301            "missing_type": {
1302                "value": "value with missing type"
1303            },
1304            "missing_value": {
1305                "type": "string"
1306            },
1307            "supported_array_string": {
1308                "type": "array",
1309                "value": ["foo", "bar"]
1310            },
1311            "supported_array_double": {
1312                "type": "array",
1313                "value": [3, 3.0, 3]
1314            },
1315            "supported_array_null": {
1316                "type": "array",
1317                "value": [null, null]
1318            },
1319            "unsupported_array_mixed": {
1320                "type": "array",
1321                "value": ["foo", 1.0]
1322            },
1323            "unsupported_array_object": {
1324                "type": "array",
1325                "value": [{}]
1326            },
1327            "unsupported_array_in_array": {
1328                "type": "array",
1329                "value": [[]]
1330            }
1331        }"#;
1332
1333        let mut attributes = Annotated::<Attributes>::from_json(json).unwrap();
1334        normalize_attribute_types(&mut attributes);
1335
1336        assert_annotated_snapshot!(attributes, @r#"
1337        {
1338          "double_with_i64": {
1339            "type": "double",
1340            "value": -42
1341          },
1342          "invalid_int": null,
1343          "invalid_int_from_invalid_string": null,
1344          "missing_type": null,
1345          "missing_value": null,
1346          "supported_array_double": {
1347            "type": "array",
1348            "value": [
1349              3,
1350              3.0,
1351              3
1352            ]
1353          },
1354          "supported_array_null": {
1355            "type": "array",
1356            "value": [
1357              null,
1358              null
1359            ]
1360          },
1361          "supported_array_string": {
1362            "type": "array",
1363            "value": [
1364              "foo",
1365              "bar"
1366            ]
1367          },
1368          "unknown_type": null,
1369          "unsupported_array_in_array": null,
1370          "unsupported_array_mixed": null,
1371          "unsupported_array_object": null,
1372          "valid_bool": {
1373            "type": "boolean",
1374            "value": true
1375          },
1376          "valid_double": {
1377            "type": "double",
1378            "value": 42.5
1379          },
1380          "valid_double_with_u64": {
1381            "type": "double",
1382            "value": 42
1383          },
1384          "valid_int_from_string": null,
1385          "valid_int_i64": {
1386            "type": "integer",
1387            "value": -42
1388          },
1389          "valid_int_u64": {
1390            "type": "integer",
1391            "value": 42
1392          },
1393          "valid_string": {
1394            "type": "string",
1395            "value": "test"
1396          },
1397          "valid_string_with_other": {
1398            "type": "string",
1399            "value": "test",
1400            "some_other_field": "some_other_value"
1401          },
1402          "_meta": {
1403            "invalid_int": {
1404              "": {
1405                "err": [
1406                  "invalid_data"
1407                ],
1408                "val": {
1409                  "type": "integer",
1410                  "value": 9223372036854775808
1411                }
1412              }
1413            },
1414            "invalid_int_from_invalid_string": {
1415              "": {
1416                "err": [
1417                  "invalid_data"
1418                ],
1419                "val": {
1420                  "type": "integer",
1421                  "value": "abc"
1422                }
1423              }
1424            },
1425            "missing_type": {
1426              "": {
1427                "err": [
1428                  "missing_attribute"
1429                ],
1430                "val": {
1431                  "type": null,
1432                  "value": "value with missing type"
1433                }
1434              }
1435            },
1436            "missing_value": {
1437              "": {
1438                "err": [
1439                  "missing_attribute"
1440                ],
1441                "val": {
1442                  "type": "string",
1443                  "value": null
1444                }
1445              }
1446            },
1447            "unknown_type": {
1448              "": {
1449                "err": [
1450                  "invalid_data"
1451                ],
1452                "val": {
1453                  "type": "custom",
1454                  "value": "test"
1455                }
1456              }
1457            },
1458            "unsupported_array_in_array": {
1459              "": {
1460                "err": [
1461                  "invalid_data"
1462                ]
1463              }
1464            },
1465            "unsupported_array_mixed": {
1466              "": {
1467                "err": [
1468                  "invalid_data"
1469                ]
1470              }
1471            },
1472            "unsupported_array_object": {
1473              "": {
1474                "err": [
1475                  "invalid_data"
1476                ]
1477              }
1478            },
1479            "valid_int_from_string": {
1480              "": {
1481                "err": [
1482                  "invalid_data"
1483                ],
1484                "val": {
1485                  "type": "integer",
1486                  "value": "42"
1487                }
1488              }
1489            }
1490          }
1491        }
1492        "#);
1493    }
1494
1495    #[test]
1496    fn test_normalize_user_geo_none() {
1497        let mut attributes = Annotated::from_json(
1498            r#"{
1499          "client.address": {
1500            "type": "string",
1501            "value": "192.168.2.1"
1502          }
1503        }"#,
1504        )
1505        .unwrap();
1506
1507        normalize_user_geo(&mut attributes, |addr| {
1508            Some(Geo {
1509                country_code: "XY".to_owned().into(),
1510                city: addr.to_string().into(),
1511                subdivision: Annotated::empty(),
1512                region: "Illu".to_owned().into(),
1513                other: Default::default(),
1514            })
1515        });
1516
1517        assert_annotated_snapshot!(attributes, @r#"
1518        {
1519          "client.address": {
1520            "type": "string",
1521            "value": "192.168.2.1"
1522          },
1523          "user.geo.city": {
1524            "type": "string",
1525            "value": "192.168.2.1"
1526          },
1527          "user.geo.country_code": {
1528            "type": "string",
1529            "value": "XY"
1530          },
1531          "user.geo.region": {
1532            "type": "string",
1533            "value": "Illu"
1534          }
1535        }
1536        "#);
1537    }
1538
1539    #[test]
1540    fn test_normalize_user_geo_existing() {
1541        let mut attributes = Annotated::from_json(
1542            r#"{
1543          "client.address": {
1544            "type": "string",
1545            "value": "192.168.2.1"
1546          },
1547          "user.geo.city": {
1548            "type": "string",
1549            "value": "Foo Hausen"
1550          }
1551        }"#,
1552        )
1553        .unwrap();
1554
1555        normalize_user_geo(&mut attributes, |_| unreachable!());
1556
1557        assert_annotated_snapshot!(attributes, @r#"
1558        {
1559          "client.address": {
1560            "type": "string",
1561            "value": "192.168.2.1"
1562          },
1563          "user.geo.city": {
1564            "type": "string",
1565            "value": "Foo Hausen"
1566          }
1567        }
1568        "#
1569        );
1570    }
1571
1572    #[test]
1573    fn test_normalize_user_geo_subregion() {
1574        let mut attributes = Annotated::from_json(
1575            r#"{
1576          "client.address": {
1577            "type": "string",
1578            "value": "192.168.2.1"
1579          }
1580        }"#,
1581        )
1582        .unwrap();
1583
1584        normalize_user_geo(&mut attributes, |_| {
1585            Some(Geo {
1586                country_code: "AT".to_owned().into(),
1587                city: Annotated::empty(),
1588                subdivision: Annotated::empty(),
1589                region: Annotated::empty(),
1590                other: Default::default(),
1591            })
1592        });
1593
1594        assert_annotated_snapshot!(attributes, @r#"
1595        {
1596          "client.address": {
1597            "type": "string",
1598            "value": "192.168.2.1"
1599          },
1600          "user.geo.country_code": {
1601            "type": "string",
1602            "value": "AT"
1603          },
1604          "user.geo.subregion": {
1605            "type": "string",
1606            "value": "155"
1607          }
1608        }
1609        "#);
1610    }
1611
1612    #[test]
1613    fn test_normalize_attributes() {
1614        fn replace_key(fragment: &str) -> String {
1615            format!("placeholder.replaced.{fragment}")
1616        }
1617
1618        fn backfill_key(fragment: &str) -> String {
1619            format!("placeholder.backfilled.{fragment}")
1620        }
1621
1622        fn mock_attribute_info(name: &str) -> Option<(&'static AttributeInfo, Option<&str>)> {
1623            use relay_conventions::ApplyScrubbing;
1624
1625            match name {
1626                "replace.empty" => Some((
1627                    &AttributeInfo {
1628                        write_behavior: WriteBehavior::NewName(ReplacementName::Static("replaced")),
1629                        apply_scrubbing: ApplyScrubbing::Manual,
1630                        aliases: &["replaced"],
1631                    },
1632                    None,
1633                )),
1634                "replace.existing" => Some((
1635                    &AttributeInfo {
1636                        write_behavior: WriteBehavior::NewName(ReplacementName::Static(
1637                            "not.replaced",
1638                        )),
1639                        apply_scrubbing: ApplyScrubbing::Manual,
1640                        aliases: &["not.replaced"],
1641                    },
1642                    None,
1643                )),
1644                "backfill.empty" => Some((
1645                    &AttributeInfo {
1646                        write_behavior: WriteBehavior::BothNames(ReplacementName::Static(
1647                            "backfilled",
1648                        )),
1649                        apply_scrubbing: ApplyScrubbing::Manual,
1650                        aliases: &["backfilled"],
1651                    },
1652                    None,
1653                )),
1654                "backfill.existing" => Some((
1655                    &AttributeInfo {
1656                        write_behavior: WriteBehavior::BothNames(ReplacementName::Static(
1657                            "not.backfilled",
1658                        )),
1659                        apply_scrubbing: ApplyScrubbing::Manual,
1660                        aliases: &["not.backfilled"],
1661                    },
1662                    None,
1663                )),
1664                _ if let Some(fragment) = name.strip_prefix("placeholder.replace.") => Some((
1665                    &AttributeInfo {
1666                        write_behavior: WriteBehavior::NewName(ReplacementName::Dynamic(
1667                            replace_key,
1668                        )),
1669                        apply_scrubbing: ApplyScrubbing::Manual,
1670                        aliases: &["placeholder.replaced.<key>"],
1671                    },
1672                    Some(fragment),
1673                )),
1674                _ if let Some(fragment) = name.strip_prefix("placeholder.backfill.") => Some((
1675                    &AttributeInfo {
1676                        write_behavior: WriteBehavior::BothNames(ReplacementName::Dynamic(
1677                            backfill_key,
1678                        )),
1679                        apply_scrubbing: ApplyScrubbing::Manual,
1680                        aliases: &["placeholder.backfilled.<key>"],
1681                    },
1682                    Some(fragment),
1683                )),
1684
1685                _ => None,
1686            }
1687        }
1688
1689        let mut attributes = Attributes::from([
1690            (
1691                "replace.empty".to_owned(),
1692                Annotated::new("Should be moved".to_owned().into()),
1693            ),
1694            (
1695                "replace.existing".to_owned(),
1696                Annotated::new("Should be removed".to_owned().into()),
1697            ),
1698            (
1699                "placeholder.replace.foo".to_owned(),
1700                Annotated::new("Should be moved".to_owned().into()),
1701            ),
1702            (
1703                "not.replaced".to_owned(),
1704                Annotated::new("Should be left alone".to_owned().into()),
1705            ),
1706            (
1707                "backfill.empty".to_owned(),
1708                Annotated::new("Should be copied".to_owned().into()),
1709            ),
1710            (
1711                "backfill.existing".to_owned(),
1712                Annotated::new("Should be left alone".to_owned().into()),
1713            ),
1714            (
1715                "placeholder.backfill.bar".to_owned(),
1716                Annotated::new("Should be copied".to_owned().into()),
1717            ),
1718            (
1719                "not.backfilled".to_owned(),
1720                Annotated::new("Should be left alone".to_owned().into()),
1721            ),
1722        ]);
1723
1724        normalize_attribute_names_inner(&mut attributes.0, mock_attribute_info);
1725
1726        assert_annotated_snapshot!(Annotated::new(attributes), @r###"
1727        {
1728          "backfill.empty": {
1729            "type": "string",
1730            "value": "Should be copied"
1731          },
1732          "backfill.existing": {
1733            "type": "string",
1734            "value": "Should be left alone"
1735          },
1736          "backfilled": {
1737            "type": "string",
1738            "value": "Should be copied"
1739          },
1740          "not.backfilled": {
1741            "type": "string",
1742            "value": "Should be left alone"
1743          },
1744          "not.replaced": {
1745            "type": "string",
1746            "value": "Should be left alone"
1747          },
1748          "placeholder.backfill.bar": {
1749            "type": "string",
1750            "value": "Should be copied"
1751          },
1752          "placeholder.backfilled.bar": {
1753            "type": "string",
1754            "value": "Should be copied"
1755          },
1756          "placeholder.replace.foo": null,
1757          "placeholder.replaced.foo": {
1758            "type": "string",
1759            "value": "Should be moved"
1760          },
1761          "replace.empty": null,
1762          "replace.existing": null,
1763          "replaced": {
1764            "type": "string",
1765            "value": "Should be moved"
1766          },
1767          "_meta": {
1768            "placeholder.replace.foo": {
1769              "": {
1770                "rem": [
1771                  [
1772                    "attribute.deprecated",
1773                    "x"
1774                  ]
1775                ]
1776              }
1777            },
1778            "replace.empty": {
1779              "": {
1780                "rem": [
1781                  [
1782                    "attribute.deprecated",
1783                    "x"
1784                  ]
1785                ]
1786              }
1787            },
1788            "replace.existing": {
1789              "": {
1790                "rem": [
1791                  [
1792                    "attribute.deprecated",
1793                    "x"
1794                  ]
1795                ]
1796              }
1797            }
1798          }
1799        }
1800        "###);
1801    }
1802
1803    #[test]
1804    fn test_normalize_span_infers_op() {
1805        let mut attributes = Annotated::<Attributes>::from_json(
1806            r#"{
1807          "db.system.name": {
1808                "type": "string",
1809                "value": "mysql"
1810            },
1811            "db.operation.name": {
1812                "type": "string",
1813                "value": "query"
1814            }
1815        }
1816        "#,
1817        )
1818        .unwrap();
1819
1820        normalize_sentry_op(&mut attributes);
1821
1822        assert_annotated_snapshot!(attributes, @r#"
1823        {
1824          "db.operation.name": {
1825            "type": "string",
1826            "value": "query"
1827          },
1828          "db.system.name": {
1829            "type": "string",
1830            "value": "mysql"
1831          },
1832          "sentry.op": {
1833            "type": "string",
1834            "value": "db"
1835          }
1836        }
1837        "#);
1838    }
1839
1840    #[test]
1841    fn test_normalize_attribute_values_mysql_db_query_attributes() {
1842        let mut attributes = Annotated::<Attributes>::from_json(
1843            r#"
1844        {
1845          "sentry.op": {
1846            "type": "string",
1847            "value": "db.query"
1848          },
1849          "sentry.origin": {
1850            "type": "string",
1851            "value": "auto.otlp.spans"
1852          },
1853          "db.system.name": {
1854            "type": "string",
1855            "value": "mysql"
1856          },
1857          "db.query.text": {
1858            "type": "string",
1859            "value": "SELECT \"not an identifier\""
1860          }
1861        }
1862        "#,
1863        )
1864        .unwrap();
1865
1866        normalize_db_attributes(&mut attributes);
1867
1868        assert_annotated_snapshot!(attributes, @r#"
1869        {
1870          "db.operation.name": {
1871            "type": "string",
1872            "value": "SELECT"
1873          },
1874          "db.query.text": {
1875            "type": "string",
1876            "value": "SELECT \"not an identifier\""
1877          },
1878          "db.system.name": {
1879            "type": "string",
1880            "value": "mysql"
1881          },
1882          "sentry.normalized_db_query": {
1883            "type": "string",
1884            "value": "SELECT %s"
1885          },
1886          "sentry.normalized_db_query.hash": {
1887            "type": "string",
1888            "value": "3a377dcc490b1690"
1889          },
1890          "sentry.op": {
1891            "type": "string",
1892            "value": "db.query"
1893          },
1894          "sentry.origin": {
1895            "type": "string",
1896            "value": "auto.otlp.spans"
1897          }
1898        }
1899        "#);
1900    }
1901
1902    #[test]
1903    fn test_normalize_mongodb_db_query_attributes() {
1904        let mut attributes = Annotated::<Attributes>::from_json(
1905            r#"
1906        {
1907          "sentry.op": {
1908            "type": "string",
1909            "value": "db"
1910          },
1911          "db.system.name": {
1912            "type": "string",
1913            "value": "mongodb"
1914          },
1915          "db.query.text": {
1916            "type": "string",
1917            "value": "{\"find\": \"documents\", \"foo\": \"bar\"}"
1918          },
1919          "db.operation.name": {
1920            "type": "string",
1921            "value": "find"
1922          },
1923          "db.collection.name": {
1924            "type": "string",
1925            "value": "documents"
1926          }
1927        }
1928        "#,
1929        )
1930        .unwrap();
1931
1932        normalize_db_attributes(&mut attributes);
1933
1934        assert_annotated_snapshot!(attributes, @r#"
1935        {
1936          "db.collection.name": {
1937            "type": "string",
1938            "value": "documents"
1939          },
1940          "db.operation.name": {
1941            "type": "string",
1942            "value": "FIND"
1943          },
1944          "db.query.text": {
1945            "type": "string",
1946            "value": "{\"find\": \"documents\", \"foo\": \"bar\"}"
1947          },
1948          "db.system.name": {
1949            "type": "string",
1950            "value": "mongodb"
1951          },
1952          "sentry.normalized_db_query": {
1953            "type": "string",
1954            "value": "{\"find\":\"documents\",\"foo\":\"?\"}"
1955          },
1956          "sentry.normalized_db_query.hash": {
1957            "type": "string",
1958            "value": "aedc5c7e8cec726b"
1959          },
1960          "sentry.op": {
1961            "type": "string",
1962            "value": "db"
1963          }
1964        }
1965        "#);
1966    }
1967
1968    #[test]
1969    fn test_normalize_db_attributes_does_not_update_attributes_if_already_normalized() {
1970        let mut attributes = Annotated::<Attributes>::from_json(
1971            r#"
1972        {
1973          "db.collection.name": {
1974            "type": "string",
1975            "value": "documents"
1976          },
1977          "db.operation.name": {
1978            "type": "string",
1979            "value": "FIND"
1980          },
1981          "db.query.text": {
1982            "type": "string",
1983            "value": "{\"find\": \"documents\", \"foo\": \"bar\"}"
1984          },
1985          "db.system.name": {
1986            "type": "string",
1987            "value": "mongodb"
1988          },
1989          "sentry.normalized_db_query": {
1990            "type": "string",
1991            "value": "{\"find\":\"documents\",\"foo\":\"?\"}"
1992          },
1993          "sentry.op": {
1994            "type": "string",
1995            "value": "db"
1996          }
1997        }
1998        "#,
1999        )
2000        .unwrap();
2001
2002        normalize_db_attributes(&mut attributes);
2003
2004        insta::assert_json_snapshot!(
2005            SerializableAnnotated(&attributes), @r#"
2006        {
2007          "db.collection.name": {
2008            "type": "string",
2009            "value": "documents"
2010          },
2011          "db.operation.name": {
2012            "type": "string",
2013            "value": "FIND"
2014          },
2015          "db.query.text": {
2016            "type": "string",
2017            "value": "{\"find\": \"documents\", \"foo\": \"bar\"}"
2018          },
2019          "db.system.name": {
2020            "type": "string",
2021            "value": "mongodb"
2022          },
2023          "sentry.normalized_db_query": {
2024            "type": "string",
2025            "value": "{\"find\":\"documents\",\"foo\":\"?\"}"
2026          },
2027          "sentry.op": {
2028            "type": "string",
2029            "value": "db"
2030          }
2031        }
2032        "#
2033        );
2034    }
2035
2036    #[test]
2037    fn test_normalize_db_attributes_does_not_change_non_db_spans() {
2038        let mut attributes = Annotated::<Attributes>::from_json(
2039            r#"
2040        {
2041          "sentry.op": {
2042            "type": "string",
2043            "value": "http.client"
2044          },
2045          "sentry.origin": {
2046            "type": "string",
2047            "value": "auto.otlp.spans"
2048          },
2049          "http.request.method": {
2050            "type": "string",
2051            "value": "GET"
2052          }
2053        }
2054      "#,
2055        )
2056        .unwrap();
2057
2058        normalize_db_attributes(&mut attributes);
2059
2060        assert_annotated_snapshot!(attributes, @r#"
2061        {
2062          "http.request.method": {
2063            "type": "string",
2064            "value": "GET"
2065          },
2066          "sentry.op": {
2067            "type": "string",
2068            "value": "http.client"
2069          },
2070          "sentry.origin": {
2071            "type": "string",
2072            "value": "auto.otlp.spans"
2073          }
2074        }
2075        "#);
2076    }
2077
2078    #[test]
2079    fn test_normalize_http_attributes() {
2080        let mut attributes = Annotated::<Attributes>::from_json(
2081            r#"
2082        {
2083          "sentry.op": {
2084            "type": "string",
2085            "value": "http.client"
2086          },
2087          "sentry.category": {
2088            "type": "string",
2089            "value": "http"
2090          },
2091          "http.request.method": {
2092            "type": "string",
2093            "value": "GET"
2094          },
2095          "url.full": {
2096            "type": "string",
2097            "value": "https://application.www.xn--85x722f.xn--55qx5d.cn"
2098          }
2099        }
2100      "#,
2101        )
2102        .unwrap();
2103
2104        normalize_http_attributes(&mut attributes, &[]);
2105
2106        assert_annotated_snapshot!(attributes, @r#"
2107        {
2108          "http.request.method": {
2109            "type": "string",
2110            "value": "GET"
2111          },
2112          "sentry.category": {
2113            "type": "string",
2114            "value": "http"
2115          },
2116          "sentry.op": {
2117            "type": "string",
2118            "value": "http.client"
2119          },
2120          "server.address": {
2121            "type": "string",
2122            "value": "*.xn--85x722f.xn--55qx5d.cn"
2123          },
2124          "url.full": {
2125            "type": "string",
2126            "value": "https://application.www.xn--85x722f.xn--55qx5d.cn"
2127          }
2128        }
2129        "#);
2130    }
2131
2132    #[test]
2133    fn test_normalize_http_attributes_server_address() {
2134        let mut attributes = Annotated::<Attributes>::from_json(
2135            r#"
2136        {
2137          "sentry.category": {
2138            "type": "string",
2139            "value": "http"
2140          },
2141          "sentry.op": {
2142            "type": "string",
2143            "value": "http.client"
2144          },
2145          "url.scheme": {
2146            "type": "string",
2147            "value": "https"
2148          },
2149          "server.address": {
2150            "type": "string",
2151            "value": "subdomain.example.com:5688"
2152          },
2153          "http.request.method": {
2154            "type": "string",
2155            "value": "GET"
2156          }
2157        }
2158      "#,
2159        )
2160        .unwrap();
2161
2162        normalize_http_attributes(&mut attributes, &[]);
2163
2164        assert_annotated_snapshot!(attributes, @r#"
2165        {
2166          "http.request.method": {
2167            "type": "string",
2168            "value": "GET"
2169          },
2170          "sentry.category": {
2171            "type": "string",
2172            "value": "http"
2173          },
2174          "sentry.op": {
2175            "type": "string",
2176            "value": "http.client"
2177          },
2178          "server.address": {
2179            "type": "string",
2180            "value": "*.example.com:5688"
2181          },
2182          "url.full": {
2183            "type": "string",
2184            "value": "https://subdomain.example.com:5688"
2185          },
2186          "url.scheme": {
2187            "type": "string",
2188            "value": "https"
2189          }
2190        }
2191        "#);
2192    }
2193
2194    #[test]
2195    fn test_normalize_http_attributes_allowed_hosts() {
2196        let mut attributes = Annotated::<Attributes>::from_json(
2197            r#"
2198        {
2199          "sentry.category": {
2200            "type": "string",
2201            "value": "http"
2202          },
2203          "sentry.op": {
2204            "type": "string",
2205            "value": "http.client"
2206          },
2207          "http.request.method": {
2208            "type": "string",
2209            "value": "GET"
2210          },
2211          "url.full": {
2212            "type": "string",
2213            "value": "https://application.www.xn--85x722f.xn--55qx5d.cn"
2214          }
2215        }
2216      "#,
2217        )
2218        .unwrap();
2219
2220        normalize_http_attributes(
2221            &mut attributes,
2222            &["application.www.xn--85x722f.xn--55qx5d.cn".to_owned()],
2223        );
2224
2225        assert_annotated_snapshot!(attributes, @r#"
2226        {
2227          "http.request.method": {
2228            "type": "string",
2229            "value": "GET"
2230          },
2231          "sentry.category": {
2232            "type": "string",
2233            "value": "http"
2234          },
2235          "sentry.op": {
2236            "type": "string",
2237            "value": "http.client"
2238          },
2239          "server.address": {
2240            "type": "string",
2241            "value": "application.www.xn--85x722f.xn--55qx5d.cn"
2242          },
2243          "url.full": {
2244            "type": "string",
2245            "value": "https://application.www.xn--85x722f.xn--55qx5d.cn"
2246          }
2247        }
2248        "#);
2249    }
2250
2251    #[test]
2252    fn test_normalize_db_attributes_from_legacy_attributes() {
2253        let mut attributes = Annotated::<Attributes>::from_json(
2254            r#"
2255        {
2256          "sentry.op": {
2257            "type": "string",
2258            "value": "db"
2259          },
2260          "db.system.name": {
2261            "type": "string",
2262            "value": "mongodb"
2263          },
2264          "sentry.description": {
2265            "type": "string",
2266            "value": "{\"find\": \"documents\", \"foo\": \"bar\"}"
2267          },
2268          "db.operation.name": {
2269            "type": "string",
2270            "value": "find"
2271          },
2272          "db.collection.name": {
2273            "type": "string",
2274            "value": "documents"
2275          }
2276        }
2277        "#,
2278        )
2279        .unwrap();
2280
2281        normalize_db_attributes(&mut attributes);
2282
2283        assert_annotated_snapshot!(attributes, @r#"
2284        {
2285          "db.collection.name": {
2286            "type": "string",
2287            "value": "documents"
2288          },
2289          "db.operation.name": {
2290            "type": "string",
2291            "value": "FIND"
2292          },
2293          "db.system.name": {
2294            "type": "string",
2295            "value": "mongodb"
2296          },
2297          "sentry.description": {
2298            "type": "string",
2299            "value": "{\"find\": \"documents\", \"foo\": \"bar\"}"
2300          },
2301          "sentry.normalized_db_query": {
2302            "type": "string",
2303            "value": "{\"find\":\"documents\",\"foo\":\"?\"}"
2304          },
2305          "sentry.normalized_db_query.hash": {
2306            "type": "string",
2307            "value": "aedc5c7e8cec726b"
2308          },
2309          "sentry.op": {
2310            "type": "string",
2311            "value": "db"
2312          }
2313        }
2314        "#);
2315    }
2316
2317    #[test]
2318    fn test_normalize_http_attributes_from_legacy_attributes() {
2319        let mut attributes = Annotated::<Attributes>::from_json(
2320            r#"
2321        {
2322          "sentry.category": {
2323            "type": "string",
2324            "value": "http"
2325          },
2326          "sentry.op": {
2327            "type": "string",
2328            "value": "http.client"
2329          },
2330          "http.request_method": {
2331            "type": "string",
2332            "value": "GET"
2333          }
2334        }
2335        "#,
2336        )
2337        .unwrap();
2338
2339        normalize_attribute_names(&mut attributes);
2340        normalize_http_attributes(&mut attributes, &[]);
2341
2342        assert_annotated_snapshot!(attributes, @r#"
2343        {
2344          "http.request.method": {
2345            "type": "string",
2346            "value": "GET"
2347          },
2348          "http.request_method": {
2349            "type": "string",
2350            "value": "GET"
2351          },
2352          "sentry.category": {
2353            "type": "string",
2354            "value": "http"
2355          },
2356          "sentry.op": {
2357            "type": "string",
2358            "value": "http.client"
2359          }
2360        }
2361        "#);
2362    }
2363
2364    #[test]
2365    fn test_normalize_http_attributes_from_description() {
2366        let mut attributes = Annotated::<Attributes>::from_json(
2367            r#"
2368        {
2369          "sentry.category": {
2370            "type": "string",
2371            "value": "http"
2372          },
2373          "sentry.op": {
2374            "type": "string",
2375            "value": "http.client"
2376          },
2377          "sentry.description": {
2378            "type": "string",
2379            "value": "GET https://application.www.xn--85x722f.xn--55qx5d.cn"
2380          }
2381        }
2382        "#,
2383        )
2384        .unwrap();
2385
2386        normalize_http_attributes(&mut attributes, &[]);
2387
2388        assert_annotated_snapshot!(attributes, @r#"
2389        {
2390          "http.request.method": {
2391            "type": "string",
2392            "value": "GET"
2393          },
2394          "sentry.category": {
2395            "type": "string",
2396            "value": "http"
2397          },
2398          "sentry.description": {
2399            "type": "string",
2400            "value": "GET https://application.www.xn--85x722f.xn--55qx5d.cn"
2401          },
2402          "sentry.op": {
2403            "type": "string",
2404            "value": "http.client"
2405          },
2406          "server.address": {
2407            "type": "string",
2408            "value": "*.xn--85x722f.xn--55qx5d.cn"
2409          },
2410          "url.full": {
2411            "type": "string",
2412            "value": "https://application.www.xn--85x722f.xn--55qx5d.cn"
2413          }
2414        }
2415        "#);
2416    }
2417
2418    #[test]
2419    fn test_write_legacy_attributes() {
2420        let mut attributes = Annotated::<Attributes>::from_json(
2421            r#"
2422        {
2423          "db.collection.name": {
2424            "type": "string",
2425            "value": "documents"
2426          },
2427          "db.operation.name": {
2428            "type": "string",
2429            "value": "FIND"
2430          },
2431          "db.query.text": {
2432            "type": "string",
2433            "value": "{\"find\": \"documents\", \"foo\": \"bar\"}"
2434          },
2435          "db.system.name": {
2436            "type": "string",
2437            "value": "mongodb"
2438          },
2439          "sentry.normalized_db_query": {
2440            "type": "string",
2441            "value": "{\"find\":\"documents\",\"foo\":\"?\"}"
2442          },
2443          "sentry.normalized_db_query.hash": {
2444            "type": "string",
2445            "value": "aedc5c7e8cec726b"
2446          },
2447          "sentry.op": {
2448            "type": "string",
2449            "value": "db"
2450          }
2451        }
2452        "#,
2453        )
2454        .unwrap();
2455
2456        write_legacy_attributes(&mut attributes);
2457
2458        assert_annotated_snapshot!(attributes, @r#"
2459        {
2460          "db.collection.name": {
2461            "type": "string",
2462            "value": "documents"
2463          },
2464          "db.operation.name": {
2465            "type": "string",
2466            "value": "FIND"
2467          },
2468          "db.query.text": {
2469            "type": "string",
2470            "value": "{\"find\": \"documents\", \"foo\": \"bar\"}"
2471          },
2472          "db.system.name": {
2473            "type": "string",
2474            "value": "mongodb"
2475          },
2476          "sentry.action": {
2477            "type": "string",
2478            "value": "FIND"
2479          },
2480          "sentry.domain": {
2481            "type": "string",
2482            "value": ",documents,"
2483          },
2484          "sentry.group": {
2485            "type": "string",
2486            "value": "aedc5c7e8cec726b"
2487          },
2488          "sentry.normalized_db_query": {
2489            "type": "string",
2490            "value": "{\"find\":\"documents\",\"foo\":\"?\"}"
2491          },
2492          "sentry.normalized_db_query.hash": {
2493            "type": "string",
2494            "value": "aedc5c7e8cec726b"
2495          },
2496          "sentry.normalized_description": {
2497            "type": "string",
2498            "value": "{\"find\":\"documents\",\"foo\":\"?\"}"
2499          },
2500          "sentry.op": {
2501            "type": "string",
2502            "value": "db"
2503          }
2504        }
2505        "#);
2506    }
2507
2508    #[test]
2509    fn test_normalize_span_category_explicit() {
2510        // Category is already explicitly set, should not be overwritten
2511        let mut attributes = Annotated::<Attributes>::from_json(
2512            r#"{
2513          "sentry.category": {
2514            "type": "string",
2515            "value": "custom"
2516          },
2517          "sentry.op": {
2518            "type": "string",
2519            "value": "db.query"
2520          }
2521        }"#,
2522        )
2523        .unwrap();
2524
2525        normalize_span_category(&mut attributes);
2526
2527        assert_annotated_snapshot!(attributes, @r#"
2528        {
2529          "sentry.category": {
2530            "type": "string",
2531            "value": "custom"
2532          },
2533          "sentry.op": {
2534            "type": "string",
2535            "value": "db.query"
2536          }
2537        }
2538        "#);
2539    }
2540
2541    #[test]
2542    fn test_normalize_span_category_from_op_db() {
2543        let mut attributes = Annotated::<Attributes>::from_json(
2544            r#"{
2545          "sentry.op": {
2546            "type": "string",
2547            "value": "db.query"
2548          }
2549        }"#,
2550        )
2551        .unwrap();
2552
2553        normalize_span_category(&mut attributes);
2554
2555        assert_annotated_snapshot!(attributes, @r#"
2556        {
2557          "sentry.category": {
2558            "type": "string",
2559            "value": "db"
2560          },
2561          "sentry.op": {
2562            "type": "string",
2563            "value": "db.query"
2564          }
2565        }
2566        "#);
2567    }
2568
2569    #[test]
2570    fn test_normalize_span_category_from_op_http() {
2571        let mut attributes = Annotated::<Attributes>::from_json(
2572            r#"{
2573          "sentry.op": {
2574            "type": "string",
2575            "value": "http.client"
2576          }
2577        }"#,
2578        )
2579        .unwrap();
2580
2581        normalize_span_category(&mut attributes);
2582
2583        assert_annotated_snapshot!(attributes, @r#"
2584        {
2585          "sentry.category": {
2586            "type": "string",
2587            "value": "http"
2588          },
2589          "sentry.op": {
2590            "type": "string",
2591            "value": "http.client"
2592          }
2593        }
2594        "#);
2595    }
2596
2597    #[test]
2598    fn test_normalize_span_category_from_op_ui_framework() {
2599        let mut attributes = Annotated::<Attributes>::from_json(
2600            r#"{
2601          "sentry.op": {
2602            "type": "string",
2603            "value": "ui.react.render"
2604          }
2605        }"#,
2606        )
2607        .unwrap();
2608
2609        normalize_span_category(&mut attributes);
2610
2611        assert_annotated_snapshot!(attributes, @r#"
2612        {
2613          "sentry.category": {
2614            "type": "string",
2615            "value": "ui.react"
2616          },
2617          "sentry.op": {
2618            "type": "string",
2619            "value": "ui.react.render"
2620          }
2621        }
2622        "#);
2623    }
2624
2625    #[test]
2626    fn test_normalize_span_category_from_db_system() {
2627        // Category derived from db.system.name when no op
2628        let mut attributes = Annotated::<Attributes>::from_json(
2629            r#"{
2630          "db.system.name": {
2631            "type": "string",
2632            "value": "mongodb"
2633          }
2634        }"#,
2635        )
2636        .unwrap();
2637
2638        normalize_span_category(&mut attributes);
2639
2640        assert_annotated_snapshot!(attributes, @r#"
2641        {
2642          "db.system.name": {
2643            "type": "string",
2644            "value": "mongodb"
2645          },
2646          "sentry.category": {
2647            "type": "string",
2648            "value": "db"
2649          }
2650        }
2651        "#);
2652    }
2653
2654    #[test]
2655    fn test_normalize_span_category_from_http_method() {
2656        // Category derived from http.request.method when no op or db
2657        let mut attributes = Annotated::<Attributes>::from_json(
2658            r#"{
2659          "http.request.method": {
2660            "type": "string",
2661            "value": "GET"
2662          }
2663        }"#,
2664        )
2665        .unwrap();
2666
2667        normalize_span_category(&mut attributes);
2668
2669        assert_annotated_snapshot!(attributes, @r#"
2670        {
2671          "http.request.method": {
2672            "type": "string",
2673            "value": "GET"
2674          },
2675          "sentry.category": {
2676            "type": "string",
2677            "value": "http"
2678          }
2679        }
2680        "#);
2681    }
2682
2683    #[test]
2684    fn test_normalize_span_category_from_ui_component() {
2685        // Category derived from ui.component_name
2686        let mut attributes = Annotated::<Attributes>::from_json(
2687            r#"{
2688          "ui.component_name": {
2689            "type": "string",
2690            "value": "MyComponent"
2691          }
2692        }"#,
2693        )
2694        .unwrap();
2695
2696        normalize_span_category(&mut attributes);
2697
2698        assert_annotated_snapshot!(attributes, @r#"
2699        {
2700          "sentry.category": {
2701            "type": "string",
2702            "value": "ui"
2703          },
2704          "ui.component_name": {
2705            "type": "string",
2706            "value": "MyComponent"
2707          }
2708        }
2709        "#);
2710    }
2711
2712    #[test]
2713    fn test_normalize_span_category_from_resource() {
2714        // Category derived from resource.render_blocking_status
2715        let mut attributes = Annotated::<Attributes>::from_json(
2716            r#"{
2717          "resource.render_blocking_status": {
2718            "type": "string",
2719            "value": "blocking"
2720          }
2721        }"#,
2722        )
2723        .unwrap();
2724
2725        normalize_span_category(&mut attributes);
2726
2727        assert_annotated_snapshot!(attributes, @r#"
2728        {
2729          "resource.render_blocking_status": {
2730            "type": "string",
2731            "value": "blocking"
2732          },
2733          "sentry.category": {
2734            "type": "string",
2735            "value": "resource"
2736          }
2737        }
2738        "#);
2739    }
2740
2741    #[test]
2742    fn test_normalize_span_category_from_browser_origin() {
2743        // Category derived from sentry.origin with browser metrics value
2744        let mut attributes = Annotated::from_json(
2745            r#"{
2746          "sentry.origin": {
2747            "type": "string",
2748            "value": "auto.ui.browser.metrics"
2749          }
2750        }"#,
2751        )
2752        .unwrap();
2753
2754        normalize_span_category(&mut attributes);
2755
2756        assert_annotated_snapshot!(attributes, @r#"
2757        {
2758          "sentry.category": {
2759            "type": "string",
2760            "value": "browser"
2761          },
2762          "sentry.origin": {
2763            "type": "string",
2764            "value": "auto.ui.browser.metrics"
2765          }
2766        }
2767        "#);
2768    }
2769
2770    fn normalized_sentry_user(json: &str) -> Option<String> {
2771        let mut attributes = Annotated::<Attributes>::from_json(json).unwrap();
2772        normalize_sentry_user(&mut attributes);
2773        attributes
2774            .value()?
2775            .get_value(SENTRY__USER)?
2776            .as_str()
2777            .map(str::to_owned)
2778    }
2779
2780    #[test]
2781    fn test_normalize_sentry_user_id() {
2782        let user = normalized_sentry_user(
2783            r#"{
2784          "user.id": {"type": "string", "value": "ident"},
2785          "user.name": {"type": "string", "value": "username"},
2786          "user.email": {"type": "string", "value": "email"},
2787          "user.ip_address": {"type": "string", "value": "127.0.0.1"}
2788        }"#,
2789        );
2790        assert_eq!(user.as_deref(), Some("id:ident"));
2791    }
2792
2793    #[test]
2794    fn test_normalize_sentry_user_integer_id() {
2795        let user = normalized_sentry_user(
2796            r#"{
2797          "user.id": {"type": "integer", "value": 42},
2798          "user.name": {"type": "string", "value": "username"}
2799        }"#,
2800        );
2801        assert_eq!(user.as_deref(), Some("id:42"));
2802    }
2803
2804    #[test]
2805    fn test_normalize_sentry_user_username() {
2806        let user = normalized_sentry_user(
2807            r#"{
2808          "user.name": {"type": "string", "value": "username"},
2809          "user.email": {"type": "string", "value": "email"},
2810          "user.ip_address": {"type": "string", "value": "127.0.0.1"}
2811        }"#,
2812        );
2813        assert_eq!(user.as_deref(), Some("username:username"));
2814    }
2815
2816    #[test]
2817    fn test_normalize_sentry_user_email() {
2818        let user = normalized_sentry_user(
2819            r#"{
2820          "user.email": {"type": "string", "value": "email"},
2821          "user.ip_address": {"type": "string", "value": "127.0.0.1"}
2822        }"#,
2823        );
2824        assert_eq!(user.as_deref(), Some("email:email"));
2825    }
2826
2827    #[test]
2828    fn test_normalize_sentry_user_ip_address() {
2829        let user = normalized_sentry_user(
2830            r#"{
2831          "user.ip_address": {"type": "string", "value": "127.0.0.1"}
2832        }"#,
2833        );
2834        assert_eq!(user.as_deref(), Some("ip:127.0.0.1"));
2835    }
2836
2837    #[test]
2838    fn test_normalize_sentry_user_none() {
2839        let user = normalized_sentry_user(
2840            r#"{
2841          "client.address": {"type": "string", "value": "127.0.0.1"}
2842        }"#,
2843        );
2844        assert_eq!(user, None);
2845    }
2846
2847    #[test]
2848    fn test_normalize_sentry_user_existing() {
2849        let user = normalized_sentry_user(
2850            r#"{
2851          "sentry.user": {"type": "string", "value": "id:existing"},
2852          "user.id": {"type": "string", "value": "ident"}
2853        }"#,
2854        );
2855        assert_eq!(user.as_deref(), Some("id:existing"));
2856    }
2857
2858    #[test]
2859    fn test_normalize_sentry_user_skips_scrubbed() {
2860        let user = normalized_sentry_user(
2861            r#"{
2862          "user.id": {"type": "string", "value": null},
2863          "user.name": {"type": "string", "value": "[Filtered]"},
2864          "user.email": {"type": "string", "value": "[email]"},
2865          "user.ip_address": {"type": "string", "value": "127.0.0.1"},
2866          "_meta": {
2867            "user.id": {"value": {"": {"rem": [["@anything:remove", "x"]]}}},
2868            "user.name": {"value": {"": {"rem": [["@password:filter", "s", 0, 10]]}}},
2869            "user.email": {"value": {"": {"rem": [["@email:replace", "s", 0, 7]]}}}
2870          }
2871        }"#,
2872        );
2873        assert_eq!(user.as_deref(), Some("ip:127.0.0.1"));
2874    }
2875
2876    #[test]
2877    fn test_normalize_sentry_user_all_scrubbed() {
2878        let user = normalized_sentry_user(
2879            r#"{
2880          "user.email": {"type": "string", "value": "[email]"},
2881          "_meta": {
2882            "user.email": {"value": {"": {"rem": [["@email:replace", "s", 0, 7]]}}}
2883          }
2884        }"#,
2885        );
2886        assert_eq!(user, None);
2887    }
2888
2889    #[test]
2890    fn test_normalize_sentry_user_keeps_pseudonymized() {
2891        let user = normalized_sentry_user(
2892            r#"{
2893          "user.email": {"type": "string", "value": "3C1B2D7A"},
2894          "user.ip_address": {"type": "string", "value": "127.0.0.1"},
2895          "_meta": {
2896            "user.email": {"value": {"": {"rem": [["@email:hash", "p", 0, 8]]}}}
2897          }
2898        }"#,
2899        );
2900        assert_eq!(user.as_deref(), Some("email:3C1B2D7A"));
2901    }
2902
2903    #[test]
2904    fn test_normalize_client_address_auto_with_ip() {
2905        let mut attributes = Annotated::from_json(
2906            r#"{
2907          "client.address": {
2908            "type": "string",
2909            "value": "{{auto}}"
2910          }
2911        }"#,
2912        )
2913        .unwrap();
2914
2915        normalize_client_address(&mut attributes, Some("192.168.1.1".parse().unwrap()));
2916
2917        assert_annotated_snapshot!(attributes, @r#"
2918        {
2919          "client.address": {
2920            "type": "string",
2921            "value": "192.168.1.1"
2922          }
2923        }
2924        "#);
2925    }
2926
2927    #[test]
2928    fn test_normalize_client_address_auto_without_ip() {
2929        let mut attributes = Annotated::from_json(
2930            r#"{
2931          "client.address": {
2932            "type": "string",
2933            "value": "{{auto}}"
2934          }
2935        }"#,
2936        )
2937        .unwrap();
2938
2939        normalize_client_address(&mut attributes, None);
2940
2941        assert_annotated_snapshot!(attributes, @r#"
2942        {}
2943        "#);
2944    }
2945
2946    #[test]
2947    fn test_normalize_client_address_explicit_not_replaced() {
2948        let mut attributes = Annotated::from_json(
2949            r#"{
2950          "client.address": {
2951            "type": "string",
2952            "value": "10.0.0.1"
2953          }
2954        }"#,
2955        )
2956        .unwrap();
2957
2958        normalize_client_address(&mut attributes, Some("192.168.1.1".parse().unwrap()));
2959
2960        assert_annotated_snapshot!(attributes, @r#"
2961        {
2962          "client.address": {
2963            "type": "string",
2964            "value": "10.0.0.1"
2965          }
2966        }
2967        "#);
2968    }
2969
2970    #[test]
2971    fn test_normalize_client_address_missing_attribute() {
2972        let mut attributes = Annotated::empty();
2973
2974        normalize_client_address(&mut attributes, Some("192.168.1.1".parse().unwrap()));
2975
2976        assert!(attributes.is_empty());
2977    }
2978
2979    #[test]
2980    fn test_normalize_client_address_user_ip_address_auto_with_ip() {
2981        let mut attributes = Annotated::from_json(
2982            r#"{
2983          "user.ip_address": {
2984            "type": "string",
2985            "value": "{{auto}}"
2986          }
2987        }"#,
2988        )
2989        .unwrap();
2990
2991        normalize_client_address(&mut attributes, Some("192.168.1.1".parse().unwrap()));
2992
2993        assert_annotated_snapshot!(attributes, @r#"
2994        {
2995          "user.ip_address": {
2996            "type": "string",
2997            "value": "192.168.1.1"
2998          }
2999        }
3000        "#);
3001    }
3002
3003    #[test]
3004    fn test_normalize_client_address_user_ip_address_auto_without_ip() {
3005        let mut attributes = Annotated::from_json(
3006            r#"{
3007          "user.ip_address": {
3008            "type": "string",
3009            "value": "{{auto}}"
3010          }
3011        }"#,
3012        )
3013        .unwrap();
3014
3015        normalize_client_address(&mut attributes, None);
3016
3017        assert_annotated_snapshot!(attributes, @r#"
3018        {}
3019        "#);
3020    }
3021
3022    #[test]
3023    fn test_normalize_client_address_auto_with_ipv6() {
3024        let mut attributes = Annotated::from_json(
3025            r#"{
3026          "client.address": {
3027            "type": "string",
3028            "value": "{{auto}}"
3029          }
3030        }"#,
3031        )
3032        .unwrap();
3033
3034        normalize_client_address(&mut attributes, Some("2001:db8::1".parse().unwrap()));
3035
3036        assert_annotated_snapshot!(attributes, @r#"
3037        {
3038          "client.address": {
3039            "type": "string",
3040            "value": "2001:db8::1"
3041          }
3042        }
3043        "#);
3044    }
3045
3046    #[test]
3047    fn test_normalize_inject_client_address_inserts_when_missing() {
3048        let mut attributes = Annotated::empty();
3049
3050        normalize_inject_client_address(&mut attributes, Some("192.168.1.1".parse().unwrap()));
3051
3052        assert_annotated_snapshot!(attributes, @r#"
3053        {
3054          "client.address": {
3055            "type": "string",
3056            "value": "192.168.1.1"
3057          }
3058        }
3059        "#);
3060    }
3061
3062    #[test]
3063    fn test_normalize_inject_client_address_does_not_overwrite() {
3064        let mut attributes = Annotated::from_json(
3065            r#"{
3066          "client.address": {
3067            "type": "string",
3068            "value": "10.0.0.1"
3069          }
3070        }"#,
3071        )
3072        .unwrap();
3073
3074        normalize_inject_client_address(&mut attributes, Some("192.168.1.1".parse().unwrap()));
3075
3076        assert_annotated_snapshot!(attributes, @r#"
3077        {
3078          "client.address": {
3079            "type": "string",
3080            "value": "10.0.0.1"
3081          }
3082        }
3083        "#);
3084    }
3085
3086    #[test]
3087    fn test_normalize_inject_client_address_none_ip() {
3088        let mut attributes = Annotated::from_json(r#"{}"#).unwrap();
3089
3090        normalize_inject_client_address(&mut attributes, None);
3091
3092        assert_annotated_snapshot!(attributes, @r#"
3093        {}
3094        "#);
3095    }
3096
3097    #[test]
3098    fn test_normalize_inject_client_address_ipv6() {
3099        let mut attributes = Annotated::empty();
3100
3101        normalize_inject_client_address(&mut attributes, Some("2001:db8::1".parse().unwrap()));
3102
3103        assert_annotated_snapshot!(attributes, @r#"
3104        {
3105          "client.address": {
3106            "type": "string",
3107            "value": "2001:db8::1"
3108          }
3109        }
3110        "#);
3111    }
3112
3113    #[test]
3114    fn test_normalize_span_category_no_match() {
3115        // No category derived when no relevant attributes are present
3116        let mut attributes = Annotated::<Attributes>::from_json(
3117            r#"{
3118          "some.other.attribute": {
3119            "type": "string",
3120            "value": "value"
3121          }
3122        }"#,
3123        )
3124        .unwrap();
3125
3126        normalize_span_category(&mut attributes);
3127
3128        assert_annotated_snapshot!(attributes, @r#"
3129        {
3130          "some.other.attribute": {
3131            "type": "string",
3132            "value": "value"
3133          }
3134        }
3135        "#);
3136    }
3137
3138    #[test]
3139    fn test_normalize_release_valid() {
3140        let mut attributes = Annotated::from_json(
3141            r#"{
3142          "sentry.release": {
3143            "type": "string",
3144            "value": "my-app@1.0.0"
3145          }
3146        }"#,
3147        )
3148        .unwrap();
3149
3150        normalize_release(&mut attributes);
3151
3152        assert_annotated_snapshot!(attributes, @r#"
3153        {
3154          "sentry.release": {
3155            "type": "string",
3156            "value": "my-app@1.0.0"
3157          }
3158        }
3159        "#);
3160    }
3161
3162    #[test]
3163    fn test_normalize_release_invalid() {
3164        let mut attributes = Annotated::from_json(
3165            r#"{
3166          "sentry.release": {
3167            "type": "string",
3168            "value": "latest"
3169          }
3170        }"#,
3171        )
3172        .unwrap();
3173
3174        normalize_release(&mut attributes);
3175
3176        assert_annotated_snapshot!(attributes, @r#"
3177        {
3178          "sentry.release": null,
3179          "_meta": {
3180            "sentry.release": {
3181              "": {
3182                "err": [
3183                  "invalid_data"
3184                ],
3185                "val": {
3186                  "type": "string",
3187                  "value": "latest"
3188                }
3189              }
3190            }
3191          }
3192        }
3193        "#);
3194    }
3195
3196    #[test]
3197    fn test_normalize_release_too_long() {
3198        let mut attributes = Annotated::new(Attributes::new());
3199        attributes
3200            .get_or_insert_with(Default::default)
3201            .insert(SENTRY__RELEASE, "a".repeat(251));
3202
3203        normalize_release(&mut attributes);
3204
3205        let release = attributes.value().unwrap().0.get(SENTRY__RELEASE).unwrap();
3206        assert!(release.value().is_none());
3207        assert!(release.meta().has_errors());
3208    }
3209
3210    #[test]
3211    fn test_normalize_client_sample_rate_valid() {
3212        let mut attributes = Annotated::from_json(
3213            r#"{
3214          "sentry.client_sample_rate": {
3215            "type": "double",
3216            "value": 1.0
3217          }
3218        }"#,
3219        )
3220        .unwrap();
3221
3222        normalize_client_sample_rate(&mut attributes, None);
3223
3224        assert_annotated_snapshot!(attributes, @r#"
3225        {
3226          "sentry.client_sample_rate": {
3227            "type": "double",
3228            "value": 1.0
3229          }
3230        }
3231        "#);
3232    }
3233
3234    #[test]
3235    fn test_normalize_client_sample_rate_missing_uses_dsc() {
3236        let mut attributes = Annotated::new(Attributes::new());
3237
3238        normalize_client_sample_rate(&mut attributes, Some(0.25));
3239
3240        assert_annotated_snapshot!(attributes, @r#"
3241        {
3242          "sentry.client_sample_rate": {
3243            "type": "double",
3244            "value": 0.25
3245          }
3246        }
3247        "#);
3248    }
3249
3250    #[test]
3251    fn test_normalize_client_sample_rate_missing_defaults_to_one() {
3252        let mut attributes = Annotated::new(Attributes::new());
3253
3254        normalize_client_sample_rate(&mut attributes, None);
3255
3256        assert_annotated_snapshot!(attributes, @r#"
3257        {
3258          "sentry.client_sample_rate": {
3259            "type": "double",
3260            "value": 1.0
3261          }
3262        }
3263        "#);
3264    }
3265
3266    #[test]
3267    fn test_normalize_client_sample_rate_invalid_dsc_marked_as_error() {
3268        let mut attributes = Annotated::new(Attributes::new());
3269
3270        normalize_client_sample_rate(&mut attributes, Some(0.0));
3271
3272        assert_annotated_snapshot!(attributes, @r#"
3273        {
3274          "sentry.client_sample_rate": null,
3275          "_meta": {
3276            "sentry.client_sample_rate": {
3277              "": {
3278                "err": [
3279                  [
3280                    "invalid_data",
3281                    {
3282                      "reason": "expected sample rate > 0.0, <= 1.0"
3283                    }
3284                  ]
3285                ]
3286              }
3287            }
3288          }
3289        }
3290        "#);
3291    }
3292
3293    #[test]
3294    fn test_normalize_client_sample_rate_invalid_too_small() {
3295        let mut attributes = {
3296            let mut attrs = Attributes::new();
3297            attrs.insert(SENTRY__CLIENT_SAMPLE_RATE, 0.0);
3298            Annotated::new(attrs)
3299        };
3300
3301        normalize_client_sample_rate(&mut attributes, None);
3302
3303        assert_annotated_snapshot!(attributes, @r#"
3304        {
3305          "sentry.client_sample_rate": null,
3306          "_meta": {
3307            "sentry.client_sample_rate": {
3308              "": {
3309                "err": [
3310                  [
3311                    "invalid_data",
3312                    {
3313                      "reason": "expected sample rate > 0.0, <= 1.0"
3314                    }
3315                  ]
3316                ]
3317              }
3318            }
3319          }
3320        }
3321        "#);
3322    }
3323
3324    #[test]
3325    fn test_normalize_client_sample_rate_invalid_too_large() {
3326        let mut attributes = {
3327            let mut attrs = Attributes::new();
3328            attrs.insert(SENTRY__CLIENT_SAMPLE_RATE, 1.1);
3329            Annotated::new(attrs)
3330        };
3331
3332        normalize_client_sample_rate(&mut attributes, None);
3333
3334        assert_annotated_snapshot!(attributes, @r#"
3335        {
3336          "sentry.client_sample_rate": null,
3337          "_meta": {
3338            "sentry.client_sample_rate": {
3339              "": {
3340                "err": [
3341                  [
3342                    "invalid_data",
3343                    {
3344                      "reason": "expected sample rate > 0.0, <= 1.0"
3345                    }
3346                  ]
3347                ]
3348              }
3349            }
3350          }
3351        }
3352        "#);
3353    }
3354
3355    #[test]
3356    fn test_normalize_client_sample_rate_invalid_type() {
3357        let mut attributes = {
3358            let mut attrs = Attributes::new();
3359            attrs.insert(SENTRY__CLIENT_SAMPLE_RATE, "foobar");
3360            Annotated::new(attrs)
3361        };
3362
3363        normalize_client_sample_rate(&mut attributes, None);
3364
3365        assert_annotated_snapshot!(attributes, @r#"
3366        {
3367          "sentry.client_sample_rate": null,
3368          "_meta": {
3369            "sentry.client_sample_rate": {
3370              "": {
3371                "err": [
3372                  [
3373                    "invalid_data",
3374                    {
3375                      "reason": "expected sample rate > 0.0, <= 1.0"
3376                    }
3377                  ]
3378                ]
3379              }
3380            }
3381          }
3382        }
3383        "#);
3384    }
3385
3386    #[test]
3387    fn test_normalize_mobile_measurements() {
3388        let json = r#"
3389        {
3390            "frames.slow": {"value": 1, "type": "integer"},
3391            "app.vitals.frames.frozen.count": {"value": 2, "type": "integer"},
3392            "frames.total": {"value": 4, "type": "integer"},
3393            "stall_total_time": {"value": 4000, "type": "integer"}
3394        }
3395        "#;
3396
3397        let mut attributes = Annotated::<Attributes>::from_json(json).unwrap();
3398
3399        normalize_attribute_names(&mut attributes);
3400        normalize_mobile_measurements(&mut attributes, Some(Duration::from_secs(5)));
3401
3402        insta::assert_json_snapshot!(SerializableAnnotated(&attributes),  @r#"
3403        {
3404          "app.vitals.frames.frozen.count": {
3405            "type": "integer",
3406            "value": 2
3407          },
3408          "app.vitals.frames.frozen.rate": {
3409            "type": "double",
3410            "value": 0.5
3411          },
3412          "app.vitals.frames.slow.count": {
3413            "type": "integer",
3414            "value": 1
3415          },
3416          "app.vitals.frames.slow.rate": {
3417            "type": "double",
3418            "value": 0.25
3419          },
3420          "app.vitals.frames.total.count": {
3421            "type": "integer",
3422            "value": 4
3423          },
3424          "app.vitals.stall.duration": {
3425            "type": "integer",
3426            "value": 4000
3427          },
3428          "app.vitals.stall.percentage": {
3429            "type": "double",
3430            "value": 0.8
3431          },
3432          "frames.slow": {
3433            "type": "integer",
3434            "value": 1
3435          },
3436          "frames.total": {
3437            "type": "integer",
3438            "value": 4
3439          },
3440          "stall_total_time": {
3441            "type": "integer",
3442            "value": 4000
3443          }
3444        }
3445        "#);
3446    }
3447}