Skip to main content

relay_event_schema/protocol/contexts/
mod.rs

1mod app;
2mod attachments;
3mod browser;
4mod chromium_stability_report;
5mod cloud_resource;
6mod culture;
7mod device;
8mod flags;
9mod gpu;
10mod memory_info;
11mod monitor;
12mod os;
13mod ota_updates;
14mod otel;
15mod performance_score;
16mod profile;
17mod replay;
18mod reprocessing;
19mod response;
20mod runtime;
21mod spring;
22mod threadpool_info;
23mod trace;
24mod unity;
25mod user_report_v2;
26pub use app::*;
27pub use attachments::*;
28pub use browser::*;
29pub use chromium_stability_report::*;
30pub use cloud_resource::*;
31pub use culture::*;
32pub use device::*;
33pub use flags::*;
34pub use gpu::*;
35pub use memory_info::*;
36pub use monitor::*;
37pub use os::*;
38pub use ota_updates::*;
39pub use otel::*;
40pub use performance_score::*;
41pub use profile::*;
42pub use replay::*;
43pub use reprocessing::*;
44pub use response::*;
45pub use runtime::*;
46pub use spring::*;
47pub use threadpool_info::*;
48pub use trace::*;
49pub use unity::*;
50pub use user_report_v2::*;
51
52use relay_protocol::{Annotated, Empty, FromValue, IntoValue, Object, Value};
53
54use crate::processor::ProcessValue;
55
56/// A span's operation type.
57///
58/// Tries to follow OpenCensus/OpenTracing's span types. Examples are `db.statement` for database
59/// queries or `http` for external HTTP calls.
60pub type OperationType = String;
61
62/// Origin type such as `auto.http`.
63/// Follows the pattern described in the [develop docs](https://develop.sentry.dev/sdk/performance/trace-origin/).
64pub type OriginType = String;
65
66/// A context describes environment info (e.g. device, os or browser).
67#[derive(Clone, Debug, PartialEq, Empty, FromValue, IntoValue, ProcessValue)]
68#[metastructure(process_func = "process_context")]
69pub enum Context {
70    /// Device information.
71    Device(#[metastructure(max_bytes = 8192)] Box<DeviceContext>),
72    /// Operating system information.
73    Os(#[metastructure(max_bytes = 8192)] Box<OsContext>),
74    /// Runtime information.
75    Runtime(#[metastructure(max_bytes = 8192)] Box<RuntimeContext>),
76    /// Application information.
77    App(#[metastructure(max_bytes = 8192)] Box<AppContext>),
78    /// Web browser information.
79    Browser(#[metastructure(max_bytes = 8192)] Box<BrowserContext>),
80    /// Information about device's GPU.
81    Gpu(#[metastructure(max_bytes = 8192)] Box<GpuContext>),
82    /// Information related to Tracing.
83    Trace(#[metastructure(max_bytes = 8192)] Box<TraceContext>),
84    /// Information related to Profiling.
85    Profile(#[metastructure(max_bytes = 8192)] Box<ProfileContext>),
86    /// Information related to Replay.
87    Replay(#[metastructure(max_bytes = 8192)] Box<ReplayContext>),
88    /// Information related to Feature flags.
89    Flags(#[metastructure(max_bytes = 131_072)] Box<flags::FlagsContext>),
90    /// Information related to User Report V2. TODO:(jferg): rename to UserFeedbackContext
91    #[metastructure(tag = "feedback")]
92    UserReportV2(#[metastructure(max_bytes = 8192)] Box<UserReportV2Context>),
93    /// Information related to Memory usage and garbage collection metrics.
94    #[metastructure(tag = "memory_info")]
95    MemoryInfo(#[metastructure(max_bytes = 8192)] Box<MemoryInfoContext>),
96    /// Information related to Monitors feature.
97    Monitor(#[metastructure(max_bytes = 8192)] Box<MonitorContext>),
98    /// Auxilliary information for reprocessing.
99    #[metastructure(omit_from_schema)]
100    Reprocessing(#[metastructure(max_bytes = 8192)] Box<ReprocessingContext>),
101    /// Information about attachments of the event.
102    Attachments(#[metastructure(max_bytes = 8192)] Box<AttachmentsContext>),
103    /// Response information.
104    Response(#[metastructure(max_bytes = 8192)] Box<ResponseContext>),
105    /// OpenTelemetry information.
106    Otel(#[metastructure(max_bytes = 8192)] Box<OtelContext>),
107    /// Cloud resource information.
108    CloudResource(#[metastructure(max_bytes = 8192)] Box<CloudResourceContext>),
109    /// Culture information.
110    Culture(#[metastructure(max_bytes = 8192)] Box<CultureContext>),
111    /// Performance score information.
112    PerformanceScore(#[metastructure(max_bytes = 8192)] Box<PerformanceScoreContext>),
113    /// Spring / Spring Boot information.
114    Spring(#[metastructure(max_bytes = 8192)] Box<SpringContext>),
115    /// Thread pool information.
116    #[metastructure(tag = "threadpool_info")]
117    ThreadPoolInfo(#[metastructure(max_bytes = 8192)] Box<ThreadPoolInfoContext>),
118    /// OTA Updates information.
119    OTAUpdates(#[metastructure(max_bytes = 8192)] Box<OTAUpdatesContext>),
120    /// Chromium Stability Report from minidump.
121    ChromiumStabilityReport(#[metastructure(max_bytes = 8192)] Box<StabilityReportContext>),
122    /// Unity information.
123    Unity(#[metastructure(max_bytes = 8192)] Box<UnityContext>),
124    /// Additional arbitrary fields for forwards compatibility.
125    #[metastructure(fallback_variant, retain = true)]
126    Other(#[metastructure(pii = "true", max_bytes = 8192)] Object<Value>),
127}
128
129#[derive(Clone, Debug, PartialEq, Empty, FromValue, IntoValue, ProcessValue)]
130pub struct ContextInner(#[metastructure(max_depth = 7)] pub Context);
131
132impl From<Context> for ContextInner {
133    fn from(c: Context) -> ContextInner {
134        ContextInner(c)
135    }
136}
137
138/// The Contexts interface provides additional context data. Typically, this is data related to the
139/// current user and the environment. For example, the device or application version. Its canonical
140/// name is `contexts`.
141///
142/// The `contexts` type can be used to define arbitrary contextual data on the event. It accepts an
143/// object of key/value pairs. The key is the “alias” of the context and can be freely chosen.
144/// However, as per policy, it should match the type of the context unless there are two values for
145/// a type. You can omit `type` if the key name is the type.
146///
147/// Unknown data for the contexts is rendered as a key/value list.
148///
149/// For more details about sending additional data with your event, see the [full documentation on
150/// Additional Data](https://docs.sentry.io/enriching-error-data/additional-data/).
151#[derive(Clone, Debug, PartialEq, Empty, IntoValue, ProcessValue, Default)]
152#[metastructure(process_func = "process_contexts")]
153pub struct Contexts(pub Object<ContextInner>);
154
155impl Contexts {
156    /// Creates an empty contexts map.
157    pub fn new() -> Contexts {
158        Contexts(Object::new())
159    }
160
161    /// Inserts a context under the default key for the context.
162    pub fn add<C>(&mut self, context: C)
163    where
164        C: DefaultContext,
165    {
166        self.insert(C::default_key().to_owned(), context.into_context());
167    }
168
169    /// Inserts a context under a custom given key.
170    ///
171    /// By convention, every typed context has a default key. Use [`add`](Self::add) to insert such
172    /// contexts, instead.
173    pub fn insert(&mut self, key: String, context: Context) {
174        self.0.insert(key, Annotated::new(ContextInner(context)));
175    }
176
177    /// Returns `true` if a matching context resides in the map at its default key.
178    pub fn contains<C>(&self) -> bool
179    where
180        C: DefaultContext,
181    {
182        // Use `get` to perform a type check.
183        self.get::<C>().is_some()
184    }
185
186    /// Returns `true` if a context with the provided key is present in the map.
187    ///
188    /// By convention, every typed context has a default key. Use [`contains`](Self::contains) to
189    /// check such contexts, instead.
190    pub fn contains_key<S>(&self, key: S) -> bool
191    where
192        S: AsRef<str>,
193    {
194        self.0.contains_key(key.as_ref())
195    }
196
197    /// Returns the context at its default key or constructs it if not present.
198    pub fn get_or_default<C>(&mut self) -> &mut C
199    where
200        C: DefaultContext,
201    {
202        if !self.contains::<C>() {
203            self.add(C::default());
204        }
205
206        self.get_mut().unwrap()
207    }
208
209    /// Returns the context at the specified key or constructs it if not present.
210    ///
211    /// By convention, every typed context has a default key. Use
212    /// [`get_or_default`](Self::get_or_default) to insert such contexts, instead.
213    pub fn get_or_insert_with<F, S>(&mut self, key: S, context_builder: F) -> &mut Context
214    where
215        F: FnOnce() -> Context,
216        S: Into<String>,
217    {
218        &mut self
219            .0
220            .entry(key.into())
221            .or_insert_with(Annotated::empty)
222            .value_mut()
223            .get_or_insert_with(|| ContextInner(context_builder()))
224            .0
225    }
226
227    /// Returns a reference to the default context by type.
228    pub fn get<C>(&self) -> Option<&C>
229    where
230        C: DefaultContext,
231    {
232        C::cast(self.get_key(C::default_key())?)
233    }
234
235    /// Returns a mutable reference to the default context by type.
236    pub fn get_mut<C>(&mut self) -> Option<&mut C>
237    where
238        C: DefaultContext,
239    {
240        C::cast_mut(self.get_key_mut(C::default_key())?)
241    }
242
243    /// Returns a reference to the context specified by `key`.
244    ///
245    /// By convention, every typed context has a default key. Use [`get`](Self::get) to retrieve
246    /// such contexts, instead.
247    pub fn get_key<S>(&self, key: S) -> Option<&Context>
248    where
249        S: AsRef<str>,
250    {
251        Some(&self.0.get(key.as_ref())?.value().as_ref()?.0)
252    }
253
254    /// Returns a mutable reference to the context specified by `key`.
255    ///
256    /// By convention, every typed context has a default key. Use [`get_mut`](Self::get_mut) to
257    /// retrieve such contexts, instead.
258    pub fn get_key_mut<S>(&mut self, key: S) -> Option<&mut Context>
259    where
260        S: AsRef<str>,
261    {
262        Some(&mut self.0.get_mut(key.as_ref())?.value_mut().as_mut()?.0)
263    }
264
265    /// Removes a context from the map, returning the context it was previously in the map.
266    ///
267    /// Returns `Some` if a matching context was removed from the default key. If the context at the
268    /// default key does not have a matching type, it is removed but `None` is returned.
269    pub fn remove<C>(&mut self) -> Option<C>
270    where
271        C: DefaultContext,
272    {
273        let context = self.remove_key(C::default_key())?;
274        C::from_context(context)
275    }
276
277    /// Removes a context from the map, returning the context it was previously in the map.
278    ///
279    /// By convention, every typed context has a default key. Use [`remove`](Self::remove) to
280    /// retrieve such contexts, instead.
281    pub fn remove_key<S>(&mut self, key: S) -> Option<Context>
282    where
283        S: AsRef<str>,
284    {
285        let inner = self.0.remove(key.as_ref())?;
286        Some(inner.into_value()?.0)
287    }
288}
289
290impl FromValue for Contexts {
291    fn from_value(mut annotated: Annotated<Value>) -> Annotated<Self> {
292        if let Annotated(Some(Value::Object(ref mut items)), _) = annotated {
293            for (key, value) in items.iter_mut() {
294                if let Annotated(Some(Value::Object(items)), _) = value {
295                    // Set the `"type"` if it's empty and overwrite it if it's an empty object or array.
296                    if !is_valid_context_type(items.get("type")) {
297                        items.insert(
298                            "type".to_owned(),
299                            Annotated::new(Value::String(key.to_string())),
300                        );
301                    }
302                }
303            }
304        }
305        FromValue::from_value(annotated).map_value(Contexts)
306    }
307}
308
309/// Returns `true` if `value` is a non-empty string, which is the only valid value
310/// for the `"type"` field of a context.
311fn is_valid_context_type(value: Option<&Annotated<Value>>) -> bool {
312    matches!(value.and_then(|v| v.value()), Some(Value::String(s)) if !s.is_empty())
313}
314
315/// A well-known context in the [`Contexts`] interface.
316///
317/// These contexts have a [default key](Self::default_key) in the contexts map and can be
318/// constructed as an empty default value.
319pub trait DefaultContext: Default {
320    /// The default key at which this context resides in [`Contexts`].
321    fn default_key() -> &'static str;
322
323    /// Converts this context type from a generic context type.
324    ///
325    /// Returns `Some` if the context is of this type. Otherwise, returns `None`.
326    fn from_context(context: Context) -> Option<Self>;
327
328    /// Casts a reference to this context type from a generic context type.
329    ///
330    /// Returns `Some` if the context is of this type. Otherwise, returns `None`.
331    fn cast(context: &Context) -> Option<&Self>;
332
333    /// Casts a mutable reference to this context type from a generic context type.
334    ///
335    /// Returns `Some` if the context is of this type. Otherwise, returns `None`.
336    fn cast_mut(context: &mut Context) -> Option<&mut Self>;
337
338    /// Boxes this context type in the generic context wrapper.
339    ///
340    /// Returns `Some` if the context is of this type. Otherwise, returns `None`.
341    fn into_context(self) -> Context;
342}
343
344#[cfg(test)]
345mod tests {
346    use relay_protocol::{Map, Meta};
347
348    use super::*;
349    use crate::processor::{ProcessingResult, ProcessingState, Processor};
350    use crate::protocol::Event;
351
352    #[test]
353    fn test_other_context_roundtrip() {
354        let json = r#"{"other":"value","type":"mytype"}"#;
355        let context = Annotated::new(Context::Other({
356            let mut map = Map::new();
357            map.insert(
358                "other".to_owned(),
359                Annotated::new(Value::String("value".to_owned())),
360            );
361            map.insert(
362                "type".to_owned(),
363                Annotated::new(Value::String("mytype".to_owned())),
364            );
365            map
366        }));
367
368        assert_eq!(context, Annotated::from_json(json).unwrap());
369        assert_eq!(json, context.to_json().unwrap());
370    }
371
372    #[test]
373    fn test_untagged_context_deserialize() {
374        let json = r#"{"os": {"name": "Linux"}}"#;
375
376        let mut map = Contexts::new();
377        map.add(OsContext {
378            name: Annotated::new("Linux".to_owned()),
379            ..Default::default()
380        });
381
382        assert_eq!(Annotated::new(map), Annotated::from_json(json).unwrap());
383    }
384
385    #[test]
386    fn test_context_invalid_type_deserialize() {
387        let json = r#"{
388            "monitor":{"name":"Foobar","type":17},
389            "os":{"name":"Linux","type":{}},
390            "profile":{"profile_id":"52df9022835246eeb317dbd739ccd059","type":""},
391            "runtime":{"name":"rustc","type":["invalid"]}
392        }"#;
393
394        let mut map = Contexts::new();
395        map.add(MonitorContext(
396            [("name".to_owned(), Value::String("Foobar".to_owned()).into())]
397                .into_iter()
398                .collect(),
399        ));
400        map.add(OsContext {
401            name: Annotated::new("Linux".to_owned()),
402            ..Default::default()
403        });
404        map.add(ProfileContext {
405            profile_id: Annotated::new("52df9022835246eeb317dbd739ccd059".parse().unwrap()),
406            ..Default::default()
407        });
408        map.add(RuntimeContext {
409            name: Annotated::new("rustc".to_owned()),
410            ..Default::default()
411        });
412
413        assert_eq!(Annotated::new(map), Annotated::from_json(json).unwrap());
414    }
415
416    #[test]
417    fn test_multiple_contexts_roundtrip() {
418        let json =
419            r#"{"os":{"name":"Linux","type":"os"},"runtime":{"name":"rustc","type":"runtime"}}"#;
420
421        let mut map = Contexts::new();
422        map.add(OsContext {
423            name: Annotated::new("Linux".to_owned()),
424            ..Default::default()
425        });
426        map.add(RuntimeContext {
427            name: Annotated::new("rustc".to_owned()),
428            ..Default::default()
429        });
430
431        let contexts = Annotated::new(map);
432        assert_eq!(contexts, Annotated::from_json(json).unwrap());
433        assert_eq!(json, contexts.to_json().unwrap());
434    }
435
436    #[test]
437    fn test_context_processing() {
438        let mut event = Annotated::new(Event {
439            contexts: {
440                let mut contexts = Contexts::new();
441                contexts.add(RuntimeContext {
442                    name: Annotated::new("php".to_owned()),
443                    version: Annotated::new("7.1.20-1+ubuntu16.04.1+deb.sury.org+1".to_owned()),
444                    ..Default::default()
445                });
446                Annotated::new(contexts)
447            },
448            ..Default::default()
449        });
450
451        struct FooProcessor {
452            called: bool,
453        }
454
455        impl Processor for FooProcessor {
456            #[inline]
457            fn process_context(
458                &mut self,
459                _value: &mut Context,
460                _meta: &mut Meta,
461                _state: &ProcessingState<'_>,
462            ) -> ProcessingResult {
463                self.called = true;
464                Ok(())
465            }
466        }
467
468        let mut processor = FooProcessor { called: false };
469        crate::processor::process_value(&mut event, &mut processor, ProcessingState::root())
470            .unwrap();
471        assert!(processor.called);
472    }
473}