1use relay_protocol::{Annotated, Array, Empty, FromValue, Getter, IntoValue, Val};
29
30use crate::processor::ProcessValue;
31use crate::protocol::{
32 AppContext, BrowserContext, ClientSdkInfo, Contexts, DefaultContext, DeviceContext, EventId,
33 LenientString, OTAUpdatesContext, OsContext, ProfileContext, Request, ResponseContext, Tags,
34 Timestamp, TraceContext, User,
35};
36use uuid::Uuid;
37
38#[derive(Clone, Debug, Default, PartialEq, Empty, FromValue, IntoValue, ProcessValue)]
39#[metastructure(process_func = "process_replay", value_type = "Replay")]
40pub struct Replay {
41 pub event_id: Annotated<EventId>,
59
60 pub replay_id: Annotated<EventId>,
73
74 #[metastructure(max_chars = 64)]
86 pub replay_type: Annotated<String>,
87
88 pub segment_id: Annotated<u64>,
102
103 pub timestamp: Annotated<Timestamp>,
129
130 pub replay_start_timestamp: Annotated<Timestamp>,
132
133 #[metastructure(pii = "true", max_depth = 7, max_bytes = 8192)]
135 pub urls: Annotated<Array<String>>,
136
137 #[metastructure(max_depth = 5, max_bytes = 2048)]
139 pub error_ids: Annotated<Array<Uuid>>,
140
141 #[metastructure(max_depth = 5, max_bytes = 2048)]
143 pub trace_ids: Annotated<Array<Uuid>>,
144
145 #[metastructure(skip_serialization = "empty")]
147 pub contexts: Annotated<Contexts>,
148
149 #[metastructure(max_chars = 64)]
154 pub platform: Annotated<String>,
155
156 #[metastructure(
161 max_chars = 200,
162 required = false,
163 trim_whitespace = true,
164 nonempty = true,
165 skip_serialization = "empty"
166 )]
167 pub release: Annotated<LenientString>,
168
169 #[metastructure(
177 allow_chars = "a-zA-Z0-9_.-",
178 trim_whitespace = true,
179 required = false,
180 nonempty = true,
181 max_chars = 64
182 )]
183 pub dist: Annotated<String>,
184
185 #[metastructure(
191 max_chars = 64,
192 nonempty = true,
193 required = false,
194 trim_whitespace = true
195 )]
196 pub environment: Annotated<String>,
197
198 #[metastructure(skip_serialization = "empty", pii = "true")]
202 pub tags: Annotated<Tags>,
203
204 #[metastructure(field = "type", max_chars = 64)]
206 pub ty: Annotated<String>,
207
208 #[metastructure(skip_serialization = "empty")]
210 pub user: Annotated<User>,
211
212 #[metastructure(skip_serialization = "empty")]
214 pub request: Annotated<Request>,
215
216 #[metastructure(field = "sdk")]
218 #[metastructure(skip_serialization = "empty")]
219 pub sdk: Annotated<ClientSdkInfo>,
220}
221
222impl Replay {
223 pub fn context<C: DefaultContext>(&self) -> Option<&C> {
225 self.contexts.value()?.get()
226 }
227
228 pub fn user_agent(&self) -> Option<&str> {
233 let headers = self.request.value()?.headers.value()?;
234
235 for item in headers.iter() {
236 if let Some((o_k, v)) = item.value()
237 && let Some(k) = o_k.as_str()
238 && k.eq_ignore_ascii_case("user-agent")
239 {
240 return v.as_str();
241 }
242 }
243
244 None
245 }
246}
247
248impl Getter for Replay {
249 fn get_value(&self, path: &str) -> Option<Val<'_>> {
250 Some(match path.strip_prefix("event.")? {
251 "release" => self.release.as_str()?.into(),
253 "dist" => self.dist.as_str()?.into(),
254 "environment" => self.environment.as_str()?.into(),
255 "platform" => self.platform.as_str().unwrap_or("other").into(),
256
257 "user.email" => or_none(&self.user.value()?.email)?.into(),
259 "user.id" => or_none(&self.user.value()?.id)?.into(),
260 "user.ip_address" => self.user.value()?.ip_address.as_str()?.into(),
261 "user.name" => self.user.value()?.name.as_str()?.into(),
262 "user.segment" => or_none(&self.user.value()?.segment)?.into(),
263 "user.geo.city" => self.user.value()?.geo.value()?.city.as_str()?.into(),
264 "user.geo.country_code" => self
265 .user
266 .value()?
267 .geo
268 .value()?
269 .country_code
270 .as_str()?
271 .into(),
272 "user.geo.region" => self.user.value()?.geo.value()?.region.as_str()?.into(),
273 "user.geo.subdivision" => self.user.value()?.geo.value()?.subdivision.as_str()?.into(),
274 "request.method" => self.request.value()?.method.as_str()?.into(),
275 "request.url" => self.request.value()?.url.as_str()?.into(),
276 "sdk.name" => self.sdk.value()?.name.as_str()?.into(),
277 "sdk.version" => self.sdk.value()?.version.as_str()?.into(),
278
279 "sentry_user" => self.user.value()?.sentry_user.as_str()?.into(),
281
282 "contexts.app.in_foreground" => {
284 self.context::<AppContext>()?.in_foreground.value()?.into()
285 }
286 "contexts.device.arch" => self.context::<DeviceContext>()?.arch.as_str()?.into(),
287 "contexts.device.battery_level" => self
288 .context::<DeviceContext>()?
289 .battery_level
290 .value()?
291 .into(),
292 "contexts.device.brand" => self.context::<DeviceContext>()?.brand.as_str()?.into(),
293 "contexts.device.charging" => self.context::<DeviceContext>()?.charging.value()?.into(),
294 "contexts.device.family" => self.context::<DeviceContext>()?.family.as_str()?.into(),
295 "contexts.device.model" => self.context::<DeviceContext>()?.model.as_str()?.into(),
296 "contexts.device.locale" => self.context::<DeviceContext>()?.locale.as_str()?.into(),
297 "contexts.device.online" => self.context::<DeviceContext>()?.online.value()?.into(),
298 "contexts.device.orientation" => self
299 .context::<DeviceContext>()?
300 .orientation
301 .as_str()?
302 .into(),
303 "contexts.device.name" => self.context::<DeviceContext>()?.name.as_str()?.into(),
304 "contexts.device.screen_density" => self
305 .context::<DeviceContext>()?
306 .screen_density
307 .value()?
308 .into(),
309 "contexts.device.screen_dpi" => {
310 self.context::<DeviceContext>()?.screen_dpi.value()?.into()
311 }
312 "contexts.device.screen_width_pixels" => self
313 .context::<DeviceContext>()?
314 .screen_width_pixels
315 .value()?
316 .into(),
317 "contexts.device.screen_height_pixels" => self
318 .context::<DeviceContext>()?
319 .screen_height_pixels
320 .value()?
321 .into(),
322 "contexts.device.simulator" => {
323 self.context::<DeviceContext>()?.simulator.value()?.into()
324 }
325 "contexts.os.build" => self.context::<OsContext>()?.build.as_str()?.into(),
326 "contexts.os.kernel_version" => {
327 self.context::<OsContext>()?.kernel_version.as_str()?.into()
328 }
329 "contexts.os.name" => self.context::<OsContext>()?.name.as_str()?.into(),
330 "contexts.os.version" => self.context::<OsContext>()?.version.as_str()?.into(),
331 "contexts.browser.name" => self.context::<BrowserContext>()?.name.as_str()?.into(),
332 "contexts.browser.version" => {
333 self.context::<BrowserContext>()?.version.as_str()?.into()
334 }
335 "contexts.profile.profile_id" => {
336 (&self.context::<ProfileContext>()?.profile_id.value()?.0).into()
337 }
338 "contexts.device.uuid" => self.context::<DeviceContext>()?.uuid.value()?.into(),
339 "contexts.trace.status" => self
340 .context::<TraceContext>()?
341 .status
342 .value()?
343 .as_str()
344 .into(),
345 "contexts.trace.op" => self.context::<TraceContext>()?.op.as_str()?.into(),
346 "contexts.response.status_code" => self
347 .context::<ResponseContext>()?
348 .status_code
349 .value()?
350 .into(),
351 "contexts.unreal.crash_type" => match self.contexts.value()?.get_key("unreal")? {
352 super::Context::Other(context) => context.get("crash_type")?.value()?.into(),
353 _ => return None,
354 },
355 "contexts.ota_updates.channel" => self
356 .context::<OTAUpdatesContext>()?
357 .channel
358 .as_str()?
359 .into(),
360 "contexts.ota_updates.runtime_version" => self
361 .context::<OTAUpdatesContext>()?
362 .runtime_version
363 .as_str()?
364 .into(),
365 "contexts.ota_updates.update_id" => self
366 .context::<OTAUpdatesContext>()?
367 .update_id
368 .as_str()?
369 .into(),
370
371 path => {
373 if let Some(rest) = path.strip_prefix("tags.") {
374 self.tags.value()?.get(rest)?.into()
375 } else if let Some(rest) = path.strip_prefix("request.headers.") {
376 self.request
377 .value()?
378 .headers
379 .value()?
380 .get_header(rest)?
381 .into()
382 } else {
383 return None;
384 }
385 }
386 })
387 }
388}
389
390fn or_none(string: &Annotated<impl AsRef<str>>) -> Option<&str> {
391 match string.as_str() {
392 None | Some("") => None,
393 Some(other) => Some(other),
394 }
395}
396
397#[cfg(test)]
398mod tests {
399 use chrono::{TimeZone, Utc};
400
401 use crate::protocol::TagEntry;
402
403 use super::*;
404
405 #[test]
406 fn test_event_roundtrip() {
407 let json = r#"{
409 "event_id": "52df9022835246eeb317dbd739ccd059",
410 "replay_id": "52df9022835246eeb317dbd739ccd059",
411 "segment_id": 0,
412 "replay_type": "session",
413 "error_sample_rate": 0.5,
414 "session_sample_rate": 0.5,
415 "timestamp": 946684800.0,
416 "replay_start_timestamp": 946684800.0,
417 "urls": ["localhost:9000"],
418 "error_ids": ["52df9022835246eeb317dbd739ccd059"],
419 "trace_ids": ["52df9022835246eeb317dbd739ccd059"],
420 "platform": "myplatform",
421 "release": "myrelease",
422 "dist": "mydist",
423 "environment": "myenv",
424 "tags": [
425 [
426 "tag",
427 "value"
428 ]
429 ]
430}"#;
431
432 let replay = Annotated::new(Replay {
433 event_id: Annotated::new(EventId("52df9022835246eeb317dbd739ccd059".parse().unwrap())),
434 replay_id: Annotated::new(EventId("52df9022835246eeb317dbd739ccd059".parse().unwrap())),
435 replay_type: Annotated::new("session".to_owned()),
436 segment_id: Annotated::new(0),
437 timestamp: Annotated::new(Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap().into()),
438 replay_start_timestamp: Annotated::new(
439 Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap().into(),
440 ),
441 urls: Annotated::new(vec![Annotated::new("localhost:9000".to_owned())]),
442 error_ids: Annotated::new(vec![Annotated::new(
443 Uuid::parse_str("52df9022835246eeb317dbd739ccd059").unwrap(),
444 )]),
445 trace_ids: Annotated::new(vec![Annotated::new(
446 Uuid::parse_str("52df9022835246eeb317dbd739ccd059").unwrap(),
447 )]),
448 platform: Annotated::new("myplatform".to_owned()),
449 release: Annotated::new("myrelease".to_owned().into()),
450 dist: Annotated::new("mydist".to_owned()),
451 environment: Annotated::new("myenv".to_owned()),
452 tags: {
453 let items = vec![Annotated::new(TagEntry(
454 Annotated::new("tag".to_owned()),
455 Annotated::new("value".to_owned()),
456 ))];
457 Annotated::new(Tags(items.into()))
458 },
459 ..Default::default()
460 });
461
462 assert_eq!(replay, Annotated::from_json(json).unwrap());
463 }
464
465 #[test]
466 fn test_lenient_release() {
467 let input = r#"{"release":42}"#;
468 let output = r#"{"release":"42"}"#;
469 let event = Annotated::new(Replay {
470 release: Annotated::new("42".to_owned().into()),
471 ..Default::default()
472 });
473
474 assert_eq!(event, Annotated::from_json(input).unwrap());
475 assert_eq!(output, event.to_json().unwrap());
476 }
477
478 #[test]
479 fn test_ota_updates_context_getter() {
480 let mut contexts = Contexts::new();
481 contexts.add(OTAUpdatesContext {
482 channel: Annotated::new("production".to_owned()),
483 runtime_version: Annotated::new("1.0.0".to_owned()),
484 update_id: Annotated::new("12345678-1234-1234-1234-1234567890ab".to_owned()),
485 ..OTAUpdatesContext::default()
486 });
487
488 let replay = Replay {
489 contexts: Annotated::new(contexts),
490 ..Default::default()
491 };
492
493 assert_eq!(
494 Some(Val::String("production")),
495 replay.get_value("event.contexts.ota_updates.channel")
496 );
497 assert_eq!(
498 Some(Val::String("1.0.0")),
499 replay.get_value("event.contexts.ota_updates.runtime_version")
500 );
501 assert_eq!(
502 Some(Val::String("12345678-1234-1234-1234-1234567890ab")),
503 replay.get_value("event.contexts.ota_updates.update_id")
504 );
505 }
506}