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    /// Additional arbitrary fields for forwards compatibility.
138    #[metastructure(additional_properties, pii = "maybe")]
139    pub other: Object<Value>,
140}
141
142impl Span {
143    /// Returns the value of an attribute on the span.
144    ///
145    /// This primarily looks up the attribute in the `data` object, but falls back to the `tags`
146    /// object if the attribute is not found.
147    fn attribute(&self, key: &str) -> Option<Val<'_>> {
148        Some(match self.data.value()?.get_value(key) {
149            Some(value) => value,
150            None => self.tags.value()?.get(key)?.as_str()?.into(),
151        })
152    }
153}
154
155impl Getter for Span {
156    fn get_value(&self, path: &str) -> Option<Val<'_>> {
157        let span_prefix = path.strip_prefix("span.");
158        if let Some(span_prefix) = span_prefix {
159            return Some(match span_prefix {
160                "exclusive_time" => self.exclusive_time.value()?.into(),
161                "description" => self.description.as_str()?.into(),
162                "op" => self.op.as_str()?.into(),
163                "span_id" => self.span_id.value()?.into(),
164                "parent_span_id" => self.parent_span_id.value()?.into(),
165                "trace_id" => self.trace_id.value()?.deref().into(),
166                "status" => self.status.as_str()?.into(),
167                "is_segment" => self.is_segment.value()?.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 (duplicate field for migration)
545    #[metastructure(field = "gen_ai.cost.total_tokens", pii = "maybe")]
546    pub gen_ai_cost_total_tokens: Annotated<Value>,
547
548    /// The cost for input tokens used
549    #[metastructure(field = "gen_ai.cost.input_tokens", pii = "maybe")]
550    pub gen_ai_cost_input_tokens: Annotated<Value>,
551
552    /// The cost for output tokens used
553    #[metastructure(field = "gen_ai.cost.output_tokens", pii = "maybe")]
554    pub gen_ai_cost_output_tokens: Annotated<Value>,
555
556    /// Prompt passed to LLM (Vercel AI SDK)
557    #[metastructure(field = "gen_ai.prompt", pii = "maybe")]
558    pub gen_ai_prompt: Annotated<Value>,
559
560    /// Prompt passed to LLM
561    #[metastructure(
562        field = "gen_ai.request.messages",
563        pii = "maybe",
564        legacy_alias = "ai.prompt.messages"
565    )]
566    pub gen_ai_request_messages: Annotated<Value>,
567
568    /// Tool call arguments
569    #[metastructure(
570        field = "gen_ai.tool.input",
571        pii = "maybe",
572        legacy_alias = "ai.toolCall.args"
573    )]
574    pub gen_ai_tool_input: Annotated<Value>,
575
576    /// Tool call result
577    #[metastructure(
578        field = "gen_ai.tool.output",
579        pii = "maybe",
580        legacy_alias = "ai.toolCall.result"
581    )]
582    pub gen_ai_tool_output: Annotated<Value>,
583
584    /// LLM decisions to use tools
585    #[metastructure(
586        field = "gen_ai.response.tool_calls",
587        legacy_alias = "ai.response.toolCalls",
588        legacy_alias = "ai.tool_calls",
589        pii = "maybe"
590    )]
591    pub gen_ai_response_tool_calls: Annotated<Value>,
592
593    /// LLM response text (Vercel AI, generateText)
594    #[metastructure(
595        field = "gen_ai.response.text",
596        legacy_alias = "ai.response.text",
597        legacy_alias = "ai.responses",
598        pii = "maybe"
599    )]
600    pub gen_ai_response_text: Annotated<Value>,
601
602    /// LLM response object (Vercel AI, generateObject)
603    #[metastructure(field = "gen_ai.response.object", pii = "maybe")]
604    pub gen_ai_response_object: Annotated<Value>,
605
606    /// Whether or not the AI model call's response was streamed back asynchronously
607    #[metastructure(field = "gen_ai.response.streaming", legacy_alias = "ai.streaming")]
608    pub gen_ai_response_streaming: Annotated<Value>,
609
610    ///  Total output tokens per seconds throughput
611    #[metastructure(field = "gen_ai.response.tokens_per_second", pii = "maybe")]
612    pub gen_ai_response_tokens_per_second: Annotated<Value>,
613
614    /// Time to first token from the LLM response
615    #[metastructure(field = "gen_ai.response.time_to_first_token", pii = "maybe")]
616    pub gen_ai_response_time_to_first_token: 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\\.cost\\.total_tokens" => self.gen_ai_cost_total_tokens.value()?.into(),
1016            "gen_ai\\.cost\\.input_tokens" => self.gen_ai_cost_input_tokens.value()?.into(),
1017            "gen_ai\\.cost\\.output_tokens" => self.gen_ai_cost_output_tokens.value()?.into(),
1018            "http\\.decoded_response_content_length" => {
1019                self.http_decoded_response_content_length.value()?.into()
1020            }
1021            "http\\.request_method" | "http\\.method" | "method" => {
1022                self.http_request_method.value()?.into()
1023            }
1024            "http\\.response_content_length" => self.http_response_content_length.value()?.into(),
1025            "http\\.response_transfer_size" => self.http_response_transfer_size.value()?.into(),
1026            "http\\.response.status_code" | "status_code" => {
1027                self.http_response_status_code.value()?.into()
1028            }
1029            "resource\\.render_blocking_status" => {
1030                self.resource_render_blocking_status.value()?.into()
1031            }
1032            "server\\.address" => self.server_address.value()?.into(),
1033            "thread\\.name" => self.thread_name.as_str()?.into(),
1034            "ui\\.component_name" => self.ui_component_name.value()?.into(),
1035            "url\\.scheme" => self.url_scheme.value()?.into(),
1036            "user" => self.user.value()?.into(),
1037            "user\\.email" => self.user_email.as_str()?.into(),
1038            "user\\.full_name" => self.user_full_name.as_str()?.into(),
1039            "user\\.geo\\.city" => self.user_geo_city.as_str()?.into(),
1040            "user\\.geo\\.country_code" => self.user_geo_country_code.as_str()?.into(),
1041            "user\\.geo\\.region" => self.user_geo_region.as_str()?.into(),
1042            "user\\.geo\\.subdivision" => self.user_geo_subdivision.as_str()?.into(),
1043            "user\\.hash" => self.user_hash.as_str()?.into(),
1044            "user\\.id" => self.user_id.as_str()?.into(),
1045            "user\\.name" => self.user_name.as_str()?.into(),
1046            "transaction" => self.segment_name.as_str()?.into(),
1047            "release" => self.release.as_str()?.into(),
1048            _ => {
1049                let escaped = path.replace("\\.", "\0");
1050                let mut path = escaped.split('.').map(|s| s.replace('\0', "."));
1051                let root = path.next()?;
1052
1053                let mut val = self.other.get(&root)?.value()?;
1054                for part in path {
1055                    // While there is path segments left, `val` has to be an Object.
1056                    let relay_protocol::Value::Object(map) = val else {
1057                        return None;
1058                    };
1059                    val = map.get(&part)?.value()?;
1060                }
1061                val.into()
1062            }
1063        })
1064    }
1065}
1066
1067/// A link from a span to another span.
1068#[derive(Clone, Debug, Default, PartialEq, Empty, FromValue, IntoValue, ProcessValue)]
1069#[metastructure(trim = false)]
1070pub struct SpanLink {
1071    /// The trace id of the linked span
1072    #[metastructure(required = true, trim = false)]
1073    pub trace_id: Annotated<TraceId>,
1074
1075    /// The span id of the linked span
1076    #[metastructure(required = true, trim = false)]
1077    pub span_id: Annotated<SpanId>,
1078
1079    /// Whether the linked span was positively/negatively sampled
1080    #[metastructure(trim = false)]
1081    pub sampled: Annotated<bool>,
1082
1083    /// Span link attributes, similar to span attributes/data
1084    #[metastructure(pii = "maybe", trim = false)]
1085    pub attributes: Annotated<Object<Value>>,
1086
1087    /// Additional arbitrary fields for forwards compatibility.
1088    #[metastructure(additional_properties, retain = true, pii = "maybe", trim = false)]
1089    pub other: Object<Value>,
1090}
1091
1092/// The route in the application, set by React Native SDK.
1093#[derive(Clone, Debug, Default, PartialEq, Empty, IntoValue, ProcessValue)]
1094pub struct Route {
1095    /// The name of the route.
1096    #[metastructure(pii = "maybe", skip_serialization = "empty")]
1097    pub name: Annotated<String>,
1098
1099    /// Parameters assigned to this route.
1100    #[metastructure(
1101        pii = "true",
1102        skip_serialization = "empty",
1103        max_depth = 5,
1104        max_bytes = 2048
1105    )]
1106    pub params: Annotated<Object<Value>>,
1107
1108    /// Additional arbitrary fields for forwards compatibility.
1109    #[metastructure(
1110        additional_properties,
1111        retain = true,
1112        pii = "maybe",
1113        skip_serialization = "empty"
1114    )]
1115    pub other: Object<Value>,
1116}
1117
1118impl FromValue for Route {
1119    fn from_value(value: Annotated<Value>) -> Annotated<Self>
1120    where
1121        Self: Sized,
1122    {
1123        match value {
1124            Annotated(Some(Value::String(name)), meta) => Annotated(
1125                Some(Route {
1126                    name: Annotated::new(name),
1127                    ..Default::default()
1128                }),
1129                meta,
1130            ),
1131            Annotated(Some(Value::Object(mut values)), meta) => {
1132                let mut route: Route = Default::default();
1133                if let Some(Annotated(Some(Value::String(name)), _)) = values.remove("name") {
1134                    route.name = Annotated::new(name);
1135                }
1136                if let Some(Annotated(Some(Value::Object(params)), _)) = values.remove("params") {
1137                    route.params = Annotated::new(params);
1138                }
1139
1140                if !values.is_empty() {
1141                    route.other = values;
1142                }
1143
1144                Annotated(Some(route), meta)
1145            }
1146            Annotated(None, meta) => Annotated(None, meta),
1147            Annotated(Some(value), mut meta) => {
1148                meta.add_error(Error::expected("route expected to be an object"));
1149                meta.set_original_value(Some(value));
1150                Annotated(None, meta)
1151            }
1152        }
1153    }
1154}
1155
1156/// The kind of a span.
1157///
1158/// This corresponds to OTEL's kind enum, plus a
1159/// catchall variant for forward compatibility.
1160#[derive(Clone, Debug, PartialEq, ProcessValue, Default)]
1161pub enum SpanKind {
1162    /// An operation internal to an application.
1163    #[default]
1164    Internal,
1165    /// Server-side processing requested by a client.
1166    Server,
1167    /// A request from a client to a server.
1168    Client,
1169    /// Scheduling of an operation.
1170    Producer,
1171    /// Processing of a scheduled operation.
1172    Consumer,
1173    /// Unknown kind, for forward compatibility.
1174    Unknown(String),
1175}
1176
1177impl SpanKind {
1178    pub fn as_str(&self) -> &str {
1179        match self {
1180            Self::Internal => "internal",
1181            Self::Server => "server",
1182            Self::Client => "client",
1183            Self::Producer => "producer",
1184            Self::Consumer => "consumer",
1185            Self::Unknown(s) => s.as_str(),
1186        }
1187    }
1188}
1189
1190impl Empty for SpanKind {
1191    fn is_empty(&self) -> bool {
1192        false
1193    }
1194}
1195
1196#[derive(Debug)]
1197pub struct ParseSpanKindError;
1198
1199impl std::str::FromStr for SpanKind {
1200    type Err = ParseSpanKindError;
1201
1202    fn from_str(s: &str) -> Result<Self, Self::Err> {
1203        Ok(match s {
1204            "internal" => SpanKind::Internal,
1205            "server" => SpanKind::Server,
1206            "client" => SpanKind::Client,
1207            "producer" => SpanKind::Producer,
1208            "consumer" => SpanKind::Consumer,
1209            other => SpanKind::Unknown(other.to_owned()),
1210        })
1211    }
1212}
1213
1214impl fmt::Display for SpanKind {
1215    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1216        write!(f, "{}", self.as_str())
1217    }
1218}
1219
1220impl FromValue for SpanKind {
1221    fn from_value(value: Annotated<Value>) -> Annotated<Self>
1222    where
1223        Self: Sized,
1224    {
1225        match value {
1226            Annotated(Some(Value::String(s)), meta) => Annotated(SpanKind::from_str(&s).ok(), meta),
1227            Annotated(_, meta) => Annotated(None, meta),
1228        }
1229    }
1230}
1231
1232impl IntoValue for SpanKind {
1233    fn into_value(self) -> Value
1234    where
1235        Self: Sized,
1236    {
1237        Value::String(self.to_string())
1238    }
1239
1240    fn serialize_payload<S>(
1241        &self,
1242        s: S,
1243        _behavior: relay_protocol::SkipSerialization,
1244    ) -> Result<S::Ok, S::Error>
1245    where
1246        Self: Sized,
1247        S: serde::Serializer,
1248    {
1249        s.serialize_str(self.as_str())
1250    }
1251}
1252
1253#[cfg(test)]
1254mod tests {
1255    use crate::protocol::Measurement;
1256    use chrono::{TimeZone, Utc};
1257    use relay_base_schema::metrics::{InformationUnit, MetricUnit};
1258    use relay_protocol::RuleCondition;
1259    use similar_asserts::assert_eq;
1260
1261    use super::*;
1262
1263    #[test]
1264    fn test_span_serialization() {
1265        let json = r#"{
1266  "timestamp": 0.0,
1267  "start_timestamp": -63158400.0,
1268  "exclusive_time": 1.23,
1269  "op": "operation",
1270  "span_id": "fa90fdead5f74052",
1271  "trace_id": "4c79f60c11214eb38604f4ae0781bfb2",
1272  "status": "ok",
1273  "description": "desc",
1274  "origin": "auto.http",
1275  "links": [
1276    {
1277      "trace_id": "4c79f60c11214eb38604f4ae0781bfb2",
1278      "span_id": "fa90fdead5f74052",
1279      "sampled": true,
1280      "attributes": {
1281        "boolAttr": true,
1282        "numAttr": 123,
1283        "stringAttr": "foo"
1284      }
1285    }
1286  ],
1287  "measurements": {
1288    "memory": {
1289      "value": 9001.0,
1290      "unit": "byte"
1291    }
1292  },
1293  "kind": "server"
1294}"#;
1295        let mut measurements = Object::new();
1296        measurements.insert(
1297            "memory".into(),
1298            Annotated::new(Measurement {
1299                value: Annotated::new(9001.0.try_into().unwrap()),
1300                unit: Annotated::new(MetricUnit::Information(InformationUnit::Byte)),
1301            }),
1302        );
1303
1304        let links = Annotated::new(vec![Annotated::new(SpanLink {
1305            trace_id: Annotated::new("4c79f60c11214eb38604f4ae0781bfb2".parse().unwrap()),
1306            span_id: Annotated::new("fa90fdead5f74052".parse().unwrap()),
1307            sampled: Annotated::new(true),
1308            attributes: Annotated::new({
1309                let mut map: std::collections::BTreeMap<String, Annotated<Value>> = Object::new();
1310                map.insert(
1311                    "stringAttr".into(),
1312                    Annotated::new(Value::String("foo".into())),
1313                );
1314                map.insert("numAttr".into(), Annotated::new(Value::I64(123)));
1315                map.insert("boolAttr".into(), Value::Bool(true).into());
1316                map
1317            }),
1318            ..Default::default()
1319        })]);
1320
1321        let span = Annotated::new(Span {
1322            timestamp: Annotated::new(Utc.with_ymd_and_hms(1970, 1, 1, 0, 0, 0).unwrap().into()),
1323            start_timestamp: Annotated::new(
1324                Utc.with_ymd_and_hms(1968, 1, 1, 0, 0, 0).unwrap().into(),
1325            ),
1326            exclusive_time: Annotated::new(1.23),
1327            description: Annotated::new("desc".to_owned()),
1328            op: Annotated::new("operation".to_owned()),
1329            trace_id: Annotated::new("4c79f60c11214eb38604f4ae0781bfb2".parse().unwrap()),
1330            span_id: Annotated::new("fa90fdead5f74052".parse().unwrap()),
1331            status: Annotated::new(SpanStatus::Ok),
1332            origin: Annotated::new("auto.http".to_owned()),
1333            kind: Annotated::new(SpanKind::Server),
1334            measurements: Annotated::new(Measurements(measurements)),
1335            links,
1336            ..Default::default()
1337        });
1338        assert_eq!(json, span.to_json_pretty().unwrap());
1339
1340        let span_from_string = Annotated::from_json(json).unwrap();
1341        assert_eq!(span, span_from_string);
1342    }
1343
1344    #[test]
1345    fn test_getter_span_data() {
1346        let span = Annotated::<Span>::from_json(
1347            r#"{
1348                "data": {
1349                    "foo": {"bar": 1},
1350                    "foo.bar": 2
1351                },
1352                "measurements": {
1353                    "some": {"value": 100.0}
1354                }
1355            }"#,
1356        )
1357        .unwrap()
1358        .into_value()
1359        .unwrap();
1360
1361        assert_eq!(span.get_value("span.data.foo.bar"), Some(Val::I64(1)));
1362        assert_eq!(span.get_value(r"span.data.foo\.bar"), Some(Val::I64(2)));
1363
1364        assert_eq!(span.get_value("span.data"), None);
1365        assert_eq!(span.get_value("span.data."), None);
1366        assert_eq!(span.get_value("span.data.x"), None);
1367
1368        assert_eq!(
1369            span.get_value("span.measurements.some.value"),
1370            Some(Val::F64(100.0))
1371        );
1372    }
1373
1374    #[test]
1375    fn test_getter_was_transaction() {
1376        let mut span = Span::default();
1377        assert_eq!(
1378            span.get_value("span.was_transaction"),
1379            Some(Val::Bool(false))
1380        );
1381        assert!(RuleCondition::eq("span.was_transaction", false).matches(&span));
1382        assert!(!RuleCondition::eq("span.was_transaction", true).matches(&span));
1383
1384        span.was_transaction.set_value(Some(false));
1385        assert_eq!(
1386            span.get_value("span.was_transaction"),
1387            Some(Val::Bool(false))
1388        );
1389        assert!(RuleCondition::eq("span.was_transaction", false).matches(&span));
1390        assert!(!RuleCondition::eq("span.was_transaction", true).matches(&span));
1391
1392        span.was_transaction.set_value(Some(true));
1393        assert_eq!(
1394            span.get_value("span.was_transaction"),
1395            Some(Val::Bool(true))
1396        );
1397        assert!(RuleCondition::eq("span.was_transaction", true).matches(&span));
1398        assert!(!RuleCondition::eq("span.was_transaction", false).matches(&span));
1399    }
1400
1401    #[test]
1402    fn test_span_fields_as_event() {
1403        let span = Annotated::<Span>::from_json(
1404            r#"{
1405                "data": {
1406                    "release": "1.0",
1407                    "environment": "prod",
1408                    "sentry.segment.name": "/api/endpoint"
1409                }
1410            }"#,
1411        )
1412        .unwrap()
1413        .into_value()
1414        .unwrap();
1415
1416        assert_eq!(span.get_value("event.release"), Some(Val::String("1.0")));
1417        assert_eq!(
1418            span.get_value("event.environment"),
1419            Some(Val::String("prod"))
1420        );
1421        assert_eq!(
1422            span.get_value("event.transaction"),
1423            Some(Val::String("/api/endpoint"))
1424        );
1425    }
1426
1427    #[test]
1428    fn test_span_duration() {
1429        let span = Annotated::<Span>::from_json(
1430            r#"{
1431                "start_timestamp": 1694732407.8367,
1432                "timestamp": 1694732408.31451233
1433            }"#,
1434        )
1435        .unwrap()
1436        .into_value()
1437        .unwrap();
1438
1439        assert_eq!(span.get_value("span.duration"), Some(Val::F64(477.812)));
1440    }
1441
1442    #[test]
1443    fn test_span_data() {
1444        let data = r#"{
1445        "foo": 2,
1446        "bar": "3",
1447        "db.system": "mysql",
1448        "code.filepath": "task.py",
1449        "code.lineno": 123,
1450        "code.function": "fn()",
1451        "code.namespace": "ns",
1452        "frames.slow": 1,
1453        "frames.frozen": 2,
1454        "frames.total": 9,
1455        "frames.delay": 100,
1456        "messaging.destination.name": "default",
1457        "messaging.message.retry.count": 3,
1458        "messaging.message.receive.latency": 40,
1459        "messaging.message.body.size": 100,
1460        "messaging.message.id": "abc123",
1461        "messaging.operation.name": "publish",
1462        "messaging.operation.type": "create",
1463        "user_agent.original": "Chrome",
1464        "url.full": "my_url.com",
1465        "client.address": "192.168.0.1"
1466    }"#;
1467        let data = Annotated::<SpanData>::from_json(data)
1468            .unwrap()
1469            .into_value()
1470            .unwrap();
1471        insta::assert_debug_snapshot!(data, @r#"
1472        SpanData {
1473            app_start_type: ~,
1474            gen_ai_request_max_tokens: ~,
1475            gen_ai_pipeline_name: ~,
1476            gen_ai_usage_total_tokens: ~,
1477            gen_ai_usage_input_tokens: ~,
1478            gen_ai_usage_input_tokens_cached: ~,
1479            gen_ai_usage_input_tokens_cache_write: ~,
1480            gen_ai_usage_input_tokens_cache_miss: ~,
1481            gen_ai_usage_output_tokens: ~,
1482            gen_ai_usage_output_tokens_reasoning: ~,
1483            gen_ai_usage_output_tokens_prediction_accepted: ~,
1484            gen_ai_usage_output_tokens_prediction_rejected: ~,
1485            gen_ai_response_model: ~,
1486            gen_ai_request_model: ~,
1487            gen_ai_cost_total_tokens: ~,
1488            gen_ai_cost_input_tokens: ~,
1489            gen_ai_cost_output_tokens: ~,
1490            gen_ai_prompt: ~,
1491            gen_ai_request_messages: ~,
1492            gen_ai_tool_input: ~,
1493            gen_ai_tool_output: ~,
1494            gen_ai_response_tool_calls: ~,
1495            gen_ai_response_text: ~,
1496            gen_ai_response_object: ~,
1497            gen_ai_response_streaming: ~,
1498            gen_ai_response_tokens_per_second: ~,
1499            gen_ai_response_time_to_first_token: ~,
1500            gen_ai_request_available_tools: ~,
1501            gen_ai_request_frequency_penalty: ~,
1502            gen_ai_request_presence_penalty: ~,
1503            gen_ai_request_seed: ~,
1504            gen_ai_request_temperature: ~,
1505            gen_ai_request_top_k: ~,
1506            gen_ai_request_top_p: ~,
1507            gen_ai_response_finish_reason: ~,
1508            gen_ai_response_id: ~,
1509            gen_ai_system: ~,
1510            gen_ai_tool_name: ~,
1511            gen_ai_operation_name: ~,
1512            gen_ai_operation_type: ~,
1513            mcp_prompt_result: ~,
1514            mcp_tool_result_content: ~,
1515            browser_name: ~,
1516            code_filepath: String(
1517                "task.py",
1518            ),
1519            code_lineno: I64(
1520                123,
1521            ),
1522            code_function: String(
1523                "fn()",
1524            ),
1525            code_namespace: String(
1526                "ns",
1527            ),
1528            db_operation: ~,
1529            db_system: String(
1530                "mysql",
1531            ),
1532            db_collection_name: ~,
1533            environment: ~,
1534            release: ~,
1535            http_decoded_response_content_length: ~,
1536            http_request_method: ~,
1537            http_response_content_length: ~,
1538            http_response_transfer_size: ~,
1539            resource_render_blocking_status: ~,
1540            server_address: ~,
1541            cache_hit: ~,
1542            cache_key: ~,
1543            cache_item_size: ~,
1544            http_response_status_code: ~,
1545            thread_name: ~,
1546            thread_id: ~,
1547            segment_name: ~,
1548            ui_component_name: ~,
1549            url_scheme: ~,
1550            user: ~,
1551            user_email: ~,
1552            user_full_name: ~,
1553            user_geo_country_code: ~,
1554            user_geo_city: ~,
1555            user_geo_subdivision: ~,
1556            user_geo_region: ~,
1557            user_hash: ~,
1558            user_id: ~,
1559            user_name: ~,
1560            user_roles: ~,
1561            exclusive_time: ~,
1562            profile_id: ~,
1563            replay_id: ~,
1564            sdk_name: ~,
1565            sdk_version: ~,
1566            frames_slow: I64(
1567                1,
1568            ),
1569            frames_frozen: I64(
1570                2,
1571            ),
1572            frames_total: I64(
1573                9,
1574            ),
1575            frames_delay: I64(
1576                100,
1577            ),
1578            messaging_destination_name: "default",
1579            messaging_message_retry_count: I64(
1580                3,
1581            ),
1582            messaging_message_receive_latency: I64(
1583                40,
1584            ),
1585            messaging_message_body_size: I64(
1586                100,
1587            ),
1588            messaging_message_id: "abc123",
1589            messaging_operation_name: "publish",
1590            messaging_operation_type: "create",
1591            user_agent_original: "Chrome",
1592            url_full: "my_url.com",
1593            client_address: IpAddr(
1594                "192.168.0.1",
1595            ),
1596            route: ~,
1597            previous_route: ~,
1598            lcp_element: ~,
1599            lcp_size: ~,
1600            lcp_id: ~,
1601            lcp_url: ~,
1602            span_name: ~,
1603            other: {
1604                "bar": String(
1605                    "3",
1606                ),
1607                "foo": I64(
1608                    2,
1609                ),
1610            },
1611        }
1612        "#);
1613
1614        assert_eq!(data.get_value("foo"), Some(Val::U64(2)));
1615        assert_eq!(data.get_value("bar"), Some(Val::String("3")));
1616        assert_eq!(data.get_value("db\\.system"), Some(Val::String("mysql")));
1617        assert_eq!(data.get_value("code\\.lineno"), Some(Val::U64(123)));
1618        assert_eq!(data.get_value("code\\.function"), Some(Val::String("fn()")));
1619        assert_eq!(data.get_value("code\\.namespace"), Some(Val::String("ns")));
1620        assert_eq!(data.get_value("unknown"), None);
1621    }
1622
1623    #[test]
1624    fn test_span_data_empty_well_known_field() {
1625        let span = r#"{
1626            "data": {
1627                "lcp.url": ""
1628            }
1629        }"#;
1630        let span: Annotated<Span> = Annotated::from_json(span).unwrap();
1631        assert_eq!(span.to_json().unwrap(), r#"{"data":{"lcp.url":""}}"#);
1632    }
1633
1634    #[test]
1635    fn test_span_data_empty_custom_field() {
1636        let span = r#"{
1637            "data": {
1638                "custom_field_empty": ""
1639            }
1640        }"#;
1641        let span: Annotated<Span> = Annotated::from_json(span).unwrap();
1642        assert_eq!(
1643            span.to_json().unwrap(),
1644            r#"{"data":{"custom_field_empty":""}}"#
1645        );
1646    }
1647
1648    #[test]
1649    fn test_span_data_completely_empty() {
1650        let span = r#"{
1651            "data": {}
1652        }"#;
1653        let span: Annotated<Span> = Annotated::from_json(span).unwrap();
1654        assert_eq!(span.to_json().unwrap(), r#"{"data":{}}"#);
1655    }
1656
1657    #[test]
1658    fn test_span_links() {
1659        let span = r#"{
1660            "links": [
1661                {
1662                    "trace_id": "5c79f60c11214eb38604f4ae0781bfb2",
1663                    "span_id": "ab90fdead5f74052",
1664                    "sampled": true,
1665                    "attributes": {
1666                        "sentry.link.type": "previous_trace"
1667                    }
1668                },
1669                {
1670                    "trace_id": "4c79f60c11214eb38604f4ae0781bfb2",
1671                    "span_id": "fa90fdead5f74052",
1672                    "sampled": true,
1673                    "attributes": {
1674                        "sentry.link.type": "next_trace"
1675                    }
1676                }
1677            ]
1678        }"#;
1679
1680        let span: Annotated<Span> = Annotated::from_json(span).unwrap();
1681        assert_eq!(
1682            span.to_json().unwrap(),
1683            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"}}]}"#
1684        );
1685    }
1686
1687    #[test]
1688    fn test_span_kind() {
1689        let span = Annotated::<Span>::from_json(
1690            r#"{
1691                "kind": "???"
1692            }"#,
1693        )
1694        .unwrap()
1695        .into_value()
1696        .unwrap();
1697        assert_eq!(
1698            span.kind.value().unwrap(),
1699            &SpanKind::Unknown("???".to_owned())
1700        );
1701    }
1702}