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    /// The total tokens that were used by an LLM call
460    #[metastructure(
461        field = "gen_ai.usage.total_tokens",
462        legacy_alias = "ai.total_tokens.used"
463    )]
464    pub gen_ai_usage_total_tokens: Annotated<Value>,
465
466    /// The input tokens used by an LLM call (usually cheaper than output tokens)
467    #[metastructure(
468        field = "gen_ai.usage.input_tokens",
469        legacy_alias = "ai.prompt_tokens.used",
470        legacy_alias = "gen_ai.usage.prompt_tokens"
471    )]
472    pub gen_ai_usage_input_tokens: Annotated<Value>,
473
474    /// The input tokens used by an LLM call that were cached
475    /// (cheaper and faster than non-cached input tokens)
476    #[metastructure(field = "gen_ai.usage.input_tokens.cached")]
477    pub gen_ai_usage_input_tokens_cached: Annotated<Value>,
478
479    /// The output tokens used by an LLM call (the ones the LLM actually generated)
480    #[metastructure(
481        field = "gen_ai.usage.output_tokens",
482        legacy_alias = "ai.completion_tokens.used",
483        legacy_alias = "gen_ai.usage.completion_tokens"
484    )]
485    pub gen_ai_usage_output_tokens: Annotated<Value>,
486
487    /// The output tokens used to represent the model's internal thought
488    /// process while generating a response
489    #[metastructure(field = "gen_ai.usage.output_tokens.reasoning")]
490    pub gen_ai_usage_output_tokens_reasoning: Annotated<Value>,
491
492    // Exact model used to generate the response (e.g. gpt-4o-mini-2024-07-18)
493    #[metastructure(field = "gen_ai.response.model")]
494    pub gen_ai_response_model: Annotated<Value>,
495
496    /// The name of the GenAI model a request is being made to (e.g. gpt-4)
497    #[metastructure(field = "gen_ai.request.model", legacy_alias = "ai.model_id")]
498    pub gen_ai_request_model: Annotated<Value>,
499
500    /// The total cost for the tokens used
501    #[metastructure(field = "gen_ai.usage.total_cost", legacy_alias = "ai.total_cost")]
502    pub gen_ai_usage_total_cost: Annotated<Value>,
503
504    /// Prompt passed to LLM (Vercel AI SDK)
505    #[metastructure(field = "gen_ai.prompt", pii = "maybe")]
506    pub gen_ai_prompt: Annotated<Value>,
507
508    /// Prompt passed to LLM
509    #[metastructure(
510        field = "gen_ai.request.messages",
511        pii = "maybe",
512        legacy_alias = "ai.prompt.messages"
513    )]
514    pub gen_ai_request_messages: Annotated<Value>,
515
516    /// Tool call arguments
517    #[metastructure(
518        field = "gen_ai.tool.input",
519        pii = "maybe",
520        legacy_alias = "ai.toolCall.args"
521    )]
522    pub gen_ai_tool_input: Annotated<Value>,
523
524    /// Tool call result
525    #[metastructure(
526        field = "gen_ai.tool.output",
527        pii = "maybe",
528        legacy_alias = "ai.toolCall.result"
529    )]
530    pub gen_ai_tool_output: Annotated<Value>,
531
532    /// LLM decisions to use calls
533    #[metastructure(
534        field = "gen_ai.response.tool_calls",
535        pii = "maybe",
536        legacy_alias = "ai.response.toolCalls"
537    )]
538    pub gen_ai_response_tool_calls: Annotated<Value>,
539
540    /// Name of the tool that was called
541    #[metastructure(field = "gen_ai.tool.name")]
542    pub gen_ai_tool_name: Annotated<Value>,
543
544    /// LLM response text (Vercel AI, generateText)
545    #[metastructure(
546        field = "gen_ai.response.text",
547        pii = "maybe",
548        legacy_alias = "ai.response.text"
549    )]
550    pub gen_ai_response_text: Annotated<Value>,
551
552    /// LLM response object (Vercel AI, generateObject)
553    #[metastructure(field = "gen_ai.response.object", pii = "maybe")]
554    pub gen_ai_response_object: Annotated<Value>,
555
556    ///  Total output tokens per seconds throughput
557    #[metastructure(field = "gen_ai.response.tokens_per_second")]
558    pub gen_ai_response_tokens_per_second: Annotated<Value>,
559
560    /// The client's browser name.
561    #[metastructure(field = "browser.name")]
562    pub browser_name: Annotated<String>,
563
564    /// The source code file name that identifies the code unit as uniquely as possible.
565    #[metastructure(field = "code.filepath", pii = "maybe")]
566    pub code_filepath: Annotated<Value>,
567    /// The line number in `code.filepath` best representing the operation.
568    #[metastructure(field = "code.lineno", pii = "maybe")]
569    pub code_lineno: Annotated<Value>,
570    /// The method or function name, or equivalent.
571    ///
572    /// Usually rightmost part of the code unit's name.
573    #[metastructure(field = "code.function", pii = "maybe")]
574    pub code_function: Annotated<Value>,
575    /// The "namespace" within which `code.function` is defined.
576    ///
577    /// Usually the qualified class or module name, such that
578    /// `code.namespace + some separator + code.function`
579    /// form a unique identifier for the code unit.
580    #[metastructure(field = "code.namespace", pii = "maybe")]
581    pub code_namespace: Annotated<Value>,
582
583    /// The name of the operation being executed.
584    ///
585    /// E.g. the MongoDB command name such as findAndModify, or the SQL keyword.
586    /// 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).
587    #[metastructure(field = "db.operation")]
588    pub db_operation: Annotated<Value>,
589
590    /// An identifier for the database management system (DBMS) product being used.
591    ///
592    /// 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).
593    #[metastructure(field = "db.system")]
594    pub db_system: Annotated<Value>,
595
596    /// The name of a collection (table, container) within the database.
597    ///
598    /// See [OpenTelemetry's database span semantic conventions](https://opentelemetry.io/docs/specs/semconv/database/database-spans/#common-attributes).
599    #[metastructure(
600        field = "db.collection.name",
601        legacy_alias = "db.cassandra.table",
602        legacy_alias = "db.cosmosdb.container",
603        legacy_alias = "db.mongodb.collection",
604        legacy_alias = "db.sql.table"
605    )]
606    pub db_collection_name: Annotated<Value>,
607
608    /// The sentry environment.
609    #[metastructure(field = "sentry.environment", legacy_alias = "environment")]
610    pub environment: Annotated<String>,
611
612    /// The release version of the project.
613    #[metastructure(field = "sentry.release", legacy_alias = "release")]
614    pub release: Annotated<LenientString>,
615
616    /// The decoded body size of the response (in bytes).
617    #[metastructure(field = "http.decoded_response_content_length")]
618    pub http_decoded_response_content_length: Annotated<Value>,
619
620    /// The HTTP method used.
621    #[metastructure(
622        field = "http.request_method",
623        legacy_alias = "http.method",
624        legacy_alias = "method"
625    )]
626    pub http_request_method: Annotated<Value>,
627
628    /// The encoded body size of the response (in bytes).
629    #[metastructure(field = "http.response_content_length")]
630    pub http_response_content_length: Annotated<Value>,
631
632    /// The transfer size of the response (in bytes).
633    #[metastructure(field = "http.response_transfer_size")]
634    pub http_response_transfer_size: Annotated<Value>,
635
636    /// The render blocking status of the resource.
637    #[metastructure(field = "resource.render_blocking_status")]
638    pub resource_render_blocking_status: Annotated<Value>,
639
640    /// Name of the web server host.
641    #[metastructure(field = "server.address")]
642    pub server_address: Annotated<Value>,
643
644    /// Whether cache was hit or miss on a read operation.
645    #[metastructure(field = "cache.hit")]
646    pub cache_hit: Annotated<Value>,
647
648    /// The name of the cache key.
649    #[metastructure(field = "cache.key")]
650    pub cache_key: Annotated<Value>,
651
652    /// The size of the cache item.
653    #[metastructure(field = "cache.item_size")]
654    pub cache_item_size: Annotated<Value>,
655
656    /// The status HTTP response.
657    #[metastructure(field = "http.response.status_code", legacy_alias = "status_code")]
658    pub http_response_status_code: Annotated<Value>,
659
660    /// Label identifying a thread from where the span originated.
661    #[metastructure(field = "thread.name")]
662    pub thread_name: Annotated<String>,
663
664    /// ID of thread from where the span originated.
665    #[metastructure(field = "thread.id")]
666    pub thread_id: Annotated<ThreadId>,
667
668    /// Name of the segment that this span belongs to (see `segment_id`).
669    ///
670    /// This corresponds to the transaction name in the transaction-based model.
671    ///
672    /// For INP spans, this is the route name where the interaction occurred.
673    #[metastructure(field = "sentry.segment.name", legacy_alias = "transaction")]
674    pub segment_name: Annotated<String>,
675
676    /// Name of the UI component (e.g. React).
677    #[metastructure(field = "ui.component_name")]
678    pub ui_component_name: Annotated<Value>,
679
680    /// The URL scheme, e.g. `"https"`.
681    #[metastructure(field = "url.scheme")]
682    pub url_scheme: Annotated<Value>,
683
684    /// User Display
685    #[metastructure(field = "user")]
686    pub user: Annotated<Value>,
687
688    /// User email address.
689    ///
690    /// <https://opentelemetry.io/docs/specs/semconv/attributes-registry/user/>
691    #[metastructure(field = "user.email")]
692    pub user_email: Annotated<String>,
693
694    /// User’s full name.
695    ///
696    /// <https://opentelemetry.io/docs/specs/semconv/attributes-registry/user/>
697    #[metastructure(field = "user.full_name")]
698    pub user_full_name: Annotated<String>,
699
700    /// Two-letter country code (ISO 3166-1 alpha-2).
701    ///
702    /// This is not an OTel convention (yet).
703    #[metastructure(field = "user.geo.country_code")]
704    pub user_geo_country_code: Annotated<String>,
705
706    /// Human readable city name.
707    ///
708    /// This is not an OTel convention (yet).
709    #[metastructure(field = "user.geo.city")]
710    pub user_geo_city: Annotated<String>,
711
712    /// Human readable subdivision name.
713    ///
714    /// This is not an OTel convention (yet).
715    #[metastructure(field = "user.geo.subdivision")]
716    pub user_geo_subdivision: Annotated<String>,
717
718    /// Human readable region name or code.
719    ///
720    /// This is not an OTel convention (yet).
721    #[metastructure(field = "user.geo.region")]
722    pub user_geo_region: Annotated<String>,
723
724    /// Unique user hash to correlate information for a user in anonymized form.
725    ///
726    /// <https://opentelemetry.io/docs/specs/semconv/attributes-registry/user/>
727    #[metastructure(field = "user.hash")]
728    pub user_hash: Annotated<String>,
729
730    /// Unique identifier of the user.
731    ///
732    /// <https://opentelemetry.io/docs/specs/semconv/attributes-registry/user/>
733    #[metastructure(field = "user.id")]
734    pub user_id: Annotated<String>,
735
736    /// Short name or login/username of the user.
737    ///
738    /// <https://opentelemetry.io/docs/specs/semconv/attributes-registry/user/>
739    #[metastructure(field = "user.name")]
740    pub user_name: Annotated<String>,
741
742    /// Array of user roles at the time of the event.
743    ///
744    /// <https://opentelemetry.io/docs/specs/semconv/attributes-registry/user/>
745    #[metastructure(field = "user.roles")]
746    pub user_roles: Annotated<Array<String>>,
747
748    /// Exclusive Time
749    #[metastructure(field = "sentry.exclusive_time")]
750    pub exclusive_time: Annotated<Value>,
751
752    /// Profile ID
753    #[metastructure(field = "profile_id")]
754    pub profile_id: Annotated<Value>,
755
756    /// Replay ID
757    #[metastructure(field = "sentry.replay.id", legacy_alias = "replay_id")]
758    pub replay_id: Annotated<Value>,
759
760    /// The sentry SDK (see [`crate::protocol::ClientSdkInfo`]).
761    #[metastructure(field = "sentry.sdk.name")]
762    pub sdk_name: Annotated<String>,
763
764    /// The sentry SDK version (see [`crate::protocol::ClientSdkInfo`]).
765    #[metastructure(field = "sentry.sdk.version")]
766    pub sdk_version: Annotated<String>,
767
768    /// Slow Frames
769    #[metastructure(field = "sentry.frames.slow", legacy_alias = "frames.slow")]
770    pub frames_slow: Annotated<Value>,
771
772    /// Frozen Frames
773    #[metastructure(field = "sentry.frames.frozen", legacy_alias = "frames.frozen")]
774    pub frames_frozen: Annotated<Value>,
775
776    /// Total Frames
777    #[metastructure(field = "sentry.frames.total", legacy_alias = "frames.total")]
778    pub frames_total: Annotated<Value>,
779
780    // Frames Delay (in seconds)
781    #[metastructure(field = "frames.delay")]
782    pub frames_delay: Annotated<Value>,
783
784    // Messaging Destination Name
785    #[metastructure(field = "messaging.destination.name")]
786    pub messaging_destination_name: Annotated<String>,
787
788    /// Message Retry Count
789    #[metastructure(field = "messaging.message.retry.count")]
790    pub messaging_message_retry_count: Annotated<Value>,
791
792    /// Message Receive Latency
793    #[metastructure(field = "messaging.message.receive.latency")]
794    pub messaging_message_receive_latency: Annotated<Value>,
795
796    /// Message Body Size
797    #[metastructure(field = "messaging.message.body.size")]
798    pub messaging_message_body_size: Annotated<Value>,
799
800    /// Message ID
801    #[metastructure(field = "messaging.message.id")]
802    pub messaging_message_id: Annotated<String>,
803
804    /// Messaging Operation Name
805    #[metastructure(field = "messaging.operation.name")]
806    pub messaging_operation_name: Annotated<String>,
807
808    /// Messaging Operation Type
809    #[metastructure(field = "messaging.operation.type")]
810    pub messaging_operation_type: Annotated<String>,
811
812    /// Value of the HTTP User-Agent header sent by the client.
813    #[metastructure(field = "user_agent.original")]
814    pub user_agent_original: Annotated<String>,
815
816    /// Absolute URL of a network resource.
817    #[metastructure(field = "url.full")]
818    pub url_full: Annotated<String>,
819
820    /// The client's IP address.
821    #[metastructure(field = "client.address")]
822    pub client_address: Annotated<IpAddr>,
823
824    /// The current route in the application.
825    ///
826    /// Set by React Native SDK.
827    #[metastructure(pii = "maybe", skip_serialization = "empty")]
828    pub route: Annotated<Route>,
829    /// The previous route in the application
830    ///
831    /// Set by React Native SDK.
832    #[metastructure(field = "previousRoute", pii = "maybe", skip_serialization = "empty")]
833    pub previous_route: Annotated<Route>,
834
835    // The dom element responsible for the largest contentful paint.
836    #[metastructure(field = "lcp.element")]
837    pub lcp_element: Annotated<String>,
838
839    // The size of the largest contentful paint element.
840    #[metastructure(field = "lcp.size")]
841    pub lcp_size: Annotated<u64>,
842
843    // The id of the largest contentful paint element.
844    #[metastructure(field = "lcp.id")]
845    pub lcp_id: Annotated<String>,
846
847    // The url of the largest contentful paint element.
848    #[metastructure(field = "lcp.url")]
849    pub lcp_url: Annotated<String>,
850
851    /// Other fields in `span.data`.
852    #[metastructure(
853        additional_properties,
854        pii = "true",
855        retain = true,
856        skip_serialization = "null" // applies to child elements
857    )]
858    pub other: Object<Value>,
859}
860
861impl Getter for SpanData {
862    fn get_value(&self, path: &str) -> Option<Val<'_>> {
863        Some(match path {
864            "app_start_type" => self.app_start_type.value()?.into(),
865            "browser\\.name" => self.browser_name.as_str()?.into(),
866            "code\\.filepath" => self.code_filepath.value()?.into(),
867            "code\\.function" => self.code_function.value()?.into(),
868            "code\\.lineno" => self.code_lineno.value()?.into(),
869            "code\\.namespace" => self.code_namespace.value()?.into(),
870            "db.operation" => self.db_operation.value()?.into(),
871            "db\\.system" => self.db_system.value()?.into(),
872            "environment" => self.environment.as_str()?.into(),
873            "gen_ai\\.request\\.max_tokens" => self.gen_ai_request_max_tokens.value()?.into(),
874            "gen_ai\\.usage\\.total_tokens" => self.gen_ai_usage_total_tokens.value()?.into(),
875            "gen_ai\\.usage\\.total_cost" => self.gen_ai_usage_total_cost.value()?.into(),
876            "http\\.decoded_response_content_length" => {
877                self.http_decoded_response_content_length.value()?.into()
878            }
879            "http\\.request_method" | "http\\.method" | "method" => {
880                self.http_request_method.value()?.into()
881            }
882            "http\\.response_content_length" => self.http_response_content_length.value()?.into(),
883            "http\\.response_transfer_size" => self.http_response_transfer_size.value()?.into(),
884            "http\\.response.status_code" | "status_code" => {
885                self.http_response_status_code.value()?.into()
886            }
887            "resource\\.render_blocking_status" => {
888                self.resource_render_blocking_status.value()?.into()
889            }
890            "server\\.address" => self.server_address.value()?.into(),
891            "thread\\.name" => self.thread_name.as_str()?.into(),
892            "ui\\.component_name" => self.ui_component_name.value()?.into(),
893            "url\\.scheme" => self.url_scheme.value()?.into(),
894            "user" => self.user.value()?.into(),
895            "user\\.email" => self.user_email.as_str()?.into(),
896            "user\\.full_name" => self.user_full_name.as_str()?.into(),
897            "user\\.geo\\.city" => self.user_geo_city.as_str()?.into(),
898            "user\\.geo\\.country_code" => self.user_geo_country_code.as_str()?.into(),
899            "user\\.geo\\.region" => self.user_geo_region.as_str()?.into(),
900            "user\\.geo\\.subdivision" => self.user_geo_subdivision.as_str()?.into(),
901            "user\\.hash" => self.user_hash.as_str()?.into(),
902            "user\\.id" => self.user_id.as_str()?.into(),
903            "user\\.name" => self.user_name.as_str()?.into(),
904            "transaction" => self.segment_name.as_str()?.into(),
905            "release" => self.release.as_str()?.into(),
906            _ => {
907                let escaped = path.replace("\\.", "\0");
908                let mut path = escaped.split('.').map(|s| s.replace('\0', "."));
909                let root = path.next()?;
910
911                let mut val = self.other.get(&root)?.value()?;
912                for part in path {
913                    // While there is path segments left, `val` has to be an Object.
914                    let relay_protocol::Value::Object(map) = val else {
915                        return None;
916                    };
917                    val = map.get(&part)?.value()?;
918                }
919                val.into()
920            }
921        })
922    }
923}
924
925/// A link from a span to another span.
926#[derive(Clone, Debug, Default, PartialEq, Empty, FromValue, IntoValue, ProcessValue)]
927#[metastructure(trim = false)]
928pub struct SpanLink {
929    /// The trace id of the linked span
930    #[metastructure(required = true, trim = false)]
931    pub trace_id: Annotated<TraceId>,
932
933    /// The span id of the linked span
934    #[metastructure(required = true, trim = false)]
935    pub span_id: Annotated<SpanId>,
936
937    /// Whether the linked span was positively/negatively sampled
938    #[metastructure(trim = false)]
939    pub sampled: Annotated<bool>,
940
941    /// Span link attributes, similar to span attributes/data
942    #[metastructure(pii = "maybe", trim = false)]
943    pub attributes: Annotated<Object<Value>>,
944
945    /// Additional arbitrary fields for forwards compatibility.
946    #[metastructure(additional_properties, retain = true, pii = "maybe", trim = false)]
947    pub other: Object<Value>,
948}
949
950/// The route in the application, set by React Native SDK.
951#[derive(Clone, Debug, Default, PartialEq, Empty, IntoValue, ProcessValue)]
952pub struct Route {
953    /// The name of the route.
954    #[metastructure(pii = "maybe", skip_serialization = "empty")]
955    pub name: Annotated<String>,
956
957    /// Parameters assigned to this route.
958    #[metastructure(
959        pii = "true",
960        skip_serialization = "empty",
961        max_depth = 5,
962        max_bytes = 2048
963    )]
964    pub params: Annotated<Object<Value>>,
965
966    /// Additional arbitrary fields for forwards compatibility.
967    #[metastructure(
968        additional_properties,
969        retain = true,
970        pii = "maybe",
971        skip_serialization = "empty"
972    )]
973    pub other: Object<Value>,
974}
975
976impl FromValue for Route {
977    fn from_value(value: Annotated<Value>) -> Annotated<Self>
978    where
979        Self: Sized,
980    {
981        match value {
982            Annotated(Some(Value::String(name)), meta) => Annotated(
983                Some(Route {
984                    name: Annotated::new(name),
985                    ..Default::default()
986                }),
987                meta,
988            ),
989            Annotated(Some(Value::Object(mut values)), meta) => {
990                let mut route: Route = Default::default();
991                if let Some(Annotated(Some(Value::String(name)), _)) = values.remove("name") {
992                    route.name = Annotated::new(name);
993                }
994                if let Some(Annotated(Some(Value::Object(params)), _)) = values.remove("params") {
995                    route.params = Annotated::new(params);
996                }
997
998                if !values.is_empty() {
999                    route.other = values;
1000                }
1001
1002                Annotated(Some(route), meta)
1003            }
1004            Annotated(None, meta) => Annotated(None, meta),
1005            Annotated(Some(value), mut meta) => {
1006                meta.add_error(Error::expected("route expected to be an object"));
1007                meta.set_original_value(Some(value));
1008                Annotated(None, meta)
1009            }
1010        }
1011    }
1012}
1013
1014#[derive(Clone, Debug, PartialEq, ProcessValue)]
1015pub enum SpanKind {
1016    Internal,
1017    Server,
1018    Client,
1019    Producer,
1020    Consumer,
1021}
1022
1023impl SpanKind {
1024    pub fn as_str(&self) -> &'static str {
1025        match self {
1026            Self::Internal => "internal",
1027            Self::Server => "server",
1028            Self::Client => "client",
1029            Self::Producer => "producer",
1030            Self::Consumer => "consumer",
1031        }
1032    }
1033}
1034
1035impl Empty for SpanKind {
1036    fn is_empty(&self) -> bool {
1037        false
1038    }
1039}
1040
1041#[derive(Debug)]
1042pub struct ParseSpanKindError;
1043
1044impl std::str::FromStr for SpanKind {
1045    type Err = ParseSpanKindError;
1046
1047    fn from_str(s: &str) -> Result<Self, Self::Err> {
1048        Ok(match s {
1049            "internal" => SpanKind::Internal,
1050            "server" => SpanKind::Server,
1051            "client" => SpanKind::Client,
1052            "producer" => SpanKind::Producer,
1053            "consumer" => SpanKind::Consumer,
1054            _ => return Err(ParseSpanKindError),
1055        })
1056    }
1057}
1058
1059impl Default for SpanKind {
1060    fn default() -> Self {
1061        Self::Internal
1062    }
1063}
1064
1065impl fmt::Display for SpanKind {
1066    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1067        write!(f, "{}", self.as_str())
1068    }
1069}
1070
1071impl FromValue for SpanKind {
1072    fn from_value(value: Annotated<Value>) -> Annotated<Self>
1073    where
1074        Self: Sized,
1075    {
1076        match value {
1077            Annotated(Some(Value::String(s)), meta) => Annotated(SpanKind::from_str(&s).ok(), meta),
1078            Annotated(_, meta) => Annotated(None, meta),
1079        }
1080    }
1081}
1082
1083impl IntoValue for SpanKind {
1084    fn into_value(self) -> Value
1085    where
1086        Self: Sized,
1087    {
1088        Value::String(self.to_string())
1089    }
1090
1091    fn serialize_payload<S>(
1092        &self,
1093        s: S,
1094        _behavior: relay_protocol::SkipSerialization,
1095    ) -> Result<S::Ok, S::Error>
1096    where
1097        Self: Sized,
1098        S: serde::Serializer,
1099    {
1100        s.serialize_str(self.as_str())
1101    }
1102}
1103
1104#[cfg(test)]
1105mod tests {
1106    use crate::protocol::Measurement;
1107    use chrono::{TimeZone, Utc};
1108    use relay_base_schema::metrics::{InformationUnit, MetricUnit};
1109    use relay_protocol::RuleCondition;
1110    use similar_asserts::assert_eq;
1111
1112    use super::*;
1113
1114    #[test]
1115    fn test_span_serialization() {
1116        let json = r#"{
1117  "timestamp": 0.0,
1118  "start_timestamp": -63158400.0,
1119  "exclusive_time": 1.23,
1120  "op": "operation",
1121  "span_id": "fa90fdead5f74052",
1122  "trace_id": "4c79f60c11214eb38604f4ae0781bfb2",
1123  "status": "ok",
1124  "description": "desc",
1125  "origin": "auto.http",
1126  "links": [
1127    {
1128      "trace_id": "4c79f60c11214eb38604f4ae0781bfb2",
1129      "span_id": "fa90fdead5f74052",
1130      "sampled": true,
1131      "attributes": {
1132        "boolAttr": true,
1133        "numAttr": 123,
1134        "stringAttr": "foo"
1135      }
1136    }
1137  ],
1138  "measurements": {
1139    "memory": {
1140      "value": 9001.0,
1141      "unit": "byte"
1142    }
1143  },
1144  "kind": "server"
1145}"#;
1146        let mut measurements = Object::new();
1147        measurements.insert(
1148            "memory".into(),
1149            Annotated::new(Measurement {
1150                value: Annotated::new(9001.0.try_into().unwrap()),
1151                unit: Annotated::new(MetricUnit::Information(InformationUnit::Byte)),
1152            }),
1153        );
1154
1155        let links = Annotated::new(vec![Annotated::new(SpanLink {
1156            trace_id: Annotated::new("4c79f60c11214eb38604f4ae0781bfb2".parse().unwrap()),
1157            span_id: Annotated::new("fa90fdead5f74052".parse().unwrap()),
1158            sampled: Annotated::new(true),
1159            attributes: Annotated::new({
1160                let mut map: std::collections::BTreeMap<String, Annotated<Value>> = Object::new();
1161                map.insert(
1162                    "stringAttr".into(),
1163                    Annotated::new(Value::String("foo".into())),
1164                );
1165                map.insert("numAttr".into(), Annotated::new(Value::I64(123)));
1166                map.insert("boolAttr".into(), Value::Bool(true).into());
1167                map
1168            }),
1169            ..Default::default()
1170        })]);
1171
1172        let span = Annotated::new(Span {
1173            timestamp: Annotated::new(Utc.with_ymd_and_hms(1970, 1, 1, 0, 0, 0).unwrap().into()),
1174            start_timestamp: Annotated::new(
1175                Utc.with_ymd_and_hms(1968, 1, 1, 0, 0, 0).unwrap().into(),
1176            ),
1177            exclusive_time: Annotated::new(1.23),
1178            description: Annotated::new("desc".to_owned()),
1179            op: Annotated::new("operation".to_owned()),
1180            trace_id: Annotated::new("4c79f60c11214eb38604f4ae0781bfb2".parse().unwrap()),
1181            span_id: Annotated::new("fa90fdead5f74052".parse().unwrap()),
1182            status: Annotated::new(SpanStatus::Ok),
1183            origin: Annotated::new("auto.http".to_owned()),
1184            kind: Annotated::new(SpanKind::Server),
1185            measurements: Annotated::new(Measurements(measurements)),
1186            links,
1187            ..Default::default()
1188        });
1189        assert_eq!(json, span.to_json_pretty().unwrap());
1190
1191        let span_from_string = Annotated::from_json(json).unwrap();
1192        assert_eq!(span, span_from_string);
1193    }
1194
1195    #[test]
1196    fn test_getter_span_data() {
1197        let span = Annotated::<Span>::from_json(
1198            r#"{
1199                "data": {
1200                    "foo": {"bar": 1},
1201                    "foo.bar": 2
1202                },
1203                "measurements": {
1204                    "some": {"value": 100.0}
1205                }
1206            }"#,
1207        )
1208        .unwrap()
1209        .into_value()
1210        .unwrap();
1211
1212        assert_eq!(span.get_value("span.data.foo.bar"), Some(Val::I64(1)));
1213        assert_eq!(span.get_value(r"span.data.foo\.bar"), Some(Val::I64(2)));
1214
1215        assert_eq!(span.get_value("span.data"), None);
1216        assert_eq!(span.get_value("span.data."), None);
1217        assert_eq!(span.get_value("span.data.x"), None);
1218
1219        assert_eq!(
1220            span.get_value("span.measurements.some.value"),
1221            Some(Val::F64(100.0))
1222        );
1223    }
1224
1225    #[test]
1226    fn test_getter_was_transaction() {
1227        let mut span = Span::default();
1228        assert_eq!(
1229            span.get_value("span.was_transaction"),
1230            Some(Val::Bool(false))
1231        );
1232        assert!(RuleCondition::eq("span.was_transaction", false).matches(&span));
1233        assert!(!RuleCondition::eq("span.was_transaction", true).matches(&span));
1234
1235        span.was_transaction.set_value(Some(false));
1236        assert_eq!(
1237            span.get_value("span.was_transaction"),
1238            Some(Val::Bool(false))
1239        );
1240        assert!(RuleCondition::eq("span.was_transaction", false).matches(&span));
1241        assert!(!RuleCondition::eq("span.was_transaction", true).matches(&span));
1242
1243        span.was_transaction.set_value(Some(true));
1244        assert_eq!(
1245            span.get_value("span.was_transaction"),
1246            Some(Val::Bool(true))
1247        );
1248        assert!(RuleCondition::eq("span.was_transaction", true).matches(&span));
1249        assert!(!RuleCondition::eq("span.was_transaction", false).matches(&span));
1250    }
1251
1252    #[test]
1253    fn test_span_fields_as_event() {
1254        let span = Annotated::<Span>::from_json(
1255            r#"{
1256                "data": {
1257                    "release": "1.0",
1258                    "environment": "prod",
1259                    "sentry.segment.name": "/api/endpoint"
1260                }
1261            }"#,
1262        )
1263        .unwrap()
1264        .into_value()
1265        .unwrap();
1266
1267        assert_eq!(span.get_value("event.release"), Some(Val::String("1.0")));
1268        assert_eq!(
1269            span.get_value("event.environment"),
1270            Some(Val::String("prod"))
1271        );
1272        assert_eq!(
1273            span.get_value("event.transaction"),
1274            Some(Val::String("/api/endpoint"))
1275        );
1276    }
1277
1278    #[test]
1279    fn test_span_duration() {
1280        let span = Annotated::<Span>::from_json(
1281            r#"{
1282                "start_timestamp": 1694732407.8367,
1283                "timestamp": 1694732408.3145
1284            }"#,
1285        )
1286        .unwrap()
1287        .into_value()
1288        .unwrap();
1289
1290        assert_eq!(span.get_value("span.duration"), Some(Val::F64(477.800131)));
1291    }
1292
1293    #[test]
1294    fn test_span_data() {
1295        let data = r#"{
1296        "foo": 2,
1297        "bar": "3",
1298        "db.system": "mysql",
1299        "code.filepath": "task.py",
1300        "code.lineno": 123,
1301        "code.function": "fn()",
1302        "code.namespace": "ns",
1303        "frames.slow": 1,
1304        "frames.frozen": 2,
1305        "frames.total": 9,
1306        "frames.delay": 100,
1307        "messaging.destination.name": "default",
1308        "messaging.message.retry.count": 3,
1309        "messaging.message.receive.latency": 40,
1310        "messaging.message.body.size": 100,
1311        "messaging.message.id": "abc123",
1312        "messaging.operation.name": "publish",
1313        "messaging.operation.type": "create",
1314        "user_agent.original": "Chrome",
1315        "url.full": "my_url.com",
1316        "client.address": "192.168.0.1"
1317    }"#;
1318        let data = Annotated::<SpanData>::from_json(data)
1319            .unwrap()
1320            .into_value()
1321            .unwrap();
1322        insta::assert_debug_snapshot!(data, @r#"
1323        SpanData {
1324            app_start_type: ~,
1325            gen_ai_request_max_tokens: ~,
1326            gen_ai_usage_total_tokens: ~,
1327            gen_ai_usage_input_tokens: ~,
1328            gen_ai_usage_input_tokens_cached: ~,
1329            gen_ai_usage_output_tokens: ~,
1330            gen_ai_usage_output_tokens_reasoning: ~,
1331            gen_ai_response_model: ~,
1332            gen_ai_request_model: ~,
1333            gen_ai_usage_total_cost: ~,
1334            gen_ai_prompt: ~,
1335            gen_ai_request_messages: ~,
1336            gen_ai_tool_input: ~,
1337            gen_ai_tool_output: ~,
1338            gen_ai_response_tool_calls: ~,
1339            gen_ai_tool_name: ~,
1340            gen_ai_response_text: ~,
1341            gen_ai_response_object: ~,
1342            gen_ai_response_tokens_per_second: ~,
1343            browser_name: ~,
1344            code_filepath: String(
1345                "task.py",
1346            ),
1347            code_lineno: I64(
1348                123,
1349            ),
1350            code_function: String(
1351                "fn()",
1352            ),
1353            code_namespace: String(
1354                "ns",
1355            ),
1356            db_operation: ~,
1357            db_system: String(
1358                "mysql",
1359            ),
1360            db_collection_name: ~,
1361            environment: ~,
1362            release: ~,
1363            http_decoded_response_content_length: ~,
1364            http_request_method: ~,
1365            http_response_content_length: ~,
1366            http_response_transfer_size: ~,
1367            resource_render_blocking_status: ~,
1368            server_address: ~,
1369            cache_hit: ~,
1370            cache_key: ~,
1371            cache_item_size: ~,
1372            http_response_status_code: ~,
1373            thread_name: ~,
1374            thread_id: ~,
1375            segment_name: ~,
1376            ui_component_name: ~,
1377            url_scheme: ~,
1378            user: ~,
1379            user_email: ~,
1380            user_full_name: ~,
1381            user_geo_country_code: ~,
1382            user_geo_city: ~,
1383            user_geo_subdivision: ~,
1384            user_geo_region: ~,
1385            user_hash: ~,
1386            user_id: ~,
1387            user_name: ~,
1388            user_roles: ~,
1389            exclusive_time: ~,
1390            profile_id: ~,
1391            replay_id: ~,
1392            sdk_name: ~,
1393            sdk_version: ~,
1394            frames_slow: I64(
1395                1,
1396            ),
1397            frames_frozen: I64(
1398                2,
1399            ),
1400            frames_total: I64(
1401                9,
1402            ),
1403            frames_delay: I64(
1404                100,
1405            ),
1406            messaging_destination_name: "default",
1407            messaging_message_retry_count: I64(
1408                3,
1409            ),
1410            messaging_message_receive_latency: I64(
1411                40,
1412            ),
1413            messaging_message_body_size: I64(
1414                100,
1415            ),
1416            messaging_message_id: "abc123",
1417            messaging_operation_name: "publish",
1418            messaging_operation_type: "create",
1419            user_agent_original: "Chrome",
1420            url_full: "my_url.com",
1421            client_address: IpAddr(
1422                "192.168.0.1",
1423            ),
1424            route: ~,
1425            previous_route: ~,
1426            lcp_element: ~,
1427            lcp_size: ~,
1428            lcp_id: ~,
1429            lcp_url: ~,
1430            other: {
1431                "bar": String(
1432                    "3",
1433                ),
1434                "foo": I64(
1435                    2,
1436                ),
1437            },
1438        }
1439        "#);
1440
1441        assert_eq!(data.get_value("foo"), Some(Val::U64(2)));
1442        assert_eq!(data.get_value("bar"), Some(Val::String("3")));
1443        assert_eq!(data.get_value("db\\.system"), Some(Val::String("mysql")));
1444        assert_eq!(data.get_value("code\\.lineno"), Some(Val::U64(123)));
1445        assert_eq!(data.get_value("code\\.function"), Some(Val::String("fn()")));
1446        assert_eq!(data.get_value("code\\.namespace"), Some(Val::String("ns")));
1447        assert_eq!(data.get_value("unknown"), None);
1448    }
1449
1450    #[test]
1451    fn test_span_data_empty_well_known_field() {
1452        let span = r#"{
1453            "data": {
1454                "lcp.url": ""
1455            }
1456        }"#;
1457        let span: Annotated<Span> = Annotated::from_json(span).unwrap();
1458        assert_eq!(span.to_json().unwrap(), r#"{"data":{"lcp.url":""}}"#);
1459    }
1460
1461    #[test]
1462    fn test_span_data_empty_custom_field() {
1463        let span = r#"{
1464            "data": {
1465                "custom_field_empty": ""
1466            }
1467        }"#;
1468        let span: Annotated<Span> = Annotated::from_json(span).unwrap();
1469        assert_eq!(
1470            span.to_json().unwrap(),
1471            r#"{"data":{"custom_field_empty":""}}"#
1472        );
1473    }
1474
1475    #[test]
1476    fn test_span_data_completely_empty() {
1477        let span = r#"{
1478            "data": {}
1479        }"#;
1480        let span: Annotated<Span> = Annotated::from_json(span).unwrap();
1481        assert_eq!(span.to_json().unwrap(), r#"{"data":{}}"#);
1482    }
1483
1484    #[test]
1485    fn test_span_links() {
1486        let span = r#"{
1487            "links": [
1488                {
1489                    "trace_id": "5c79f60c11214eb38604f4ae0781bfb2",
1490                    "span_id": "ab90fdead5f74052",
1491                    "sampled": true,
1492                    "attributes": {
1493                        "sentry.link.type": "previous_trace"
1494                    }
1495                },
1496                {
1497                    "trace_id": "4c79f60c11214eb38604f4ae0781bfb2",
1498                    "span_id": "fa90fdead5f74052",
1499                    "sampled": true,
1500                    "attributes": {
1501                        "sentry.link.type": "next_trace"
1502                    }
1503                }
1504            ]
1505        }"#;
1506
1507        let span: Annotated<Span> = Annotated::from_json(span).unwrap();
1508        assert_eq!(
1509            span.to_json().unwrap(),
1510            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"}}]}"#
1511        );
1512    }
1513}