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