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(pii = "true", max_depth = 5, max_bytes = 2048)]
147 pub segment_names: Annotated<Array<String>>,
148
149 #[metastructure(skip_serialization = "empty")]
151 pub contexts: Annotated<Contexts>,
152
153 #[metastructure(max_chars = 64)]
158 pub platform: Annotated<String>,
159
160 #[metastructure(
165 max_chars = 200,
166 required = false,
167 trim_whitespace = true,
168 nonempty = true,
169 skip_serialization = "empty"
170 )]
171 pub release: Annotated<LenientString>,
172
173 #[metastructure(
181 allow_chars = "a-zA-Z0-9_.-",
182 trim_whitespace = true,
183 required = false,
184 nonempty = true,
185 max_chars = 64
186 )]
187 pub dist: Annotated<String>,
188
189 #[metastructure(
195 max_chars = 64,
196 nonempty = true,
197 required = false,
198 trim_whitespace = true
199 )]
200 pub environment: Annotated<String>,
201
202 #[metastructure(skip_serialization = "empty", pii = "true")]
206 pub tags: Annotated<Tags>,
207
208 #[metastructure(field = "type", max_chars = 64)]
210 pub ty: Annotated<String>,
211
212 #[metastructure(skip_serialization = "empty")]
214 pub user: Annotated<User>,
215
216 #[metastructure(skip_serialization = "empty")]
218 pub request: Annotated<Request>,
219
220 #[metastructure(field = "sdk")]
222 #[metastructure(skip_serialization = "empty")]
223 pub sdk: Annotated<ClientSdkInfo>,
224}
225
226impl Replay {
227 pub fn context<C: DefaultContext>(&self) -> Option<&C> {
229 self.contexts.value()?.get()
230 }
231
232 pub fn user_agent(&self) -> Option<&str> {
237 let headers = self.request.value()?.headers.value()?;
238
239 for item in headers.iter() {
240 if let Some((o_k, v)) = item.value()
241 && let Some(k) = o_k.as_str()
242 && k.eq_ignore_ascii_case("user-agent")
243 {
244 return v.as_str();
245 }
246 }
247
248 None
249 }
250}
251
252impl Getter for Replay {
253 fn get_value(&self, path: &str) -> Option<Val<'_>> {
254 let path = path
255 .strip_prefix("event.")
256 .or_else(|| path.strip_prefix("replay."))?;
257
258 Some(match path {
259 "release" => self.release.as_str()?.into(),
261 "dist" => self.dist.as_str()?.into(),
262 "environment" => self.environment.as_str()?.into(),
263 "platform" => self.platform.as_str().unwrap_or("other").into(),
264
265 "user.email" => or_none(&self.user.value()?.email)?.into(),
267 "user.id" => or_none(&self.user.value()?.id)?.into(),
268 "user.ip_address" => self.user.value()?.ip_address.as_str()?.into(),
269 "user.name" => self.user.value()?.name.as_str()?.into(),
270 "user.segment" => or_none(&self.user.value()?.segment)?.into(),
271 "user.geo.city" => self.user.value()?.geo.value()?.city.as_str()?.into(),
272 "user.geo.country_code" => self
273 .user
274 .value()?
275 .geo
276 .value()?
277 .country_code
278 .as_str()?
279 .into(),
280 "user.geo.region" => self.user.value()?.geo.value()?.region.as_str()?.into(),
281 "user.geo.subdivision" => self.user.value()?.geo.value()?.subdivision.as_str()?.into(),
282 "request.method" => self.request.value()?.method.as_str()?.into(),
283 "request.url" => self.request.value()?.url.as_str()?.into(),
284 "sdk.name" => self.sdk.value()?.name.as_str()?.into(),
285 "sdk.version" => self.sdk.value()?.version.as_str()?.into(),
286
287 "contexts.app.in_foreground" => {
289 self.context::<AppContext>()?.in_foreground.value()?.into()
290 }
291 "contexts.device.arch" => self.context::<DeviceContext>()?.arch.as_str()?.into(),
292 "contexts.device.battery_level" => self
293 .context::<DeviceContext>()?
294 .battery_level
295 .value()?
296 .into(),
297 "contexts.device.brand" => self.context::<DeviceContext>()?.brand.as_str()?.into(),
298 "contexts.device.charging" => self.context::<DeviceContext>()?.charging.value()?.into(),
299 "contexts.device.family" => self.context::<DeviceContext>()?.family.as_str()?.into(),
300 "contexts.device.model" => self.context::<DeviceContext>()?.model.as_str()?.into(),
301 "contexts.device.locale" => self.context::<DeviceContext>()?.locale.as_str()?.into(),
302 "contexts.device.online" => self.context::<DeviceContext>()?.online.value()?.into(),
303 "contexts.device.orientation" => self
304 .context::<DeviceContext>()?
305 .orientation
306 .as_str()?
307 .into(),
308 "contexts.device.name" => self.context::<DeviceContext>()?.name.as_str()?.into(),
309 "contexts.device.screen_density" => self
310 .context::<DeviceContext>()?
311 .screen_density
312 .value()?
313 .into(),
314 "contexts.device.screen_dpi" => {
315 self.context::<DeviceContext>()?.screen_dpi.value()?.into()
316 }
317 "contexts.device.screen_width_pixels" => self
318 .context::<DeviceContext>()?
319 .screen_width_pixels
320 .value()?
321 .into(),
322 "contexts.device.screen_height_pixels" => self
323 .context::<DeviceContext>()?
324 .screen_height_pixels
325 .value()?
326 .into(),
327 "contexts.device.simulator" => {
328 self.context::<DeviceContext>()?.simulator.value()?.into()
329 }
330 "contexts.os.build" => self.context::<OsContext>()?.build.as_str()?.into(),
331 "contexts.os.kernel_version" => {
332 self.context::<OsContext>()?.kernel_version.as_str()?.into()
333 }
334 "contexts.os.name" => self.context::<OsContext>()?.name.as_str()?.into(),
335 "contexts.os.version" => self.context::<OsContext>()?.version.as_str()?.into(),
336 "contexts.browser.name" => self.context::<BrowserContext>()?.name.as_str()?.into(),
337 "contexts.browser.version" => {
338 self.context::<BrowserContext>()?.version.as_str()?.into()
339 }
340 "contexts.profile.profile_id" => {
341 (&self.context::<ProfileContext>()?.profile_id.value()?.0).into()
342 }
343 "contexts.device.uuid" => self.context::<DeviceContext>()?.uuid.value()?.into(),
344 "contexts.trace.status" => self
345 .context::<TraceContext>()?
346 .status
347 .value()?
348 .as_str()
349 .into(),
350 "contexts.trace.op" => self.context::<TraceContext>()?.op.as_str()?.into(),
351 "contexts.response.status_code" => self
352 .context::<ResponseContext>()?
353 .status_code
354 .value()?
355 .into(),
356 "contexts.unreal.crash_type" => match self.contexts.value()?.get_key("unreal")? {
357 super::Context::Other(context) => context.get("crash_type")?.value()?.into(),
358 _ => return None,
359 },
360 "contexts.ota_updates.channel" => self
361 .context::<OTAUpdatesContext>()?
362 .channel
363 .as_str()?
364 .into(),
365 "contexts.ota_updates.runtime_version" => self
366 .context::<OTAUpdatesContext>()?
367 .runtime_version
368 .as_str()?
369 .into(),
370 "contexts.ota_updates.update_id" => self
371 .context::<OTAUpdatesContext>()?
372 .update_id
373 .as_str()?
374 .into(),
375
376 path => {
378 if let Some(rest) = path.strip_prefix("tags.") {
379 self.tags.value()?.get(rest)?.into()
380 } else {
381 let rest = path.strip_prefix("request.headers.")?;
382 self.request
383 .value()?
384 .headers
385 .value()?
386 .get_header(rest)?
387 .into()
388 }
389 }
390 })
391 }
392}
393
394fn or_none(string: &Annotated<impl AsRef<str>>) -> Option<&str> {
395 match string.as_str() {
396 None | Some("") => None,
397 Some(other) => Some(other),
398 }
399}
400
401#[cfg(test)]
402mod tests {
403 use chrono::{TimeZone, Utc};
404
405 use crate::protocol::TagEntry;
406
407 use super::*;
408
409 #[test]
410 fn test_event_roundtrip() {
411 let json = r#"{
413 "event_id": "52df9022835246eeb317dbd739ccd059",
414 "replay_id": "52df9022835246eeb317dbd739ccd059",
415 "segment_id": 0,
416 "replay_type": "session",
417 "error_sample_rate": 0.5,
418 "session_sample_rate": 0.5,
419 "timestamp": 946684800.0,
420 "replay_start_timestamp": 946684800.0,
421 "urls": ["localhost:9000"],
422 "error_ids": ["52df9022835246eeb317dbd739ccd059"],
423 "trace_ids": ["52df9022835246eeb317dbd739ccd059"],
424 "platform": "myplatform",
425 "release": "myrelease",
426 "dist": "mydist",
427 "environment": "myenv",
428 "tags": [
429 [
430 "tag",
431 "value"
432 ]
433 ]
434}"#;
435
436 let replay = Annotated::new(Replay {
437 event_id: Annotated::new(EventId("52df9022835246eeb317dbd739ccd059".parse().unwrap())),
438 replay_id: Annotated::new(EventId("52df9022835246eeb317dbd739ccd059".parse().unwrap())),
439 replay_type: Annotated::new("session".to_owned()),
440 segment_id: Annotated::new(0),
441 timestamp: Annotated::new(Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap().into()),
442 replay_start_timestamp: Annotated::new(
443 Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap().into(),
444 ),
445 urls: Annotated::new(vec![Annotated::new("localhost:9000".to_owned())]),
446 error_ids: Annotated::new(vec![Annotated::new(
447 Uuid::parse_str("52df9022835246eeb317dbd739ccd059").unwrap(),
448 )]),
449 trace_ids: Annotated::new(vec![Annotated::new(
450 Uuid::parse_str("52df9022835246eeb317dbd739ccd059").unwrap(),
451 )]),
452 platform: Annotated::new("myplatform".to_owned()),
453 release: Annotated::new("myrelease".to_owned().into()),
454 dist: Annotated::new("mydist".to_owned()),
455 environment: Annotated::new("myenv".to_owned()),
456 tags: {
457 let items = vec![Annotated::new(TagEntry(
458 Annotated::new("tag".to_owned()),
459 Annotated::new("value".to_owned()),
460 ))];
461 Annotated::new(Tags(items.into()))
462 },
463 ..Default::default()
464 });
465
466 assert_eq!(replay, Annotated::from_json(json).unwrap());
467 }
468
469 #[test]
470 fn test_lenient_release() {
471 let input = r#"{"release":42}"#;
472 let output = r#"{"release":"42"}"#;
473 let event = Annotated::new(Replay {
474 release: Annotated::new("42".to_owned().into()),
475 ..Default::default()
476 });
477
478 assert_eq!(event, Annotated::from_json(input).unwrap());
479 assert_eq!(output, event.to_json().unwrap());
480 }
481
482 #[test]
483 fn test_ota_updates_context_getter() {
484 let mut contexts = Contexts::new();
485 contexts.add(OTAUpdatesContext {
486 channel: Annotated::new("production".to_owned()),
487 runtime_version: Annotated::new("1.0.0".to_owned()),
488 update_id: Annotated::new("12345678-1234-1234-1234-1234567890ab".to_owned()),
489 ..OTAUpdatesContext::default()
490 });
491
492 let replay = Replay {
493 contexts: Annotated::new(contexts),
494 ..Default::default()
495 };
496
497 assert_eq!(
498 Some(Val::String("production")),
499 replay.get_value("event.contexts.ota_updates.channel")
500 );
501 assert_eq!(
502 Some(Val::String("1.0.0")),
503 replay.get_value("event.contexts.ota_updates.runtime_version")
504 );
505 assert_eq!(
506 Some(Val::String("12345678-1234-1234-1234-1234567890ab")),
507 replay.get_value("event.contexts.ota_updates.update_id")
508 );
509 }
510
511 #[test]
512 fn test_getter_replay_prefix() {
513 let replay = Replay {
514 release: Annotated::new("1.1.1".to_owned().into()),
515 ..Default::default()
516 };
517
518 assert_eq!(
519 Some(Val::String("1.1.1")),
520 replay.get_value("event.release")
521 );
522 assert_eq!(
523 Some(Val::String("1.1.1")),
524 replay.get_value("replay.release")
525 );
526 assert_eq!(None, replay.get_value("transaction.release"));
527 }
528}