relay_event_schema/protocol/contexts/
mod.rs1mod 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
56pub type OperationType = String;
61
62pub type OriginType = String;
65
66#[derive(Clone, Debug, PartialEq, Empty, FromValue, IntoValue, ProcessValue)]
68#[metastructure(process_func = "process_context")]
69pub enum Context {
70 Device(#[metastructure(max_bytes = 8192)] Box<DeviceContext>),
72 Os(#[metastructure(max_bytes = 8192)] Box<OsContext>),
74 Runtime(#[metastructure(max_bytes = 8192)] Box<RuntimeContext>),
76 App(#[metastructure(max_bytes = 8192)] Box<AppContext>),
78 Browser(#[metastructure(max_bytes = 8192)] Box<BrowserContext>),
80 Gpu(#[metastructure(max_bytes = 8192)] Box<GpuContext>),
82 Trace(#[metastructure(max_bytes = 8192)] Box<TraceContext>),
84 Profile(#[metastructure(max_bytes = 8192)] Box<ProfileContext>),
86 Replay(#[metastructure(max_bytes = 8192)] Box<ReplayContext>),
88 Flags(#[metastructure(max_bytes = 131_072)] Box<flags::FlagsContext>),
90 #[metastructure(tag = "feedback")]
92 UserReportV2(#[metastructure(max_bytes = 8192)] Box<UserReportV2Context>),
93 #[metastructure(tag = "memory_info")]
95 MemoryInfo(#[metastructure(max_bytes = 8192)] Box<MemoryInfoContext>),
96 Monitor(#[metastructure(max_bytes = 8192)] Box<MonitorContext>),
98 #[metastructure(omit_from_schema)]
100 Reprocessing(#[metastructure(max_bytes = 8192)] Box<ReprocessingContext>),
101 Attachments(#[metastructure(max_bytes = 8192)] Box<AttachmentsContext>),
103 Response(#[metastructure(max_bytes = 8192)] Box<ResponseContext>),
105 Otel(#[metastructure(max_bytes = 8192)] Box<OtelContext>),
107 CloudResource(#[metastructure(max_bytes = 8192)] Box<CloudResourceContext>),
109 Culture(#[metastructure(max_bytes = 8192)] Box<CultureContext>),
111 PerformanceScore(#[metastructure(max_bytes = 8192)] Box<PerformanceScoreContext>),
113 Spring(#[metastructure(max_bytes = 8192)] Box<SpringContext>),
115 #[metastructure(tag = "threadpool_info")]
117 ThreadPoolInfo(#[metastructure(max_bytes = 8192)] Box<ThreadPoolInfoContext>),
118 OTAUpdates(#[metastructure(max_bytes = 8192)] Box<OTAUpdatesContext>),
120 ChromiumStabilityReport(#[metastructure(max_bytes = 8192)] Box<StabilityReportContext>),
122 Unity(#[metastructure(max_bytes = 8192)] Box<UnityContext>),
124 #[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#[derive(Clone, Debug, PartialEq, Empty, IntoValue, ProcessValue, Default)]
152#[metastructure(process_func = "process_contexts")]
153pub struct Contexts(pub Object<ContextInner>);
154
155impl Contexts {
156 pub fn new() -> Contexts {
158 Contexts(Object::new())
159 }
160
161 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 pub fn insert(&mut self, key: String, context: Context) {
174 self.0.insert(key, Annotated::new(ContextInner(context)));
175 }
176
177 pub fn contains<C>(&self) -> bool
179 where
180 C: DefaultContext,
181 {
182 self.get::<C>().is_some()
184 }
185
186 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 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 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 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 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 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 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 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 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 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
309fn 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
315pub trait DefaultContext: Default {
320 fn default_key() -> &'static str;
322
323 fn from_context(context: Context) -> Option<Self>;
327
328 fn cast(context: &Context) -> Option<&Self>;
332
333 fn cast_mut(context: &mut Context) -> Option<&mut Self>;
337
338 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}