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