Skip to main content

relay_event_schema/protocol/
span.rs

1mod convert;
2
3use std::fmt;
4use std::ops::Deref;
5use std::str::FromStr;
6
7use relay_protocol::{
8    Annotated, Array, Empty, Error, FromValue, Getter, IntoValue, Object, Val, Value,
9};
10
11use crate::processor::{Pii, ProcessValue, ProcessingState};
12use crate::protocol::{
13    EventId, IpAddr, JsonLenientString, LenientString, Measurements, OperationType, OriginType,
14    SpanId, SpanStatus, ThreadId, Timestamp, TraceId,
15};
16
17#[derive(Clone, Debug, Default, PartialEq, Empty, FromValue, IntoValue, ProcessValue)]
18#[metastructure(process_func = "process_span", value_type = "Span", trim = false)]
19pub struct Span {
20    /// Timestamp when the span was ended.
21    #[metastructure(required = true)]
22    pub timestamp: Annotated<Timestamp>,
23
24    /// Timestamp when the span started.
25    #[metastructure(required = true)]
26    pub start_timestamp: Annotated<Timestamp>,
27
28    /// The amount of time in milliseconds spent in this span,
29    /// excluding its immediate child spans.
30    pub exclusive_time: Annotated<f64>,
31
32    /// Span type (see `OperationType` docs).
33    #[metastructure(max_chars = 128)]
34    pub op: Annotated<OperationType>,
35
36    /// The Span id.
37    #[metastructure(required = true)]
38    pub span_id: Annotated<SpanId>,
39
40    /// The ID of the span enclosing this span.
41    pub parent_span_id: Annotated<SpanId>,
42
43    /// The ID of the trace the span belongs to.
44    #[metastructure(required = true)]
45    pub trace_id: Annotated<TraceId>,
46
47    /// A unique identifier for a segment within a trace (8 byte hexadecimal string).
48    ///
49    /// For spans embedded in transactions, the `segment_id` is the `span_id` of the containing
50    /// transaction.
51    pub segment_id: Annotated<SpanId>,
52
53    /// Whether or not the current span is the root of the segment.
54    pub is_segment: Annotated<bool>,
55
56    /// Indicates whether a span's parent is remote.
57    ///
58    /// For OpenTelemetry spans, this is derived from span flags bits 8 and 9. See
59    /// `SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK` and `SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK`.
60    ///
61    /// The states are:
62    ///  - `empty`: unknown
63    ///  - `false`: is not remote
64    ///  - `true`: is remote
65    pub is_remote: Annotated<bool>,
66
67    /// The status of a span.
68    pub status: Annotated<SpanStatus>,
69
70    /// Human readable description of a span (e.g. method URL).
71    #[metastructure(pii = "maybe")]
72    pub description: Annotated<String>,
73
74    /// Arbitrary tags on a span, like on the top-level event.
75    #[metastructure(pii = "maybe")]
76    pub tags: Annotated<Object<JsonLenientString>>,
77
78    /// The origin of the span indicates what created the span (see [OriginType] docs).
79    #[metastructure(max_chars = 128, allow_chars = "a-zA-Z0-9_.")]
80    pub origin: Annotated<OriginType>,
81
82    /// ID of a profile that can be associated with the span.
83    pub profile_id: Annotated<EventId>,
84
85    /// Arbitrary additional data on a span.
86    ///
87    /// Besides arbitrary user data, this object also contains SDK-provided fields used by the
88    /// product (see <https://develop.sentry.dev/sdk/performance/span-data-conventions/>).
89    #[metastructure(pii = "true")]
90    pub data: Annotated<SpanData>,
91
92    /// Links from this span to other spans
93    #[metastructure(pii = "maybe")]
94    pub links: Annotated<Array<SpanLink>>,
95
96    /// Tags generated by Relay. These tags are a superset of the tags set on span metrics.
97    pub sentry_tags: Annotated<SentryTags>,
98
99    /// Timestamp when the span has been received by Sentry.
100    pub received: Annotated<Timestamp>,
101
102    /// Measurements which holds observed values such as web vitals.
103    #[metastructure(skip_serialization = "empty")]
104    #[metastructure(omit_from_schema)] // we only document error events for now
105    pub measurements: Annotated<Measurements>,
106
107    /// Platform identifier.
108    ///
109    /// See [`Event::platform`](`crate::protocol::Event::platform`).
110    #[metastructure(skip_serialization = "empty")]
111    pub platform: Annotated<String>,
112
113    /// Whether the span is a segment span that was converted from a transaction.
114    #[metastructure(skip_serialization = "empty")]
115    pub was_transaction: Annotated<bool>,
116
117    // Used to clarify the relationship between parents and children, or to distinguish between
118    // spans, e.g. a `server` and `client` span with the same name.
119    //
120    // See <https://opentelemetry.io/docs/specs/otel/trace/api/#spankind>
121    #[metastructure(skip_serialization = "empty", trim = false)]
122    pub kind: Annotated<SpanKind>,
123
124    /// Additional arbitrary fields for forwards compatibility.
125    #[metastructure(additional_properties, pii = "maybe")]
126    pub other: Object<Value>,
127}
128
129impl Span {
130    /// Returns the value of an attribute on the span.
131    ///
132    /// This primarily looks up the attribute in the `data` object, but falls back to the `tags`
133    /// object if the attribute is not found.
134    fn attribute(&self, key: &str) -> Option<Val<'_>> {
135        Some(match self.data.value()?.get_value(key) {
136            Some(value) => value,
137            None => self.tags.value()?.get(key)?.as_str()?.into(),
138        })
139    }
140}
141
142impl Getter for Span {
143    fn get_value(&self, path: &str) -> Option<Val<'_>> {
144        let span_prefix = path.strip_prefix("span.");
145        if let Some(span_prefix) = span_prefix {
146            return Some(match span_prefix {
147                "exclusive_time" => self.exclusive_time.value()?.into(),
148                "description" => self.description.as_str()?.into(),
149                "op" => self.op.as_str()?.into(),
150                "span_id" => self.span_id.value()?.into(),
151                "parent_span_id" => self.parent_span_id.value()?.into(),
152                "trace_id" => self.trace_id.value()?.deref().into(),
153                "status" => self.status.as_str()?.into(),
154                "is_segment" => self.is_segment.value()?.into(),
155                "origin" => self.origin.as_str()?.into(),
156                "duration" => {
157                    let start_timestamp = *self.start_timestamp.value()?;
158                    let timestamp = *self.timestamp.value()?;
159                    relay_common::time::chrono_to_positive_millis(timestamp - start_timestamp)
160                        .into()
161                }
162                "was_transaction" => self.was_transaction.value().unwrap_or(&false).into(),
163                path => {
164                    if let Some(key) = path.strip_prefix("tags.") {
165                        self.tags.value()?.get(key)?.as_str()?.into()
166                    } else if let Some(key) = path.strip_prefix("data.") {
167                        self.attribute(key)?
168                    } else if let Some(key) = path.strip_prefix("sentry_tags.") {
169                        self.sentry_tags.value()?.get_value(key)?
170                    } else {
171                        let rest = path.strip_prefix("measurements.")?;
172                        let name = rest.strip_suffix(".value")?;
173                        self.measurements
174                            .value()?
175                            .get(name)?
176                            .value()?
177                            .value
178                            .value()?
179                            .into()
180                    }
181                }
182            });
183        }
184
185        // For backward compatibility with event-based rules, we try to support `event.` fields also
186        // for a span.
187        let event_prefix = path.strip_prefix("event.")?;
188        Some(match event_prefix {
189            "release" => self.data.value()?.release.as_str()?.into(),
190            "environment" => self.data.value()?.environment.as_str()?.into(),
191            "transaction" => self.data.value()?.segment_name.as_str()?.into(),
192            "contexts.browser.name" => self.data.value()?.browser_name.as_str()?.into(),
193            // TODO: we might want to add additional fields once they are added to the span.
194            _ => return None,
195        })
196    }
197}
198
199/// Indexable fields added by sentry (server-side).
200#[derive(Clone, Debug, Default, PartialEq, Empty, FromValue, IntoValue, ProcessValue)]
201#[metastructure(trim = false, pii = "maybe")]
202pub struct SentryTags {
203    pub release: Annotated<String>,
204    #[metastructure(pii = "true")]
205    pub user: Annotated<String>,
206    #[metastructure(pii = "true", field = "user.id")]
207    pub user_id: Annotated<String>,
208    #[metastructure(pii = "true", field = "user.ip")]
209    pub user_ip: Annotated<String>,
210    #[metastructure(pii = "true", field = "user.username")]
211    pub user_username: Annotated<String>,
212    #[metastructure(pii = "true", field = "user.email")]
213    pub user_email: Annotated<String>,
214    pub environment: Annotated<String>,
215    pub transaction: Annotated<String>,
216    #[metastructure(field = "transaction.method")]
217    pub transaction_method: Annotated<String>,
218    #[metastructure(field = "transaction.op")]
219    pub transaction_op: Annotated<String>,
220    #[metastructure(field = "browser.name")]
221    pub browser_name: Annotated<String>,
222    #[metastructure(field = "sdk.name")]
223    pub sdk_name: Annotated<String>,
224    #[metastructure(field = "sdk.version")]
225    pub sdk_version: Annotated<String>,
226    pub platform: Annotated<String>,
227    // `"true"` if the transaction was sent by a mobile SDK(String).
228    pub mobile: Annotated<String>,
229    #[metastructure(field = "device.class")]
230    pub device_class: Annotated<String>,
231    #[metastructure(field = "device.family")]
232    pub device_family: Annotated<String>,
233    #[metastructure(field = "device.arch")]
234    pub device_arch: Annotated<String>,
235    #[metastructure(field = "device.battery_level")]
236    pub device_battery_level: Annotated<String>,
237    #[metastructure(field = "device.brand")]
238    pub device_brand: Annotated<String>,
239    #[metastructure(field = "device.charging")]
240    pub device_charging: Annotated<String>,
241    #[metastructure(field = "device.locale")]
242    pub device_locale: Annotated<String>,
243    #[metastructure(field = "device.model_id")]
244    pub device_model_id: Annotated<String>,
245    #[metastructure(field = "device.name")]
246    pub device_name: Annotated<String>,
247    #[metastructure(field = "device.online")]
248    pub device_online: Annotated<String>,
249    #[metastructure(field = "device.orientation")]
250    pub device_orientation: Annotated<String>,
251    #[metastructure(field = "device.screen_density")]
252    pub device_screen_density: Annotated<String>,
253    #[metastructure(field = "device.screen_dpi")]
254    pub device_screen_dpi: Annotated<String>,
255    #[metastructure(field = "device.screen_height_pixels")]
256    pub device_screen_height_pixels: Annotated<String>,
257    #[metastructure(field = "device.screen_width_pixels")]
258    pub device_screen_width_pixels: Annotated<String>,
259    #[metastructure(field = "device.simulator")]
260    pub device_simulator: Annotated<String>,
261    #[metastructure(field = "device.uuid")]
262    pub device_uuid: Annotated<String>,
263    #[metastructure(field = "app.device")]
264    pub app_device: Annotated<String>,
265    #[metastructure(field = "device.model")]
266    pub device_model: Annotated<String>,
267    pub runtime: Annotated<String>,
268    #[metastructure(field = "runtime.name")]
269    pub runtime_name: Annotated<String>,
270    pub browser: Annotated<String>,
271    pub os: Annotated<String>,
272    #[metastructure(field = "os.rooted")]
273    pub os_rooted: Annotated<String>,
274    #[metastructure(field = "gpu.name")]
275    pub gpu_name: Annotated<String>,
276    #[metastructure(field = "gpu.vendor")]
277    pub gpu_vendor: Annotated<String>,
278    #[metastructure(field = "monitor.id")]
279    pub monitor_id: Annotated<String>,
280    #[metastructure(field = "monitor.slug")]
281    pub monitor_slug: Annotated<String>,
282    #[metastructure(field = "request.url")]
283    pub request_url: Annotated<String>,
284    #[metastructure(field = "request.method")]
285    pub request_method: Annotated<String>,
286    // Mobile OS the transaction originated from(String).
287    #[metastructure(field = "os.name")]
288    pub os_name: Annotated<String>,
289    pub action: Annotated<String>,
290    pub category: Annotated<String>,
291    pub description: Annotated<String>,
292    pub domain: Annotated<String>,
293    pub raw_domain: Annotated<String>,
294    pub group: Annotated<String>,
295    #[metastructure(field = "http.decoded_response_content_length")]
296    pub http_decoded_response_content_length: Annotated<String>,
297    #[metastructure(field = "http.response_content_length")]
298    pub http_response_content_length: Annotated<String>,
299    #[metastructure(field = "http.response_transfer_size")]
300    pub http_response_transfer_size: Annotated<String>,
301    #[metastructure(field = "resource.render_blocking_status")]
302    pub resource_render_blocking_status: Annotated<String>,
303    pub op: Annotated<String>,
304    pub status: Annotated<String>,
305    pub status_code: Annotated<String>,
306    pub system: Annotated<String>,
307    /// Contributes to Time-To-Initial-Display(String).
308    pub ttid: Annotated<String>,
309    /// Contributes to Time-To-Full-Display(String).
310    pub ttfd: Annotated<String>,
311    /// File extension for resource spans(String).
312    pub file_extension: Annotated<String>,
313    /// Span started on main thread(String).
314    pub main_thread: Annotated<String>,
315    /// The start type of the application when the span occurred(String).
316    pub app_start_type: Annotated<String>,
317    pub replay_id: Annotated<String>,
318    #[metastructure(field = "cache.hit")]
319    pub cache_hit: Annotated<String>,
320    #[metastructure(field = "cache.key")]
321    pub cache_key: Annotated<String>,
322    #[metastructure(field = "trace.status")]
323    pub trace_status: Annotated<String>,
324    #[metastructure(field = "messaging.destination.name")]
325    pub messaging_destination_name: Annotated<String>,
326    #[metastructure(field = "messaging.message.id")]
327    pub messaging_message_id: Annotated<String>,
328    #[metastructure(field = "messaging.operation.name")]
329    pub messaging_operation_name: Annotated<String>,
330    #[metastructure(field = "messaging.operation.type")]
331    pub messaging_operation_type: Annotated<String>,
332    #[metastructure(field = "thread.name")]
333    pub thread_name: Annotated<String>,
334    #[metastructure(field = "thread.id")]
335    pub thread_id: Annotated<String>,
336    pub profiler_id: Annotated<String>,
337    #[metastructure(field = "user.geo.city")]
338    pub user_city: Annotated<String>,
339    #[metastructure(field = "user.geo.country_code")]
340    pub user_country_code: Annotated<String>,
341    #[metastructure(field = "user.geo.region")]
342    pub user_region: Annotated<String>,
343    #[metastructure(field = "user.geo.subdivision")]
344    pub user_subdivision: Annotated<String>,
345    #[metastructure(field = "user.geo.subregion")]
346    pub user_subregion: Annotated<String>,
347    pub name: Annotated<String>,
348    // no need for an `other` entry here because these fields are added server-side.
349    // If an upstream relay does not recognize a field it will be dropped.
350}
351
352impl Getter for SentryTags {
353    fn get_value(&self, path: &str) -> Option<Val<'_>> {
354        let value = match path {
355            "action" => &self.action,
356            "app_start_type" => &self.app_start_type,
357            "browser.name" => &self.browser_name,
358            "cache.hit" => &self.cache_hit,
359            "cache.key" => &self.cache_key,
360            "category" => &self.category,
361            "description" => &self.description,
362            "device.class" => &self.device_class,
363            "device.family" => &self.device_family,
364            "device.arch" => &self.device_arch,
365            "device.battery_level" => &self.device_battery_level,
366            "device.brand" => &self.device_brand,
367            "device.charging" => &self.device_charging,
368            "device.locale" => &self.device_locale,
369            "device.model_id" => &self.device_model_id,
370            "device.name" => &self.device_name,
371            "device.online" => &self.device_online,
372            "device.orientation" => &self.device_orientation,
373            "device.screen_density" => &self.device_screen_density,
374            "device.screen_dpi" => &self.device_screen_dpi,
375            "device.screen_height_pixels" => &self.device_screen_height_pixels,
376            "device.screen_width_pixels" => &self.device_screen_width_pixels,
377            "device.simulator" => &self.device_simulator,
378            "device.uuid" => &self.device_uuid,
379            "app.device" => &self.app_device,
380            "device.model" => &self.device_model,
381            "runtime" => &self.runtime,
382            "runtime.name" => &self.runtime_name,
383            "browser" => &self.browser,
384            "os" => &self.os,
385            "os.rooted" => &self.os_rooted,
386            "gpu.name" => &self.gpu_name,
387            "gpu.vendor" => &self.gpu_vendor,
388            "monitor.id" => &self.monitor_id,
389            "monitor.slug" => &self.monitor_slug,
390            "request.url" => &self.request_url,
391            "request.method" => &self.request_method,
392            "domain" => &self.domain,
393            "environment" => &self.environment,
394            "file_extension" => &self.file_extension,
395            "group" => &self.group,
396            "http.decoded_response_content_length" => &self.http_decoded_response_content_length,
397            "http.response_content_length" => &self.http_response_content_length,
398            "http.response_transfer_size" => &self.http_response_transfer_size,
399            "main_thread" => &self.main_thread,
400            "messaging.destination.name" => &self.messaging_destination_name,
401            "messaging.message.id" => &self.messaging_message_id,
402            "messaging.operation.name" => &self.messaging_operation_name,
403            "messaging.operation.type" => &self.messaging_operation_type,
404            "mobile" => &self.mobile,
405            "name" => &self.name,
406            "op" => &self.op,
407            "os.name" => &self.os_name,
408            "platform" => &self.platform,
409            "profiler_id" => &self.profiler_id,
410            "raw_domain" => &self.raw_domain,
411            "release" => &self.release,
412            "replay_id" => &self.replay_id,
413            "resource.render_blocking_status" => &self.resource_render_blocking_status,
414            "sdk.name" => &self.sdk_name,
415            "sdk.version" => &self.sdk_version,
416            "status_code" => &self.status_code,
417            "status" => &self.status,
418            "system" => &self.system,
419            "thread.id" => &self.thread_id,
420            "thread.name" => &self.thread_name,
421            "trace.status" => &self.trace_status,
422            "transaction.method" => &self.transaction_method,
423            "transaction.op" => &self.transaction_op,
424            "transaction" => &self.transaction,
425            "ttfd" => &self.ttfd,
426            "ttid" => &self.ttid,
427            "user.email" => &self.user_email,
428            "user.geo.city" => &self.user_city,
429            "user.geo.country_code" => &self.user_country_code,
430            "user.geo.region" => &self.user_region,
431            "user.geo.subdivision" => &self.user_subdivision,
432            "user.geo.subregion" => &self.user_subregion,
433            "user.id" => &self.user_id,
434            "user.ip" => &self.user_ip,
435            "user.username" => &self.user_username,
436            "user" => &self.user,
437            _ => return None,
438        };
439        Some(value.as_str()?.into())
440    }
441}
442
443/// Determines the `Pii` value for a field of [`SpanData`] by looking it up in `relay-conventions`.
444///
445/// If the field is not found in the conventions, this returns `Pii::True`
446/// as a precaution.
447fn span_data_pii_from_conventions(state: &ProcessingState) -> Pii {
448    fn inner(state: &ProcessingState) -> Option<Pii> {
449        // `state.keys().next()` is the _last_ segment in the state's
450        // path, i.e. the field name.
451        let key = state.keys().next()?;
452
453        match relay_conventions::attribute_info(key)?.pii {
454            relay_conventions::Pii::True => Some(Pii::True),
455            relay_conventions::Pii::False => Some(Pii::False),
456            relay_conventions::Pii::Maybe => Some(Pii::Maybe),
457        }
458    }
459
460    inner(state).unwrap_or(Pii::True)
461}
462
463/// Arbitrary additional data on a span.
464///
465/// Besides arbitrary user data, this type also contains SDK-provided fields used by the
466/// product (see <https://develop.sentry.dev/sdk/performance/span-data-conventions/>).
467#[derive(Clone, Debug, Default, PartialEq, Empty, FromValue, IntoValue, ProcessValue)]
468#[metastructure(trim = false, pii = "span_data_pii_from_conventions")]
469pub struct SpanData {
470    /// Mobile app start variant.
471    ///
472    /// Can be either "cold" or "warm".
473    #[metastructure(field = "app_start_type")] // TODO: no dot?
474    pub app_start_type: Annotated<Value>,
475
476    /// Name of the AI pipeline or chain being executed.
477    #[metastructure(field = "gen_ai.pipeline.name", legacy_alias = "ai.pipeline.name")]
478    pub gen_ai_pipeline_name: Annotated<Value>,
479
480    /// The total tokens that were used by an LLM call
481    #[metastructure(
482        field = "gen_ai.usage.total_tokens",
483        legacy_alias = "ai.total_tokens.used"
484    )]
485    pub gen_ai_usage_total_tokens: Annotated<Value>,
486
487    /// The input tokens used by an LLM call (usually cheaper than output tokens)
488    #[metastructure(
489        field = "gen_ai.usage.input_tokens",
490        legacy_alias = "ai.prompt_tokens.used",
491        legacy_alias = "gen_ai.usage.prompt_tokens"
492    )]
493    pub gen_ai_usage_input_tokens: Annotated<Value>,
494
495    /// The input tokens used by an LLM call that were cached
496    /// (cheaper and faster than non-cached input tokens)
497    #[metastructure(field = "gen_ai.usage.input_tokens.cached")]
498    pub gen_ai_usage_input_tokens_cached: Annotated<Value>,
499
500    /// The input tokens written to cache during an LLM call
501    #[metastructure(field = "gen_ai.usage.input_tokens.cache_write")]
502    pub gen_ai_usage_input_tokens_cache_write: Annotated<Value>,
503
504    /// The output tokens used by an LLM call (the ones the LLM actually generated)
505    #[metastructure(
506        field = "gen_ai.usage.output_tokens",
507        legacy_alias = "ai.completion_tokens.used",
508        legacy_alias = "gen_ai.usage.completion_tokens"
509    )]
510    pub gen_ai_usage_output_tokens: Annotated<Value>,
511
512    /// The output tokens used to represent the model's internal thought
513    /// process while generating a response
514    #[metastructure(field = "gen_ai.usage.output_tokens.reasoning")]
515    pub gen_ai_usage_output_tokens_reasoning: Annotated<Value>,
516
517    // Exact model used to generate the response (e.g. gpt-4o-mini-2024-07-18)
518    #[metastructure(field = "gen_ai.response.model")]
519    pub gen_ai_response_model: Annotated<Value>,
520
521    /// The name of the GenAI model a request is being made to (e.g. gpt-4)
522    #[metastructure(field = "gen_ai.request.model", legacy_alias = "ai.model_id")]
523    pub gen_ai_request_model: Annotated<Value>,
524
525    /// The context window size of the model in tokens.
526    #[metastructure(field = "gen_ai.context.window_size")]
527    pub gen_ai_context_window_size: Annotated<Value>,
528
529    /// The fraction of the context window used by total tokens.
530    #[metastructure(field = "gen_ai.context.utilization")]
531    pub gen_ai_context_utilization: Annotated<Value>,
532
533    /// The total cost for the tokens used (duplicate field for migration)
534    #[metastructure(field = "gen_ai.cost.total_tokens")]
535    pub gen_ai_cost_total_tokens: Annotated<Value>,
536
537    /// The cost for input tokens used
538    #[metastructure(field = "gen_ai.cost.input_tokens")]
539    pub gen_ai_cost_input_tokens: Annotated<Value>,
540
541    /// The cost for output tokens used
542    #[metastructure(field = "gen_ai.cost.output_tokens")]
543    pub gen_ai_cost_output_tokens: Annotated<Value>,
544
545    /// The input messages to the model call.
546    #[metastructure(
547        field = "gen_ai.input.messages",
548        legacy_alias = "gen_ai.prompt",
549        legacy_alias = "gen_ai.request.messages",
550        legacy_alias = "ai.prompt.messages"
551    )]
552    pub gen_ai_input_messages: Annotated<Value>,
553
554    /// Tool call arguments.
555    #[metastructure(
556        field = "gen_ai.tool.call.arguments",
557        legacy_alias = "gen_ai.tool.input",
558        legacy_alias = "ai.toolCall.args"
559    )]
560    pub gen_ai_tool_call_arguments: Annotated<Value>,
561
562    /// Tool call result.
563    #[metastructure(
564        field = "gen_ai.tool.call.result",
565        legacy_alias = "gen_ai.tool.output",
566        legacy_alias = "ai.toolCall.result"
567    )]
568    pub gen_ai_tool_call_result: Annotated<Value>,
569
570    /// The output messages from the model call.
571    #[metastructure(
572        field = "gen_ai.output.messages",
573        legacy_alias = "gen_ai.response.tool_calls",
574        legacy_alias = "ai.response.toolCalls",
575        legacy_alias = "ai.tool_calls",
576        legacy_alias = "gen_ai.response.text",
577        legacy_alias = "ai.response.text",
578        legacy_alias = "ai.responses"
579    )]
580    pub gen_ai_output_messages: Annotated<Value>,
581
582    /// Whether or not the AI model call's response was streamed back asynchronously
583    #[metastructure(field = "gen_ai.response.streaming", legacy_alias = "ai.streaming")]
584    pub gen_ai_response_streaming: Annotated<Value>,
585
586    ///  Total output tokens per seconds throughput
587    #[metastructure(field = "gen_ai.response.tokens_per_second")]
588    pub gen_ai_response_tokens_per_second: Annotated<Value>,
589
590    /// The tool definitions available for a request to an LLM.
591    #[metastructure(
592        field = "gen_ai.tool.definitions",
593        legacy_alias = "gen_ai.request.available_tools",
594        legacy_alias = "ai.tools"
595    )]
596    pub gen_ai_tool_definitions: Annotated<Value>,
597
598    /// The frequency penalty for a request to an LLM
599    #[metastructure(
600        field = "gen_ai.request.frequency_penalty",
601        legacy_alias = "ai.frequency_penalty"
602    )]
603    pub gen_ai_request_frequency_penalty: Annotated<Value>,
604
605    /// The presence penalty for a request to an LLM
606    #[metastructure(
607        field = "gen_ai.request.presence_penalty",
608        legacy_alias = "ai.presence_penalty"
609    )]
610    pub gen_ai_request_presence_penalty: Annotated<Value>,
611
612    /// The seed for a request to an LLM
613    #[metastructure(field = "gen_ai.request.seed", legacy_alias = "ai.seed")]
614    pub gen_ai_request_seed: Annotated<Value>,
615
616    /// The temperature for a request to an LLM
617    #[metastructure(field = "gen_ai.request.temperature", legacy_alias = "ai.temperature")]
618    pub gen_ai_request_temperature: Annotated<Value>,
619
620    /// The top_k parameter for a request to an LLM
621    #[metastructure(field = "gen_ai.request.top_k", legacy_alias = "ai.top_k")]
622    pub gen_ai_request_top_k: Annotated<Value>,
623
624    /// The top_p parameter for a request to an LLM
625    #[metastructure(field = "gen_ai.request.top_p", legacy_alias = "ai.top_p")]
626    pub gen_ai_request_top_p: Annotated<Value>,
627
628    /// The finish reasons for a response from an LLM.
629    #[metastructure(
630        field = "gen_ai.response.finish_reasons",
631        legacy_alias = "gen_ai.response.finish_reason",
632        legacy_alias = "ai.finish_reason"
633    )]
634    pub gen_ai_response_finish_reasons: Annotated<Value>,
635
636    /// The unique identifier for a response from an LLM
637    #[metastructure(field = "gen_ai.response.id", legacy_alias = "ai.generation_id")]
638    pub gen_ai_response_id: Annotated<Value>,
639
640    /// The GenAI provider name.
641    #[metastructure(
642        field = "gen_ai.provider.name",
643        legacy_alias = "gen_ai.system",
644        legacy_alias = "ai.model.provider"
645    )]
646    pub gen_ai_provider_name: Annotated<Value>,
647
648    /// The system instructions passed to the model.
649    #[metastructure(
650        field = "gen_ai.system_instructions",
651        legacy_alias = "gen_ai.system.message"
652    )]
653    pub gen_ai_system_instructions: Annotated<Value>,
654
655    /// The name of the tool being called
656    #[metastructure(field = "gen_ai.tool.name", legacy_alias = "ai.function_call")]
657    pub gen_ai_tool_name: Annotated<Value>,
658
659    /// The name of the operation being performed.
660    #[metastructure(field = "gen_ai.operation.name")]
661    pub gen_ai_operation_name: Annotated<String>,
662
663    /// The type of the operation being performed.
664    #[metastructure(field = "gen_ai.operation.type")]
665    pub gen_ai_operation_type: Annotated<String>,
666
667    /// The name of the AI agent.
668    #[metastructure(field = "gen_ai.agent.name")]
669    pub gen_ai_agent_name: Annotated<String>,
670
671    /// The function ID of the AI agent.
672    #[metastructure(field = "gen_ai.function_id")]
673    pub gen_ai_function_id: Annotated<String>,
674
675    /// The client's browser name.
676    #[metastructure(field = "browser.name")]
677    pub browser_name: Annotated<String>,
678
679    /// The name of the operation being executed.
680    ///
681    /// E.g. the MongoDB command name such as findAndModify, or the SQL keyword.
682    /// Based on [OpenTelemetry's call level db attributes](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/database.md#call-level-attributes).
683    #[metastructure(field = "db.operation")]
684    pub db_operation: Annotated<Value>,
685
686    /// An identifier for the database management system (DBMS) product being used.
687    ///
688    /// See [OpenTelemetry docs for a list of well-known identifiers](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/database.md#notes-and-well-known-identifiers-for-dbsystem).
689    #[metastructure(field = "db.system")]
690    pub db_system: Annotated<Value>,
691
692    /// The name of a collection (table, container) within the database.
693    ///
694    /// See [OpenTelemetry's database span semantic conventions](https://opentelemetry.io/docs/specs/semconv/database/database-spans/#common-attributes).
695    #[metastructure(
696        field = "db.collection.name",
697        legacy_alias = "db.cassandra.table",
698        legacy_alias = "db.cosmosdb.container",
699        legacy_alias = "db.mongodb.collection",
700        legacy_alias = "db.sql.table"
701    )]
702    pub db_collection_name: Annotated<Value>,
703
704    /// The sentry environment.
705    #[metastructure(field = "sentry.environment", legacy_alias = "environment")]
706    pub environment: Annotated<String>,
707
708    /// The release version of the project.
709    #[metastructure(field = "sentry.release", legacy_alias = "release")]
710    pub release: Annotated<LenientString>,
711
712    /// The decoded body size of the response (in bytes).
713    #[metastructure(field = "http.decoded_response_content_length")]
714    pub http_decoded_response_content_length: Annotated<Value>,
715
716    /// The HTTP method used.
717    #[metastructure(
718        field = "http.request_method",
719        legacy_alias = "http.method",
720        legacy_alias = "method"
721    )]
722    pub http_request_method: Annotated<Value>,
723
724    /// The encoded body size of the response (in bytes).
725    #[metastructure(field = "http.response_content_length")]
726    pub http_response_content_length: Annotated<Value>,
727
728    /// The transfer size of the response (in bytes).
729    #[metastructure(field = "http.response_transfer_size")]
730    pub http_response_transfer_size: Annotated<Value>,
731
732    /// The render blocking status of the resource.
733    #[metastructure(field = "resource.render_blocking_status")]
734    pub resource_render_blocking_status: Annotated<Value>,
735
736    /// Name of the web server host.
737    #[metastructure(field = "server.address")]
738    pub server_address: Annotated<Value>,
739
740    /// Whether cache was hit or miss on a read operation.
741    #[metastructure(field = "cache.hit")]
742    pub cache_hit: Annotated<Value>,
743
744    /// The name of the cache key.
745    #[metastructure(field = "cache.key")]
746    pub cache_key: Annotated<Value>,
747
748    /// The size of the cache item.
749    #[metastructure(field = "cache.item_size")]
750    pub cache_item_size: Annotated<Value>,
751
752    /// The status HTTP response.
753    #[metastructure(field = "http.response.status_code", legacy_alias = "status_code")]
754    pub http_response_status_code: Annotated<Value>,
755
756    /// Label identifying a thread from where the span originated.
757    #[metastructure(field = "thread.name")]
758    pub thread_name: Annotated<String>,
759
760    /// ID of thread from where the span originated.
761    #[metastructure(field = "thread.id")]
762    pub thread_id: Annotated<ThreadId>,
763
764    /// Name of the segment that this span belongs to (see `segment_id`).
765    ///
766    /// This corresponds to the transaction name in the transaction-based model.
767    ///
768    /// For INP spans, this is the route name where the interaction occurred.
769    #[metastructure(field = "sentry.segment.name", legacy_alias = "transaction")]
770    pub segment_name: Annotated<String>,
771
772    /// Name of the UI component (e.g. React).
773    #[metastructure(field = "ui.component_name")]
774    pub ui_component_name: Annotated<Value>,
775
776    /// The URL scheme, e.g. `"https"`.
777    #[metastructure(field = "url.scheme")]
778    pub url_scheme: Annotated<Value>,
779
780    /// User Display
781    #[metastructure(field = "user")]
782    pub user: Annotated<Value>,
783
784    /// Two-letter country code (ISO 3166-1 alpha-2).
785    ///
786    /// This is not an OTel convention (yet).
787    #[metastructure(field = "user.geo.country_code")]
788    pub user_geo_country_code: Annotated<String>,
789
790    /// Human readable city name.
791    ///
792    /// This is not an OTel convention (yet).
793    #[metastructure(field = "user.geo.city")]
794    pub user_geo_city: Annotated<String>,
795
796    /// Human readable subdivision name.
797    ///
798    /// This is not an OTel convention (yet).
799    #[metastructure(field = "user.geo.subdivision")]
800    pub user_geo_subdivision: Annotated<String>,
801
802    /// Human readable region name or code.
803    ///
804    /// This is not an OTel convention (yet).
805    #[metastructure(field = "user.geo.region")]
806    pub user_geo_region: Annotated<String>,
807
808    /// Exclusive Time
809    #[metastructure(field = "sentry.exclusive_time")]
810    pub exclusive_time: Annotated<Value>,
811
812    /// Profile ID
813    #[metastructure(
814        field = "profile_id",
815        // This field is not defined in conventions, so we need to set
816        // PII explicitly.
817        pii = "false"
818    )]
819    pub profile_id: Annotated<Value>,
820
821    /// Replay ID
822    #[metastructure(field = "sentry.replay_id", legacy_alias = "replay_id")]
823    pub replay_id: Annotated<Value>,
824
825    /// The sentry SDK (see [`crate::protocol::ClientSdkInfo`]).
826    #[metastructure(field = "sentry.sdk.name")]
827    pub sdk_name: Annotated<String>,
828
829    /// The sentry SDK version (see [`crate::protocol::ClientSdkInfo`]).
830    #[metastructure(field = "sentry.sdk.version")]
831    pub sdk_version: Annotated<String>,
832
833    /// Slow Frames
834    #[metastructure(field = "sentry.frames.slow", legacy_alias = "frames.slow")]
835    pub frames_slow: Annotated<Value>,
836
837    /// Frozen Frames
838    #[metastructure(field = "sentry.frames.frozen", legacy_alias = "frames.frozen")]
839    pub frames_frozen: Annotated<Value>,
840
841    /// Total Frames
842    #[metastructure(field = "sentry.frames.total", legacy_alias = "frames.total")]
843    pub frames_total: Annotated<Value>,
844
845    // Frames Delay (in seconds)
846    #[metastructure(field = "frames.delay")]
847    pub frames_delay: Annotated<Value>,
848
849    // Messaging Destination Name
850    #[metastructure(field = "messaging.destination.name")]
851    pub messaging_destination_name: Annotated<String>,
852
853    /// Message Retry Count
854    #[metastructure(field = "messaging.message.retry.count")]
855    pub messaging_message_retry_count: Annotated<Value>,
856
857    /// Message Receive Latency
858    #[metastructure(field = "messaging.message.receive.latency")]
859    pub messaging_message_receive_latency: Annotated<Value>,
860
861    /// Message Body Size
862    #[metastructure(field = "messaging.message.body.size")]
863    pub messaging_message_body_size: Annotated<Value>,
864
865    /// Message ID
866    #[metastructure(field = "messaging.message.id")]
867    pub messaging_message_id: Annotated<String>,
868
869    /// Messaging Operation Name
870    #[metastructure(field = "messaging.operation.name")]
871    pub messaging_operation_name: Annotated<String>,
872
873    /// Messaging Operation Type
874    #[metastructure(field = "messaging.operation.type")]
875    pub messaging_operation_type: Annotated<String>,
876
877    /// Value of the HTTP User-Agent header sent by the client.
878    #[metastructure(field = "user_agent.original")]
879    pub user_agent_original: Annotated<String>,
880
881    /// Absolute URL of a network resource.
882    #[metastructure(field = "url.full")]
883    pub url_full: Annotated<String>,
884
885    /// The query string component of the URL, without a leading `?`.
886    #[metastructure(field = "url.query")]
887    pub url_query: Annotated<String>,
888
889    /// The query string component of the URL, with a leading `?`.
890    #[metastructure(field = "http.query")]
891    pub http_query: Annotated<String>,
892
893    /// The client's IP address.
894    #[metastructure(field = "client.address")]
895    pub client_address: Annotated<IpAddr>,
896
897    /// The current route in the application.
898    ///
899    /// Set by React Native SDK.
900    #[metastructure(skip_serialization = "empty")]
901    pub route: Annotated<Route>,
902
903    /// The previous route in the application
904    ///
905    /// Set by React Native SDK.
906    #[metastructure(field = "previousRoute", skip_serialization = "empty")]
907    pub previous_route: Annotated<Route>,
908
909    // The dom element responsible for the largest contentful paint.
910    #[metastructure(field = "lcp.element")]
911    pub lcp_element: Annotated<String>,
912
913    // The size of the largest contentful paint element.
914    #[metastructure(field = "lcp.size")]
915    pub lcp_size: Annotated<u64>,
916
917    // The id of the largest contentful paint element.
918    #[metastructure(field = "lcp.id")]
919    pub lcp_id: Annotated<String>,
920
921    // The url of the largest contentful paint element.
922    #[metastructure(field = "lcp.url")]
923    pub lcp_url: Annotated<String>,
924
925    // Trace ID.
926    #[metastructure(field = "sentry.dsc.trace_id")]
927    pub sentry_dsc_trace_id: Annotated<String>,
928
929    // Name of the transaction/segment that started the trace.
930    #[metastructure(field = "sentry.dsc.transaction")]
931    pub sentry_dsc_transaction: Annotated<String>,
932
933    // ID of the project that started the trace.
934    #[metastructure(field = "sentry.dsc.project_id")]
935    pub sentry_dsc_project_id: Annotated<String>,
936
937    // The span's name, a brief, human-readable, low cardinality description of operation
938    // represented by the span (as per OpenTelemetry/Sentry's Span V2 schema).
939    #[metastructure(field = "sentry.name")]
940    pub span_name: Annotated<String>,
941
942    /// Other fields in `span.data`.
943    #[metastructure(
944        additional_properties,
945        retain = true,
946        skip_serialization = "null" // applies to child elements
947    )]
948    pub other: Object<Value>,
949}
950
951impl Getter for SpanData {
952    fn get_value(&self, path: &str) -> Option<Val<'_>> {
953        Some(match path {
954            "app_start_type" => self.app_start_type.value()?.into(),
955            "browser\\.name" => self.browser_name.as_str()?.into(),
956            "db.operation" => self.db_operation.value()?.into(),
957            "db\\.system" => self.db_system.value()?.into(),
958            "environment" => self.environment.as_str()?.into(),
959            "gen_ai\\.usage\\.total_tokens" => self.gen_ai_usage_total_tokens.value()?.into(),
960            "gen_ai\\.cost\\.total_tokens" => self.gen_ai_cost_total_tokens.value()?.into(),
961            "gen_ai\\.cost\\.input_tokens" => self.gen_ai_cost_input_tokens.value()?.into(),
962            "gen_ai\\.cost\\.output_tokens" => self.gen_ai_cost_output_tokens.value()?.into(),
963            "gen_ai\\.input\\.messages" => self.gen_ai_input_messages.value()?.into(),
964            "gen_ai\\.output\\.messages" => self.gen_ai_output_messages.value()?.into(),
965            "gen_ai\\.operation\\.name" => self.gen_ai_operation_name.as_str()?.into(),
966            "gen_ai\\.agent\\.name" => self.gen_ai_agent_name.as_str()?.into(),
967            "gen_ai\\.request\\.model" => self.gen_ai_request_model.value()?.into(),
968            "http\\.decoded_response_content_length" => {
969                self.http_decoded_response_content_length.value()?.into()
970            }
971            "http\\.request_method" | "http\\.method" | "method" => {
972                self.http_request_method.value()?.into()
973            }
974            "http\\.response_content_length" => self.http_response_content_length.value()?.into(),
975            "http\\.response_transfer_size" => self.http_response_transfer_size.value()?.into(),
976            "http\\.response.status_code" | "status_code" => {
977                self.http_response_status_code.value()?.into()
978            }
979            "resource\\.render_blocking_status" => {
980                self.resource_render_blocking_status.value()?.into()
981            }
982            "server\\.address" => self.server_address.value()?.into(),
983            "thread\\.name" => self.thread_name.as_str()?.into(),
984            "ui\\.component_name" => self.ui_component_name.value()?.into(),
985            "url\\.scheme" => self.url_scheme.value()?.into(),
986            "url\\.query" => self.url_query.as_str()?.into(),
987            "http\\.query" => self.http_query.as_str()?.into(),
988            "user" => self.user.value()?.into(),
989            "user\\.geo\\.city" => self.user_geo_city.as_str()?.into(),
990            "user\\.geo\\.country_code" => self.user_geo_country_code.as_str()?.into(),
991            "user\\.geo\\.region" => self.user_geo_region.as_str()?.into(),
992            "user\\.geo\\.subdivision" => self.user_geo_subdivision.as_str()?.into(),
993            "transaction" => self.segment_name.as_str()?.into(),
994            "release" => self.release.as_str()?.into(),
995            _ => {
996                let escaped = path.replace("\\.", "\0");
997                let mut path = escaped.split('.').map(|s| s.replace('\0', "."));
998                let root = path.next()?;
999
1000                let mut val = self.other.get(&root)?.value()?;
1001                for part in path {
1002                    // While there is path segments left, `val` has to be an Object.
1003                    let relay_protocol::Value::Object(map) = val else {
1004                        return None;
1005                    };
1006                    val = map.get(&part)?.value()?;
1007                }
1008                val.into()
1009            }
1010        })
1011    }
1012}
1013
1014/// A link from a span to another span.
1015#[derive(Clone, Debug, Default, PartialEq, Empty, FromValue, IntoValue, ProcessValue)]
1016#[metastructure(trim = false)]
1017pub struct SpanLink {
1018    /// The trace id of the linked span
1019    #[metastructure(required = true, trim = false)]
1020    pub trace_id: Annotated<TraceId>,
1021
1022    /// The span id of the linked span
1023    #[metastructure(required = true, trim = false)]
1024    pub span_id: Annotated<SpanId>,
1025
1026    /// Whether the linked span was positively/negatively sampled
1027    #[metastructure(trim = false)]
1028    pub sampled: Annotated<bool>,
1029
1030    /// Span link attributes, similar to span attributes/data
1031    #[metastructure(pii = "maybe", trim = false)]
1032    pub attributes: Annotated<Object<Value>>,
1033
1034    /// Additional arbitrary fields for forwards compatibility.
1035    #[metastructure(additional_properties, retain = true, pii = "maybe", trim = false)]
1036    pub other: Object<Value>,
1037}
1038
1039/// The route in the application, set by React Native SDK.
1040#[derive(Clone, Debug, Default, PartialEq, Empty, IntoValue, ProcessValue)]
1041pub struct Route {
1042    /// The name of the route.
1043    #[metastructure(pii = "maybe", skip_serialization = "empty")]
1044    pub name: Annotated<String>,
1045
1046    /// Parameters assigned to this route.
1047    #[metastructure(
1048        pii = "true",
1049        skip_serialization = "empty",
1050        max_depth = 5,
1051        max_bytes = 2048
1052    )]
1053    pub params: Annotated<Object<Value>>,
1054
1055    /// Additional arbitrary fields for forwards compatibility.
1056    #[metastructure(
1057        additional_properties,
1058        retain = true,
1059        pii = "maybe",
1060        skip_serialization = "empty"
1061    )]
1062    pub other: Object<Value>,
1063}
1064
1065impl FromValue for Route {
1066    fn from_value(value: Annotated<Value>) -> Annotated<Self>
1067    where
1068        Self: Sized,
1069    {
1070        match value {
1071            Annotated(Some(Value::String(name)), meta) => Annotated(
1072                Some(Route {
1073                    name: Annotated::new(name),
1074                    ..Default::default()
1075                }),
1076                meta,
1077            ),
1078            Annotated(Some(Value::Object(mut values)), meta) => {
1079                let mut route: Route = Default::default();
1080                if let Some(Annotated(Some(Value::String(name)), _)) = values.remove("name") {
1081                    route.name = Annotated::new(name);
1082                }
1083                if let Some(Annotated(Some(Value::Object(params)), _)) = values.remove("params") {
1084                    route.params = Annotated::new(params);
1085                }
1086
1087                if !values.is_empty() {
1088                    route.other = values;
1089                }
1090
1091                Annotated(Some(route), meta)
1092            }
1093            Annotated(None, meta) => Annotated(None, meta),
1094            Annotated(Some(value), mut meta) => {
1095                meta.add_error(Error::expected("route expected to be an object"));
1096                meta.set_original_value(Some(value));
1097                Annotated(None, meta)
1098            }
1099        }
1100    }
1101}
1102
1103/// The kind of a span.
1104///
1105/// This corresponds to OTEL's kind enum, plus a
1106/// catchall variant for forward compatibility.
1107#[derive(Clone, Debug, PartialEq, ProcessValue, Default)]
1108pub enum SpanKind {
1109    /// An operation internal to an application.
1110    #[default]
1111    Internal,
1112    /// Server-side processing requested by a client.
1113    Server,
1114    /// A request from a client to a server.
1115    Client,
1116    /// Scheduling of an operation.
1117    Producer,
1118    /// Processing of a scheduled operation.
1119    Consumer,
1120    /// Unknown kind, for forward compatibility.
1121    Unknown(String),
1122}
1123
1124impl SpanKind {
1125    pub fn as_str(&self) -> &str {
1126        match self {
1127            Self::Internal => "internal",
1128            Self::Server => "server",
1129            Self::Client => "client",
1130            Self::Producer => "producer",
1131            Self::Consumer => "consumer",
1132            Self::Unknown(s) => s.as_str(),
1133        }
1134    }
1135}
1136
1137impl Empty for SpanKind {
1138    fn is_empty(&self) -> bool {
1139        false
1140    }
1141}
1142
1143#[derive(Debug)]
1144pub struct ParseSpanKindError;
1145
1146impl std::str::FromStr for SpanKind {
1147    type Err = ParseSpanKindError;
1148
1149    fn from_str(s: &str) -> Result<Self, Self::Err> {
1150        Ok(match s {
1151            "internal" => SpanKind::Internal,
1152            "server" => SpanKind::Server,
1153            "client" => SpanKind::Client,
1154            "producer" => SpanKind::Producer,
1155            "consumer" => SpanKind::Consumer,
1156            other => SpanKind::Unknown(other.to_owned()),
1157        })
1158    }
1159}
1160
1161impl fmt::Display for SpanKind {
1162    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1163        write!(f, "{}", self.as_str())
1164    }
1165}
1166
1167impl FromValue for SpanKind {
1168    fn from_value(value: Annotated<Value>) -> Annotated<Self>
1169    where
1170        Self: Sized,
1171    {
1172        match value {
1173            Annotated(Some(Value::String(s)), meta) => Annotated(SpanKind::from_str(&s).ok(), meta),
1174            Annotated(_, meta) => Annotated(None, meta),
1175        }
1176    }
1177}
1178
1179impl IntoValue for SpanKind {
1180    fn into_value(self) -> Value
1181    where
1182        Self: Sized,
1183    {
1184        Value::String(self.to_string())
1185    }
1186
1187    fn serialize_payload<S>(
1188        &self,
1189        s: S,
1190        _behavior: relay_protocol::SkipSerialization,
1191    ) -> Result<S::Ok, S::Error>
1192    where
1193        Self: Sized,
1194        S: serde::Serializer,
1195    {
1196        s.serialize_str(self.as_str())
1197    }
1198}
1199
1200#[cfg(test)]
1201mod tests {
1202    use crate::protocol::Measurement;
1203    use chrono::{TimeZone, Utc};
1204    use relay_base_schema::metrics::{InformationUnit, MetricUnit};
1205    use relay_conventions::attributes::*;
1206    use relay_protocol::RuleCondition;
1207    use similar_asserts::assert_eq;
1208
1209    use super::*;
1210
1211    /// Test that span data attributes expected to follow sentry conventions actually do so. This
1212    /// is achieved by 1) creating a json which uses sentry conventions constants, 2) creating a
1213    /// `SpanData` object from the json, and 3) verifying that the json values end up in the
1214    /// expected `SpanData` fields (which wouldn't happen if the sentry conventions constants don't
1215    /// match the declared field names).
1216    #[test]
1217    fn test_span_data_attributes_follow_sentry_conventions() {
1218        let my_trace = &"my_trace".to_owned();
1219        let my_transaction = &"my_transaction".to_owned();
1220        let my_project_id = &"my_project_id".to_owned();
1221        let json = format!(
1222            r#"{{
1223                "{SENTRY__DSC__TRACE_ID}": "{my_trace}",
1224                "{SENTRY__DSC__TRANSACTION}": "{my_transaction}",
1225                "{SENTRY__DSC__PROJECT_ID}": "{my_project_id}"
1226            }}"#,
1227        );
1228        let data = Annotated::<SpanData>::from_json(&json).unwrap();
1229        let data = data.value().unwrap();
1230        assert_eq!(data.sentry_dsc_trace_id.value(), Some(my_trace));
1231        assert_eq!(data.sentry_dsc_transaction.value(), Some(my_transaction));
1232        assert_eq!(data.sentry_dsc_project_id.value(), Some(my_project_id));
1233        assert!(data.other.is_empty());
1234    }
1235
1236    #[test]
1237    fn test_span_serialization() {
1238        let json = r#"{
1239  "timestamp": 0.0,
1240  "start_timestamp": -63158400.0,
1241  "exclusive_time": 1.23,
1242  "op": "operation",
1243  "span_id": "fa90fdead5f74052",
1244  "trace_id": "4c79f60c11214eb38604f4ae0781bfb2",
1245  "status": "ok",
1246  "description": "desc",
1247  "origin": "auto.http",
1248  "links": [
1249    {
1250      "trace_id": "4c79f60c11214eb38604f4ae0781bfb2",
1251      "span_id": "fa90fdead5f74052",
1252      "sampled": true,
1253      "attributes": {
1254        "boolAttr": true,
1255        "numAttr": 123,
1256        "stringAttr": "foo"
1257      }
1258    }
1259  ],
1260  "measurements": {
1261    "memory": {
1262      "value": 9001.0,
1263      "unit": "byte"
1264    }
1265  },
1266  "kind": "server"
1267}"#;
1268        let mut measurements = Object::new();
1269        measurements.insert(
1270            "memory".into(),
1271            Annotated::new(Measurement {
1272                value: Annotated::new(9001.0.try_into().unwrap()),
1273                unit: Annotated::new(MetricUnit::Information(InformationUnit::Byte)),
1274            }),
1275        );
1276
1277        let links = Annotated::new(vec![Annotated::new(SpanLink {
1278            trace_id: Annotated::new("4c79f60c11214eb38604f4ae0781bfb2".parse().unwrap()),
1279            span_id: Annotated::new("fa90fdead5f74052".parse().unwrap()),
1280            sampled: Annotated::new(true),
1281            attributes: Annotated::new({
1282                let mut map: std::collections::BTreeMap<String, Annotated<Value>> = Object::new();
1283                map.insert(
1284                    "stringAttr".into(),
1285                    Annotated::new(Value::String("foo".into())),
1286                );
1287                map.insert("numAttr".into(), Annotated::new(Value::I64(123)));
1288                map.insert("boolAttr".into(), Value::Bool(true).into());
1289                map
1290            }),
1291            ..Default::default()
1292        })]);
1293
1294        let span = Annotated::new(Span {
1295            timestamp: Annotated::new(Utc.with_ymd_and_hms(1970, 1, 1, 0, 0, 0).unwrap().into()),
1296            start_timestamp: Annotated::new(
1297                Utc.with_ymd_and_hms(1968, 1, 1, 0, 0, 0).unwrap().into(),
1298            ),
1299            exclusive_time: Annotated::new(1.23),
1300            description: Annotated::new("desc".to_owned()),
1301            op: Annotated::new("operation".to_owned()),
1302            trace_id: Annotated::new("4c79f60c11214eb38604f4ae0781bfb2".parse().unwrap()),
1303            span_id: Annotated::new("fa90fdead5f74052".parse().unwrap()),
1304            status: Annotated::new(SpanStatus::Ok),
1305            origin: Annotated::new("auto.http".to_owned()),
1306            kind: Annotated::new(SpanKind::Server),
1307            measurements: Annotated::new(Measurements(measurements)),
1308            links,
1309            ..Default::default()
1310        });
1311        assert_eq!(json, span.to_json_pretty().unwrap());
1312
1313        let span_from_string = Annotated::from_json(json).unwrap();
1314        assert_eq!(span, span_from_string);
1315    }
1316
1317    #[test]
1318    fn test_getter_span_data() {
1319        let span = Annotated::<Span>::from_json(
1320            r#"{
1321                "data": {
1322                    "foo": {"bar": 1},
1323                    "foo.bar": 2
1324                },
1325                "measurements": {
1326                    "some": {"value": 100.0}
1327                }
1328            }"#,
1329        )
1330        .unwrap()
1331        .into_value()
1332        .unwrap();
1333
1334        assert_eq!(span.get_value("span.data.foo.bar"), Some(Val::I64(1)));
1335        assert_eq!(span.get_value(r"span.data.foo\.bar"), Some(Val::I64(2)));
1336
1337        assert_eq!(span.get_value("span.data"), None);
1338        assert_eq!(span.get_value("span.data."), None);
1339        assert_eq!(span.get_value("span.data.x"), None);
1340
1341        assert_eq!(
1342            span.get_value("span.measurements.some.value"),
1343            Some(Val::F64(100.0))
1344        );
1345    }
1346
1347    #[test]
1348    fn test_getter_was_transaction() {
1349        let mut span = Span::default();
1350        assert_eq!(
1351            span.get_value("span.was_transaction"),
1352            Some(Val::Bool(false))
1353        );
1354        assert!(RuleCondition::eq("span.was_transaction", false).matches(&span));
1355        assert!(!RuleCondition::eq("span.was_transaction", true).matches(&span));
1356
1357        span.was_transaction.set_value(Some(false));
1358        assert_eq!(
1359            span.get_value("span.was_transaction"),
1360            Some(Val::Bool(false))
1361        );
1362        assert!(RuleCondition::eq("span.was_transaction", false).matches(&span));
1363        assert!(!RuleCondition::eq("span.was_transaction", true).matches(&span));
1364
1365        span.was_transaction.set_value(Some(true));
1366        assert_eq!(
1367            span.get_value("span.was_transaction"),
1368            Some(Val::Bool(true))
1369        );
1370        assert!(RuleCondition::eq("span.was_transaction", true).matches(&span));
1371        assert!(!RuleCondition::eq("span.was_transaction", false).matches(&span));
1372    }
1373
1374    #[test]
1375    fn test_span_fields_as_event() {
1376        let span = Annotated::<Span>::from_json(
1377            r#"{
1378                "data": {
1379                    "release": "1.0",
1380                    "environment": "prod",
1381                    "sentry.segment.name": "/api/endpoint"
1382                }
1383            }"#,
1384        )
1385        .unwrap()
1386        .into_value()
1387        .unwrap();
1388
1389        assert_eq!(span.get_value("event.release"), Some(Val::String("1.0")));
1390        assert_eq!(
1391            span.get_value("event.environment"),
1392            Some(Val::String("prod"))
1393        );
1394        assert_eq!(
1395            span.get_value("event.transaction"),
1396            Some(Val::String("/api/endpoint"))
1397        );
1398    }
1399
1400    #[test]
1401    fn test_span_duration() {
1402        let span = Annotated::<Span>::from_json(
1403            r#"{
1404                "start_timestamp": 1694732407.8367,
1405                "timestamp": 1694732408.31451233
1406            }"#,
1407        )
1408        .unwrap()
1409        .into_value()
1410        .unwrap();
1411
1412        assert_eq!(span.get_value("span.duration"), Some(Val::F64(477.812)));
1413    }
1414
1415    #[test]
1416    fn test_span_data() {
1417        let data = r#"{
1418        "foo": 2,
1419        "bar": "3",
1420        "db.system": "mysql",
1421        "code.filepath": "task.py",
1422        "code.lineno": 123,
1423        "code.function": "fn()",
1424        "code.namespace": "ns",
1425        "frames.slow": 1,
1426        "frames.frozen": 2,
1427        "frames.total": 9,
1428        "frames.delay": 100,
1429        "messaging.destination.name": "default",
1430        "messaging.message.retry.count": 3,
1431        "messaging.message.receive.latency": 40,
1432        "messaging.message.body.size": 100,
1433        "messaging.message.id": "abc123",
1434        "messaging.operation.name": "publish",
1435        "messaging.operation.type": "create",
1436        "user_agent.original": "Chrome",
1437        "url.full": "my_url.com",
1438        "client.address": "192.168.0.1"
1439    }"#;
1440        let data = Annotated::<SpanData>::from_json(data)
1441            .unwrap()
1442            .into_value()
1443            .unwrap();
1444        insta::assert_debug_snapshot!(data, @r###"
1445        SpanData {
1446            app_start_type: ~,
1447            gen_ai_pipeline_name: ~,
1448            gen_ai_usage_total_tokens: ~,
1449            gen_ai_usage_input_tokens: ~,
1450            gen_ai_usage_input_tokens_cached: ~,
1451            gen_ai_usage_input_tokens_cache_write: ~,
1452            gen_ai_usage_output_tokens: ~,
1453            gen_ai_usage_output_tokens_reasoning: ~,
1454            gen_ai_response_model: ~,
1455            gen_ai_request_model: ~,
1456            gen_ai_context_window_size: ~,
1457            gen_ai_context_utilization: ~,
1458            gen_ai_cost_total_tokens: ~,
1459            gen_ai_cost_input_tokens: ~,
1460            gen_ai_cost_output_tokens: ~,
1461            gen_ai_input_messages: ~,
1462            gen_ai_tool_call_arguments: ~,
1463            gen_ai_tool_call_result: ~,
1464            gen_ai_output_messages: ~,
1465            gen_ai_response_streaming: ~,
1466            gen_ai_response_tokens_per_second: ~,
1467            gen_ai_tool_definitions: ~,
1468            gen_ai_request_frequency_penalty: ~,
1469            gen_ai_request_presence_penalty: ~,
1470            gen_ai_request_seed: ~,
1471            gen_ai_request_temperature: ~,
1472            gen_ai_request_top_k: ~,
1473            gen_ai_request_top_p: ~,
1474            gen_ai_response_finish_reasons: ~,
1475            gen_ai_response_id: ~,
1476            gen_ai_provider_name: ~,
1477            gen_ai_system_instructions: ~,
1478            gen_ai_tool_name: ~,
1479            gen_ai_operation_name: ~,
1480            gen_ai_operation_type: ~,
1481            gen_ai_agent_name: ~,
1482            gen_ai_function_id: ~,
1483            browser_name: ~,
1484            db_operation: ~,
1485            db_system: String(
1486                "mysql",
1487            ),
1488            db_collection_name: ~,
1489            environment: ~,
1490            release: ~,
1491            http_decoded_response_content_length: ~,
1492            http_request_method: ~,
1493            http_response_content_length: ~,
1494            http_response_transfer_size: ~,
1495            resource_render_blocking_status: ~,
1496            server_address: ~,
1497            cache_hit: ~,
1498            cache_key: ~,
1499            cache_item_size: ~,
1500            http_response_status_code: ~,
1501            thread_name: ~,
1502            thread_id: ~,
1503            segment_name: ~,
1504            ui_component_name: ~,
1505            url_scheme: ~,
1506            user: ~,
1507            user_geo_country_code: ~,
1508            user_geo_city: ~,
1509            user_geo_subdivision: ~,
1510            user_geo_region: ~,
1511            exclusive_time: ~,
1512            profile_id: ~,
1513            replay_id: ~,
1514            sdk_name: ~,
1515            sdk_version: ~,
1516            frames_slow: I64(
1517                1,
1518            ),
1519            frames_frozen: I64(
1520                2,
1521            ),
1522            frames_total: I64(
1523                9,
1524            ),
1525            frames_delay: I64(
1526                100,
1527            ),
1528            messaging_destination_name: "default",
1529            messaging_message_retry_count: I64(
1530                3,
1531            ),
1532            messaging_message_receive_latency: I64(
1533                40,
1534            ),
1535            messaging_message_body_size: I64(
1536                100,
1537            ),
1538            messaging_message_id: "abc123",
1539            messaging_operation_name: "publish",
1540            messaging_operation_type: "create",
1541            user_agent_original: "Chrome",
1542            url_full: "my_url.com",
1543            url_query: ~,
1544            http_query: ~,
1545            client_address: IpAddr(
1546                "192.168.0.1",
1547            ),
1548            route: ~,
1549            previous_route: ~,
1550            lcp_element: ~,
1551            lcp_size: ~,
1552            lcp_id: ~,
1553            lcp_url: ~,
1554            sentry_dsc_trace_id: ~,
1555            sentry_dsc_transaction: ~,
1556            sentry_dsc_project_id: ~,
1557            span_name: ~,
1558            other: {
1559                "bar": String(
1560                    "3",
1561                ),
1562                "code.filepath": String(
1563                    "task.py",
1564                ),
1565                "code.function": String(
1566                    "fn()",
1567                ),
1568                "code.lineno": I64(
1569                    123,
1570                ),
1571                "code.namespace": String(
1572                    "ns",
1573                ),
1574                "foo": I64(
1575                    2,
1576                ),
1577            },
1578        }
1579        "###);
1580
1581        assert_eq!(data.get_value("foo"), Some(Val::U64(2)));
1582        assert_eq!(data.get_value("bar"), Some(Val::String("3")));
1583        assert_eq!(data.get_value("db\\.system"), Some(Val::String("mysql")));
1584        assert_eq!(data.get_value("code\\.lineno"), Some(Val::U64(123)));
1585        assert_eq!(data.get_value("code\\.function"), Some(Val::String("fn()")));
1586        assert_eq!(data.get_value("code\\.namespace"), Some(Val::String("ns")));
1587        assert_eq!(data.get_value("unknown"), None);
1588    }
1589
1590    #[test]
1591    fn test_span_data_empty_well_known_field() {
1592        let span = r#"{
1593            "data": {
1594                "lcp.url": ""
1595            }
1596        }"#;
1597        let span: Annotated<Span> = Annotated::from_json(span).unwrap();
1598        assert_eq!(span.to_json().unwrap(), r#"{"data":{"lcp.url":""}}"#);
1599    }
1600
1601    #[test]
1602    fn test_span_data_empty_custom_field() {
1603        let span = r#"{
1604            "data": {
1605                "custom_field_empty": ""
1606            }
1607        }"#;
1608        let span: Annotated<Span> = Annotated::from_json(span).unwrap();
1609        assert_eq!(
1610            span.to_json().unwrap(),
1611            r#"{"data":{"custom_field_empty":""}}"#
1612        );
1613    }
1614
1615    #[test]
1616    fn test_span_data_completely_empty() {
1617        let span = r#"{
1618            "data": {}
1619        }"#;
1620        let span: Annotated<Span> = Annotated::from_json(span).unwrap();
1621        assert_eq!(span.to_json().unwrap(), r#"{"data":{}}"#);
1622    }
1623
1624    #[test]
1625    fn test_span_links() {
1626        let span = r#"{
1627            "links": [
1628                {
1629                    "trace_id": "5c79f60c11214eb38604f4ae0781bfb2",
1630                    "span_id": "ab90fdead5f74052",
1631                    "sampled": true,
1632                    "attributes": {
1633                        "sentry.link.type": "previous_trace"
1634                    }
1635                },
1636                {
1637                    "trace_id": "4c79f60c11214eb38604f4ae0781bfb2",
1638                    "span_id": "fa90fdead5f74052",
1639                    "sampled": true,
1640                    "attributes": {
1641                        "sentry.link.type": "next_trace"
1642                    }
1643                }
1644            ]
1645        }"#;
1646
1647        let span: Annotated<Span> = Annotated::from_json(span).unwrap();
1648        assert_eq!(
1649            span.to_json().unwrap(),
1650            r#"{"links":[{"trace_id":"5c79f60c11214eb38604f4ae0781bfb2","span_id":"ab90fdead5f74052","sampled":true,"attributes":{"sentry.link.type":"previous_trace"}},{"trace_id":"4c79f60c11214eb38604f4ae0781bfb2","span_id":"fa90fdead5f74052","sampled":true,"attributes":{"sentry.link.type":"next_trace"}}]}"#
1651        );
1652    }
1653
1654    #[test]
1655    fn test_span_kind() {
1656        let span = Annotated::<Span>::from_json(
1657            r#"{
1658                "kind": "???"
1659            }"#,
1660        )
1661        .unwrap()
1662        .into_value()
1663        .unwrap();
1664        assert_eq!(
1665            span.kind.value().unwrap(),
1666            &SpanKind::Unknown("???".to_owned())
1667        );
1668    }
1669}