lightyear 0.3.0

Server-client networking library for the Bevy game engine
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
use crate::netcode::ClientId;
use crate::prelude::{MainSet, Replicate, ReplicationSet};
use crate::protocol::Protocol;
use crate::server::resource::Server;
use crate::server::systems::is_ready_to_send;
use crate::shared::replication::components::DespawnTracker;
use crate::utils::wrapping_id::wrapping_id;
use bevy::app::App;
use bevy::prelude::{
    Entity, IntoSystemConfigs, IntoSystemSetConfigs, Plugin, PostUpdate, Query, RemovedComponents,
    Res, ResMut, Resource, SystemSet,
};
use bevy::utils::{HashMap, HashSet};
use tracing::info;

// Id for a room, used to perform interest management
// An entity will be replicated to a client only if they are in the same room
wrapping_id!(RoomId);

/// Resource that will track any changes in the rooms
/// (we cannot use bevy `Events` directly because we don't need to send this every frame.
/// Also, we only need to keep track of updates for each send_interval frame. That means that if an entity
/// leaves then re-joins a room within the same send_interval period, we don't need to send any update)
///
/// This will be cleared every time the Server sends updates to the Client (every send_interval)
#[derive(Resource, Debug, Default)]
pub struct RoomEvents {
    client_enter_room: HashMap<ClientId, HashSet<RoomId>>,
    client_leave_room: HashMap<ClientId, HashSet<RoomId>>,
    entity_enter_room: HashMap<Entity, HashSet<RoomId>>,
    entity_leave_room: HashMap<Entity, HashSet<RoomId>>,
}

#[derive(Default, Debug)]
pub struct RoomData {
    client_to_rooms: HashMap<ClientId, HashSet<RoomId>>,
    entity_to_rooms: HashMap<Entity, HashSet<RoomId>>,
    rooms: HashMap<RoomId, Room>,
}

#[derive(Debug, Default)]
pub struct Room {
    /// list of clients that are in the room
    clients: HashSet<ClientId>,
    /// list of entities that are in the room
    entities: HashSet<Entity>,
}

#[derive(Default)]
pub struct RoomManager {
    events: RoomEvents,
    data: RoomData,
}

pub struct RoomPlugin<P: Protocol> {
    _marker: std::marker::PhantomData<P>,
}

impl<P: Protocol> Default for RoomPlugin<P> {
    fn default() -> Self {
        Self {
            _marker: std::marker::PhantomData,
        }
    }
}

/// System sets related to Rooms
#[derive(SystemSet, Debug, Hash, PartialEq, Eq, Clone, Copy)]
pub enum RoomSystemSets {
    /// Use all the room events that happened, and use those to update
    /// the replication caches
    UpdateReplicationCaches,
    /// Perform bookkeeping for the rooms
    /// (remove despawned entities, update the replication caches, etc.)
    RoomBookkeeping,
}

impl<P: Protocol> Plugin for RoomPlugin<P> {
    fn build(&self, app: &mut App) {
        // SETS
        app.configure_sets(
            PostUpdate,
            (
                (
                    // update replication caches must happen before replication
                    RoomSystemSets::UpdateReplicationCaches,
                    ReplicationSet::All,
                    RoomSystemSets::RoomBookkeeping,
                )
                    .chain(),
                // the room systems can run every send_interval
                (
                    RoomSystemSets::UpdateReplicationCaches,
                    RoomSystemSets::RoomBookkeeping,
                )
                    .run_if(is_ready_to_send::<P>),
            ),
        );
        // SYSTEMS
        app.add_systems(
            PostUpdate,
            (
                update_entity_replication_cache::<P>
                    .in_set(RoomSystemSets::UpdateReplicationCaches),
                (
                    clear_entity_replication_cache,
                    clean_entity_despawns::<P>,
                    clear_room_events::<P>,
                )
                    .in_set(RoomSystemSets::RoomBookkeeping),
            ),
        );
    }
}

impl RoomManager {
    /// Remove the client from all the rooms it was in
    pub(crate) fn client_disconnect(&mut self, client_id: ClientId) {
        if let Some(rooms) = self.data.client_to_rooms.remove(&client_id) {
            for room_id in rooms {
                RoomMut::new(self, room_id).remove_client(client_id);
                self.remove_client(room_id, client_id);
            }
        }
    }

    /// Remove the entity from all the rooms it was in
    pub(crate) fn entity_despawn(&mut self, entity: Entity) {
        if let Some(rooms) = self.data.entity_to_rooms.remove(&entity) {
            for room_id in rooms {
                RoomMut::new(self, room_id).remove_entity(entity);
                self.remove_entity(room_id, entity);
            }
        }
    }

    fn add_client(&mut self, room_id: RoomId, client_id: ClientId) {
        self.data
            .client_to_rooms
            .entry(client_id)
            .or_default()
            .insert(room_id);
        self.data
            .rooms
            .entry(room_id)
            .or_default()
            .clients
            .insert(client_id);
        self.events.client_enter_room(room_id, client_id);
    }

    fn remove_client(&mut self, room_id: RoomId, client_id: ClientId) {
        self.data
            .client_to_rooms
            .entry(client_id)
            .or_default()
            .remove(&room_id);
        self.data
            .rooms
            .entry(room_id)
            .or_default()
            .clients
            .remove(&client_id);
        self.events.client_leave_room(room_id, client_id);
    }

    fn add_entity(&mut self, room_id: RoomId, entity: Entity) {
        self.data
            .entity_to_rooms
            .entry(entity)
            .or_default()
            .insert(room_id);
        self.data
            .rooms
            .entry(room_id)
            .or_default()
            .entities
            .insert(entity);
        self.events.entity_enter_room(room_id, entity);
    }

    fn remove_entity(&mut self, room_id: RoomId, entity: Entity) {
        self.data
            .entity_to_rooms
            .entry(entity)
            .or_default()
            .remove(&room_id);
        self.data
            .rooms
            .entry(room_id)
            .or_default()
            .entities
            .remove(&entity);
        self.events.entity_leave_room(room_id, entity);
    }
}

/// Convenient wrapper to mutate a room
pub struct RoomMut<'s> {
    pub(crate) id: RoomId,
    pub(crate) manager: &'s mut RoomManager,
}

impl<'s> RoomMut<'s> {
    fn new(manager: &'s mut RoomManager, id: RoomId) -> Self {
        Self { id, manager }
    }

    pub fn add_client(&mut self, client_id: ClientId) {
        self.manager.add_client(self.id, client_id)
    }

    pub fn remove_client(&mut self, client_id: ClientId) {
        self.manager.remove_client(self.id, client_id)
    }

    pub fn add_entity(&mut self, entity: Entity) {
        self.manager.add_entity(self.id, entity)
    }

    pub fn remove_entity(&mut self, entity: Entity) {
        self.manager.remove_entity(self.id, entity)
    }
}

/// Convenient wrapper to mutate a room
pub struct RoomRef<'s> {
    pub(crate) id: RoomId,
    pub(crate) manager: &'s RoomManager,
}

impl<'s> RoomRef<'s> {
    fn new(manager: &'s RoomManager, id: RoomId) -> Self {
        Self { id, manager }
    }

    pub fn has_client_id(&self, client_id: ClientId) -> bool {
        self.manager
            .data
            .rooms
            .get(&self.id)
            .map_or_else(|| false, |room| room.clients.contains(&client_id))
    }

    pub fn has_entity(&mut self, entity: Entity) -> bool {
        self.manager
            .data
            .rooms
            .get(&self.id)
            .map_or_else(|| false, |room| room.entities.contains(&entity))
    }
}

impl RoomEvents {
    fn clear(&mut self) {
        self.client_enter_room.clear();
        self.client_leave_room.clear();
        self.entity_enter_room.clear();
        self.entity_leave_room.clear();
    }

    /// A client joined a room
    pub fn client_enter_room(&mut self, room_id: RoomId, client_id: ClientId) {
        // if the client had left the room and re-entered, no need to track the enter
        if !self
            .client_leave_room
            .entry(client_id)
            .or_default()
            .remove(&room_id)
        {
            self.client_enter_room
                .entry(client_id)
                .or_default()
                .insert(room_id);
        }
    }

    pub fn client_leave_room(&mut self, room_id: RoomId, client_id: ClientId) {
        // if the client had entered the room and left, no need to track the leaving
        if !self
            .client_enter_room
            .entry(client_id)
            .or_default()
            .remove(&room_id)
        {
            self.client_leave_room
                .entry(client_id)
                .or_default()
                .insert(room_id);
        }
    }

    pub fn entity_enter_room(&mut self, room_id: RoomId, entity: Entity) {
        if !self
            .entity_leave_room
            .entry(entity)
            .or_default()
            .remove(&room_id)
        {
            self.entity_enter_room
                .entry(entity)
                .or_default()
                .insert(room_id);
        }
    }

    pub fn entity_leave_room(&mut self, room_id: RoomId, entity: Entity) {
        if !self
            .entity_enter_room
            .entry(entity)
            .or_default()
            .remove(&room_id)
        {
            self.entity_leave_room
                .entry(entity)
                .or_default()
                .insert(room_id);
        }
    }

    fn iter_client_enter_room(&self) -> impl Iterator<Item = (&ClientId, &HashSet<RoomId>)> {
        self.client_enter_room.iter()
    }

    fn iter_client_leave_room(&self) -> impl Iterator<Item = (&ClientId, &HashSet<RoomId>)> {
        self.client_leave_room.iter()
    }

    fn iter_entity_enter_room(&self) -> impl Iterator<Item = (&Entity, &HashSet<RoomId>)> {
        self.entity_enter_room.iter()
    }

    fn iter_entity_leave_room(&self) -> impl Iterator<Item = (&Entity, &HashSet<RoomId>)> {
        self.entity_leave_room.iter()
    }
}

// TODO: this should not be public
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum ClientVisibility {
    /// the entity was not replicated to the client, but now is
    Gained,
    /// the entity was replicated to the client, but not anymore
    Lost,
    /// the entity was already replicated to the client, and still is
    Maintained,
}

/// Update each entities' replication-client-list based on the room events
/// Note that the rooms' entities/clients have already been updated at this point
fn update_entity_replication_cache<P: Protocol>(
    server: Res<Server<P>>,
    mut query: Query<&mut Replicate>,
) {
    // entity joined room
    for (entity, rooms) in server.room_manager.events.iter_entity_enter_room() {
        // for each room joined, update the entity's client visibility list
        rooms.iter().for_each(|room_id| {
            let room = server.room_manager.data.rooms.get(room_id).unwrap();
            room.clients.iter().for_each(|client_id| {
                if let Ok(mut replicate) = query.get_mut(*entity) {
                    // only set it to gained if it wasn't present before
                    replicate
                        .replication_clients_cache
                        .entry(*client_id)
                        .or_insert(ClientVisibility::Gained);
                }
            });
        });
    }
    // entity left room
    for (entity, rooms) in server.room_manager.events.iter_entity_leave_room() {
        // for each room left, update the entity's client visibility list if the client was in the room
        rooms.iter().for_each(|room_id| {
            let room = server.room_manager.data.rooms.get(room_id).unwrap();
            room.clients.iter().for_each(|client_id| {
                if let Ok(mut replicate) = query.get_mut(*entity) {
                    if let Some(visibility) = replicate.replication_clients_cache.get_mut(client_id)
                    {
                        *visibility = ClientVisibility::Lost;
                    }
                }
            });
        });
    }
    // client joined room: update all the entities that are in that room
    for (client_id, rooms) in server.room_manager.events.iter_client_enter_room() {
        rooms.iter().for_each(|room_id| {
            let room = server.room_manager.data.rooms.get(room_id).unwrap();
            room.entities.iter().for_each(|entity| {
                if let Ok(mut replicate) = query.get_mut(*entity) {
                    replicate
                        .replication_clients_cache
                        .entry(*client_id)
                        .or_insert(ClientVisibility::Gained);
                }
            });
        });
    }
    // client left room: update all the entities that are in that room
    for (client_id, rooms) in server.room_manager.events.iter_client_leave_room() {
        rooms.iter().for_each(|room_id| {
            let room = server.room_manager.data.rooms.get(room_id).unwrap();
            room.entities.iter().for_each(|entity| {
                if let Ok(mut replicate) = query.get_mut(*entity) {
                    if let Some(visibility) = replicate.replication_clients_cache.get_mut(client_id)
                    {
                        *visibility = ClientVisibility::Lost;
                    }
                }
            });
        });
    }
}

/// After replication, update the Replication Cache:
/// - Visibility Gained becomes Visibility Maintained
/// - Visibility Lost gets removed from the cache
fn clear_entity_replication_cache(mut query: Query<&mut Replicate>) {
    for mut replicate in query.iter_mut() {
        replicate
            .replication_clients_cache
            .retain(|_, visibility| match visibility {
                ClientVisibility::Gained => {
                    *visibility = ClientVisibility::Maintained;
                    true
                }
                ClientVisibility::Lost => false,
                ClientVisibility::Maintained => true,
            });
    }
}

/// Clear every room event that happened
fn clear_room_events<P: Protocol>(mut server: ResMut<Server<P>>) {
    server.room_manager.events.clear();
}

/// Clear out the room metadata for any entity that was ever replicated
fn clean_entity_despawns<P: Protocol>(
    mut server: ResMut<Server<P>>,
    mut despawned: RemovedComponents<DespawnTracker>,
) {
    for entity in despawned.read() {
        server.room_manager.entity_despawn(entity);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::prelude::client::*;
    use crate::prelude::*;
    use crate::shared::replication::components::ReplicationMode;
    use crate::tests::protocol::*;
    use crate::tests::stepper::{BevyStepper, Step};
    use bevy::ecs::system::RunSystemOnce;
    use bevy::prelude::{EventReader, Events};
    use std::time::Duration;

    fn setup() -> BevyStepper {
        let frame_duration = Duration::from_millis(10);
        let tick_duration = Duration::from_millis(10);
        let shared_config = SharedConfig {
            enable_replication: true,
            tick: TickConfig::new(tick_duration),
            ..Default::default()
        };
        let link_conditioner = LinkConditionerConfig {
            incoming_latency: Duration::from_millis(0),
            incoming_jitter: Duration::from_millis(0),
            incoming_loss: 0.0,
        };
        let sync_config = SyncConfig::default().speedup_factor(1.0);
        let prediction_config = PredictionConfig::default().disable(false);
        let interpolation_config = InterpolationConfig::default();
        let mut stepper = BevyStepper::new(
            shared_config,
            sync_config,
            prediction_config,
            interpolation_config,
            link_conditioner,
            frame_duration,
        );
        stepper.client_mut().connect();
        stepper.client_mut().set_synced();

        // Advance the world to let the connection process complete
        for _ in 0..20 {
            stepper.frame_step();
        }

        stepper
    }

    #[test]
    // client is in a room
    // we add an entity to that room, then we remove it
    fn test_add_remove_entity_room() {
        let mut stepper = setup();

        // Client joins room
        let client_id = 111;
        let room_id = RoomId(0);
        stepper.server_mut().room_mut(room_id).add_client(client_id);

        // Spawn an entity on server
        let server_entity = stepper
            .server_app
            .world
            .spawn(Replicate {
                replication_mode: ReplicationMode::Room,
                ..Default::default()
            })
            .id();

        stepper.frame_step();
        stepper.frame_step();

        // Check room states
        assert!(stepper
            .server()
            .room_manager
            .data
            .rooms
            .get(&room_id)
            .unwrap()
            .clients
            .contains(&client_id),);

        // Add the entity in the same room
        stepper
            .server_mut()
            .room_mut(room_id)
            .add_entity(server_entity);
        // Run update replication cache once
        stepper
            .server_app
            .world
            .run_system_once(update_entity_replication_cache::<MyProtocol>);
        assert!(stepper
            .server()
            .room_manager
            .events
            .entity_enter_room
            .get(&server_entity)
            .unwrap()
            .contains(&room_id));
        assert_eq!(
            stepper
                .server_app
                .world
                .entity(server_entity)
                .get::<Replicate>()
                .unwrap()
                .replication_clients_cache,
            HashMap::from([(client_id, ClientVisibility::Gained)])
        );

        stepper.frame_step();
        // Bookkeeping should get applied
        // Check room states
        assert!(stepper
            .server()
            .room_manager
            .data
            .rooms
            .get(&room_id)
            .unwrap()
            .entities
            .contains(&server_entity));
        assert_eq!(
            stepper
                .server_app
                .world
                .entity(server_entity)
                .get::<Replicate>()
                .unwrap()
                .replication_clients_cache,
            HashMap::from([(client_id, ClientVisibility::Maintained)])
        );

        // Check that the entity gets replicated to client
        stepper.frame_step();
        assert_eq!(
            stepper
                .client_app
                .world
                .resource::<Events<EntitySpawnEvent>>()
                .len(),
            1
        );
        let client_entity = *stepper
            .client()
            .connection()
            .base()
            .replication_manager
            .entity_map
            .get_local(server_entity)
            .unwrap();

        // Remove the entity from the room
        stepper
            .server_mut()
            .room_mut(room_id)
            .remove_entity(server_entity);
        stepper
            .server_app
            .world
            .run_system_once(update_entity_replication_cache::<MyProtocol>);
        assert!(stepper
            .server()
            .room_manager
            .events
            .entity_leave_room
            .get(&server_entity)
            .unwrap()
            .contains(&room_id));
        assert_eq!(
            stepper
                .server_app
                .world
                .entity(server_entity)
                .get::<Replicate>()
                .unwrap()
                .replication_clients_cache,
            HashMap::from([(client_id, ClientVisibility::Lost)])
        );
        stepper.frame_step();
        // after bookkeeping, the entity should not have any clients in its replication cache
        assert!(stepper
            .server_app
            .world
            .entity(server_entity)
            .get::<Replicate>()
            .unwrap()
            .replication_clients_cache
            .is_empty());

        stepper.frame_step();
        // Check that the entity gets despawned on client
        assert_eq!(
            stepper
                .client_app
                .world
                .resource::<Events<EntityDespawnEvent>>()
                .len(),
            1
        );
        assert!(stepper.client_app.world.get_entity(client_entity).is_none());
    }

    #[test]
    // entity is in a room
    // we add a client to that room, then we remove it
    fn test_add_remove_client_room() {
        let mut stepper = setup();

        // Client joins room
        let client_id = 111;
        let room_id = RoomId(0);

        // Spawn an entity on server
        let server_entity = stepper
            .server_app
            .world
            .spawn(Replicate {
                replication_mode: ReplicationMode::Room,
                ..Default::default()
            })
            .id();
        stepper
            .server_mut()
            .room_mut(room_id)
            .add_entity(server_entity);

        stepper.frame_step();
        stepper.frame_step();

        // Check room states
        assert!(stepper
            .server()
            .room_manager
            .data
            .rooms
            .get(&room_id)
            .unwrap()
            .entities
            .contains(&server_entity));

        // Add the client in the same room
        stepper.server_mut().room_mut(room_id).add_client(client_id);
        // Run update replication cache once
        stepper
            .server_app
            .world
            .run_system_once(update_entity_replication_cache::<MyProtocol>);
        assert!(stepper
            .server()
            .room_manager
            .events
            .client_enter_room
            .get(&client_id)
            .unwrap()
            .contains(&room_id));
        assert_eq!(
            stepper
                .server_app
                .world
                .entity(server_entity)
                .get::<Replicate>()
                .unwrap()
                .replication_clients_cache,
            HashMap::from([(client_id, ClientVisibility::Gained)])
        );

        stepper.frame_step();
        // Bookkeeping should get applied
        // Check room states
        assert!(stepper
            .server()
            .room_manager
            .data
            .rooms
            .get(&room_id)
            .unwrap()
            .entities
            .contains(&server_entity));
        assert_eq!(
            stepper
                .server_app
                .world
                .entity(server_entity)
                .get::<Replicate>()
                .unwrap()
                .replication_clients_cache,
            HashMap::from([(client_id, ClientVisibility::Maintained)])
        );

        // Check that the entity gets replicated to client
        stepper.frame_step();
        assert_eq!(
            stepper
                .client_app
                .world
                .resource::<Events<EntitySpawnEvent>>()
                .len(),
            1
        );
        let client_entity = *stepper
            .client()
            .connection()
            .base()
            .replication_manager
            .entity_map
            .get_local(server_entity)
            .unwrap();

        // Remove the client from the room
        stepper
            .server_mut()
            .room_mut(room_id)
            .remove_client(client_id);
        stepper
            .server_app
            .world
            .run_system_once(update_entity_replication_cache::<MyProtocol>);
        assert!(stepper
            .server()
            .room_manager
            .events
            .client_leave_room
            .get(&client_id)
            .unwrap()
            .contains(&room_id));
        assert_eq!(
            stepper
                .server_app
                .world
                .entity(server_entity)
                .get::<Replicate>()
                .unwrap()
                .replication_clients_cache,
            HashMap::from([(client_id, ClientVisibility::Lost)])
        );
        stepper.frame_step();
        // after bookkeeping, the entity should not have any clients in its replication cache
        assert!(stepper
            .server_app
            .world
            .entity(server_entity)
            .get::<Replicate>()
            .unwrap()
            .replication_clients_cache
            .is_empty());

        stepper.frame_step();
        // Check that the entity gets despawned on client
        assert_eq!(
            stepper
                .client_app
                .world
                .resource::<Events<EntityDespawnEvent>>()
                .len(),
            1
        );
        assert!(stepper.client_app.world.get_entity(client_entity).is_none());
    }

    // TODO: check that entity despawn/client disconnect cleans the room metadata

    // TODO: check
}