Skip to main content

phytrace_sdk/models/
event.rs

1//! UDM Event - The core event envelope that contains all domain data.
2//!
3//! The `UdmEvent` is the primary data structure emitted by PhyTrace SDK.
4//! It contains optional fields for all 23 UDM domains plus metadata for
5//! event classification, provenance, and extensions.
6
7use 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/// UDM Event - The unified data model event envelope.
22///
23/// This is the primary structure emitted by the PhyTrace SDK. It contains:
24/// - Required envelope fields (event_id, timestamp, source_type)
25/// - Optional domain data for all 23 UDM domains
26/// - Provenance information for data integrity verification
27/// - Extension point for custom data
28///
29/// # Example
30///
31/// ```rust
32/// use phytrace_sdk::{UdmEvent, EventType, SourceType};
33/// use phytrace_sdk::models::domains::{IdentityDomain, LocationDomain};
34/// use phytrace_sdk::models::domains::location::LocalCoordinates;
35///
36/// let event = UdmEvent::new(SourceType::Amr)
37///     .with_event_type(EventType::TelemetryPeriodic)
38///     .with_identity(IdentityDomain {
39///         source_id: Some("robot-001".to_string()),
40///         ..Default::default()
41///     })
42///     .with_location(LocationDomain {
43///         local: Some(LocalCoordinates {
44///             x_m: Some(10.0),
45///             y_m: Some(20.0),
46///             ..Default::default()
47///         }),
48///         ..Default::default()
49///     });
50/// ```
51#[derive(Debug, Clone, Default, Serialize, Deserialize, Validate)]
52pub struct UdmEvent {
53    // =========================================================================
54    // Required Envelope Fields
55    // =========================================================================
56    /// Unique event identifier (UUIDv7 for time-ordering).
57    pub event_id: String,
58
59    /// When data was captured at source (ISO 8601 format).
60    /// Note: This matches PhyCloud's expected field name.
61    #[serde(alias = "timestamp")]
62    pub captured_at: DateTime<Utc>,
63
64    /// Type of event.
65    #[serde(default)]
66    pub event_type: EventType,
67
68    /// Unique source identifier (e.g., robot-001).
69    /// This is a required top-level field for PhyCloud compatibility.
70    #[serde(default)]
71    pub source_id: String,
72
73    /// Type of source generating this event.
74    pub source_type: SourceType,
75
76    /// UDM schema version.
77    #[serde(alias = "schema_version")]
78    pub udm_version: String,
79
80    /// SDK version that generated this event.
81    pub sdk_version: String,
82
83    // =========================================================================
84    // UDM Domains (all optional)
85    // =========================================================================
86    /// Identity domain - who/what is reporting.
87    #[serde(skip_serializing_if = "Option::is_none")]
88    pub identity: Option<IdentityDomain>,
89
90    /// Location domain - where the source is.
91    #[serde(skip_serializing_if = "Option::is_none")]
92    pub location: Option<LocationDomain>,
93
94    /// Motion domain - velocity, acceleration, odometry.
95    #[serde(skip_serializing_if = "Option::is_none")]
96    pub motion: Option<MotionDomain>,
97
98    /// Power domain - battery, charging, energy.
99    #[serde(skip_serializing_if = "Option::is_none")]
100    pub power: Option<PowerDomain>,
101
102    /// Operational domain - mode, state, tasks.
103    #[serde(skip_serializing_if = "Option::is_none")]
104    pub operational: Option<OperationalDomain>,
105
106    /// Navigation domain - localization, path, obstacles.
107    #[serde(skip_serializing_if = "Option::is_none")]
108    pub navigation: Option<NavigationDomain>,
109
110    /// Perception domain - sensors, detections.
111    #[serde(skip_serializing_if = "Option::is_none")]
112    pub perception: Option<PerceptionDomain>,
113
114    /// Safety domain - e-stop, zones, violations.
115    #[serde(skip_serializing_if = "Option::is_none")]
116    pub safety: Option<SafetyDomain>,
117
118    /// Actuators domain - motors, joints, grippers.
119    #[serde(skip_serializing_if = "Option::is_none")]
120    pub actuators: Option<ActuatorsDomain>,
121
122    /// Communication domain - network, fleet comms.
123    #[serde(skip_serializing_if = "Option::is_none")]
124    pub communication: Option<CommunicationDomain>,
125
126    /// Compute domain - CPU, memory, processes.
127    #[serde(skip_serializing_if = "Option::is_none")]
128    pub compute: Option<ComputeDomain>,
129
130    /// AI domain - models, decisions, anomalies.
131    #[serde(skip_serializing_if = "Option::is_none")]
132    pub ai: Option<AiDomain>,
133
134    /// Maintenance domain - component health, diagnostics.
135    #[serde(skip_serializing_if = "Option::is_none")]
136    pub maintenance: Option<MaintenanceDomain>,
137
138    /// Context domain - time, facility, weather context.
139    #[serde(skip_serializing_if = "Option::is_none")]
140    pub context: Option<ContextDomain>,
141
142    /// Payload domain - carried items, compartments.
143    #[serde(skip_serializing_if = "Option::is_none")]
144    pub payload: Option<PayloadDomain>,
145
146    /// Manipulation domain - arms, grippers, workspace.
147    #[serde(skip_serializing_if = "Option::is_none")]
148    pub manipulation: Option<ManipulationDomain>,
149
150    /// HRI domain - human interaction, social navigation.
151    #[serde(skip_serializing_if = "Option::is_none")]
152    pub hri: Option<HriDomain>,
153
154    /// Coordination domain - fleet coordination, formations.
155    #[serde(skip_serializing_if = "Option::is_none")]
156    pub coordination: Option<CoordinationDomain>,
157
158    /// Simulation domain - simulator info, scenarios.
159    #[serde(skip_serializing_if = "Option::is_none")]
160    pub simulation: Option<SimulationDomain>,
161
162    /// Thermal domain - temperatures, cooling.
163    #[serde(skip_serializing_if = "Option::is_none")]
164    pub thermal: Option<ThermalDomain>,
165
166    /// Audio domain - microphones, speakers, sounds.
167    #[serde(skip_serializing_if = "Option::is_none")]
168    pub audio: Option<AudioDomain>,
169
170    /// Environment interaction domain - doors, elevators.
171    #[serde(skip_serializing_if = "Option::is_none")]
172    pub environment_interaction: Option<EnvironmentInteractionDomain>,
173
174    /// Compliance domain - certifications, safety standards.
175    #[serde(skip_serializing_if = "Option::is_none")]
176    pub compliance: Option<ComplianceDomain>,
177
178    // =========================================================================
179    // Provenance & Extensions
180    // =========================================================================
181    /// Provenance information for data integrity.
182    #[serde(skip_serializing_if = "Option::is_none")]
183    pub provenance: Option<Provenance>,
184
185    /// ROS 2 graph baseline or changes for `security_ros_graph_*` events
186    /// (PhyUDM `ros_graph`).
187    #[serde(skip_serializing_if = "Option::is_none")]
188    pub ros_graph: Option<serde_json::Value>,
189
190    /// Producer liveness for `system_heartbeat` events (PhyUDM
191    /// `heartbeat`): `interval_sec`, `agent_id`, `agent_version`.
192    #[serde(skip_serializing_if = "Option::is_none")]
193    pub heartbeat: Option<serde_json::Value>,
194
195    /// Extension point for custom data.
196    #[serde(skip_serializing_if = "Option::is_none")]
197    pub extensions: Option<serde_json::Value>,
198}
199
200/// Provenance information for data integrity verification.
201#[derive(Debug, Clone, Default, Serialize, Deserialize)]
202pub struct Provenance {
203    /// HMAC-SHA256 signature of the event.
204    #[serde(skip_serializing_if = "Option::is_none")]
205    pub signature: Option<String>,
206
207    /// Key ID used for signing.
208    #[serde(skip_serializing_if = "Option::is_none")]
209    pub key_id: Option<String>,
210
211    /// Signature algorithm (`"hmac-sha256"` or `"es256"`).
212    #[serde(skip_serializing_if = "Option::is_none")]
213    pub algorithm: Option<String>,
214
215    /// Fields included in signature.
216    #[serde(skip_serializing_if = "Option::is_none")]
217    pub signed_fields: Option<Vec<String>>,
218
219    /// Timestamp when signature was created.
220    #[serde(skip_serializing_if = "Option::is_none")]
221    pub signed_at: Option<DateTime<Utc>>,
222
223    /// Per-agent sequence number; never decreases across restarts when the
224    /// agent has a sequence state file.
225    #[serde(skip_serializing_if = "Option::is_none")]
226    pub sequence_num: Option<u64>,
227
228    /// Random ID generated at agent start, so a receiver can tell a restart
229    /// from a replay.
230    #[serde(skip_serializing_if = "Option::is_none")]
231    pub boot_epoch: Option<String>,
232
233    /// Signer class that produced the signature (`"hmac"` or `"tpm"`).
234    #[serde(skip_serializing_if = "Option::is_none")]
235    pub signer: Option<String>,
236
237    /// TPM NV counter value, incremented once per agent start (TPM signer
238    /// only).  Order events by `(boot_counter, sequence_num)`.
239    #[serde(skip_serializing_if = "Option::is_none")]
240    pub boot_counter: Option<u64>,
241
242    /// Device attestation: `{"mode": "tpm", "quote_id": ...}` referencing
243    /// the latest TPM quote, or `{"mode": "software", ...}` without a TPM.
244    #[serde(skip_serializing_if = "Option::is_none")]
245    pub device_attestation: Option<serde_json::Value>,
246
247    /// Merkle batch signature (issue #392): the signed batch statement,
248    /// its signature, and this event's leaf index and inclusion proof.
249    /// Present instead of `signature` when events are batch-signed; see
250    /// [`crate::core::merkle`].
251    #[serde(default, skip_serializing_if = "Option::is_none")]
252    pub batch: Option<serde_json::Value>,
253    /// License state from the agent's license validator (issue #249).
254    #[serde(default, skip_serializing_if = "Option::is_none")]
255    pub license: Option<serde_json::Value>,
256}
257
258impl UdmEvent {
259    /// Create a new UDM event with required fields.
260    ///
261    /// Automatically generates a UUIDv7 event ID and sets the captured_at timestamp.
262    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    /// Set the event type.
275    pub fn with_event_type(mut self, event_type: EventType) -> Self {
276        self.event_type = event_type;
277        self
278    }
279
280    /// Set the identity domain.
281    pub fn with_identity(mut self, identity: IdentityDomain) -> Self {
282        self.identity = Some(identity);
283        self
284    }
285
286    /// Set the location domain.
287    pub fn with_location(mut self, location: LocationDomain) -> Self {
288        self.location = Some(location);
289        self
290    }
291
292    /// Set the motion domain.
293    pub fn with_motion(mut self, motion: MotionDomain) -> Self {
294        self.motion = Some(motion);
295        self
296    }
297
298    /// Set the power domain.
299    pub fn with_power(mut self, power: PowerDomain) -> Self {
300        self.power = Some(power);
301        self
302    }
303
304    /// Set the operational domain.
305    pub fn with_operational(mut self, operational: OperationalDomain) -> Self {
306        self.operational = Some(operational);
307        self
308    }
309
310    /// Set the navigation domain.
311    pub fn with_navigation(mut self, navigation: NavigationDomain) -> Self {
312        self.navigation = Some(navigation);
313        self
314    }
315
316    /// Set the perception domain.
317    pub fn with_perception(mut self, perception: PerceptionDomain) -> Self {
318        self.perception = Some(perception);
319        self
320    }
321
322    /// Set the safety domain.
323    pub fn with_safety(mut self, safety: SafetyDomain) -> Self {
324        self.safety = Some(safety);
325        self
326    }
327
328    /// Set the actuators domain.
329    pub fn with_actuators(mut self, actuators: ActuatorsDomain) -> Self {
330        self.actuators = Some(actuators);
331        self
332    }
333
334    /// Set the communication domain.
335    pub fn with_communication(mut self, communication: CommunicationDomain) -> Self {
336        self.communication = Some(communication);
337        self
338    }
339
340    /// Set the compute domain.
341    pub fn with_compute(mut self, compute: ComputeDomain) -> Self {
342        self.compute = Some(compute);
343        self
344    }
345
346    /// Set the AI domain.
347    pub fn with_ai(mut self, ai: AiDomain) -> Self {
348        self.ai = Some(ai);
349        self
350    }
351
352    /// Set the maintenance domain.
353    pub fn with_maintenance(mut self, maintenance: MaintenanceDomain) -> Self {
354        self.maintenance = Some(maintenance);
355        self
356    }
357
358    /// Set the context domain.
359    pub fn with_context(mut self, context: ContextDomain) -> Self {
360        self.context = Some(context);
361        self
362    }
363
364    /// Set the payload domain.
365    pub fn with_payload(mut self, payload: PayloadDomain) -> Self {
366        self.payload = Some(payload);
367        self
368    }
369
370    /// Set the manipulation domain.
371    pub fn with_manipulation(mut self, manipulation: ManipulationDomain) -> Self {
372        self.manipulation = Some(manipulation);
373        self
374    }
375
376    /// Set the HRI domain.
377    pub fn with_hri(mut self, hri: HriDomain) -> Self {
378        self.hri = Some(hri);
379        self
380    }
381
382    /// Set the coordination domain.
383    pub fn with_coordination(mut self, coordination: CoordinationDomain) -> Self {
384        self.coordination = Some(coordination);
385        self
386    }
387
388    /// Set the simulation domain.
389    pub fn with_simulation(mut self, simulation: SimulationDomain) -> Self {
390        self.simulation = Some(simulation);
391        self
392    }
393
394    /// Set the thermal domain.
395    pub fn with_thermal(mut self, thermal: ThermalDomain) -> Self {
396        self.thermal = Some(thermal);
397        self
398    }
399
400    /// Set the audio domain.
401    pub fn with_audio(mut self, audio: AudioDomain) -> Self {
402        self.audio = Some(audio);
403        self
404    }
405
406    /// Set the environment interaction domain.
407    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    /// Set the compliance domain.
416    pub fn with_compliance(mut self, compliance: ComplianceDomain) -> Self {
417        self.compliance = Some(compliance);
418        self
419    }
420
421    /// Set custom extensions.
422    pub fn with_extensions(mut self, extensions: serde_json::Value) -> Self {
423        self.extensions = Some(extensions);
424        self
425    }
426
427    /// Put license metadata in the event's `provenance.license`.
428    ///
429    /// Called by the agent before signing; the signer keeps the block and
430    /// signs it.  It is SDK-owned, so it never goes in the customer's
431    /// `extensions` (issue #249).
432    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    /// Set provenance information.
439    pub fn with_provenance(mut self, provenance: Provenance) -> Self {
440        self.provenance = Some(provenance);
441        self
442    }
443
444    /// Check if the event has any domain data.
445    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    /// Get estimated size in bytes (serialized JSON).
472    pub fn estimated_size(&self) -> usize {
473        serde_json::to_string(self).map(|s| s.len()).unwrap_or(0)
474    }
475
476    /// Serialize to JSON string.
477    pub fn to_json(&self) -> Result<String, serde_json::Error> {
478        serde_json::to_string(self)
479    }
480
481    /// Serialize to pretty JSON string.
482    pub fn to_json_pretty(&self) -> Result<String, serde_json::Error> {
483        serde_json::to_string_pretty(self)
484    }
485
486    /// Deserialize from JSON string.
487    pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
488        serde_json::from_str(json)
489    }
490}
491
492impl Provenance {
493    /// Create new provenance with algorithm.
494    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    /// Set the signature.
503    pub fn with_signature(mut self, signature: impl Into<String>) -> Self {
504        self.signature = Some(signature.into());
505        self
506    }
507
508    /// Set the key ID.
509    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    /// Set signed fields.
515    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    // ==========================================================================
595    // UdmEvent Additional Tests
596    // ==========================================================================
597
598    #[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        // Test each domain individually
683        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        // Pretty JSON contains newlines
721        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    // ==========================================================================
740    // Provenance Additional Tests
741    // ==========================================================================
742
743    #[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    // ==========================================================================
797    // Serialization Roundtrip Tests
798    // ==========================================================================
799
800    #[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}