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