reactive_graph_reactive_service_impl/
reactive_relation_manager_impl.rs

1use std::ops::Deref;
2use std::sync::Arc;
3use std::sync::atomic::AtomicBool;
4use std::sync::atomic::Ordering;
5
6use async_trait::async_trait;
7use dashmap::DashMap;
8use dashmap::DashSet;
9use reactive_graph_reactive_service_api::EventChannels;
10use reactive_graph_reactive_service_api::ReactiveInstanceEvent;
11use reactive_graph_reactive_service_api::ReactiveInstanceEventManager;
12use reactive_graph_reactive_service_api::ReactiveRelationComponentAddError;
13use reactive_graph_reactive_service_api::ReactiveRelationComponentRemoveError;
14use reactive_graph_reactive_service_api::ReactiveRelationCreationError;
15use reactive_graph_reactive_service_api::ReactiveRelationPropertyAddError;
16use reactive_graph_reactive_service_api::ReactiveRelationPropertyRemoveError;
17use reactive_graph_reactive_service_api::ReactiveRelationRegistrationError;
18use serde_json::Value;
19use springtime_di::Component;
20use tokio::time::Duration;
21use tokio::time::sleep;
22use uuid::Uuid;
23
24use reactive_graph_behaviour_model_api::BehaviourTypeId;
25use reactive_graph_behaviour_model_api::BehaviourTypesContainer;
26use reactive_graph_behaviour_model_api::ComponentBehaviourTypeId;
27use reactive_graph_behaviour_model_api::RelationBehaviourTypeId;
28use reactive_graph_behaviour_service_api::RelationBehaviourManager;
29use reactive_graph_behaviour_service_api::RelationComponentBehaviourManager;
30use reactive_graph_graph::ComponentContainer;
31use reactive_graph_graph::ComponentTypeId;
32use reactive_graph_graph::InboundOutboundType;
33use reactive_graph_graph::MatchingInboundOutboundType;
34use reactive_graph_graph::Mutability;
35use reactive_graph_graph::Namespace;
36use reactive_graph_graph::NamespacedTypeGetter;
37use reactive_graph_graph::PropertyInstances;
38use reactive_graph_graph::PropertyTypeContainer;
39use reactive_graph_graph::RelationInstance;
40use reactive_graph_graph::RelationInstanceId;
41use reactive_graph_graph::RelationTypeId;
42use reactive_graph_graph::TypeDefinitionComponent;
43use reactive_graph_graph::TypeDefinitionGetter;
44use reactive_graph_graph::TypeDefinitionProperty;
45use reactive_graph_lifecycle::Lifecycle;
46use reactive_graph_model_core::reactive_graph::core::event::EventProperties::EVENT;
47use reactive_graph_reactive_model_api::ReactiveInstance;
48use reactive_graph_reactive_model_api::ReactivePropertyContainer;
49use reactive_graph_reactive_model_impl::ReactiveRelation;
50use reactive_graph_reactive_service_api::ReactiveEntityManager;
51use reactive_graph_reactive_service_api::ReactiveRelationManager;
52use reactive_graph_type_system_api::ComponentManager;
53use reactive_graph_type_system_api::RelationTypeManager;
54use reactive_graph_type_system_api::TypeSystemEventManager;
55use reactive_graph_type_system_api::TypeSystemEventSubscriber;
56use reactive_graph_type_system_api::TypeSystemEventTypes;
57use springtime_di::component_alias;
58
59static HANDLE_ID_RELATION_TYPE_COMPONENT_ADDED: u128 = 0x6ba7b9210e1513d350b300c04fe530c7;
60static HANDLE_ID_RELATION_TYPE_COMPONENT_REMOVED: u128 = 0x6ba8b8119e1513ee59b300c04fe630c7;
61static HANDLE_ID_RELATION_TYPE_PROPERTY_ADDED: u128 = 0x6bb9b9232e1513d350b300c04fe530c7;
62static HANDLE_ID_RELATION_TYPE_PROPERTY_REMOVED: u128 = 0x6ba8b8339e1535ee5bd300c0410630c7;
63
64pub struct OutboundInstances(DashMap<Uuid, DashSet<RelationInstanceId>>);
65
66impl OutboundInstances {
67    pub fn new() -> Self {
68        OutboundInstances(DashMap::new())
69    }
70
71    pub fn insert(&self, id: &RelationInstanceId) {
72        match self.0.get(&id.outbound_id) {
73            Some(outbound_instances) => {
74                outbound_instances.insert(id.clone());
75            }
76            None => {
77                let outbound_instances = DashSet::new();
78                outbound_instances.insert(id.clone());
79                self.0.insert(id.outbound_id, outbound_instances);
80            }
81        }
82    }
83
84    pub fn remove(&self, id: &RelationInstanceId) {
85        self.0.get(&id.outbound_id).and_then(|outbound_instances| outbound_instances.remove(id));
86    }
87
88    pub fn get(&self, id: Uuid) -> Option<DashSet<RelationInstanceId>> {
89        self.0.get(&id).map(|entry| entry.value().clone())
90    }
91}
92
93impl Default for OutboundInstances {
94    fn default() -> Self {
95        Self::new()
96    }
97}
98
99pub struct InboundInstances(DashMap<Uuid, DashSet<RelationInstanceId>>);
100
101impl InboundInstances {
102    pub fn new() -> Self {
103        InboundInstances(DashMap::new())
104    }
105
106    pub fn insert(&self, id: &RelationInstanceId) {
107        match self.0.get(&id.inbound_id) {
108            Some(inbound_instances) => {
109                inbound_instances.insert(id.clone());
110            }
111            None => {
112                let inbound_instances = DashSet::new();
113                inbound_instances.insert(id.clone());
114                self.0.insert(id.inbound_id, inbound_instances);
115            }
116        }
117    }
118
119    pub fn remove(&self, id: &RelationInstanceId) {
120        self.0.get(&id.inbound_id).and_then(|inbound_instances| inbound_instances.remove(id));
121    }
122
123    pub fn get(&self, id: Uuid) -> Option<DashSet<RelationInstanceId>> {
124        self.0.get(&id).map(|entry| entry.value().clone())
125    }
126}
127
128impl Default for InboundInstances {
129    fn default() -> Self {
130        Self::new()
131    }
132}
133
134fn create_running_state() -> Arc<AtomicBool> {
135    Arc::new(AtomicBool::new(true))
136}
137
138fn create_event_channels() -> EventChannels {
139    let event_channels = EventChannels::new();
140    event_channels.insert(HANDLE_ID_RELATION_TYPE_COMPONENT_ADDED, crossbeam::channel::unbounded());
141    event_channels.insert(HANDLE_ID_RELATION_TYPE_COMPONENT_REMOVED, crossbeam::channel::unbounded());
142    event_channels.insert(HANDLE_ID_RELATION_TYPE_PROPERTY_ADDED, crossbeam::channel::unbounded());
143    event_channels.insert(HANDLE_ID_RELATION_TYPE_PROPERTY_REMOVED, crossbeam::channel::unbounded());
144    event_channels
145}
146
147#[derive(Component)]
148pub struct ReactiveRelationManagerImpl {
149    reactive_instance_event_manager: Arc<dyn ReactiveInstanceEventManager + Send + Sync>,
150
151    type_system_event_manager: Arc<dyn TypeSystemEventManager + Send + Sync>,
152
153    component_manager: Arc<dyn ComponentManager + Send + Sync>,
154
155    relation_type_manager: Arc<dyn RelationTypeManager + Send + Sync>,
156
157    reactive_entity_manager: Arc<dyn ReactiveEntityManager + Send + Sync>,
158
159    relation_behaviour_manager: Arc<dyn RelationBehaviourManager + Send + Sync>,
160
161    relation_component_behaviour_manager: Arc<dyn RelationComponentBehaviourManager + Send + Sync>,
162
163    #[component(default = "DashMap::new")]
164    reactive_relation_instances: DashMap<RelationInstanceId, ReactiveRelation>, // ReactiveRelations,
165
166    #[component(default = "OutboundInstances::new")]
167    outbound_instances: OutboundInstances, // DashMap<Uuid, DashSet<RelationInstanceId>>, //
168
169    #[component(default = "InboundInstances::new")]
170    inbound_instances: InboundInstances, // DashMap<Uuid, DashSet<RelationInstanceId>>, //
171
172    #[component(default = "create_running_state")]
173    running: Arc<AtomicBool>, // RunningState,
174
175    #[component(default = "create_event_channels")]
176    event_channels: EventChannels,
177}
178
179#[async_trait]
180#[component_alias]
181impl ReactiveRelationManager for ReactiveRelationManagerImpl {
182    fn has(&self, id: &RelationInstanceId) -> bool {
183        self.reactive_relation_instances.contains_key(id)
184    }
185
186    fn get(&self, id: &RelationInstanceId) -> Option<ReactiveRelation> {
187        self.reactive_relation_instances.get(id).map(|r| r.value().clone())
188    }
189
190    fn get_by_outbound_entity(&self, outbound_entity_id: Uuid) -> Vec<ReactiveRelation> {
191        self.outbound_instances
192            .get(outbound_entity_id)
193            .and_then(|outbound_instances| outbound_instances.iter().map(|id| self.get(id.deref())).collect())
194            .unwrap_or_default()
195    }
196
197    fn get_by_inbound_entity(&self, inbound_entity_id: Uuid) -> Vec<ReactiveRelation> {
198        self.inbound_instances
199            .get(inbound_entity_id)
200            .and_then(|inbound_instances| inbound_instances.iter().map(|id| self.get(id.deref())).collect())
201            .unwrap_or_default()
202    }
203
204    fn get_all(&self) -> Vec<ReactiveRelation> {
205        self.reactive_relation_instances.iter().map(|r| r.value().clone()).collect()
206    }
207
208    fn get_by_type(&self, ty: &RelationTypeId) -> Vec<ReactiveRelation> {
209        self.reactive_relation_instances
210            .iter()
211            .filter(|r| &r.relation_type_id() == ty)
212            .map(|r| r.value().clone())
213            .collect()
214    }
215
216    fn get_by_component(&self, ty: &ComponentTypeId) -> Vec<ReactiveRelation> {
217        self.reactive_relation_instances
218            .iter()
219            .filter(|e| e.is_a(ty))
220            .map(|e| e.value().clone())
221            .collect()
222    }
223
224    fn get_by_behaviour(&self, behaviour_ty: &BehaviourTypeId) -> Vec<ReactiveRelation> {
225        self.reactive_relation_instances
226            .iter()
227            .filter(|e| e.behaves_as(behaviour_ty))
228            .map(|e| e.value().clone())
229            .collect()
230    }
231
232    fn get_by_namespace(&self, namespace: &Namespace) -> Vec<ReactiveRelation> {
233        self.reactive_relation_instances
234            .iter()
235            .filter(|r| &r.path() == namespace)
236            .map(|r| r.value().clone())
237            .collect()
238    }
239
240    fn count(&self) -> usize {
241        self.reactive_relation_instances.len()
242    }
243
244    fn count_by_type(&self, ty: &RelationTypeId) -> usize {
245        self.reactive_relation_instances.iter().filter(|r| &r.relation_type_id() == ty).count()
246    }
247
248    fn count_by_component(&self, component_ty: &ComponentTypeId) -> usize {
249        self.reactive_relation_instances.iter().filter(|r| r.is_a(component_ty)).count()
250    }
251
252    fn count_by_behaviour(&self, behaviour_ty: &BehaviourTypeId) -> usize {
253        self.reactive_relation_instances.iter().filter(|r| r.behaves_as(behaviour_ty)).count()
254    }
255
256    fn get_relation_instance_ids(&self) -> Vec<RelationInstanceId> {
257        self.reactive_relation_instances.iter().map(|e| e.key().clone()).collect()
258    }
259
260    fn create_reactive_relation(&self, id: &RelationInstanceId, properties: PropertyInstances) -> Result<ReactiveRelation, ReactiveRelationCreationError> {
261        let relation_instance = RelationInstance::builder()
262            .outbound_id(id.outbound_id)
263            .ty(id.ty.clone())
264            .inbound_id(id.inbound_id)
265            .properties(properties)
266            .build();
267        self.create_reactive_instance(relation_instance)
268        // match self.relation_instance_manager.create(relation_instance_id, properties) {
269        //     Ok(relation_instance_id) => match self.relation_instance_manager.get(&relation_instance_id) {
270        //         Some(relation_instance) => self.create_reactive_instance(relation_instance),
271        //         None => Err(ReactiveRelationCreationError::MissingInstance(relation_instance_id)),
272        //     },
273        //     Err(e) => Err(ReactiveRelationCreationError::RelationInstanceCreationError(e)),
274        // }
275    }
276
277    fn create_reactive_instance(&self, reactive_relation_instance: RelationInstance) -> Result<ReactiveRelation, ReactiveRelationCreationError> {
278        let outbound = self
279            .reactive_entity_manager
280            .get(reactive_relation_instance.outbound_id)
281            .ok_or(ReactiveRelationCreationError::MissingOutboundEntityInstance(reactive_relation_instance.outbound_id))?;
282        let inbound = self
283            .reactive_entity_manager
284            .get(reactive_relation_instance.inbound_id)
285            .ok_or(ReactiveRelationCreationError::MissingInboundEntityInstance(reactive_relation_instance.inbound_id))?;
286        let ty = reactive_relation_instance.ty.clone();
287        let relation_ty = ty.relation_type_id();
288        let relation_type = self
289            .relation_type_manager
290            .get(&relation_ty)
291            .ok_or_else(|| ReactiveRelationCreationError::UnknownRelationType(relation_ty.clone()))?;
292
293        match &relation_type.outbound_type {
294            InboundOutboundType::Component(MatchingInboundOutboundType::NamespacedType(component_ty)) => {
295                if !outbound.components.contains(component_ty) {
296                    return Err(ReactiveRelationCreationError::OutboundEntityDoesNotHaveComponent(outbound.id, component_ty.clone()));
297                }
298            }
299            InboundOutboundType::EntityType(MatchingInboundOutboundType::NamespacedType(entity_ty)) => {
300                if &outbound.ty != entity_ty {
301                    return Err(ReactiveRelationCreationError::OutboundEntityIsNotOfType(outbound.id, outbound.ty.clone(), entity_ty.clone()));
302                }
303            }
304            _ => {}
305        }
306
307        match &relation_type.inbound_type {
308            InboundOutboundType::Component(MatchingInboundOutboundType::NamespacedType(component_ty)) => {
309                if !inbound.components.contains(component_ty) {
310                    return Err(ReactiveRelationCreationError::InboundEntityDoesNotHaveComponent(inbound.id, component_ty.clone()));
311                }
312            }
313            InboundOutboundType::EntityType(MatchingInboundOutboundType::NamespacedType(entity_ty)) => {
314                if &inbound.ty != entity_ty {
315                    return Err(ReactiveRelationCreationError::InboundEntityIsNotOfType(inbound.id, inbound.ty.clone(), entity_ty.clone()));
316                }
317            }
318            _ => {}
319        }
320
321        let relation_instance = ReactiveRelation::new_from_instance(outbound, inbound, reactive_relation_instance);
322
323        // Initialize property mutability states
324        if let Some(entity_type) = self.relation_type_manager.get(&relation_instance.relation_type_id()) {
325            for component_ty in entity_type.components {
326                if let Some(component) = self.component_manager.get(&component_ty) {
327                    for property_type in component.properties.iter() {
328                        if let Some(mut property) = relation_instance.properties.get_mut(&property_type.name) {
329                            property.set_mutability(property_type.mutability);
330                        }
331                    }
332                }
333            }
334            for property_type in entity_type.properties.iter() {
335                if let Some(mut property) = relation_instance.properties.get_mut(&property_type.name) {
336                    property.set_mutability(property_type.mutability);
337                }
338            }
339        }
340
341        self.register_reactive_instance(relation_instance)
342            .map_err(ReactiveRelationCreationError::ReactiveRelationRegistrationError)
343    }
344
345    fn register_reactive_instance(&self, reactive_relation: ReactiveRelation) -> Result<ReactiveRelation, ReactiveRelationRegistrationError> {
346        let id = reactive_relation.id();
347        if self.reactive_relation_instances.contains_key(&id) {
348            return Err(ReactiveRelationRegistrationError::RelationInstanceAlreadyExists(id.clone()));
349        }
350        // TODO: check if id already exists
351        self.reactive_relation_instances.insert(id.clone(), reactive_relation.clone());
352        self.outbound_instances.insert(&id);
353        self.inbound_instances.insert(&id);
354        // Apply all components that are predefined in the relation type
355        let relation_ty = reactive_relation.relation_type_id();
356        if let Some(components) = self.relation_type_manager.get(&relation_ty).map(|relation_type| relation_type.components) {
357            components.iter().for_each(|component_ty| {
358                reactive_relation.components.insert(component_ty.clone());
359            });
360        }
361        // Add component behaviours
362        self.relation_component_behaviour_manager.add_behaviours_to_relation(reactive_relation.clone());
363        // Add relation behaviours
364        self.relation_behaviour_manager.add_behaviours(reactive_relation.clone());
365        self.reactive_instance_event_manager
366            .emit_event(ReactiveInstanceEvent::RelationInstanceCreated(id));
367        Ok(reactive_relation)
368
369        // match self
370        //     .relation_instance_manager
371        //     .create_from_instance_if_not_exist(reactive_relation_instance.clone().into())
372        // {
373        //     Ok(relation_instance_id) => {
374        //         self.reactive_relation_instances.insert(relation_instance_id.clone(), reactive_relation_instance.clone());
375        //         // Apply all components that are predefined in the relation type
376        //         let relation_ty = reactive_relation_instance.relation_type_id();
377        //         if let Some(components) = self.relation_type_manager.get(&relation_ty).map(|relation_type| relation_type.components) {
378        //             components.iter().for_each(|component_ty| {
379        //                 reactive_relation_instance.components.insert(component_ty.clone());
380        //             });
381        //         }
382        //         // Add component behaviours
383        //         self.relation_component_behaviour_manager
384        //             .add_behaviours_to_relation(reactive_relation_instance.clone());
385        //         // Add relation behaviours
386        //         self.relation_behaviour_manager.add_behaviours(reactive_relation_instance.clone());
387        //         self.event_manager.emit_event(SystemEvent::RelationInstanceCreated(relation_instance_id));
388        //         Ok(reactive_relation_instance)
389        //     }
390        //     Err(e) => Err(ReactiveRelationRegistrationError::RelationInstanceCreationError(e)),
391        // }
392    }
393
394    fn register_or_merge_reactive_instance(&self, relation_instance: ReactiveRelation) -> Result<ReactiveRelation, ReactiveRelationRegistrationError> {
395        let id = relation_instance.id();
396        match self.get(&id) {
397            // No instance with the given relation instance id exists yet, try to register the given reactive instance
398            None => self.register_reactive_instance(relation_instance),
399            // Instance with the given relation instance id exists. Don't register but return the existing reactive instance instead of the given instance
400            Some(reactive_relation_instance) => Ok(reactive_relation_instance),
401        }
402    }
403
404    fn add_component(&self, id: &RelationInstanceId, component_ty: &ComponentTypeId) -> Result<(), ReactiveRelationComponentAddError> {
405        let Some(component) = self.component_manager.get(component_ty) else {
406            return Err(ReactiveRelationComponentAddError::ComponentNotRegistered(component_ty.clone()));
407        };
408        let Some(reactive_relation) = self.get(id) else {
409            return Err(ReactiveRelationComponentAddError::MissingInstance(id.clone()));
410        };
411        if reactive_relation.is_a(component_ty) {
412            return Err(ReactiveRelationComponentAddError::IsAlreadyA(component_ty.clone()));
413        }
414        // Add components with properties
415        reactive_relation.add_component_with_properties(&component);
416        // Add component behaviours
417        self.relation_component_behaviour_manager
418            .add_behaviours_to_relation_component(reactive_relation, component);
419        Ok(())
420    }
421
422    fn remove_component(&self, id: &RelationInstanceId, component_ty: &ComponentTypeId) -> Result<(), ReactiveRelationComponentRemoveError> {
423        let Some(reactive_relation) = self.get(id) else {
424            return Err(ReactiveRelationComponentRemoveError::MissingInstance(id.clone()));
425        };
426        if !reactive_relation.is_a(component_ty) {
427            return Err(ReactiveRelationComponentRemoveError::IsNotA(component_ty.clone()));
428        }
429        let Some(component) = self.component_manager.get(component_ty) else {
430            return Err(ReactiveRelationComponentRemoveError::ComponentNotRegistered(component_ty.clone()));
431        };
432        // Remove component
433        reactive_relation.remove_component(component_ty);
434        //
435        // We do not remove properties because we cannot ensure that the removal is intended
436        // (At least yet)
437        //
438        // Remove component behaviours
439        self.relation_component_behaviour_manager
440            .remove_behaviours_from_relation_component(reactive_relation, component);
441        Ok(())
442    }
443
444    fn add_property(
445        &self,
446        relation_instance_id: &RelationInstanceId,
447        property_name: &str,
448        mutability: Mutability,
449        value: Value,
450    ) -> Result<(), ReactiveRelationPropertyAddError> {
451        match self.get(relation_instance_id) {
452            Some(relation_instance) => {
453                if relation_instance.has_property(property_name) {
454                    return Err(ReactiveRelationPropertyAddError::PropertyAlreadyExists(property_name.to_string()));
455                }
456                relation_instance.add_property(property_name, mutability, value);
457                Ok(())
458            }
459            None => Err(ReactiveRelationPropertyAddError::MissingInstance(relation_instance_id.clone())),
460        }
461    }
462
463    fn remove_property(&self, relation_instance_id: &RelationInstanceId, property_name: &str) -> Result<(), ReactiveRelationPropertyRemoveError> {
464        match self.get(relation_instance_id) {
465            Some(relation_instance) => {
466                if !relation_instance.has_property(property_name) {
467                    return Err(ReactiveRelationPropertyRemoveError::MissingProperty(property_name.to_string()));
468                }
469                for component_ty in relation_instance.get_components() {
470                    if let Some(component) = self.component_manager.get(&component_ty) {
471                        if component.has_own_property(property_name) {
472                            return Err(ReactiveRelationPropertyRemoveError::PropertyInUseByComponent(component_ty.clone()));
473                        }
474                    }
475                }
476                relation_instance.remove_property(property_name);
477                Ok(())
478            }
479            None => Err(ReactiveRelationPropertyRemoveError::MissingInstance(relation_instance_id.clone())),
480        }
481    }
482
483    fn add_behaviour_to_all_relation_instances(&self, relation_behaviour_ty: &RelationBehaviourTypeId) {
484        for relation_instance in self.reactive_relation_instances.iter() {
485            if relation_instance.relation_type_id() == relation_behaviour_ty.relation_ty {
486                self.relation_behaviour_manager
487                    .add_behaviour(relation_instance.clone(), &relation_behaviour_ty.behaviour_ty);
488            }
489        }
490    }
491
492    fn add_behaviour_to_all_relation_components(&self, component_behaviour_ty: &ComponentBehaviourTypeId) {
493        for relation_instance in self.reactive_relation_instances.iter() {
494            if relation_instance.components.contains(&component_behaviour_ty.component_ty) {
495                self.relation_component_behaviour_manager
496                    .add_behaviour_to_relation_component(relation_instance.clone(), component_behaviour_ty);
497            }
498        }
499    }
500
501    // fn commit(&self, relation_instance_id: &RelationInstanceId) {
502    //     if let Some(reactive_relation_instance) = self.get(relation_instance_id) {
503    //         self.relation_instance_manager.commit(reactive_relation_instance.into());
504    //     }
505    // }
506
507    fn delete(&self, id: &RelationInstanceId) -> bool {
508        if self.has(id) {
509            self.unregister_reactive_instance(id);
510            self.reactive_instance_event_manager
511                .emit_event(ReactiveInstanceEvent::RelationInstanceDeleted(id.clone()));
512            true
513        } else {
514            false
515        }
516    }
517
518    fn unregister_reactive_instance(&self, id: &RelationInstanceId) {
519        match self.get(id) {
520            Some(relation_instance) => {
521                // Remove relation behaviours
522                self.relation_behaviour_manager.remove_behaviours(relation_instance.clone());
523                // Remove component behaviours
524                self.relation_component_behaviour_manager.remove_behaviours_from_relation(relation_instance);
525            }
526            None => {
527                // Remove relation behaviours
528                self.relation_behaviour_manager.remove_behaviours_by_key(id);
529                // Remove component behaviours
530                self.relation_component_behaviour_manager.remove_behaviours_by_key(id);
531            }
532        }
533        self.outbound_instances.remove(id);
534        self.inbound_instances.remove(id);
535        self.reactive_relation_instances.remove(id);
536    }
537
538    fn handle_component_added_events(&self) {
539        let component_manager = self.component_manager.clone();
540        let relation_component_behaviour_manager = self.relation_component_behaviour_manager.clone();
541        let reactive_relation_instances = self.reactive_relation_instances.clone();
542        let running = self.running.clone();
543        if let Some(receiver) = self.event_channels.receiver(&HANDLE_ID_RELATION_TYPE_COMPONENT_ADDED) {
544            tokio::task::spawn(async move {
545                while running.load(Ordering::Relaxed) {
546                    match receiver.try_recv() {
547                        Ok(type_definition_component_event) => {
548                            if let Ok(type_definition_component) = TypeDefinitionComponent::try_from(type_definition_component_event.clone()) {
549                                if let Some(component) = component_manager.get(&type_definition_component.component_ty) {
550                                    for reactive_relation_instance in reactive_relation_instances
551                                        .iter()
552                                        .filter(|relation_instance| {
553                                            relation_instance.relation_type_id().type_definition() == type_definition_component.type_definition
554                                        })
555                                        .map(|relation_instance| relation_instance.value().clone())
556                                    {
557                                        reactive_relation_instance.add_component_with_properties(&component);
558                                        relation_component_behaviour_manager
559                                            .add_behaviours_to_relation_component(reactive_relation_instance, component.clone());
560                                    }
561                                }
562                            }
563                        }
564                        Err(_) => {
565                            sleep(Duration::from_millis(100)).await;
566                        }
567                    }
568                }
569            });
570        }
571    }
572
573    fn handle_component_removed_events(&self) {
574        let component_manager = self.component_manager.clone();
575        let relation_component_behaviour_manager = self.relation_component_behaviour_manager.clone();
576        let reactive_relation_instances = self.reactive_relation_instances.clone();
577        let running = self.running.clone();
578        if let Some(receiver) = self.event_channels.receiver(&HANDLE_ID_RELATION_TYPE_COMPONENT_REMOVED) {
579            tokio::spawn(async move {
580                while running.load(Ordering::Relaxed) {
581                    match receiver.try_recv() {
582                        Ok(type_definition_component_event) => {
583                            if let Ok(type_definition_component) = TypeDefinitionComponent::try_from(type_definition_component_event.clone()) {
584                                if let Some(component) = component_manager.get(&type_definition_component.component_ty) {
585                                    for reactive_relation_instance in reactive_relation_instances
586                                        .iter()
587                                        .filter(|relation_instance| {
588                                            relation_instance.relation_type_id().type_definition() == type_definition_component.type_definition
589                                        })
590                                        .map(|relation_instance| relation_instance.value().clone())
591                                    {
592                                        reactive_relation_instance.remove_component(&component.ty);
593                                        relation_component_behaviour_manager
594                                            .remove_behaviours_from_relation_component(reactive_relation_instance, component.clone());
595                                    }
596                                }
597                            }
598                        }
599                        Err(_) => {
600                            sleep(Duration::from_millis(100)).await;
601                        }
602                    }
603                }
604            });
605        }
606    }
607
608    fn handle_property_added_events(&self) {
609        let relation_type_manager = self.relation_type_manager.clone();
610        let reactive_relation_instances = self.reactive_relation_instances.clone();
611        let running = self.running.clone();
612        if let Some(receiver) = self.event_channels.receiver(&HANDLE_ID_RELATION_TYPE_PROPERTY_ADDED) {
613            tokio::spawn(async move {
614                while running.load(Ordering::Relaxed) {
615                    match receiver.try_recv() {
616                        Ok(type_definition_property_event) => {
617                            if let Ok(type_definition_property) = TypeDefinitionProperty::try_from(type_definition_property_event.clone()) {
618                                if let Ok(relation_ty) = RelationTypeId::try_from(&type_definition_property.type_definition) {
619                                    if let Some(relation_type) = relation_type_manager.get(&relation_ty) {
620                                        for reactive_relation_instance in reactive_relation_instances
621                                            .iter()
622                                            .filter(|relation_instance| relation_instance.relation_type_id() == relation_ty)
623                                            .map(|relation_instance| relation_instance.value().clone())
624                                        {
625                                            if let Some(property_type) = relation_type.get_own_property(&type_definition_property.property) {
626                                                reactive_relation_instance.add_property_by_type(&property_type);
627                                            }
628                                        }
629                                    }
630                                }
631                            }
632                        }
633                        Err(_) => {
634                            sleep(Duration::from_millis(100)).await;
635                        }
636                    }
637                }
638            });
639        }
640    }
641
642    fn handle_property_removed_events(&self) {
643        let reactive_relation_instances = self.reactive_relation_instances.clone();
644        let running = self.running.clone();
645        if let Some(receiver) = self.event_channels.receiver(&HANDLE_ID_RELATION_TYPE_PROPERTY_REMOVED) {
646            tokio::spawn(async move {
647                while running.load(Ordering::Relaxed) {
648                    match receiver.try_recv() {
649                        Ok(type_definition_property_event) => {
650                            if let Ok(type_definition_property) = TypeDefinitionProperty::try_from(type_definition_property_event.clone()) {
651                                for reactive_relation_instance in reactive_relation_instances
652                                    .iter()
653                                    .filter(|relation_instance| {
654                                        relation_instance.relation_type_id().type_definition() == type_definition_property.type_definition
655                                    })
656                                    .map(|relation_instance| relation_instance.value().clone())
657                                {
658                                    reactive_relation_instance.remove_property(&type_definition_property.property);
659                                }
660                            }
661                        }
662                        Err(_) => {
663                            sleep(Duration::from_millis(100)).await;
664                        }
665                    }
666                }
667            });
668        }
669    }
670}
671
672impl TypeSystemEventSubscriber for ReactiveRelationManagerImpl {
673    fn subscribe_type_system_event(&self, system_event_type: TypeSystemEventTypes, handle_id: u128) {
674        if let Some(entity_instance) = self.type_system_event_manager.get_type_system_event_instance(system_event_type) {
675            if let Some(sender) = self.event_channels.sender(&handle_id) {
676                entity_instance.observe_with_handle(
677                    EVENT.as_ref(),
678                    move |v| {
679                        let _ = sender.send(v.clone());
680                    },
681                    handle_id,
682                );
683            }
684        }
685    }
686
687    fn unsubscribe_type_system_event(&self, system_event_type: TypeSystemEventTypes, handle_id: u128) {
688        if let Some(entity_instance) = self.type_system_event_manager.get_type_system_event_instance(system_event_type) {
689            entity_instance.remove_observer(EVENT.as_ref(), handle_id);
690        }
691    }
692}
693
694#[async_trait]
695impl Lifecycle for ReactiveRelationManagerImpl {
696    async fn post_init(&self) {
697        self.subscribe_type_system_event(TypeSystemEventTypes::RelationTypeComponentAdded, HANDLE_ID_RELATION_TYPE_COMPONENT_ADDED);
698        self.subscribe_type_system_event(TypeSystemEventTypes::RelationTypeComponentRemoved, HANDLE_ID_RELATION_TYPE_COMPONENT_REMOVED);
699        self.subscribe_type_system_event(TypeSystemEventTypes::RelationTypePropertyAdded, HANDLE_ID_RELATION_TYPE_PROPERTY_ADDED);
700        self.subscribe_type_system_event(TypeSystemEventTypes::RelationTypePropertyRemoved, HANDLE_ID_RELATION_TYPE_PROPERTY_REMOVED);
701
702        self.handle_component_added_events();
703        self.handle_component_removed_events();
704        self.handle_property_added_events();
705        self.handle_property_removed_events();
706    }
707
708    async fn pre_shutdown(&self) {
709        self.running.store(false, Ordering::Relaxed);
710
711        self.unsubscribe_type_system_event(TypeSystemEventTypes::RelationTypePropertyRemoved, HANDLE_ID_RELATION_TYPE_PROPERTY_REMOVED);
712        self.unsubscribe_type_system_event(TypeSystemEventTypes::RelationTypePropertyAdded, HANDLE_ID_RELATION_TYPE_PROPERTY_ADDED);
713        self.unsubscribe_type_system_event(TypeSystemEventTypes::RelationTypeComponentRemoved, HANDLE_ID_RELATION_TYPE_COMPONENT_REMOVED);
714        self.unsubscribe_type_system_event(TypeSystemEventTypes::RelationTypeComponentAdded, HANDLE_ID_RELATION_TYPE_COMPONENT_ADDED);
715    }
716}