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