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