reactive_graph_reactive_model_impl/relations/
reactive_relation.rs

1use std::fmt::Display;
2use std::fmt::Formatter;
3use std::ops::Deref;
4use std::sync::Arc;
5
6use dashmap::DashMap;
7use serde::Serialize;
8use serde::Serializer;
9use serde_json::Map;
10use serde_json::Value;
11use typed_builder::TypedBuilder;
12
13use crate::ReactiveEntity;
14use crate::ReactiveProperties;
15use crate::ReactiveProperty;
16use reactive_graph_behaviour_model_api::BehaviourTypeId;
17use reactive_graph_behaviour_model_api::BehaviourTypeIds;
18use reactive_graph_behaviour_model_api::BehaviourTypesContainer;
19use reactive_graph_graph::Component;
20use reactive_graph_graph::ComponentContainer;
21use reactive_graph_graph::ComponentTypeId;
22use reactive_graph_graph::ComponentTypeIds;
23use reactive_graph_graph::Extensions;
24use reactive_graph_graph::InstanceId;
25use reactive_graph_graph::JsonSchemaId;
26use reactive_graph_graph::Mutability;
27use reactive_graph_graph::Namespace;
28use reactive_graph_graph::NamespaceSegment;
29use reactive_graph_graph::NamespacedType;
30use reactive_graph_graph::NamespacedTypeGetter;
31use reactive_graph_graph::PropertyInstanceGetter;
32use reactive_graph_graph::PropertyInstanceSetter;
33use reactive_graph_graph::PropertyInstances;
34use reactive_graph_graph::PropertyType;
35use reactive_graph_graph::PropertyTypes;
36use reactive_graph_graph::RelationInstance;
37use reactive_graph_graph::RelationInstanceId;
38use reactive_graph_graph::RelationInstanceTypeId;
39use reactive_graph_graph::RelationType;
40use reactive_graph_graph::RelationTypeId;
41use reactive_graph_graph::TypeDefinition;
42use reactive_graph_graph::TypeDefinitionGetter;
43use reactive_graph_graph::TypeIdType;
44use reactive_graph_graph::instances::named::NamedInstanceContainer;
45use reactive_graph_reactive_model_api::ReactiveInstance;
46use reactive_graph_reactive_model_api::ReactiveInstanceUnidentifiable;
47use reactive_graph_reactive_model_api::ReactivePropertyContainer;
48
49/// Reactive instance of a relation in the directed property graph.
50///
51/// Property Graph: The relation instance can store properties.
52///
53/// Directed Graph: The direction of the relation point from the outbound
54/// entity instance to the inbound entity instance.
55///
56/// Reactive Instance: The properties are streams with a local copies of
57/// the last result. The streams can be connected, combined, folded or zipped.
58///
59/// One example for a directed reactive relation instance is a connector which
60/// propagates changes on a property of the outbound entity to a property of
61/// the inbound entity.
62///
63/// Another example would be the velocity transformation which are also using
64/// the streams of the properties of the outbound entity, the inbound entity
65/// and/or the relation itself.
66///
67/// Last but not least relation instances can be used for semantic
68/// representations like the current camera of a player:
69/// Player--(CurrentCamera)-->Camera
70///
71#[derive(TypedBuilder)]
72#[builder(
73    build_method(vis="pub", into=ReactiveRelation),
74    builder_method(vis = ""),
75    builder_type(vis="pub", name=ReactiveRelationInstanceBuilder),
76)]
77pub struct ReactiveRelationInstance {
78    // Possible optimization: Final field id would speed up getting the id
79    // pub id: RelationInstanceId,
80    /// The outbound entity instance.
81    pub outbound: ReactiveEntity,
82
83    /// The type definition of the relation type.
84    #[builder(setter(into))]
85    pub ty: RelationInstanceTypeId,
86
87    /// The outbound entity instance.
88    pub inbound: ReactiveEntity,
89
90    /// The name of the relation instance.
91    #[builder(default, setter(into))]
92    pub name: String,
93
94    /// Textual description of the relation instance.
95    #[builder(default, setter(into))]
96    pub description: String,
97
98    /// The reactive properties.
99    #[builder(default, setter(into))]
100    pub properties: ReactiveProperties<RelationInstanceId>,
101
102    /// The names of the components which are applied on this relation instance.
103    #[builder(default, setter(into))]
104    pub components: ComponentTypeIds,
105
106    /// The names of the behaviours which are applied on this relation instance.
107    #[builder(default, setter(into))]
108    pub behaviours: BehaviourTypeIds,
109}
110
111#[allow(clippy::result_unit_err)]
112impl ReactiveRelationInstance {
113    pub fn new_from_properties<T: Into<RelationInstanceTypeId>, P: Into<PropertyInstances>>(
114        outbound: ReactiveEntity,
115        ty: T,
116        inbound: ReactiveEntity,
117        properties: P,
118    ) -> ReactiveRelationInstance {
119        let ty = ty.into();
120        let id = RelationInstanceId::new(outbound.id, ty.clone(), inbound.id);
121        let properties = ReactiveProperties::new_with_id_from_properties(id.clone(), properties.into());
122        ReactiveRelationInstance {
123            outbound,
124            ty,
125            inbound,
126            name: String::new(),
127            description: String::new(),
128            properties,
129            components: ComponentTypeIds::new(),
130            behaviours: BehaviourTypeIds::new(),
131        }
132    }
133
134    pub fn new_from_instance(outbound: ReactiveEntity, inbound: ReactiveEntity, instance: RelationInstance) -> ReactiveRelationInstance {
135        let id = instance.id();
136        let properties = ReactiveProperties::new_with_id_from_properties(id.clone(), instance.properties);
137        // let properties = instance.properties;
138        // ::<RelationInstanceId>
139        // let properties = instance
140        //     .properties
141        //     .iter()
142        //     // TODO: mutability
143        //     .map(|(name, value)| (name.clone(), ReactiveProperty::new(instance.ty.clone(), name.clone(), Mutable, value.clone())))
144        //     .collect();
145        ReactiveRelationInstance {
146            outbound,
147            ty: instance.ty,
148            inbound,
149            name: instance.name,
150            description: instance.description,
151            properties,
152            components: ComponentTypeIds::new(),
153            behaviours: BehaviourTypeIds::new(),
154        }
155    }
156
157    /// Returns the inner relation type id.
158    pub fn relation_type_id(&self) -> RelationTypeId {
159        self.ty.relation_type_id()
160    }
161
162    /// Returns the relation instance type id.
163    pub fn instance_id(&self) -> InstanceId {
164        self.ty.instance_id()
165    }
166}
167
168#[derive(Clone)]
169pub struct ReactiveRelation(Arc<ReactiveRelationInstance>);
170
171impl ReactiveRelation {
172    pub fn builder() -> ReactiveRelationInstanceBuilder {
173        ReactiveRelationInstance::builder()
174    }
175
176    #[allow(clippy::type_complexity)]
177    pub fn builder_with_entities(
178        outbound: ReactiveEntity,
179        ty: &RelationInstanceTypeId,
180        inbound: ReactiveEntity,
181    ) -> ReactiveRelationInstanceBuilder<((ReactiveEntity,), (RelationInstanceTypeId,), (ReactiveEntity,), (), (), (), (), ())> {
182        ReactiveRelation::builder().outbound(outbound).ty(ty).inbound(inbound)
183    }
184
185    /// Creates a builder for the given relation instance type id.
186    /// Generates an id for the reactive relation.
187    /// Converts property types into reactive properties and initializes the properties with default values.
188    #[allow(clippy::type_complexity)]
189    pub fn builder_with_entities_and_properties(
190        outbound: ReactiveEntity,
191        ty: &RelationInstanceTypeId,
192        inbound: ReactiveEntity,
193        properties: &PropertyTypes,
194    ) -> ReactiveRelationInstanceBuilder<(
195        (ReactiveEntity,),
196        (RelationInstanceTypeId,),
197        (ReactiveEntity,),
198        (),
199        (),
200        (ReactiveProperties<RelationInstanceId>,),
201        (),
202        (),
203    )> {
204        let id = RelationInstanceId::new(outbound.id, ty, inbound.id);
205        let properties = PropertyInstances::new_from_property_types_with_defaults(properties);
206        let reactive_properties: ReactiveProperties<RelationInstanceId> = ReactiveProperties::new_with_id_from_properties(id, properties);
207        ReactiveRelation::builder_with_entities(outbound, ty, inbound).properties(reactive_properties)
208    }
209
210    #[allow(clippy::type_complexity)]
211    pub fn builder_from_type_with_unique_id(
212        outbound: ReactiveEntity,
213        relation_type: &RelationType,
214        inbound: ReactiveEntity,
215    ) -> ReactiveRelationInstanceBuilder<(
216        (ReactiveEntity,),
217        (RelationInstanceTypeId,),
218        (ReactiveEntity,),
219        (),
220        (),
221        (ReactiveProperties<RelationInstanceId>,),
222        (),
223        (),
224    )> {
225        let ty = RelationInstanceTypeId::new_singleton(&relation_type.ty);
226        ReactiveRelation::builder_with_entities_and_properties(outbound, &ty, inbound, &relation_type.properties)
227    }
228
229    #[allow(clippy::type_complexity)]
230    pub fn builder_from_type_with_unique_instance_id(
231        outbound: ReactiveEntity,
232        relation_type: &RelationType,
233        instance_id: InstanceId,
234        inbound: ReactiveEntity,
235    ) -> ReactiveRelationInstanceBuilder<(
236        (ReactiveEntity,),
237        (RelationInstanceTypeId,),
238        (ReactiveEntity,),
239        (),
240        (),
241        (ReactiveProperties<RelationInstanceId>,),
242        (),
243        (),
244    )> {
245        let ty = RelationInstanceTypeId::new(&relation_type.ty, instance_id);
246        ReactiveRelation::builder_with_entities_and_properties(outbound, &ty, inbound, &relation_type.properties)
247    }
248
249    #[allow(clippy::type_complexity)]
250    pub fn builder_from_type_with_random_instance_id(
251        outbound: ReactiveEntity,
252        relation_type: &RelationType,
253        inbound: ReactiveEntity,
254    ) -> ReactiveRelationInstanceBuilder<(
255        (ReactiveEntity,),
256        (RelationInstanceTypeId,),
257        (ReactiveEntity,),
258        (),
259        (),
260        (ReactiveProperties<RelationInstanceId>,),
261        (),
262        (),
263    )> {
264        let ty = RelationInstanceTypeId::new_with_random_instance_id(&relation_type.ty);
265        ReactiveRelation::builder_with_entities_and_properties(outbound, &ty, inbound, &relation_type.properties)
266    }
267    // }
268    //
269    // impl ReactiveRelation {
270    pub fn new_from_properties(
271        outbound: ReactiveEntity,
272        ty: RelationInstanceTypeId,
273        inbound: ReactiveEntity,
274        properties: DashMap<String, Value>,
275    ) -> ReactiveRelation {
276        ReactiveRelationInstance::new_from_properties(outbound, ty, inbound, properties).into()
277    }
278
279    pub fn new_from_instance(outbound: ReactiveEntity, inbound: ReactiveEntity, instance: RelationInstance) -> ReactiveRelation {
280        ReactiveRelationInstance::new_from_instance(outbound, inbound, instance).into()
281    }
282}
283
284impl NamedInstanceContainer for ReactiveRelation {
285    fn name(&self) -> String {
286        self.name.clone()
287    }
288
289    fn description(&self) -> String {
290        self.description.clone()
291    }
292}
293
294impl Deref for ReactiveRelation {
295    type Target = Arc<ReactiveRelationInstance>;
296
297    fn deref(&self) -> &Self::Target {
298        &self.0
299    }
300}
301
302impl ReactiveInstanceUnidentifiable for ReactiveRelation {}
303
304impl ReactiveInstance<RelationInstanceId> for ReactiveRelation {
305    /// Returns the relation instance id.
306    fn id(&self) -> RelationInstanceId {
307        RelationInstanceId::new(self.outbound.id, self.ty.clone(), self.inbound.id)
308    }
309}
310
311impl ReactivePropertyContainer for ReactiveRelation {
312    fn tick_checked(&self) {
313        for property_instance in self.properties.iter() {
314            property_instance.tick_checked();
315        }
316    }
317
318    fn tick(&self) {
319        for property_instance in self.properties.iter() {
320            property_instance.tick();
321        }
322    }
323
324    fn has_property(&self, name: &str) -> bool {
325        self.properties.contains_key(name)
326    }
327
328    fn add_property(&self, name: &str, mutability: Mutability, value: Value) {
329        let name = name.into();
330        let id = self.id();
331        if !self.properties.contains_key(&name) {
332            let property_instance = ReactiveProperty::new(id.clone(), &name, mutability, value);
333            self.properties.insert(name, property_instance);
334        }
335    }
336
337    fn add_property_by_type(&self, property: &PropertyType) {
338        let property_instance = ReactiveProperty::new(self.id().clone(), &property.name, property.mutability, property.data_type.default_value());
339        self.properties.insert(property.name.clone(), property_instance);
340    }
341
342    fn remove_property(&self, name: &str) {
343        self.properties.retain(|property_name, _| property_name != &name);
344    }
345
346    fn observe_with_handle<F>(&self, name: &str, subscriber: F, handle_id: u128)
347    where
348        F: FnMut(&Value) + 'static + Send,
349    {
350        if let Some(property) = self.properties.get(name) {
351            property.stream.read().unwrap().observe_with_handle(subscriber, handle_id);
352        }
353    }
354
355    fn remove_observer(&self, name: &str, handle_id: u128) {
356        if let Some(property) = self.properties.get(name) {
357            property.stream.read().unwrap().remove(handle_id);
358        }
359    }
360
361    fn remove_observers(&self, name: &str) {
362        if let Some(property_instance) = self.properties.get(name) {
363            property_instance.stream.read().unwrap().clear();
364        }
365    }
366
367    fn remove_all_observers(&self) {
368        for property_instance in self.properties.iter() {
369            property_instance.stream.read().unwrap().clear();
370        }
371    }
372}
373
374impl ComponentContainer for ReactiveRelation {
375    fn get_components(&self) -> ComponentTypeIds {
376        self.components.clone()
377        // self.components.iter().map(|c| c.key().clone()).collect()
378    }
379
380    fn add_component(&self, ty: ComponentTypeId) {
381        self.components.insert(ty);
382    }
383
384    fn add_component_with_properties(&self, component: &Component) {
385        self.add_component(component.ty.clone());
386        for property_type in component.properties.iter() {
387            if !self.properties.contains_key(&property_type.name) {
388                self.add_property_by_type(&property_type);
389            }
390        }
391    }
392
393    fn remove_component(&self, ty: &ComponentTypeId) {
394        self.components.remove(ty);
395    }
396
397    fn is_a(&self, ty: &ComponentTypeId) -> bool {
398        self.components.contains(ty)
399    }
400
401    fn is_all(&self, tys: &ComponentTypeIds) -> bool {
402        tys.iter().all(|ty| self.components.contains(&ty))
403    }
404}
405
406impl BehaviourTypesContainer for ReactiveRelation {
407    fn get_behaviours(&self) -> Vec<BehaviourTypeId> {
408        self.behaviours.iter().map(|b| b.key().clone()).collect()
409    }
410
411    fn add_behaviour(&self, ty: BehaviourTypeId) {
412        self.behaviours.insert(ty);
413    }
414
415    fn remove_behaviour(&self, ty: &BehaviourTypeId) {
416        self.behaviours.remove(ty);
417    }
418
419    fn behaves_as(&self, ty: &BehaviourTypeId) -> bool {
420        self.behaviours.contains(ty)
421    }
422
423    fn behaves_as_all(&self, tys: &BehaviourTypeIds) -> bool {
424        tys.iter().all(|ty| self.behaviours.contains(&ty))
425    }
426}
427
428impl PropertyInstanceGetter for ReactiveRelation {
429    fn get(&self, property_name: &str) -> Option<Value> {
430        self.properties.get(property_name).map(|p| p.get())
431    }
432
433    fn as_bool(&self, property_name: &str) -> Option<bool> {
434        self.properties.get(property_name).and_then(|p| p.as_bool())
435    }
436
437    fn as_u64(&self, property_name: &str) -> Option<u64> {
438        self.properties.get(property_name).and_then(|p| p.as_u64())
439    }
440
441    fn as_i64(&self, property_name: &str) -> Option<i64> {
442        self.properties.get(property_name).and_then(|p| p.as_i64())
443    }
444
445    fn as_f64(&self, property_name: &str) -> Option<f64> {
446        self.properties.get(property_name).and_then(|p| p.as_f64())
447    }
448
449    fn as_string(&self, property_name: &str) -> Option<String> {
450        self.properties.get(property_name).and_then(|p| p.as_string())
451    }
452
453    fn as_array(&self, property_name: &str) -> Option<Vec<Value>> {
454        self.properties.get(property_name).and_then(|p| p.as_array())
455    }
456
457    fn as_object(&self, property_name: &str) -> Option<Map<String, Value>> {
458        self.properties.get(property_name).and_then(|p| p.as_object())
459    }
460}
461
462impl PropertyInstanceSetter for ReactiveRelation {
463    fn set_checked(&self, property_name: &str, value: Value) {
464        if let Some(instance) = self.properties.get(property_name) {
465            instance.set_checked(value);
466        }
467    }
468
469    fn set(&self, property_name: &str, value: Value) {
470        if let Some(instance) = self.properties.get(property_name) {
471            instance.set(value);
472        }
473    }
474
475    fn set_no_propagate_checked(&self, property_name: &str, value: Value) {
476        if let Some(instance) = self.properties.get(property_name) {
477            instance.set_no_propagate_checked(value);
478        }
479    }
480
481    fn set_no_propagate(&self, property_name: &str, value: Value) {
482        if let Some(instance) = self.properties.get(property_name) {
483            instance.set_no_propagate(value);
484        }
485    }
486
487    fn mutability(&self, property_name: &str) -> Option<Mutability> {
488        self.properties.get(property_name).map(|p| p.value().mutability)
489    }
490
491    fn set_mutability(&self, property_name: &str, mutability: Mutability) {
492        if let Some(mut property_instance) = self.properties.get_mut(property_name) {
493            property_instance.set_mutability(mutability);
494        }
495    }
496}
497
498impl NamespacedTypeGetter for ReactiveRelation {
499    fn namespaced_type(&self) -> NamespacedType {
500        self.ty.namespaced_type()
501    }
502
503    fn namespace(&self) -> Namespace {
504        self.ty.namespace()
505    }
506
507    fn path(&self) -> Namespace {
508        self.ty.path()
509    }
510
511    fn type_name(&self) -> NamespaceSegment {
512        self.ty.type_name()
513    }
514}
515
516impl TypeDefinitionGetter for ReactiveRelation {
517    fn type_definition(&self) -> TypeDefinition {
518        self.ty.type_definition()
519    }
520
521    fn type_id_type() -> TypeIdType {
522        TypeIdType::RelationType
523    }
524}
525
526impl TypeDefinitionGetter for &ReactiveRelation {
527    fn type_definition(&self) -> TypeDefinition {
528        self.ty.type_definition()
529    }
530
531    fn type_id_type() -> TypeIdType {
532        TypeIdType::RelationType
533    }
534}
535
536impl AsRef<NamespacedType> for ReactiveRelation {
537    fn as_ref(&self) -> &NamespacedType {
538        self.ty.as_ref()
539    }
540}
541
542impl AsRef<Namespace> for ReactiveRelation {
543    fn as_ref(&self) -> &Namespace {
544        self.ty.as_ref()
545    }
546}
547
548impl Display for ReactiveRelation {
549    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
550        write!(f, "{}--[{}]-->{}", self.outbound.id, &self.ty, self.inbound.id)
551    }
552}
553
554impl From<ReactiveRelation> for RelationInstance {
555    fn from(relation: ReactiveRelation) -> Self {
556        RelationInstance {
557            outbound_id: relation.outbound.id,
558            ty: relation.ty.clone(),
559            inbound_id: relation.inbound.id,
560            name: relation.name.clone(),
561            description: relation.description.clone(),
562            properties: PropertyInstances::from(&relation.properties),
563            components: relation.components.clone(),
564            extensions: Extensions::new(),
565        }
566    }
567}
568
569impl From<&ReactiveRelation> for RelationInstance {
570    fn from(relation: &ReactiveRelation) -> Self {
571        RelationInstance {
572            outbound_id: relation.outbound.id,
573            ty: relation.ty.clone(),
574            inbound_id: relation.inbound.id,
575            name: relation.name.clone(),
576            description: relation.description.clone(),
577            properties: PropertyInstances::from(&relation.properties),
578            components: relation.components.clone(),
579            extensions: Extensions::new(),
580        }
581    }
582}
583
584impl From<ReactiveRelationInstance> for ReactiveRelation {
585    fn from(relation_instance: ReactiveRelationInstance) -> Self {
586        ReactiveRelation(Arc::new(relation_instance))
587    }
588}
589
590impl Serialize for ReactiveRelation {
591    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
592    where
593        S: Serializer,
594    {
595        let property_instances = PropertyInstances::from(&self.properties);
596        property_instances.insert("$id".to_string(), JsonSchemaId::from(&self).into());
597        property_instances.insert("outbound_id".to_string(), Value::String(self.outbound.id.to_string()));
598        property_instances.insert("instance_id".to_string(), Value::String(self.instance_id().to_string()));
599        property_instances.insert("inbound_id".to_string(), Value::String(self.inbound.id.to_string()));
600        serializer.collect_map(property_instances)
601    }
602}