reactive_graph_graphql_schema/mutation/instances/
flow_instance.rs

1use std::str::FromStr;
2use std::sync::Arc;
3
4use async_graphql::Context;
5use async_graphql::Object;
6use async_graphql::Result;
7use uuid::Uuid;
8
9use reactive_graph_graph::CreateFlowInstanceError;
10use reactive_graph_graph::EntityTypeId;
11use reactive_graph_graph::FlowInstance;
12use reactive_graph_graph::FlowTypeId;
13use reactive_graph_graph::RelationInstanceId;
14use reactive_graph_reactive_model_impl::ReactiveFlow;
15use reactive_graph_reactive_service_api::ReactiveEntityManager;
16use reactive_graph_reactive_service_api::ReactiveFlowManager;
17use reactive_graph_reactive_service_api::ReactiveRelationManager;
18use reactive_graph_type_system_api::EntityTypeManager;
19use reactive_graph_type_system_api::FlowTypeManager;
20use reactive_graph_type_system_api::RelationTypeManager;
21
22use crate::error::flow::FlowMutationError;
23use crate::mutation::GraphQLFlowInstanceDefinition;
24use crate::mutation::GraphQLRelationInstanceId;
25use crate::query::GraphQLFlowInstance;
26use crate::query::GraphQLPropertyInstance;
27use crate::validator::NamespacedTypeValidator;
28
29#[derive(Default)]
30pub struct MutationFlowInstances;
31
32/// Mutations for flows and their contained instances.
33#[Object]
34impl MutationFlowInstances {
35    /// Creates a new flow and a corresponding wrapper entity instance.
36    ///
37    /// The given entity type must exist. It provides the properties for the wrapper entity instance
38    /// and therefore defines which properties of the flow are the inputs and outputs.
39    ///
40    /// Optionally, a UUID can be specified.
41    ///
42    /// Optionally, the initial values of the properties can be specified. Specified properties
43    /// which are not provided by the given entity type are lacking of a definition (data type,
44    /// socket type).
45    async fn create(
46        &self,
47        context: &Context<'_>,
48        #[graphql(
49            name = "type",
50            desc = "The fully qualified namespace of the entity type",
51            validator(custom = "NamespacedTypeValidator::new()")
52        )]
53        _type: String,
54        #[graphql(desc = "The unique identifier of the flow instance and the wrapper entity instance")] flow_id: Option<Uuid>,
55        #[graphql(desc = "The properties of the flow instance and the wrapper entity instance")] properties: Option<Vec<GraphQLPropertyInstance>>,
56    ) -> Result<GraphQLFlowInstance> {
57        let reactive_flow_manager = context.data::<Arc<dyn ReactiveFlowManager + Send + Sync>>()?;
58        let entity_type_manager = context.data::<Arc<dyn EntityTypeManager + Send + Sync>>()?;
59        let reactive_entity_manager = context.data::<Arc<dyn ReactiveEntityManager + Send + Sync>>()?;
60
61        let entity_ty = EntityTypeId::from_str(&_type)?;
62        let entity_type = entity_type_manager
63            .get(&entity_ty)
64            .ok_or(CreateFlowInstanceError::EntityTypeDoesNotExist(entity_ty.clone()))?;
65
66        if let Some(flow_id) = flow_id {
67            if reactive_flow_manager.has(flow_id) {
68                return Err(CreateFlowInstanceError::FlowAlreadyExists(flow_id).into());
69            }
70            if reactive_entity_manager.has(flow_id) {
71                return Err(CreateFlowInstanceError::WrapperEntityInstanceAlreadyExists(flow_id).into());
72            }
73        }
74
75        let properties = GraphQLPropertyInstance::to_property_instances_with_defaults(properties, entity_type.properties);
76
77        let reactive_entity = match flow_id {
78            Some(id) => reactive_entity_manager.create_with_id(&entity_ty, id, properties),
79            None => reactive_entity_manager.create_reactive_entity(&entity_ty, properties),
80        }?;
81
82        let flow_instance = ReactiveFlow::new(reactive_entity);
83        reactive_flow_manager.register_flow_instance(flow_instance.clone());
84
85        Ok(flow_instance.into())
86    }
87
88    /// Creates a new flow from the given type.
89    ///
90    /// The corresponding wrapper entity instance will be created with the type.
91    ///
92    /// The given entity type must exist. It provides the properties for the wrapper entity instance
93    /// and therefore defines which properties of the flow are the inputs and outputs.
94    ///
95    /// Optionally, an UUID can be specified.
96    ///
97    /// Optionally, the initial values of the properties can be specified. Specified properties
98    /// which are not provided by the given entity type are lacking of a definition (data type,
99    /// socket type).
100    async fn create_from_type(
101        &self,
102        context: &Context<'_>,
103        #[graphql(
104            name = "type",
105            desc = "The fully qualified namespace of the flow type.",
106            validator(custom = "NamespacedTypeValidator::new()")
107        )]
108        _type: String,
109        id: Option<Uuid>,
110        #[graphql(desc = "Parametrized construction of a flow instance using variables of a flow type.")] variables: Option<Vec<GraphQLPropertyInstance>>,
111        #[graphql(desc = "A list of properties of the wrapper entity instance.")] properties: Option<Vec<GraphQLPropertyInstance>>,
112    ) -> Result<GraphQLFlowInstance> {
113        let entity_type_manager = context.data::<Arc<dyn EntityTypeManager + Send + Sync>>()?;
114        let flow_type_manager = context.data::<Arc<dyn FlowTypeManager + Send + Sync>>()?;
115        let reactive_flow_manager = context.data::<Arc<dyn ReactiveFlowManager + Send + Sync>>()?;
116
117        let flow_ty = FlowTypeId::from_str(&_type)?;
118
119        let Some(flow_type) = flow_type_manager.get(&flow_ty) else {
120            return Err(FlowMutationError::MissingFlowType(flow_ty.clone()).into());
121        };
122
123        let entity_ty = flow_type.wrapper_type();
124        let Some(entity_type) = entity_type_manager.get(&entity_ty) else {
125            return Err(FlowMutationError::MissingEntityType(entity_ty).into());
126        };
127
128        let variables = GraphQLPropertyInstance::to_property_instances_with_defaults(variables, flow_type.variables);
129        let properties = GraphQLPropertyInstance::to_property_instances_with_defaults(properties, entity_type.properties);
130
131        let flow_instance = reactive_flow_manager.create_from_type(&flow_ty, id, variables, properties)?;
132        Ok(flow_instance.into())
133    }
134
135    // /// Manually ticks all entity instances and relation instances of this flow. This means, for
136    // /// each property of each entity instance and relation instance the corresponding reactive
137    // /// stream will be activated with it's last value.
138    // ///
139    // /// This leads to a recalculation if the instance is controlled by an behaviour which
140    // /// consumes the reactive streams.
141    // ///
142    // /// In case of entity instances, it furthermore leads to a new value propagation if the output
143    // /// property is connected to other properties.
144    // async fn commit(&self, context: &Context<'_>, id: Uuid) -> Result<GraphQLFlowInstance> {
145    //     let reactive_flow_manager = context.data::<Arc<dyn ReactiveFlowManager + Send + Sync>>()?;
146    //     let reactive_flow = reactive_flow_manager.get(id);
147    //     if reactive_flow.is_none() {
148    //         return Err(FlowMutationError::MissingFlow(id).into());
149    //     }
150    //     let reactive_flow: ReactiveFlow = reactive_flow.unwrap();
151    //     reactive_flow_manager.commit(reactive_flow.id);
152    //     Ok(reactive_flow.into())
153    // }
154
155    /// Creates a new entity instance and adds the entity instance to the given flow by id.
156    async fn create_entity(
157        &self,
158        context: &Context<'_>,
159        flow_id: Uuid,
160        #[graphql(
161            name = "type",
162            desc = "The fully qualified namespace of the entity type.",
163            validator(custom = "NamespacedTypeValidator::new()")
164        )]
165        _type: String,
166        entity_id: Option<Uuid>,
167        properties: Option<Vec<GraphQLPropertyInstance>>,
168    ) -> Result<GraphQLFlowInstance> {
169        let reactive_flow_manager = context.data::<Arc<dyn ReactiveFlowManager + Send + Sync>>()?;
170        let entity_type_manager = context.data::<Arc<dyn EntityTypeManager + Send + Sync>>()?;
171        let reactive_entity_manager = context.data::<Arc<dyn ReactiveEntityManager + Send + Sync>>()?;
172
173        let Some(reactive_flow) = reactive_flow_manager.get(flow_id) else {
174            return Err(FlowMutationError::MissingFlow(flow_id).into());
175        };
176
177        let entity_ty = EntityTypeId::from_str(&_type)?;
178        let Some(entity_type) = entity_type_manager.get(&entity_ty) else {
179            return Err(FlowMutationError::MissingEntityType(entity_ty).into());
180        };
181
182        let properties = GraphQLPropertyInstance::to_property_instances_with_defaults(properties, entity_type.properties);
183
184        let Ok(reactive_entity) = (match entity_id {
185            Some(id) => reactive_entity_manager.create_with_id(&entity_ty, id, properties),
186            None => reactive_entity_manager.create_reactive_entity(&entity_ty, properties),
187        }) else {
188            return Err(FlowMutationError::EntityInstanceCreationError().into());
189        };
190        reactive_flow.add_entity(reactive_entity);
191        Ok(reactive_flow.into())
192    }
193
194    /// Adds an existing entity instance by id to the given flow by id
195    async fn add_entity(&self, context: &Context<'_>, flow_id: Uuid, entity_id: Uuid) -> Result<GraphQLFlowInstance> {
196        let reactive_flow_manager = context.data::<Arc<dyn ReactiveFlowManager + Send + Sync>>()?;
197        let reactive_entity_manager = context.data::<Arc<dyn ReactiveEntityManager + Send + Sync>>()?;
198        let Some(reactive_flow) = reactive_flow_manager.get(flow_id) else {
199            return Err(FlowMutationError::MissingFlow(flow_id).into());
200        };
201        let Some(reactive_entity) = reactive_entity_manager.get(entity_id) else {
202            return Err(FlowMutationError::MissingEntityInstance(entity_id).into());
203        };
204        reactive_flow.add_entity(reactive_entity);
205        // No commit necessary _> The reactive entity  is registered in the reactive_entity_manager
206        Ok(reactive_flow.into())
207    }
208
209    /// Removes an entity instance from flow.
210    async fn remove_entity(&self, context: &Context<'_>, flow_id: Uuid, entity_id: Uuid) -> Result<GraphQLFlowInstance> {
211        let reactive_flow_manager = context.data::<Arc<dyn ReactiveFlowManager + Send + Sync>>()?;
212        let reactive_entity_manager = context.data::<Arc<dyn ReactiveEntityManager + Send + Sync>>()?;
213
214        let flow_instance = reactive_flow_manager.get(flow_id);
215        if flow_instance.is_none() {
216            return Err(FlowMutationError::MissingFlow(flow_id).into());
217        }
218        let flow_instance = flow_instance.unwrap();
219
220        let entity_instance = reactive_entity_manager.get(entity_id);
221        if entity_instance.is_none() {
222            return Err(FlowMutationError::MissingEntityInstance(entity_id).into());
223        }
224        let entity_instance = entity_instance.unwrap();
225
226        if !flow_instance.has_entity_by_id(entity_id) {
227            return Err(FlowMutationError::FlowInstanceDoesNotContainEntityInstance(entity_id).into());
228        }
229
230        flow_instance.remove_entity(entity_instance.id);
231        // The entity is removed from the flow but not yet deleted
232        // TODO: How to handle this? It may be that a entity is used in multiple flows?
233        // Orphaned instances / Do not delete instances used in other flows?
234
235        Ok(flow_instance.into())
236    }
237
238    /// Creates a new relation instance and adds the relation instance to the given flow by id.
239    async fn create_relation(
240        &self,
241        context: &Context<'_>,
242        flow_id: Uuid,
243        relation_instance_id: GraphQLRelationInstanceId,
244        properties: Option<Vec<GraphQLPropertyInstance>>,
245    ) -> Result<GraphQLFlowInstance> {
246        let reactive_flow_manager = context.data::<Arc<dyn ReactiveFlowManager + Send + Sync>>()?;
247        let relation_type_manager = context.data::<Arc<dyn RelationTypeManager + Send + Sync>>()?;
248        let reactive_relation_manager = context.data::<Arc<dyn ReactiveRelationManager + Send + Sync>>()?;
249
250        let relation_instance_id = RelationInstanceId::try_from(relation_instance_id)?;
251        let relation_ty = relation_instance_id.ty.relation_type_id();
252
253        let relation_type = relation_type_manager
254            .get(&relation_ty)
255            .ok_or::<FlowMutationError>(FlowMutationError::MissingRelationType(relation_ty))?;
256
257        let flow_instance = reactive_flow_manager
258            .get(flow_id)
259            .ok_or::<FlowMutationError>(FlowMutationError::MissingFlow(flow_id))?;
260
261        if !flow_instance.has_entity_by_id(relation_instance_id.outbound_id) {
262            return Err(FlowMutationError::MissingOutboundEntityInstance(relation_instance_id.outbound_id).into());
263        }
264
265        if !flow_instance.has_entity_by_id(relation_instance_id.inbound_id) {
266            return Err(FlowMutationError::MissingInboundEntityInstance(relation_instance_id.inbound_id).into());
267        }
268
269        // TODO: optionally we could check if the reactive_entity_manager contains the outbound_id and inbound_id
270
271        let properties = GraphQLPropertyInstance::to_property_instances_with_defaults(properties, relation_type.properties);
272
273        let relation_instance = reactive_relation_manager.create_reactive_relation(&relation_instance_id, properties);
274
275        if relation_instance.is_err() {
276            return Err(FlowMutationError::RelationInstanceCreationError().into());
277        }
278
279        let relation_instance = relation_instance.unwrap();
280
281        // Add relation to flow
282        flow_instance.add_relation(relation_instance);
283
284        Ok(flow_instance.into())
285    }
286
287    /// Adds an existing relation instance by relation_instance_id to the given flow by id
288    async fn add_relation(&self, context: &Context<'_>, flow_id: Uuid, relation_instance_id: GraphQLRelationInstanceId) -> Result<GraphQLFlowInstance> {
289        let reactive_flow_manager = context.data::<Arc<dyn ReactiveFlowManager + Send + Sync>>()?;
290        let reactive_relation_manager = context.data::<Arc<dyn ReactiveRelationManager + Send + Sync>>()?;
291
292        let flow_instance = reactive_flow_manager.get(flow_id);
293        if flow_instance.is_none() {
294            return Err(FlowMutationError::MissingFlow(flow_id).into());
295        }
296        let flow_instance = flow_instance.unwrap();
297
298        let relation_instance_id = RelationInstanceId::try_from(relation_instance_id)?;
299        let relation_instance = reactive_relation_manager.get(&relation_instance_id);
300        if relation_instance.is_none() {
301            return Err(FlowMutationError::MissingRelationInstance(relation_instance_id).into());
302        }
303        let relation_instance = relation_instance.unwrap();
304
305        flow_instance.add_relation(relation_instance);
306
307        Ok(flow_instance.into())
308    }
309
310    /// Removes an existing relation instance by relation_instance_id from the given flow by id
311    async fn remove_relation(&self, context: &Context<'_>, flow_id: Uuid, relation_instance_id: GraphQLRelationInstanceId) -> Result<GraphQLFlowInstance> {
312        let reactive_flow_manager = context.data::<Arc<dyn ReactiveFlowManager + Send + Sync>>()?;
313
314        let flow_instance = reactive_flow_manager.get(flow_id);
315        if flow_instance.is_none() {
316            return Err(FlowMutationError::MissingFlow(flow_id).into());
317        }
318        let flow_instance = flow_instance.unwrap();
319
320        let relation_instance_id = RelationInstanceId::try_from(relation_instance_id)?;
321
322        if !flow_instance.has_relation_by_key(&relation_instance_id) {
323            return Err(FlowMutationError::FlowInstanceDoesNotContainRelationInstance(relation_instance_id).into());
324        }
325
326        flow_instance.remove_relation(&relation_instance_id);
327        // The relation is removed from flow, but not yet deleted
328        // TODO: How to handle this? It may be that a relation is used in multiple flows?
329        // Orphaned instances / Do not delete instances used in other flows?
330
331        Ok(flow_instance.into())
332    }
333
334    async fn delete(&self, context: &Context<'_>, #[graphql(desc = "The id of the entity instance")] id: Uuid) -> Result<bool> {
335        let reactive_flow_manager = context.data::<Arc<dyn ReactiveFlowManager + Send + Sync>>()?;
336        Ok(reactive_flow_manager.delete(id))
337    }
338
339    /// Imports the given flow. Creates entity instances and relation instances which are contained
340    /// in the given flow.
341    async fn import(&self, context: &Context<'_>, flow: GraphQLFlowInstanceDefinition) -> Result<GraphQLFlowInstance> {
342        let reactive_flow_manager = context.data::<Arc<dyn ReactiveFlowManager + Send + Sync>>()?;
343        let flow_instance = FlowInstance::try_from(flow)?;
344        let reactive_flow = reactive_flow_manager.create_reactive_flow(flow_instance)?;
345        Ok(reactive_flow.into())
346    }
347}