bevy_event_bus 0.2.0

A Bevy plugin that connects Bevy's event system to external message brokers like Kafka
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
//! Enhanced registration API for multi-decoder pipeline

use bevy::prelude::*;
use crate::{BusEvent, decoder::{DecoderRegistry, TypedDecoder}};

/// Extension trait for the Bevy App to simplify event bus registration
pub trait EventBusAppExt {
    /// Register an event with the event bus and automatically set up JSON decoding for topic(s)
    /// 
    /// This is the main convenience method that:
    /// 1. Registers the event in Bevy's event system (like `app.add_event::<T>()`)
    /// 2. Registers the event as a bus event
    /// 3. Sets up a JSON decoder for the specified topic(s)
    /// 
    /// # Examples
    /// ```rust
    /// use bevy::prelude::*;
    /// use bevy_event_bus::prelude::*;
    /// 
    /// #[derive(Event, Clone, serde::Serialize, serde::Deserialize)]
    /// struct PlayerMove { x: f32, y: f32 }
    /// 
    /// let mut app = App::new();
    /// // Single topic
    /// app.add_bus_event::<PlayerMove>("game_events");
    /// ```
    fn add_bus_event<T: BusEvent + Event>(&mut self, topic: &str) -> &mut Self;
    
    /// Register an event for a slice of topics 
    /// 
    /// # Example
    /// ```rust
    /// use bevy::prelude::*;
    /// use bevy_event_bus::prelude::*;
    /// 
    /// #[derive(Event, Clone, serde::Serialize, serde::Deserialize)]
    /// struct PlayerMove { x: f32, y: f32 }
    /// 
    /// let mut app = App::new();
    /// // Multiple topics at once
    /// app.add_bus_event_topics::<PlayerMove>(&["game_events", "move_events"]);
    /// ```
    fn add_bus_event_topics<T: BusEvent + Event>(&mut self, topics: &[&str]) -> &mut Self;

    /// Register an event for multiple topics with automatic JSON decoding
    /// 
    /// This supports many-to-many relationships between events and topics.
    /// One event type can be decoded from multiple topics.
    /// 
    /// # Example
    /// ```rust
    /// use bevy::prelude::*;
    /// use bevy_event_bus::prelude::*;
    /// 
    /// #[derive(Event, Clone, serde::Serialize, serde::Deserialize)]
    /// struct PlayerMove { x: f32, y: f32 }
    /// 
    /// let mut app = App::new();
    /// app.add_bus_event_multi::<PlayerMove>(&["game_events", "move_events"]);
    /// ```
    fn add_bus_event_multi<T: BusEvent + Event>(&mut self, topics: &[&str]) -> &mut Self;
    
    /// Register a custom decoder for a specific topic and event type
    /// 
    /// This allows you to register multiple decoders per topic, enabling a single topic
    /// to carry multiple event types or use custom decoding logic.
    /// 
    /// # Example
    /// ```rust
    /// use bevy::prelude::*;
    /// use bevy_event_bus::app_ext::EventBusAppExt;
    /// 
    /// #[derive(Event, Clone, serde::Serialize, serde::Deserialize)]
    /// struct PlayerMove { x: f32, y: f32 }
    /// 
    /// let mut app = App::new();
    /// app.register_topic_decoder("game_events", |data: &[u8]| {
    ///     serde_json::from_slice::<PlayerMove>(data).ok()
    /// });
    /// ```
    fn register_topic_decoder<T: BusEvent + Event>(
        &mut self, 
        topic: &str, 
        decoder: impl Fn(&[u8]) -> Option<T> + Send + Sync + 'static
    ) -> &mut Self;
}

impl EventBusAppExt for App {
    fn add_bus_event<T: BusEvent + Event>(&mut self, topic: &str) -> &mut Self {
        // Add the event to Bevy's event system (equivalent to app.add_event::<T>())
        bevy::prelude::App::add_event::<T>(self);
        
        // Auto-register the corresponding error event type
        bevy::prelude::App::add_event::<crate::EventBusError<T>>(self);
        
        // Register JSON decoder for the topic
        self.add_bus_event_multi::<T>(&[topic])
    }
    
    fn add_bus_event_topics<T: BusEvent + Event>(&mut self, topics: &[&str]) -> &mut Self {
        // Add the event to Bevy's event system (equivalent to app.add_event::<T>())
        bevy::prelude::App::add_event::<T>(self);
        
        // Auto-register the corresponding error event type
        bevy::prelude::App::add_event::<crate::EventBusError<T>>(self);
        
        // Register JSON decoder for the topics
        self.add_bus_event_multi::<T>(topics)
    }
    
    fn add_bus_event_multi<T: BusEvent + Event>(&mut self, topics: &[&str]) -> &mut Self {
        // Ensure event is registered first
        if !self.world().contains_resource::<Events<T>>() {
            bevy::prelude::App::add_event::<T>(self);
        }
        
        // Auto-register the corresponding error event type
        if !self.world().contains_resource::<Events<crate::EventBusError<T>>>() {
            bevy::prelude::App::add_event::<crate::EventBusError<T>>(self);
        }
        
        // Initialize decoder registry if it doesn't exist
        if !self.world().contains_resource::<DecoderRegistry>() {
            self.insert_resource(DecoderRegistry::new());
        }
        
        // Register JSON decoder for each topic
        for &topic in topics {
            let typed_decoder = TypedDecoder::<T>::json_decoder();
            
            if let Some(mut registry) = self.world_mut().get_resource_mut::<DecoderRegistry>() {
                registry.register_decoder(topic, typed_decoder);
            } else {
                let mut registry = DecoderRegistry::new();
                registry.register_decoder(topic, typed_decoder);
                self.insert_resource(registry);
            }
            
            tracing::info!(
                topic = %topic,
                event_type = std::any::type_name::<T>(),
                "Registered JSON decoder for topic"
            );
        }
        
        self
    }
    
    fn register_topic_decoder<T: BusEvent + Event>(
        &mut self, 
        topic: &str, 
        decoder: impl Fn(&[u8]) -> Option<T> + Send + Sync + 'static
    ) -> &mut Self {
        // Ensure event is registered first
        if !self.world().contains_resource::<Events<T>>() {
            bevy::prelude::App::add_event::<T>(self);
        }
        
        // Auto-register the corresponding error event type
        if !self.world().contains_resource::<Events<crate::EventBusError<T>>>() {
            bevy::prelude::App::add_event::<crate::EventBusError<T>>(self);
        }
        
        // Add custom decoder to registry
        let typed_decoder = TypedDecoder::new(decoder, std::any::type_name::<T>());
        
        if let Some(mut registry) = self.world_mut().get_resource_mut::<DecoderRegistry>() {
            registry.register_decoder(topic, typed_decoder);
        } else {
            let mut registry = DecoderRegistry::new();
            registry.register_decoder(topic, typed_decoder);
            self.insert_resource(registry);
        }
        
        tracing::info!(
            topic = %topic,
            event_type = std::any::type_name::<T>(),
            "Registered custom topic decoder"
        );
        
        self
    }
    
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde::{Deserialize, Serialize};
    use crate::EventBusPlugin;
    
    #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Event)]
    struct TestMove {
        x: f32,
        y: f32,
    }
    
    #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Event)]
    struct TestAttack {
        damage: u32,
    }
    
    #[test]
    fn test_add_event_bevy_like() {
        let mut app = App::new();
        app.add_bus_event::<TestMove>("game_events");
        
        // Verify event was added to Bevy
        assert!(app.world().contains_resource::<Events<TestMove>>());
        
        // Verify decoder registry was created
        assert!(app.world().contains_resource::<DecoderRegistry>());
        
        // Verify JSON decoder was registered
        let registry = app.world().resource::<DecoderRegistry>();
        assert_eq!(registry.decoder_count("game_events"), 1);
    }
    
    #[test]
    fn test_register_json_decoder_multiple_topics() {
        let mut app = App::new();
        app.add_bus_event_multi::<TestMove>(&["game_events", "move_events", "input_events"]);
        
        // Verify event was added to Bevy
        assert!(app.world().contains_resource::<Events<TestMove>>());
        
        // Verify decoders were registered for all topics
        let registry = app.world().resource::<DecoderRegistry>();
        assert_eq!(registry.decoder_count("game_events"), 1);
        assert_eq!(registry.decoder_count("move_events"), 1);
        assert_eq!(registry.decoder_count("input_events"), 1);
    }
    
    #[test]
    fn test_many_to_many_event_topic_relationship() {
        let mut app = App::new();
        
        // Register TestMove on multiple topics using new API
        app.add_bus_event_multi::<TestMove>(&["game_events", "move_events"]);
        
        // Register TestAttack on some overlapping topics using new API
        app.add_bus_event_multi::<TestAttack>(&["game_events", "combat_events"]);
        
        let registry = app.world().resource::<DecoderRegistry>();
        
        // game_events should have both TestMove and TestAttack decoders
        assert_eq!(registry.decoder_count("game_events"), 2);
        
        // move_events should have only TestMove
        assert_eq!(registry.decoder_count("move_events"), 1);
        
        // combat_events should have only TestAttack  
        assert_eq!(registry.decoder_count("combat_events"), 1);
    }
    
    #[test]
    fn test_mixed_registration_patterns() {
        let mut app = App::new();
        
        // Use the new single-topic API
        app.add_bus_event::<TestMove>("primary_events");
        
        // Use multi-topic registration
        app.add_bus_event_multi::<TestAttack>(&["primary_events", "secondary_events"]);
        
        let registry = app.world().resource::<DecoderRegistry>();
        
        // primary_events should have both events
        assert_eq!(registry.decoder_count("primary_events"), 2);
        
        // secondary_events should have only TestAttack
        assert_eq!(registry.decoder_count("secondary_events"), 1);
    }
    
    #[test]
    fn test_register_custom_decoder() {
        let mut app = App::new();
        
        app.register_topic_decoder("custom_topic", |data: &[u8]| {
            // Custom decoder that always returns a fixed TestMove
            if data.len() > 0 {
                Some(TestMove { x: 1.0, y: 2.0 })
            } else {
                None
            }
        });
        
        let registry = app.world().resource::<DecoderRegistry>();
        assert_eq!(registry.decoder_count("custom_topic"), 1);
    }

    // Multi-decoder tests moved from tests/multi_decoder_tests.rs

    #[derive(Event, Deserialize, Serialize, Debug, Clone, PartialEq)]
    struct PlayerMove {
        player_id: u32,
        x: f32,
        y: f32,
    }

    #[derive(Event, Deserialize, Serialize, Debug, Clone, PartialEq)]
    struct PlayerAttack {
        player_id: u32,
        target_id: u32,
        damage: i32,
    }

    /// Test that multiple event types can be decoded from the same topic
    #[test]
    fn test_single_topic_multiple_event_types() {
        let mut app = App::new();
        app.add_plugins(EventBusPlugin);
        
        // Register events in Bevy and set up JSON decoders for specific topic
        app.add_bus_event::<PlayerMove>("game_events");
        app.add_bus_event::<PlayerAttack>("game_events");
        
        app.update(); // Initialize systems
        
        // Verify decoders are registered
        let decoder_registry = app.world().resource::<DecoderRegistry>();
        let decoders = decoder_registry.get_decoders("game_events");
        assert_eq!(decoders.len(), 2, "Should have 2 decoders for game_events topic");
        
        // Create test messages
        let move_event = PlayerMove { player_id: 1, x: 10.0, y: 20.0 };
        let attack_event = PlayerAttack { player_id: 1, target_id: 2, damage: 50 };
        
        let move_json = serde_json::to_string(&move_event).unwrap();
        let attack_json = serde_json::to_string(&attack_event).unwrap();
        
        // Test decoding both message types
        let world = app.world_mut();
        let mut decoder_registry = world.resource_mut::<DecoderRegistry>();
        
        let decoded_move = decoder_registry.decode_all("game_events", move_json.as_bytes());
        let decoded_attack = decoder_registry.decode_all("game_events", attack_json.as_bytes());
        
        assert_eq!(decoded_move.len(), 1, "Should decode 1 event from move message");
        assert_eq!(decoded_attack.len(), 1, "Should decode 1 event from attack message");
        
        // Verify correct types were decoded
        let move_decoded = decoded_move[0].as_any().downcast_ref::<PlayerMove>().unwrap();
        let attack_decoded = decoded_attack[0].as_any().downcast_ref::<PlayerAttack>().unwrap();
        
        assert_eq!(*move_decoded, move_event);
        assert_eq!(*attack_decoded, attack_event);
    }

    /// Test that partial decode success is handled gracefully
    #[test]
    fn test_partial_decode_success() {
        let mut app = App::new();
        app.add_plugins(EventBusPlugin);
        
        // Register events and decoders for a topic
        app.add_bus_event::<PlayerMove>("mixed_events");
        // Note: We don't register PlayerAttack decoder for this topic
        
        app.update();
        
        let world = app.world_mut();
        let mut decoder_registry = world.resource_mut::<DecoderRegistry>();
        
        // Create a message that only matches PlayerMove decoder
        let move_event = PlayerMove { player_id: 1, x: 15.0, y: 25.0 };
        let move_json = serde_json::to_string(&move_event).unwrap();
        
        // Attempt to decode with all decoders
        let decoded_events = decoder_registry.decode_all("mixed_events", move_json.as_bytes());
        
        // Should succeed with only one decoder (PlayerMove)
        assert_eq!(decoded_events.len(), 1, "Should decode exactly 1 event");
        
        let decoded = decoded_events[0].as_any().downcast_ref::<PlayerMove>().unwrap();
        assert_eq!(*decoded, move_event);
    }

    /// Test malformed message handling
    #[test]
    fn test_malformed_message_handling() {
        let mut app = App::new();
        app.add_plugins(EventBusPlugin);
        
        // Register both event types to listen on the same topic
        app.add_bus_event_multi::<PlayerMove>(&["robust_events"]);
        app.add_bus_event_multi::<PlayerAttack>(&["robust_events"]);
        
        app.update();
        
        let world = app.world_mut();
        let mut decoder_registry = world.resource_mut::<DecoderRegistry>();
        
        // Test various malformed messages
        let malformed_messages = vec![
            "",                           // Empty message
            "not json at all",           // Not JSON
            "{}",                        // Empty JSON object
            "{\"invalid\": \"structure\"}", // Wrong structure
            "{\"player_id\": \"not_a_number\"}", // Wrong type
            "null",                      // Null JSON
            "[1, 2]",                    // Array with wrong number of elements
            "[1, 2, 3, 4]",              // Array with too many elements
        ];
        
        for malformed_msg in malformed_messages {
            let decoded = decoder_registry.decode_all("robust_events", malformed_msg.as_bytes());
            assert_eq!(decoded.len(), 0, "Malformed message '{}' should not decode to any events", malformed_msg);
        }
    }

    /// Test that decoder names are properly set
    #[test]
    fn test_decoder_names() {
        let mut app = App::new();
        app.add_plugins(EventBusPlugin);
        
        app.add_bus_event_multi::<PlayerMove>(&["named_topic"]);
        app.add_bus_event_multi::<PlayerAttack>(&["named_topic"]);
        
        app.update();
        
        let decoder_registry = app.world().resource::<DecoderRegistry>();
        let decoders = decoder_registry.get_decoders("named_topic");
        
        assert_eq!(decoders.len(), 2);
        
        let names: Vec<String> = decoders.iter().map(|d| d.name().to_string()).collect();
        // The actual type names will include the full module path
        println!("Decoder names: {:?}", names);
        
        // Check that both event types are present (allowing for different module paths)
        assert!(names.iter().any(|name| name.contains("PlayerMove")));
        assert!(names.iter().any(|name| name.contains("PlayerAttack")));
    }

    /// Test many-to-many relationship: one event type on multiple topics
    #[test]
    fn test_one_event_multiple_topics() {
        let mut app = App::new();
        app.add_plugins(EventBusPlugin);
        
        // Register PlayerMove for multiple topics using the new multi-topic API
        app.add_bus_event_multi::<PlayerMove>(&["game_events", "move_events", "input_events"]);
        
        app.update();
        
        let registry = app.world().resource::<DecoderRegistry>();
        
        // Verify PlayerMove decoder is registered on all topics
        assert_eq!(registry.decoder_count("game_events"), 1);
        assert_eq!(registry.decoder_count("move_events"), 1);
        assert_eq!(registry.decoder_count("input_events"), 1);
        
        // Test that the same event can be decoded from all topics
        let move_event = PlayerMove { player_id: 1, x: 10.0, y: 20.0 };
        let move_json = serde_json::to_string(&move_event).unwrap();
        
        let mut decoder_registry = app.world_mut().resource_mut::<DecoderRegistry>();
        
        // Test decoding from each topic
        for topic in ["game_events", "move_events", "input_events"] {
            let decoded = decoder_registry.decode_all(topic, move_json.as_bytes());
            assert_eq!(decoded.len(), 1, "Should decode 1 event from {}", topic);
            
            let decoded_move = decoded[0].as_any().downcast_ref::<PlayerMove>().unwrap();
            assert_eq!(*decoded_move, move_event);
        }
    }

    /// Test complex many-to-many scenario
    #[test]
    fn test_complex_many_to_many() {
        let mut app = App::new();
        app.add_plugins(EventBusPlugin);
        
        // Register PlayerMove on multiple topics  
        app.add_bus_event_multi::<PlayerMove>(&["game_events", "move_events"]);
        
        // Register PlayerAttack on overlapping and different topics
        app.add_bus_event_multi::<PlayerAttack>(&["game_events", "combat_events"]);
        
        // Use the simple API to add another event to a single topic
        app.add_bus_event::<PlayerMove>("special_events");
        
        app.update();
        
        let registry = app.world().resource::<DecoderRegistry>();
        
        // game_events should have both PlayerMove and PlayerAttack decoders
        assert_eq!(registry.decoder_count("game_events"), 2);
        
        // move_events should have only PlayerMove  
        assert_eq!(registry.decoder_count("move_events"), 1);
        
        // combat_events should have only PlayerAttack
        assert_eq!(registry.decoder_count("combat_events"), 1);
        
        // special_events should have only PlayerMove (from add_bus_event)
        assert_eq!(registry.decoder_count("special_events"), 1);
        
        // Test decoding different events from the shared topic
        let move_event = PlayerMove { player_id: 1, x: 10.0, y: 20.0 };
        let attack_event = PlayerAttack { player_id: 1, target_id: 2, damage: 50 };
        
        let move_json = serde_json::to_string(&move_event).unwrap();
        let attack_json = serde_json::to_string(&attack_event).unwrap();
        
        let mut decoder_registry = app.world_mut().resource_mut::<DecoderRegistry>();
        
        // Decode move event from game_events (should work with PlayerMove decoder)
        let decoded_move = decoder_registry.decode_all("game_events", move_json.as_bytes());
        assert_eq!(decoded_move.len(), 1);
        let decoded = decoded_move[0].as_any().downcast_ref::<PlayerMove>().unwrap();
        assert_eq!(*decoded, move_event);
        
        // Decode attack event from game_events (should work with PlayerAttack decoder)
        let decoded_attack = decoder_registry.decode_all("game_events", attack_json.as_bytes());
        assert_eq!(decoded_attack.len(), 1);
        let decoded = decoded_attack[0].as_any().downcast_ref::<PlayerAttack>().unwrap();
        assert_eq!(*decoded, attack_event);
    }
}