1use chrono::{DateTime, Utc};
8use serde::{Deserialize, Serialize};
9use uuid::Uuid;
10use validator::Validate;
11
12use crate::models::domains::{
13 ActuatorsDomain, AiDomain, AudioDomain, CommunicationDomain, ComplianceDomain, ComputeDomain,
14 ContextDomain, CoordinationDomain, EnvironmentInteractionDomain, HriDomain, IdentityDomain,
15 LocationDomain, MaintenanceDomain, ManipulationDomain, MotionDomain, NavigationDomain,
16 OperationalDomain, PayloadDomain, PerceptionDomain, PowerDomain, SafetyDomain,
17 SimulationDomain, ThermalDomain,
18};
19use crate::models::enums::{EventType, SourceType};
20
21#[derive(Debug, Clone, Default, Serialize, Deserialize, Validate)]
52pub struct UdmEvent {
53 pub event_id: String,
58
59 #[serde(alias = "timestamp")]
62 pub captured_at: DateTime<Utc>,
63
64 #[serde(default)]
66 pub event_type: EventType,
67
68 #[serde(default)]
71 pub source_id: String,
72
73 pub source_type: SourceType,
75
76 #[serde(alias = "schema_version")]
78 pub udm_version: String,
79
80 pub sdk_version: String,
82
83 #[serde(skip_serializing_if = "Option::is_none")]
88 pub identity: Option<IdentityDomain>,
89
90 #[serde(skip_serializing_if = "Option::is_none")]
92 pub location: Option<LocationDomain>,
93
94 #[serde(skip_serializing_if = "Option::is_none")]
96 pub motion: Option<MotionDomain>,
97
98 #[serde(skip_serializing_if = "Option::is_none")]
100 pub power: Option<PowerDomain>,
101
102 #[serde(skip_serializing_if = "Option::is_none")]
104 pub operational: Option<OperationalDomain>,
105
106 #[serde(skip_serializing_if = "Option::is_none")]
108 pub navigation: Option<NavigationDomain>,
109
110 #[serde(skip_serializing_if = "Option::is_none")]
112 pub perception: Option<PerceptionDomain>,
113
114 #[serde(skip_serializing_if = "Option::is_none")]
116 pub safety: Option<SafetyDomain>,
117
118 #[serde(skip_serializing_if = "Option::is_none")]
120 pub actuators: Option<ActuatorsDomain>,
121
122 #[serde(skip_serializing_if = "Option::is_none")]
124 pub communication: Option<CommunicationDomain>,
125
126 #[serde(skip_serializing_if = "Option::is_none")]
128 pub compute: Option<ComputeDomain>,
129
130 #[serde(skip_serializing_if = "Option::is_none")]
132 pub ai: Option<AiDomain>,
133
134 #[serde(skip_serializing_if = "Option::is_none")]
136 pub maintenance: Option<MaintenanceDomain>,
137
138 #[serde(skip_serializing_if = "Option::is_none")]
140 pub context: Option<ContextDomain>,
141
142 #[serde(skip_serializing_if = "Option::is_none")]
144 pub payload: Option<PayloadDomain>,
145
146 #[serde(skip_serializing_if = "Option::is_none")]
148 pub manipulation: Option<ManipulationDomain>,
149
150 #[serde(skip_serializing_if = "Option::is_none")]
152 pub hri: Option<HriDomain>,
153
154 #[serde(skip_serializing_if = "Option::is_none")]
156 pub coordination: Option<CoordinationDomain>,
157
158 #[serde(skip_serializing_if = "Option::is_none")]
160 pub simulation: Option<SimulationDomain>,
161
162 #[serde(skip_serializing_if = "Option::is_none")]
164 pub thermal: Option<ThermalDomain>,
165
166 #[serde(skip_serializing_if = "Option::is_none")]
168 pub audio: Option<AudioDomain>,
169
170 #[serde(skip_serializing_if = "Option::is_none")]
172 pub environment_interaction: Option<EnvironmentInteractionDomain>,
173
174 #[serde(skip_serializing_if = "Option::is_none")]
176 pub compliance: Option<ComplianceDomain>,
177
178 #[serde(skip_serializing_if = "Option::is_none")]
183 pub provenance: Option<Provenance>,
184
185 #[serde(skip_serializing_if = "Option::is_none")]
188 pub ros_graph: Option<serde_json::Value>,
189
190 #[serde(skip_serializing_if = "Option::is_none")]
193 pub heartbeat: Option<serde_json::Value>,
194
195 #[serde(skip_serializing_if = "Option::is_none")]
197 pub extensions: Option<serde_json::Value>,
198}
199
200#[derive(Debug, Clone, Default, Serialize, Deserialize)]
202pub struct Provenance {
203 #[serde(skip_serializing_if = "Option::is_none")]
205 pub signature: Option<String>,
206
207 #[serde(skip_serializing_if = "Option::is_none")]
209 pub key_id: Option<String>,
210
211 #[serde(skip_serializing_if = "Option::is_none")]
213 pub algorithm: Option<String>,
214
215 #[serde(skip_serializing_if = "Option::is_none")]
217 pub signed_fields: Option<Vec<String>>,
218
219 #[serde(skip_serializing_if = "Option::is_none")]
221 pub signed_at: Option<DateTime<Utc>>,
222
223 #[serde(skip_serializing_if = "Option::is_none")]
226 pub sequence_num: Option<u64>,
227
228 #[serde(skip_serializing_if = "Option::is_none")]
231 pub boot_epoch: Option<String>,
232
233 #[serde(skip_serializing_if = "Option::is_none")]
235 pub signer: Option<String>,
236
237 #[serde(skip_serializing_if = "Option::is_none")]
240 pub boot_counter: Option<u64>,
241
242 #[serde(skip_serializing_if = "Option::is_none")]
245 pub device_attestation: Option<serde_json::Value>,
246
247 #[serde(default, skip_serializing_if = "Option::is_none")]
252 pub batch: Option<serde_json::Value>,
253 #[serde(default, skip_serializing_if = "Option::is_none")]
255 pub license: Option<serde_json::Value>,
256}
257
258impl UdmEvent {
259 pub fn new(source_type: SourceType) -> Self {
263 Self {
264 event_id: Uuid::now_v7().to_string(),
265 captured_at: Utc::now(),
266 event_type: EventType::default(),
267 source_type,
268 udm_version: crate::UDM_VERSION.to_string(),
269 sdk_version: crate::SDK_VERSION.to_string(),
270 ..Default::default()
271 }
272 }
273
274 pub fn with_event_type(mut self, event_type: EventType) -> Self {
276 self.event_type = event_type;
277 self
278 }
279
280 pub fn with_identity(mut self, identity: IdentityDomain) -> Self {
282 self.identity = Some(identity);
283 self
284 }
285
286 pub fn with_location(mut self, location: LocationDomain) -> Self {
288 self.location = Some(location);
289 self
290 }
291
292 pub fn with_motion(mut self, motion: MotionDomain) -> Self {
294 self.motion = Some(motion);
295 self
296 }
297
298 pub fn with_power(mut self, power: PowerDomain) -> Self {
300 self.power = Some(power);
301 self
302 }
303
304 pub fn with_operational(mut self, operational: OperationalDomain) -> Self {
306 self.operational = Some(operational);
307 self
308 }
309
310 pub fn with_navigation(mut self, navigation: NavigationDomain) -> Self {
312 self.navigation = Some(navigation);
313 self
314 }
315
316 pub fn with_perception(mut self, perception: PerceptionDomain) -> Self {
318 self.perception = Some(perception);
319 self
320 }
321
322 pub fn with_safety(mut self, safety: SafetyDomain) -> Self {
324 self.safety = Some(safety);
325 self
326 }
327
328 pub fn with_actuators(mut self, actuators: ActuatorsDomain) -> Self {
330 self.actuators = Some(actuators);
331 self
332 }
333
334 pub fn with_communication(mut self, communication: CommunicationDomain) -> Self {
336 self.communication = Some(communication);
337 self
338 }
339
340 pub fn with_compute(mut self, compute: ComputeDomain) -> Self {
342 self.compute = Some(compute);
343 self
344 }
345
346 pub fn with_ai(mut self, ai: AiDomain) -> Self {
348 self.ai = Some(ai);
349 self
350 }
351
352 pub fn with_maintenance(mut self, maintenance: MaintenanceDomain) -> Self {
354 self.maintenance = Some(maintenance);
355 self
356 }
357
358 pub fn with_context(mut self, context: ContextDomain) -> Self {
360 self.context = Some(context);
361 self
362 }
363
364 pub fn with_payload(mut self, payload: PayloadDomain) -> Self {
366 self.payload = Some(payload);
367 self
368 }
369
370 pub fn with_manipulation(mut self, manipulation: ManipulationDomain) -> Self {
372 self.manipulation = Some(manipulation);
373 self
374 }
375
376 pub fn with_hri(mut self, hri: HriDomain) -> Self {
378 self.hri = Some(hri);
379 self
380 }
381
382 pub fn with_coordination(mut self, coordination: CoordinationDomain) -> Self {
384 self.coordination = Some(coordination);
385 self
386 }
387
388 pub fn with_simulation(mut self, simulation: SimulationDomain) -> Self {
390 self.simulation = Some(simulation);
391 self
392 }
393
394 pub fn with_thermal(mut self, thermal: ThermalDomain) -> Self {
396 self.thermal = Some(thermal);
397 self
398 }
399
400 pub fn with_audio(mut self, audio: AudioDomain) -> Self {
402 self.audio = Some(audio);
403 self
404 }
405
406 pub fn with_environment_interaction(
408 mut self,
409 environment_interaction: EnvironmentInteractionDomain,
410 ) -> Self {
411 self.environment_interaction = Some(environment_interaction);
412 self
413 }
414
415 pub fn with_compliance(mut self, compliance: ComplianceDomain) -> Self {
417 self.compliance = Some(compliance);
418 self
419 }
420
421 pub fn with_extensions(mut self, extensions: serde_json::Value) -> Self {
423 self.extensions = Some(extensions);
424 self
425 }
426
427 pub fn inject_license_metadata(&mut self, metadata: &crate::core::license::LicenseMetadata) {
433 self.provenance
434 .get_or_insert_with(Provenance::default)
435 .license = serde_json::to_value(metadata).ok();
436 }
437
438 pub fn with_provenance(mut self, provenance: Provenance) -> Self {
440 self.provenance = Some(provenance);
441 self
442 }
443
444 pub fn has_domain_data(&self) -> bool {
446 self.identity.is_some()
447 || self.location.is_some()
448 || self.motion.is_some()
449 || self.power.is_some()
450 || self.operational.is_some()
451 || self.navigation.is_some()
452 || self.perception.is_some()
453 || self.safety.is_some()
454 || self.actuators.is_some()
455 || self.communication.is_some()
456 || self.compute.is_some()
457 || self.ai.is_some()
458 || self.maintenance.is_some()
459 || self.context.is_some()
460 || self.payload.is_some()
461 || self.manipulation.is_some()
462 || self.hri.is_some()
463 || self.coordination.is_some()
464 || self.simulation.is_some()
465 || self.thermal.is_some()
466 || self.audio.is_some()
467 || self.environment_interaction.is_some()
468 || self.compliance.is_some()
469 }
470
471 pub fn estimated_size(&self) -> usize {
473 serde_json::to_string(self).map(|s| s.len()).unwrap_or(0)
474 }
475
476 pub fn to_json(&self) -> Result<String, serde_json::Error> {
478 serde_json::to_string(self)
479 }
480
481 pub fn to_json_pretty(&self) -> Result<String, serde_json::Error> {
483 serde_json::to_string_pretty(self)
484 }
485
486 pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
488 serde_json::from_str(json)
489 }
490}
491
492impl Provenance {
493 pub fn new(algorithm: impl Into<String>) -> Self {
495 Self {
496 algorithm: Some(algorithm.into()),
497 signed_at: Some(Utc::now()),
498 ..Default::default()
499 }
500 }
501
502 pub fn with_signature(mut self, signature: impl Into<String>) -> Self {
504 self.signature = Some(signature.into());
505 self
506 }
507
508 pub fn with_key_id(mut self, key_id: impl Into<String>) -> Self {
510 self.key_id = Some(key_id.into());
511 self
512 }
513
514 pub fn with_signed_fields(mut self, fields: Vec<String>) -> Self {
516 self.signed_fields = Some(fields);
517 self
518 }
519}
520
521#[cfg(test)]
522mod tests {
523 use super::*;
524
525 #[test]
526 fn test_event_creation() {
527 let event = UdmEvent::new(SourceType::Amr);
528
529 assert!(!event.event_id.is_empty());
530 assert_eq!(event.source_type, SourceType::Amr);
531 assert_eq!(event.event_type, EventType::TelemetryPeriodic);
532 assert!(!event.has_domain_data());
533 }
534
535 #[test]
536 fn test_event_with_domains() {
537 use crate::models::domains::location::LocalCoordinates;
538
539 let event = UdmEvent::new(SourceType::Amr)
540 .with_identity(IdentityDomain {
541 source_id: Some("robot-001".to_string()),
542 ..Default::default()
543 })
544 .with_location(LocationDomain {
545 local: Some(LocalCoordinates {
546 x_m: Some(10.0),
547 y_m: Some(20.0),
548 ..Default::default()
549 }),
550 ..Default::default()
551 });
552
553 assert!(event.has_domain_data());
554 assert_eq!(
555 event.identity.as_ref().unwrap().source_id,
556 Some("robot-001".to_string())
557 );
558 }
559
560 #[test]
561 fn test_event_serialization() {
562 let event = UdmEvent::new(SourceType::Amr).with_event_type(EventType::StateTransition);
563
564 let json = event.to_json().unwrap();
565 assert!(json.contains("\"event_id\""));
566 assert!(json.contains("\"state_transition\""));
567
568 let deserialized = UdmEvent::from_json(&json).unwrap();
569 assert_eq!(deserialized.event_type, EventType::StateTransition);
570 }
571
572 #[test]
573 fn test_provenance() {
574 let provenance = Provenance::new("hmac-sha256")
575 .with_signature("abc123")
576 .with_key_id("key-001");
577
578 assert_eq!(provenance.algorithm, Some("hmac-sha256".to_string()));
579 assert_eq!(provenance.signature, Some("abc123".to_string()));
580 }
581
582 #[test]
583 fn test_event_with_extensions() {
584 let extensions = serde_json::json!({
585 "custom_field": "custom_value",
586 "nested": { "key": 42 }
587 });
588
589 let event = UdmEvent::new(SourceType::Custom).with_extensions(extensions.clone());
590
591 assert_eq!(event.extensions, Some(extensions));
592 }
593
594 #[test]
599 fn test_event_default() {
600 let event = UdmEvent::default();
601 assert!(event.event_id.is_empty());
602 assert!(event.identity.is_none());
603 assert!(event.location.is_none());
604 }
605
606 #[test]
607 fn test_event_with_event_type() {
608 let event = UdmEvent::new(SourceType::Amr).with_event_type(EventType::SafetyViolation);
609 assert_eq!(event.event_type, EventType::SafetyViolation);
610 }
611
612 #[test]
613 fn test_event_with_all_domains() {
614 let event = UdmEvent::new(SourceType::Amr)
615 .with_identity(IdentityDomain::default())
616 .with_location(LocationDomain::default())
617 .with_motion(MotionDomain::default())
618 .with_power(PowerDomain::default())
619 .with_operational(OperationalDomain::default())
620 .with_navigation(NavigationDomain::default())
621 .with_perception(PerceptionDomain::default())
622 .with_safety(SafetyDomain::default())
623 .with_actuators(ActuatorsDomain::default())
624 .with_communication(CommunicationDomain::default())
625 .with_compute(ComputeDomain::default())
626 .with_ai(AiDomain::default())
627 .with_maintenance(MaintenanceDomain::default())
628 .with_context(ContextDomain::default())
629 .with_payload(PayloadDomain::default())
630 .with_manipulation(ManipulationDomain::default())
631 .with_hri(HriDomain::default())
632 .with_coordination(CoordinationDomain::default())
633 .with_simulation(SimulationDomain::default())
634 .with_thermal(ThermalDomain::default())
635 .with_audio(AudioDomain::default())
636 .with_environment_interaction(EnvironmentInteractionDomain::default())
637 .with_compliance(ComplianceDomain::default());
638
639 assert!(event.has_domain_data());
640 assert!(event.identity.is_some());
641 assert!(event.location.is_some());
642 assert!(event.motion.is_some());
643 assert!(event.power.is_some());
644 assert!(event.operational.is_some());
645 assert!(event.navigation.is_some());
646 assert!(event.perception.is_some());
647 assert!(event.safety.is_some());
648 assert!(event.actuators.is_some());
649 assert!(event.communication.is_some());
650 assert!(event.compute.is_some());
651 assert!(event.ai.is_some());
652 assert!(event.maintenance.is_some());
653 assert!(event.context.is_some());
654 assert!(event.payload.is_some());
655 assert!(event.manipulation.is_some());
656 assert!(event.hri.is_some());
657 assert!(event.coordination.is_some());
658 assert!(event.simulation.is_some());
659 assert!(event.thermal.is_some());
660 assert!(event.audio.is_some());
661 assert!(event.environment_interaction.is_some());
662 assert!(event.compliance.is_some());
663 }
664
665 #[test]
666 fn test_event_with_provenance() {
667 let prov = Provenance::new("hmac-sha256")
668 .with_signature("sig123")
669 .with_key_id("key-001");
670
671 let event = UdmEvent::new(SourceType::Amr).with_provenance(prov);
672
673 assert!(event.provenance.is_some());
674 assert_eq!(
675 event.provenance.as_ref().unwrap().signature,
676 Some("sig123".to_string())
677 );
678 }
679
680 #[test]
681 fn test_event_has_domain_data_single() {
682 let event_identity =
684 UdmEvent::new(SourceType::Amr).with_identity(IdentityDomain::default());
685 assert!(event_identity.has_domain_data());
686
687 let event_motion = UdmEvent::new(SourceType::Amr).with_motion(MotionDomain::default());
688 assert!(event_motion.has_domain_data());
689
690 let event_ai = UdmEvent::new(SourceType::Amr).with_ai(AiDomain::default());
691 assert!(event_ai.has_domain_data());
692 }
693
694 #[test]
695 fn test_event_estimated_size() {
696 let event = UdmEvent::new(SourceType::Amr).with_identity(IdentityDomain {
697 source_id: Some("robot-001".to_string()),
698 ..Default::default()
699 });
700
701 let size = event.estimated_size();
702 assert!(size > 0);
703 }
704
705 #[test]
706 fn test_event_to_json() {
707 let event = UdmEvent::new(SourceType::Amr);
708 let json = event.to_json().unwrap();
709
710 assert!(json.contains("event_id"));
711 assert!(json.contains("captured_at"));
712 assert!(json.contains("source_type"));
713 }
714
715 #[test]
716 fn test_event_to_json_pretty() {
717 let event = UdmEvent::new(SourceType::Amr);
718 let json = event.to_json_pretty().unwrap();
719
720 assert!(json.contains("\n"));
722 }
723
724 #[test]
725 fn test_event_from_json() {
726 let event = UdmEvent::new(SourceType::Drone);
727 let json = event.to_json().unwrap();
728
729 let deserialized = UdmEvent::from_json(&json).unwrap();
730 assert_eq!(deserialized.source_type, SourceType::Drone);
731 }
732
733 #[test]
734 fn test_event_from_json_invalid() {
735 let result = UdmEvent::from_json("invalid json");
736 result.unwrap_err();
737 }
738
739 #[test]
744 fn test_provenance_default() {
745 let prov = Provenance::default();
746 assert!(prov.signature.is_none());
747 assert!(prov.key_id.is_none());
748 assert!(prov.algorithm.is_none());
749 assert!(prov.signed_fields.is_none());
750 assert!(prov.signed_at.is_none());
751 }
752
753 #[test]
754 fn test_provenance_new() {
755 let prov = Provenance::new("hmac-sha256");
756 assert_eq!(prov.algorithm, Some("hmac-sha256".to_string()));
757 assert!(prov.signed_at.is_some());
758 }
759
760 #[test]
761 fn test_provenance_with_signature() {
762 let prov = Provenance::new("hmac-sha256").with_signature("abc123def456");
763 assert_eq!(prov.signature, Some("abc123def456".to_string()));
764 }
765
766 #[test]
767 fn test_provenance_with_key_id() {
768 let prov = Provenance::new("hmac-sha256").with_key_id("my-key-001");
769 assert_eq!(prov.key_id, Some("my-key-001".to_string()));
770 }
771
772 #[test]
773 fn test_provenance_with_signed_fields() {
774 let fields = vec![
775 "event_id".to_string(),
776 "timestamp".to_string(),
777 "identity".to_string(),
778 ];
779 let prov = Provenance::new("hmac-sha256").with_signed_fields(fields.clone());
780 assert_eq!(prov.signed_fields, Some(fields));
781 }
782
783 #[test]
784 fn test_provenance_chained_builders() {
785 let prov = Provenance::new("hmac-sha256")
786 .with_signature("sig")
787 .with_key_id("key")
788 .with_signed_fields(vec!["event_id".to_string()]);
789
790 assert!(prov.algorithm.is_some());
791 assert!(prov.signature.is_some());
792 assert!(prov.key_id.is_some());
793 assert!(prov.signed_fields.is_some());
794 }
795
796 #[test]
801 fn test_event_full_serialization_roundtrip() {
802 let event = UdmEvent::new(SourceType::Amr)
803 .with_event_type(EventType::TelemetryPeriodic)
804 .with_identity(IdentityDomain {
805 source_id: Some("robot-001".to_string()),
806 ..Default::default()
807 })
808 .with_location(LocationDomain::default())
809 .with_provenance(Provenance::new("hmac-sha256").with_signature("test"));
810
811 let json = event.to_json().unwrap();
812 let deserialized = UdmEvent::from_json(&json).unwrap();
813
814 assert_eq!(deserialized.source_type, SourceType::Amr);
815 assert!(deserialized.identity.is_some());
816 assert!(deserialized.location.is_some());
817 assert!(deserialized.provenance.is_some());
818 }
819
820 #[test]
821 fn test_event_clone() {
822 let event = UdmEvent::new(SourceType::Amr).with_identity(IdentityDomain {
823 source_id: Some("robot-001".to_string()),
824 ..Default::default()
825 });
826
827 let cloned = event.clone();
828 assert_eq!(cloned.event_id, event.event_id);
829 assert_eq!(cloned.source_type, event.source_type);
830 }
831}