reactive_graph_reactive_model_impl/entities/
reactive_entity.rs

1use serde::Serialize;
2use serde::Serializer;
3use serde_json::Map;
4use serde_json::Value;
5use std::fmt::Display;
6use std::fmt::Formatter;
7use std::ops::Deref;
8use std::sync::Arc;
9use typed_builder::TypedBuilder;
10use uuid::Uuid;
11
12use reactive_graph_behaviour_model_api::BehaviourTypeId;
13use reactive_graph_behaviour_model_api::BehaviourTypeIds;
14use reactive_graph_behaviour_model_api::BehaviourTypesContainer;
15use reactive_graph_graph::Component;
16use reactive_graph_graph::ComponentContainer;
17use reactive_graph_graph::ComponentTypeId;
18use reactive_graph_graph::ComponentTypeIds;
19use reactive_graph_graph::EntityInstance;
20use reactive_graph_graph::EntityType;
21use reactive_graph_graph::EntityTypeId;
22use reactive_graph_graph::Extensions;
23use reactive_graph_graph::JsonSchemaId;
24use reactive_graph_graph::Mutability;
25use reactive_graph_graph::Mutability::Mutable;
26use reactive_graph_graph::NamedInstanceContainer;
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::TypeDefinition;
36use reactive_graph_graph::TypeDefinitionGetter;
37use reactive_graph_graph::TypeIdType;
38
39use crate::ReactiveProperties;
40use crate::ReactiveProperty;
41use reactive_graph_reactive_model_api::ReactiveInstance;
42use reactive_graph_reactive_model_api::ReactiveInstanceUnidentifiable;
43use reactive_graph_reactive_model_api::ReactivePropertyContainer;
44
45#[derive(TypedBuilder)]
46#[builder(
47    build_method(vis="pub", into=ReactiveEntity),
48    builder_method(vis = ""),
49    builder_type(vis="pub", name=ReactiveEntityInstanceBuilder),
50)]
51pub struct ReactiveEntityInstance {
52    /// The type definition of the entity type.
53    #[builder(setter(into))]
54    pub ty: EntityTypeId,
55
56    /// The unique identifier of the entity instance.
57    #[builder(default=Uuid::new_v4())]
58    pub id: Uuid,
59
60    /// The name of the entity instance.
61    #[builder(default, setter(into))]
62    pub name: String,
63
64    /// Textual description of the entity instance.
65    #[builder(default, setter(into))]
66    pub description: String,
67
68    /// The reactive properties.
69    #[builder(default, setter(into))]
70    pub properties: ReactiveProperties<Uuid>,
71
72    /// The names of the components which are applied on this entity instance.
73    #[builder(default, setter(into))]
74    pub components: ComponentTypeIds,
75
76    /// The names of the behaviours which are applied on this entity instance.
77    #[builder(default, setter(into))]
78    pub behaviours: BehaviourTypeIds,
79}
80
81#[derive(Clone)]
82pub struct ReactiveEntity(Arc<ReactiveEntityInstance>);
83
84impl ReactiveEntity {
85    pub fn builder() -> ReactiveEntityInstanceBuilder {
86        ReactiveEntityInstance::builder()
87    }
88
89    /// Creates a builder from the given entity type.
90    /// Generates an id for the reactive entity.
91    /// Converts property types into reactive properties and initializes the properties with default values.
92    #[allow(clippy::type_complexity)]
93    pub fn builder_from_entity_type(
94        entity_type: &EntityType,
95    ) -> ReactiveEntityInstanceBuilder<((EntityTypeId,), (Uuid,), (), (), (ReactiveProperties<Uuid>,), (), ())> {
96        let id = Uuid::new_v4();
97        let properties = PropertyInstances::new_from_property_types_with_defaults(&entity_type.properties);
98        let reactive_properties = ReactiveProperties::new_with_id_from_properties(id, properties);
99        ReactiveEntity::builder().ty(&entity_type.ty).id(id).properties(reactive_properties)
100    }
101}
102
103impl NamedInstanceContainer for ReactiveEntity {
104    fn name(&self) -> String {
105        self.name.clone()
106    }
107
108    fn description(&self) -> String {
109        self.description.clone()
110    }
111}
112
113impl Deref for ReactiveEntity {
114    type Target = Arc<ReactiveEntityInstance>;
115
116    fn deref(&self) -> &Self::Target {
117        &self.0
118    }
119}
120
121impl ReactiveInstanceUnidentifiable for ReactiveEntity {}
122
123impl ReactiveInstance<Uuid> for ReactiveEntity {
124    fn id(&self) -> Uuid {
125        self.id
126    }
127}
128
129impl ReactivePropertyContainer for ReactiveEntity {
130    fn tick_checked(&self) {
131        for property in self.properties.iter() {
132            property.tick_checked();
133        }
134    }
135
136    fn tick(&self) {
137        for property in self.properties.iter() {
138            property.tick();
139        }
140    }
141
142    fn has_property(&self, name: &str) -> bool {
143        self.properties.contains_key(name)
144    }
145
146    fn add_property(&self, name: &str, mutability: Mutability, value: Value) {
147        let name = name.into();
148        if !self.properties.contains_key(&name) {
149            let property_instance = ReactiveProperty::new(self.id, &name, mutability, value);
150            self.properties.insert(name, property_instance);
151        }
152    }
153
154    fn add_property_by_type(&self, property: &PropertyType) {
155        let property_instance = ReactiveProperty::new(self.id, &property.name, property.mutability, property.data_type.default_value());
156        self.properties.insert(property.name.clone(), property_instance);
157    }
158
159    fn remove_property(&self, name: &str) {
160        self.properties.retain(|property_name, _| property_name != &name);
161    }
162
163    fn observe_with_handle<F>(&self, name: &str, subscriber: F, handle_id: u128)
164    where
165        F: FnMut(&Value) + 'static + Send,
166    {
167        if let Some(property_instance) = self.properties.get(name) {
168            property_instance.stream.read().unwrap().observe_with_handle(subscriber, handle_id);
169        }
170    }
171
172    fn remove_observer(&self, name: &str, handle_id: u128) {
173        if let Some(property_instance) = self.properties.get(name) {
174            property_instance.stream.read().unwrap().remove(handle_id);
175        }
176    }
177
178    fn remove_observers(&self, name: &str) {
179        if let Some(property_instance) = self.properties.get(name) {
180            property_instance.stream.read().unwrap().clear();
181        }
182    }
183
184    fn remove_all_observers(&self) {
185        for property_instance in self.properties.iter() {
186            property_instance.stream.read().unwrap().clear();
187        }
188    }
189}
190
191impl ComponentContainer for ReactiveEntity {
192    fn get_components(&self) -> ComponentTypeIds {
193        self.components.clone()
194        // self.components.iter().map(|c| c.key().clone()).collect()
195    }
196
197    fn add_component(&self, ty: ComponentTypeId) {
198        self.components.insert(ty);
199    }
200
201    fn add_component_with_properties(&self, component: &Component) {
202        self.add_component(component.ty.clone());
203        for property_type in component.properties.iter() {
204            if !self.properties.contains_key(&property_type.name) {
205                self.add_property_by_type(&property_type);
206            }
207        }
208    }
209
210    fn remove_component(&self, ty: &ComponentTypeId) {
211        self.components.remove(ty);
212    }
213
214    fn is_a(&self, ty: &ComponentTypeId) -> bool {
215        self.components.contains(ty)
216    }
217
218    fn is_all(&self, tys: &ComponentTypeIds) -> bool {
219        tys.iter().all(|ty| self.components.contains(&ty))
220    }
221}
222
223impl BehaviourTypesContainer for ReactiveEntity {
224    fn get_behaviours(&self) -> Vec<BehaviourTypeId> {
225        self.behaviours.iter().map(|b| b.key().clone()).collect()
226    }
227
228    fn add_behaviour(&self, ty: BehaviourTypeId) {
229        self.behaviours.insert(ty);
230    }
231
232    fn remove_behaviour(&self, ty: &BehaviourTypeId) {
233        self.behaviours.remove(ty);
234    }
235
236    fn behaves_as(&self, ty: &BehaviourTypeId) -> bool {
237        self.behaviours.contains(ty)
238    }
239
240    fn behaves_as_all(&self, tys: &BehaviourTypeIds) -> bool {
241        tys.iter().all(|ty| self.behaviours.contains(&ty))
242    }
243}
244
245impl PropertyInstanceGetter for ReactiveEntity {
246    fn get(&self, property_name: &str) -> Option<Value> {
247        self.properties.get(property_name).map(|p| p.get())
248    }
249
250    fn as_bool(&self, property_name: &str) -> Option<bool> {
251        self.properties.get(property_name).and_then(|p| p.as_bool())
252    }
253
254    fn as_u64(&self, property_name: &str) -> Option<u64> {
255        self.properties.get(property_name).and_then(|p| p.as_u64())
256    }
257
258    fn as_i64(&self, property_name: &str) -> Option<i64> {
259        self.properties.get(property_name).and_then(|p| p.as_i64())
260    }
261
262    fn as_f64(&self, property_name: &str) -> Option<f64> {
263        self.properties.get(property_name).and_then(|p| p.as_f64())
264    }
265
266    fn as_string(&self, property_name: &str) -> Option<String> {
267        self.properties.get(property_name).and_then(|p| p.as_string())
268    }
269
270    fn as_array(&self, property_name: &str) -> Option<Vec<Value>> {
271        self.properties.get(property_name).and_then(|p| p.as_array())
272    }
273
274    fn as_object(&self, property_name: &str) -> Option<Map<String, Value>> {
275        self.properties.get(property_name).and_then(|p| p.as_object())
276    }
277}
278
279impl PropertyInstanceSetter for ReactiveEntity {
280    fn set_checked(&self, property_name: &str, value: Value) {
281        if let Some(instance) = self.properties.get(property_name) {
282            instance.set_checked(value);
283        }
284    }
285
286    fn set(&self, property_name: &str, value: Value) {
287        if let Some(instance) = self.properties.get(property_name) {
288            instance.set(value);
289        }
290    }
291
292    fn set_no_propagate_checked(&self, property_name: &str, value: Value) {
293        if let Some(instance) = self.properties.get(property_name) {
294            instance.set_no_propagate_checked(value);
295        }
296    }
297
298    fn set_no_propagate(&self, property_name: &str, value: Value) {
299        if let Some(instance) = self.properties.get(property_name) {
300            instance.set_no_propagate(value);
301        }
302    }
303
304    fn mutability(&self, property_name: &str) -> Option<Mutability> {
305        self.properties.get(property_name).map(|p| p.value().mutability)
306    }
307
308    fn set_mutability(&self, property_name: &str, mutability: Mutability) {
309        if let Some(mut property_instance) = self.properties.get_mut(property_name) {
310            property_instance.set_mutability(mutability);
311        }
312    }
313
314    // TODO: fn set(&self, Map<String, Value>
315    // TODO: Set values transactional: first set all values internally, then send all affected streams
316}
317
318impl NamespacedTypeGetter for ReactiveEntity {
319    fn namespaced_type(&self) -> NamespacedType {
320        self.ty.namespaced_type()
321    }
322
323    fn namespace(&self) -> Namespace {
324        self.ty.namespace()
325    }
326
327    fn path(&self) -> Namespace {
328        self.ty.path()
329    }
330
331    fn type_name(&self) -> NamespaceSegment {
332        self.ty.type_name()
333    }
334}
335
336impl TypeDefinitionGetter for ReactiveEntity {
337    fn type_definition(&self) -> TypeDefinition {
338        self.ty.type_definition()
339    }
340
341    fn type_id_type() -> TypeIdType {
342        TypeIdType::EntityType
343    }
344}
345
346impl TypeDefinitionGetter for &ReactiveEntity {
347    fn type_definition(&self) -> TypeDefinition {
348        self.ty.type_definition()
349    }
350
351    fn type_id_type() -> TypeIdType {
352        TypeIdType::EntityType
353    }
354}
355
356impl AsRef<NamespacedType> for ReactiveEntity {
357    fn as_ref(&self) -> &NamespacedType {
358        self.ty.as_ref()
359    }
360}
361
362impl AsRef<Namespace> for ReactiveEntity {
363    fn as_ref(&self) -> &Namespace {
364        self.ty.as_ref()
365    }
366}
367
368impl Display for ReactiveEntity {
369    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
370        write!(f, "{}__{}", &self.ty, self.id)
371    }
372}
373
374impl From<ReactiveEntity> for EntityInstance {
375    fn from(entity: ReactiveEntity) -> Self {
376        EntityInstance {
377            ty: entity.ty.clone(),
378            id: entity.id,
379            name: entity.name.clone(),
380            description: entity.description.clone(),
381            properties: PropertyInstances::from(&entity.properties),
382            components: entity.components.clone(),
383            extensions: Extensions::new(),
384        }
385    }
386}
387
388impl From<&ReactiveEntity> for EntityInstance {
389    fn from(entity: &ReactiveEntity) -> Self {
390        EntityInstance {
391            ty: entity.ty.clone(),
392            id: entity.id,
393            name: entity.name.clone(),
394            description: entity.description.clone(),
395            properties: PropertyInstances::from(&entity.properties),
396            components: entity.components.clone(),
397            extensions: Extensions::new(),
398        }
399    }
400}
401
402impl From<ReactiveEntityInstance> for ReactiveEntity {
403    fn from(reactive_entity: ReactiveEntityInstance) -> Self {
404        ReactiveEntity(Arc::new(reactive_entity))
405    }
406}
407
408impl From<EntityInstance> for ReactiveEntity {
409    fn from(instance: EntityInstance) -> Self {
410        let properties: ReactiveProperties<Uuid> = instance
411            .properties
412            .iter()
413            .map(|property| ReactiveProperty::new(instance.id, property.key(), Mutable, property.value().clone()))
414            .collect();
415
416        let entity_instance = ReactiveEntityInstance {
417            ty: instance.ty.clone(),
418            id: instance.id,
419            name: instance.name.clone(),
420            description: instance.description,
421            properties,
422            components: ComponentTypeIds::new(),
423            behaviours: BehaviourTypeIds::new(),
424        };
425        entity_instance.into()
426    }
427}
428
429impl Serialize for ReactiveEntity {
430    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
431    where
432        S: Serializer,
433    {
434        let property_instances = PropertyInstances::from(&self.properties);
435        property_instances.insert("$id".to_string(), JsonSchemaId::from(&self).into());
436        property_instances.insert("id".to_string(), Value::String(self.id.to_string()));
437        serializer.collect_map(property_instances)
438    }
439}
440
441// impl Deserialize for ReactiveEntity {
442//
443// }