reactive_graph_graphql_schema/mutation/instances/
entity_instance.rs

1use std::str::FromStr;
2use std::sync::Arc;
3
4use async_graphql::Context;
5use async_graphql::Object;
6use async_graphql::Result;
7use log::debug;
8use serde_json::json;
9use uuid::Uuid;
10
11use reactive_graph_behaviour_model_api::BehaviourTypeId;
12use reactive_graph_behaviour_service_api::EntityBehaviourManager;
13use reactive_graph_behaviour_service_api::EntityComponentBehaviourManager;
14use reactive_graph_graph::ComponentTypeIds;
15use reactive_graph_graph::CreateEntityInstanceError;
16use reactive_graph_graph::CreateRelationInstanceError;
17use reactive_graph_graph::EntityInstance;
18use reactive_graph_graph::EntityTypeId;
19use reactive_graph_graph::PropertyInstanceSetter;
20use reactive_graph_graph::TriggerEntityInstanceError;
21use reactive_graph_graph::UpdateEntityInstanceError;
22use reactive_graph_model_core::reactive_graph::core::action::ActionProperties::TRIGGER;
23use reactive_graph_reactive_model_api::ReactiveInstance;
24use reactive_graph_reactive_model_api::ReactivePropertyContainer;
25use reactive_graph_reactive_model_impl::ReactiveEntity;
26use reactive_graph_reactive_service_api::ReactiveEntityManager;
27use reactive_graph_reactive_service_api::ReactiveRelationManager;
28use reactive_graph_type_system_api::ComponentManager;
29use reactive_graph_type_system_api::EntityTypeManager;
30
31use crate::mutation::PropertyTypeDefinitions;
32use crate::query::GraphQLEntityInstance;
33use crate::query::GraphQLPropertyInstance;
34use crate::validator::NamespacedTypeValidator;
35
36#[derive(Default)]
37pub struct MutationEntityInstances;
38
39impl MutationEntityInstances {
40    fn get_reactive_entity_by_id_or_label(&self, context: &Context<'_>, id: Option<Uuid>, label: Option<String>) -> Result<ReactiveEntity> {
41        let reactive_entity_manager = context.data::<Arc<dyn ReactiveEntityManager + Send + Sync>>()?;
42        if let Some(id) = id {
43            Ok(reactive_entity_manager
44                .get(id)
45                .ok_or(UpdateEntityInstanceError::EntityInstanceDoesNotExist(id))?)
46        } else if let Some(label) = label {
47            Ok(reactive_entity_manager
48                .get_by_label(label.as_str())
49                .ok_or(UpdateEntityInstanceError::EntityInstanceWithLabelDoesNotExist(label.clone()))?)
50        } else {
51            Err(UpdateEntityInstanceError::EitherUuidOrLabelMustBeGiven.into())
52        }
53    }
54}
55
56/// Mutation of entity instances.
57#[Object]
58impl MutationEntityInstances {
59    /// Creates a new entity instance of the given type.
60    ///
61    /// The entity type must exist.
62    ///
63    /// Optionally, a UUID can be specified. If no UUID is specified one will be generated
64    /// randomly.
65    ///
66    /// The given properties consists of a list of pairs of property name and property value.
67    /// If properties are not provided, default values will be used depending on the data type
68    /// of the property.
69    async fn create(
70        &self,
71        context: &Context<'_>,
72        #[graphql(
73            name = "type",
74            desc = "The fully qualified namespace of the entity type.",
75            validator(custom = "NamespacedTypeValidator::new()")
76        )]
77        _type: String,
78        #[graphql(desc = "The id of the entity instance. If none is given a random uuid will be generated.")] id: Option<Uuid>,
79        #[graphql(desc = "Name of the entity instance.")] name: Option<String>,
80        #[graphql(desc = "Description of the entity instance.")] description: Option<String>,
81        #[graphql(desc = "Creates the entity instance with the given components.")] components: Option<Vec<String>>,
82        properties: Option<Vec<GraphQLPropertyInstance>>,
83    ) -> Result<GraphQLEntityInstance> {
84        let reactive_entity_manager = context.data::<Arc<dyn ReactiveEntityManager + Send + Sync>>()?;
85        let entity_type_manager = context.data::<Arc<dyn EntityTypeManager + Send + Sync>>()?;
86        let component_manager = context.data::<Arc<dyn ComponentManager + Send + Sync>>()?;
87
88        let entity_ty = EntityTypeId::from_str(&_type)?;
89        let component_tys = ComponentTypeIds::parse_optional_namespaces(components)?;
90
91        let entity_type = entity_type_manager
92            .get(&entity_ty)
93            .ok_or(CreateEntityInstanceError::EntityTypeDoesNotExist(entity_ty.clone()))?;
94        if !component_manager.has_all(&component_tys) {
95            return Err(CreateEntityInstanceError::ComponentsDoesNotExist.into());
96        }
97
98        let properties = GraphQLPropertyInstance::to_property_instances_with_defaults(properties, entity_type.properties);
99
100        let entity_instance = EntityInstance::builder()
101            .ty(&entity_ty)
102            .id(id.unwrap_or(Uuid::new_v4()))
103            .name(name.unwrap_or_default())
104            .description(description.unwrap_or_default())
105            .properties(properties)
106            .build();
107        let entity_instance = reactive_entity_manager.create_reactive_instance(entity_instance)?;
108        for component_ty in component_tys {
109            // TODO: handle the case when one or multiple components wasn't added
110            let _ = reactive_entity_manager.add_component(entity_instance.id, &component_ty);
111        }
112        Ok(entity_instance.into())
113    }
114
115    /// Updates the properties of the entity instance with the given id.
116    #[allow(clippy::too_many_arguments)]
117    async fn update(
118        &self,
119        context: &Context<'_>,
120        #[graphql(desc = "Updates the entity instance with the given id.")] id: Option<Uuid>,
121        #[graphql(desc = "Updates the entity instance with the given label.")] label: Option<String>,
122        #[graphql(name = "addComponents", desc = "Adds the given components.")] add_component_namespaces: Option<Vec<String>>,
123        #[graphql(name = "removeComponents", desc = "Removes the given components.")] remove_component_namespaces: Option<Vec<String>>,
124        #[graphql(desc = "Updates the given properties")] properties: Option<Vec<GraphQLPropertyInstance>>,
125        #[graphql(desc = "Adds the given properties")] add_properties: Option<Vec<crate::mutation::PropertyTypeDefinition>>,
126        #[graphql(desc = "Removes the given properties")] remove_properties: Option<Vec<String>>,
127    ) -> Result<GraphQLEntityInstance> {
128        let reactive_entity_manager = context.data::<Arc<dyn ReactiveEntityManager + Send + Sync>>()?;
129        let component_manager = context.data::<Arc<dyn ComponentManager + Send + Sync>>()?;
130
131        let add_component_tys = ComponentTypeIds::parse_optional_namespaces(add_component_namespaces)?;
132        let remove_component_tys = ComponentTypeIds::parse_optional_namespaces(remove_component_namespaces)?;
133        let add_properties = PropertyTypeDefinitions::parse_optional_definitions(add_properties)?;
134
135        if !component_manager.has_all(&add_component_tys) || !component_manager.has_all(&remove_component_tys) {
136            return Err(CreateRelationInstanceError::ComponentsDoesNotExist.into());
137        }
138
139        let reactive_entity: ReactiveEntity = self.get_reactive_entity_by_id_or_label(context, id, label)?;
140
141        for component in add_component_tys {
142            // TODO: handle the case when one or multiple components wasn't added
143            let _ = reactive_entity_manager.add_component(reactive_entity.id, &component);
144        }
145        for component in remove_component_tys {
146            reactive_entity_manager.remove_component(reactive_entity.id, &component);
147        }
148
149        if let Some(properties) = properties {
150            // fill all values first without propagation
151            for property in properties.clone() {
152                debug!("set property {} = {}", property.name.clone(), property.value.clone());
153                // Set with respect to the mutability state
154                reactive_entity.set_no_propagate_checked(&property.name, property.value.clone());
155            }
156            // tick every property that has been changed before, this is still not transactional
157            for property in properties {
158                debug!("tick property {} = {}", property.name.clone(), property.value.clone());
159                if let Some(property_instance) = reactive_entity.properties.get(property.name.as_str()) {
160                    // Tick with respect to the mutability state
161                    property_instance.tick_checked();
162                }
163            }
164        }
165        for property_type in add_properties.iter() {
166            // let property_type: PropertyType = property_type.into();
167            debug!("add property {} ({})", &property_type.name, &property_type.data_type);
168            reactive_entity.add_property_by_type(&property_type);
169        }
170        if let Some(remove_properties) = remove_properties {
171            for property_name in remove_properties.iter() {
172                debug!("remove property {property_name}");
173                reactive_entity.remove_property(property_name);
174            }
175        }
176        // TODO: it's still not a transactional mutation
177        // entity_instance.tick();
178        Ok(reactive_entity.into())
179    }
180
181    /// Triggers the entity instance with the given id.
182    async fn trigger(
183        &self,
184        context: &Context<'_>,
185        #[graphql(desc = "Triggers the entity instance with the given id")] id: Option<Uuid>,
186        #[graphql(desc = "Triggers the entity instance with the given label")] label: Option<String>,
187    ) -> Result<GraphQLEntityInstance> {
188        let reactive_entity = self.get_reactive_entity_by_id_or_label(context, id, label)?;
189        if !reactive_entity.has_property(TRIGGER.as_ref()) {
190            return Err(TriggerEntityInstanceError::TriggerPropertyMissing(reactive_entity.id).into());
191        }
192        reactive_entity.set_checked(TRIGGER.as_ref(), json!(true));
193        Ok(reactive_entity.into())
194    }
195
196    /// Manually tick the entity instance. This means for each property of the entity instance
197    /// the corresponding reactive stream will be activated with its last value.
198    ///
199    /// This leads to a recalculation if the entity instance is controlled by a behaviour which
200    /// consumes the reactive streams.
201    ///
202    /// Furthermore, this leads to a new value propagation if the output property is connected
203    /// to other properties.
204    async fn tick(
205        &self,
206        context: &Context<'_>,
207        #[graphql(desc = "The id of the entity instance")] id: Option<Uuid>,
208        #[graphql(desc = "The label of the entity instance")] label: Option<String>,
209    ) -> Result<GraphQLEntityInstance> {
210        let reactive_entity = self.get_reactive_entity_by_id_or_label(context, id, label)?;
211        reactive_entity.tick();
212        Ok(reactive_entity.into())
213    }
214
215    /// Deletes an entity instance.
216    async fn delete(
217        &self,
218        context: &Context<'_>,
219        #[graphql(desc = "The id of the entity instance")] id: Uuid,
220        #[graphql(desc = "If true, all relations to and from the entity instance will be deleted as well")] delete_relations: Option<bool>,
221    ) -> Result<bool> {
222        let reactive_entity_manager = context.data::<Arc<dyn ReactiveEntityManager + Send + Sync>>()?;
223        if delete_relations.unwrap_or_default() {
224            let relation_instance_manager = context.data::<Arc<dyn ReactiveRelationManager + Send + Sync>>()?;
225            relation_instance_manager.get_by_inbound_entity(id).iter().for_each(|reactive_relation| {
226                let id = reactive_relation.id();
227                relation_instance_manager.delete(&id);
228            });
229            relation_instance_manager.get_by_outbound_entity(id).iter().for_each(|reactive_relation| {
230                let id = reactive_relation.id();
231                relation_instance_manager.delete(&id);
232            });
233        }
234        Ok(reactive_entity_manager.delete(id))
235    }
236
237    async fn connect(
238        &self,
239        context: &Context<'_>,
240        id: Uuid,
241        #[graphql(name = "behaviour", desc = "The fully qualified namespace of the behaviour")] behaviour_namespace: String,
242    ) -> Result<GraphQLEntityInstance> {
243        let reactive_entity_manager = context.data::<Arc<dyn ReactiveEntityManager + Send + Sync>>()?;
244        let entity_behaviour_manager = context.data::<Arc<dyn EntityBehaviourManager + Send + Sync>>()?;
245        let entity_component_behaviour_manager = context.data::<Arc<dyn EntityComponentBehaviourManager + Send + Sync>>()?;
246        let behaviour_ty = BehaviourTypeId::from_str(&behaviour_namespace)?;
247        let reactive_instance = reactive_entity_manager
248            .get(id)
249            .ok_or(UpdateEntityInstanceError::EntityInstanceDoesNotExist(id))?;
250        if entity_behaviour_manager.has(reactive_instance.clone(), &behaviour_ty) {
251            entity_behaviour_manager.connect(reactive_instance.clone(), &behaviour_ty)?;
252        }
253        if entity_component_behaviour_manager.has(reactive_instance.clone(), &behaviour_ty) {
254            entity_component_behaviour_manager.connect(reactive_instance.clone(), &behaviour_ty)?;
255        }
256        Ok(reactive_instance.into())
257    }
258
259    async fn disconnect(
260        &self,
261        context: &Context<'_>,
262        id: Uuid,
263        #[graphql(name = "behaviour", desc = "The fully qualified namespace of the behaviour")] behaviour_namespace: String,
264    ) -> Result<GraphQLEntityInstance> {
265        let reactive_entity_manager = context.data::<Arc<dyn ReactiveEntityManager + Send + Sync>>()?;
266        let entity_behaviour_manager = context.data::<Arc<dyn EntityBehaviourManager + Send + Sync>>()?;
267        let entity_component_behaviour_manager = context.data::<Arc<dyn EntityComponentBehaviourManager + Send + Sync>>()?;
268        let behaviour_ty = BehaviourTypeId::from_str(&behaviour_namespace)?;
269        let reactive_instance = reactive_entity_manager
270            .get(id)
271            .ok_or(UpdateEntityInstanceError::EntityInstanceDoesNotExist(id))?;
272        if entity_behaviour_manager.has(reactive_instance.clone(), &behaviour_ty) {
273            entity_behaviour_manager.disconnect(reactive_instance.clone(), &behaviour_ty)?;
274        }
275        if entity_component_behaviour_manager.has(reactive_instance.clone(), &behaviour_ty) {
276            entity_component_behaviour_manager.disconnect(reactive_instance.clone(), &behaviour_ty)?;
277        }
278        Ok(reactive_instance.into())
279    }
280
281    async fn reconnect(
282        &self,
283        context: &Context<'_>,
284        id: Uuid,
285        #[graphql(name = "behaviour", desc = "The fully qualified namespace of the behaviour")] behaviour_namespace: String,
286    ) -> Result<GraphQLEntityInstance> {
287        let reactive_entity_manager = context.data::<Arc<dyn ReactiveEntityManager + Send + Sync>>()?;
288        let entity_behaviour_manager = context.data::<Arc<dyn EntityBehaviourManager + Send + Sync>>()?;
289        let entity_component_behaviour_manager = context.data::<Arc<dyn EntityComponentBehaviourManager + Send + Sync>>()?;
290        let behaviour_ty = BehaviourTypeId::from_str(&behaviour_namespace)?;
291        let reactive_instance = reactive_entity_manager
292            .get(id)
293            .ok_or(UpdateEntityInstanceError::EntityInstanceDoesNotExist(id))?;
294        if entity_behaviour_manager.has(reactive_instance.clone(), &behaviour_ty) {
295            entity_behaviour_manager.reconnect(reactive_instance.clone(), &behaviour_ty)?;
296        }
297        if entity_component_behaviour_manager.has(reactive_instance.clone(), &behaviour_ty) {
298            entity_component_behaviour_manager.reconnect(reactive_instance.clone(), &behaviour_ty)?;
299        }
300        Ok(reactive_instance.into())
301    }
302}