reactive_graph_graph/instances/flows/
flow_instance.rs

1use std::borrow::Cow;
2use std::cmp::Ordering;
3use std::fmt::Display;
4use std::fmt::Formatter;
5use std::hash::Hash;
6use std::hash::Hasher;
7use std::ops::Deref;
8use std::ops::DerefMut;
9
10use const_format::formatcp;
11use dashmap::DashMap;
12use dashmap::iter::OwningIter;
13use schemars::JsonSchema;
14use schemars::Schema;
15use schemars::SchemaGenerator;
16use schemars::json_schema;
17use serde::Deserialize;
18use serde::Deserializer;
19use serde::Serialize;
20use serde::Serializer;
21use typed_builder::TypedBuilder;
22use uuid::Uuid;
23
24use crate::EntityInstance;
25use crate::EntityInstances;
26use crate::EntityTypeId;
27use crate::JSON_SCHEMA_ID_URI_PREFIX;
28use crate::NAMESPACE_SEPARATOR;
29use crate::NamedInstanceContainer;
30use crate::Namespace;
31use crate::NamespaceSegment;
32use crate::NamespacedType;
33use crate::NamespacedTypeGetter;
34use crate::RelationInstances;
35use crate::TypeDefinition;
36use crate::TypeDefinitionGetter;
37use crate::TypeIdType;
38
39#[cfg(any(test, feature = "test"))]
40use crate::EntityType;
41#[cfg(any(test, feature = "test"))]
42use crate::NamespacedTypeError;
43#[cfg(any(test, feature = "test"))]
44use crate::RandomInstance;
45#[cfg(any(test, feature = "test"))]
46use crate::RandomInstances;
47#[cfg(any(test, feature = "test"))]
48use crate::RandomNamespacedType;
49#[cfg(any(test, feature = "test"))]
50use crate::RandomNamespacedTypeId;
51#[cfg(any(test, feature = "test"))]
52use rand::Rng;
53#[cfg(any(test, feature = "test"))]
54use reactive_graph_utils_test::DefaultFrom;
55#[cfg(any(test, feature = "test"))]
56use reactive_graph_utils_test::DefaultTryFrom;
57
58pub const JSON_SCHEMA_ID_FLOW_INSTANCE: &str = formatcp!("{}/flow-instance.schema.json", JSON_SCHEMA_ID_URI_PREFIX);
59
60/// A flow instance is a container for entity instances and relation instances.
61///
62/// A flow instance is strictly associated with a wrapper entity instance. The properties
63/// of the wrapper entity instance are the properties of the flow.
64///
65/// Additionally, flows can be nested -  from the perspective of the outer flow
66/// the inner flow acts like an entity instance. The wrapper entity instance of
67/// the inner flow is the interface which can be accessed by the outer flow.
68///
69/// Entity instances and relation instances can be shared with multiple flows.
70///
71/// It's even possible to connect entity instances from different flows with relation
72/// instances.
73///
74#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize, JsonSchema, TypedBuilder)]
75#[serde(tag = "$id", rename = "https://schema.reactive-graph.io/schema/json/flow-instance.schema.json")]
76#[schemars(
77    title = "FlowInstance",
78    deny_unknown_fields,
79    extend("$id" = JSON_SCHEMA_ID_FLOW_INSTANCE),
80    transform = add_json_schema_id_property
81)]
82pub struct FlowInstance {
83    /// The id of the flow corresponds to the id of the wrapper entity instance
84    ///
85    /// This means the vector of entity instances must contain an instance with
86    /// the id of the flow.
87    pub id: Uuid,
88
89    /// The type definition of the entity type of the wrapper entity instance.
90    #[serde(rename = "type")]
91    #[builder(setter(into))]
92    pub ty: EntityTypeId,
93
94    /// The name of the flow instance.
95    #[serde(default = "String::new")]
96    #[builder(default, setter(into))]
97    pub name: String,
98
99    /// Textual description of the flow instance.
100    #[serde(default = "String::new")]
101    #[builder(default, setter(into))]
102    pub description: String,
103
104    /// The entity instances which are contained in this flow instance.
105    ///
106    /// It can't have a default because the wrapper entity instance must be
107    /// present in the list of entities.
108    #[serde(default = "EntityInstances::new", alias = "entities")]
109    #[builder(default, setter(into))]
110    pub entity_instances: EntityInstances,
111
112    /// The relation instances which are contained in this flow instance.
113    ///
114    /// By default, no relation instances are contained in this flow instance.
115    #[serde(default = "RelationInstances::new", alias = "relations")]
116    #[builder(default, setter(into))]
117    pub relation_instances: RelationInstances,
118}
119
120impl FlowInstance {
121    /// Constructs a new flow instance from the wrapper entity instance.
122    pub fn from_instance_with_name<S: Into<String>>(wrapper_entity_instance: EntityInstance, name: S) -> FlowInstance {
123        FlowInstance {
124            id: wrapper_entity_instance.id,
125            ty: wrapper_entity_instance.ty.clone(),
126            name: name.into(),
127            description: String::new(),
128            entity_instances: EntityInstances::new_with_instance(wrapper_entity_instance),
129            relation_instances: RelationInstances::new(),
130        }
131    }
132}
133
134impl NamedInstanceContainer for FlowInstance {
135    fn name(&self) -> String {
136        self.name.clone()
137    }
138
139    fn description(&self) -> String {
140        self.description.clone()
141    }
142}
143
144impl From<EntityInstance> for FlowInstance {
145    fn from(wrapper_entity_instance: EntityInstance) -> FlowInstance {
146        FlowInstance {
147            id: wrapper_entity_instance.id,
148            ty: wrapper_entity_instance.ty.clone(),
149            name: String::new(),
150            description: String::new(),
151            entity_instances: EntityInstances::new_with_instance(wrapper_entity_instance),
152            relation_instances: RelationInstances::new(),
153        }
154    }
155}
156
157impl NamespacedTypeGetter for FlowInstance {
158    fn namespaced_type(&self) -> NamespacedType {
159        self.ty.namespaced_type()
160    }
161
162    fn namespace(&self) -> Namespace {
163        self.ty.namespace()
164    }
165
166    fn path(&self) -> Namespace {
167        self.ty.path()
168    }
169
170    fn type_name(&self) -> NamespaceSegment {
171        self.ty.type_name()
172    }
173}
174
175impl TypeDefinitionGetter for FlowInstance {
176    fn type_definition(&self) -> TypeDefinition {
177        self.ty.type_definition()
178    }
179
180    fn type_id_type() -> TypeIdType {
181        TypeIdType::FlowType
182    }
183}
184impl PartialEq<Uuid> for FlowInstance {
185    fn eq(&self, id: &Uuid) -> bool {
186        self.id == *id
187    }
188}
189
190impl PartialOrd<Self> for FlowInstance {
191    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
192        Some(self.cmp(other))
193    }
194}
195
196impl Ord for FlowInstance {
197    fn cmp(&self, other: &Self) -> Ordering {
198        self.id.cmp(&other.id)
199    }
200}
201
202impl Display for FlowInstance {
203    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
204        write!(f, "{}{}{}", &self.ty, NAMESPACE_SEPARATOR, self.id)
205    }
206}
207
208#[derive(Clone, Debug, Default)]
209pub struct FlowInstances(DashMap<Uuid, FlowInstance>);
210
211impl FlowInstances {
212    pub fn new() -> Self {
213        FlowInstances(DashMap::new())
214    }
215
216    pub fn new_with_instance<E: Into<FlowInstance>>(flow_instance: E) -> Self {
217        let flow_instances = FlowInstances::new();
218        flow_instances.push(flow_instance.into());
219        flow_instances
220    }
221
222    pub fn push<E: Into<FlowInstance>>(&self, flow_instance: E) {
223        let flow_instance = flow_instance.into();
224        self.0.insert(flow_instance.id, flow_instance);
225    }
226
227    pub fn to_vec(&self) -> Vec<FlowInstance> {
228        let mut items: Vec<_> = self.iter().map(|item| item.value().clone()).collect();
229        items.sort();
230        items
231    }
232
233    // TODO: deduplicate?
234    // pub fn get_type_ids(&self) -> FlowTypeIds {
235    //     self.iter().map(|flow_instance| flow_instance.ty.clone()).collect()
236    // }
237}
238
239impl Deref for FlowInstances {
240    type Target = DashMap<Uuid, FlowInstance>;
241
242    fn deref(&self) -> &Self::Target {
243        &self.0
244    }
245}
246
247impl DerefMut for FlowInstances {
248    fn deref_mut(&mut self) -> &mut Self::Target {
249        &mut self.0
250    }
251}
252
253impl IntoIterator for FlowInstances {
254    type Item = (Uuid, FlowInstance);
255    type IntoIter = OwningIter<Uuid, FlowInstance>;
256
257    fn into_iter(self) -> Self::IntoIter {
258        self.0.into_iter()
259    }
260}
261
262impl PartialEq for FlowInstances {
263    fn eq(&self, other: &Self) -> bool {
264        self.0.iter().all(|self_flow_instance| other.contains_key(&self_flow_instance.id))
265            && other.iter().all(|other_flow_instance| self.contains_key(&other_flow_instance.id))
266    }
267}
268
269impl Eq for FlowInstances {}
270
271impl Hash for FlowInstances {
272    fn hash<H: Hasher>(&self, state: &mut H) {
273        self.to_vec().hash(state);
274    }
275}
276
277impl Serialize for FlowInstances {
278    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
279    where
280        S: Serializer,
281    {
282        serializer.collect_seq(self.iter())
283    }
284}
285
286impl<'de> Deserialize<'de> for FlowInstances {
287    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
288    where
289        D: Deserializer<'de>,
290    {
291        Ok(Vec::<FlowInstance>::deserialize(deserializer)?.into())
292    }
293}
294
295impl JsonSchema for FlowInstances {
296    fn schema_name() -> Cow<'static, str> {
297        "FlowInstances".into()
298    }
299
300    fn json_schema(schema_generator: &mut SchemaGenerator) -> Schema {
301        let sub_schema: Schema = schema_generator.subschema_for::<FlowInstance>();
302        json_schema!({
303            "type": "array",
304            "items": sub_schema,
305            "description": "Flow Instances",
306        })
307    }
308}
309
310impl From<Vec<FlowInstance>> for FlowInstances {
311    fn from(flow_instances: Vec<FlowInstance>) -> Self {
312        Self(flow_instances.into_iter().map(|flow_instance| (flow_instance.id, flow_instance)).collect())
313    }
314}
315
316impl From<FlowInstances> for Vec<FlowInstance> {
317    fn from(flow_instances: FlowInstances) -> Self {
318        flow_instances.to_vec()
319    }
320}
321
322impl From<&FlowInstances> for Vec<FlowInstance> {
323    fn from(flow_instances: &FlowInstances) -> Self {
324        flow_instances.0.iter().map(|flow_instance| flow_instance.clone()).collect()
325    }
326}
327
328impl From<DashMap<Uuid, FlowInstance>> for FlowInstances {
329    fn from(flow_instances: DashMap<Uuid, FlowInstance>) -> Self {
330        Self(flow_instances)
331    }
332}
333
334impl From<&DashMap<Uuid, FlowInstance>> for FlowInstances {
335    fn from(flow_instances: &DashMap<Uuid, FlowInstance>) -> Self {
336        Self(flow_instances.clone())
337    }
338}
339
340impl From<FlowInstances> for DashMap<Uuid, FlowInstance> {
341    fn from(flow_instances: FlowInstances) -> Self {
342        flow_instances.0
343    }
344}
345
346impl FromIterator<FlowInstance> for FlowInstances {
347    fn from_iter<I: IntoIterator<Item = FlowInstance>>(iter: I) -> Self {
348        let flow_instances = Self::new();
349        for flow_instance in iter {
350            flow_instances.insert(flow_instance.id, flow_instance);
351        }
352        flow_instances
353    }
354}
355
356#[cfg(any(test, feature = "test"))]
357impl RandomInstance for FlowInstance {
358    type Error = NamespacedTypeError;
359    type TypeId = EntityTypeId;
360
361    fn random_instance() -> Result<Self, NamespacedTypeError> {
362        Self::random_instance_with_id(&EntityTypeId::random_type_id()?)
363    }
364
365    fn random_instance_with_id(ty: &Self::TypeId) -> Result<Self, Self::Error> {
366        let entity_type = EntityType::random_type_with_id(ty)?;
367        let wrapper_entity_instance = EntityInstance::default_try_from(&entity_type)?;
368        let id = wrapper_entity_instance.id;
369
370        let entity_instances = EntityInstances::random_instances()?;
371        entity_instances.push(wrapper_entity_instance);
372
373        Ok(FlowInstance::builder()
374            .ty(entity_type.ty.clone())
375            .id(id)
376            .entity_instances(entity_instances)
377            .build())
378    }
379}
380
381#[cfg(any(test, feature = "test"))]
382impl DefaultTryFrom<&EntityType> for FlowInstance {
383    type Error = NamespacedTypeError;
384
385    fn default_try_from(entity_type: &EntityType) -> Result<Self, NamespacedTypeError> {
386        let wrapper_entity_instance = EntityInstance::default_try_from(entity_type)?;
387        Ok(Self::default_from(&wrapper_entity_instance))
388    }
389}
390
391#[cfg(any(test, feature = "test"))]
392impl DefaultFrom<&EntityInstance> for FlowInstance {
393    fn default_from(wrapper_entity_instance: &EntityInstance) -> Self {
394        FlowInstance::from(wrapper_entity_instance.clone())
395    }
396}
397
398#[cfg(any(test, feature = "test"))]
399impl RandomInstances for FlowInstances {
400    type Error = NamespacedTypeError;
401
402    fn random_instances() -> Result<Self, NamespacedTypeError> {
403        let instances = Self::new();
404        let mut rng = rand::rng();
405        for _ in 0..rng.random_range(0..10) {
406            instances.push(FlowInstance::random_instance()?);
407        }
408        Ok(instances)
409    }
410}
411
412fn add_json_schema_id_property(schema: &mut Schema) {
413    crate::json_schema::add_json_schema_id_property(schema, JSON_SCHEMA_ID_FLOW_INSTANCE);
414}
415
416#[cfg(test)]
417mod tests {
418    use schemars::schema_for;
419    use uuid::Uuid;
420
421    use crate::EntityInstance;
422    use crate::EntityInstances;
423    use crate::EntityTypeId;
424    use crate::FlowInstance;
425    use crate::NamespacedTypeGetter;
426    use crate::RandomInstance;
427    use crate::RandomNamespacedTypeId;
428    use crate::RelationInstances;
429    use reactive_graph_utils_test::r_string;
430
431    #[test]
432    fn flow_instance_test() {
433        let flow_id = Uuid::new_v4();
434        let flow_name = r_string();
435        let flow_description = r_string();
436
437        let ty = EntityTypeId::random_type_id().unwrap();
438        let flow_instance = FlowInstance {
439            id: flow_id,
440            ty: ty.clone(),
441            name: flow_name.clone(),
442            description: flow_description.to_string(),
443            entity_instances: EntityInstances::new(),
444            relation_instances: RelationInstances::new(),
445        };
446
447        assert_eq!(ty.namespace(), flow_instance.namespace());
448        assert_eq!(ty.path(), flow_instance.path());
449        assert_eq!(ty.type_name(), flow_instance.type_name());
450        assert_eq!(flow_id.clone(), flow_instance.id.clone());
451        assert_eq!(flow_name.clone(), flow_instance.name.clone());
452        assert_eq!(flow_description.clone(), flow_instance.description.clone());
453        assert_eq!(0, flow_instance.entity_instances.len());
454        assert_eq!(0, flow_instance.relation_instances.len());
455    }
456
457    #[test]
458    fn flow_instance_from_entity_instance_test() {
459        let wrapper_entity_instance = EntityInstance::random_instance().unwrap();
460        let wrapper_type = wrapper_entity_instance.ty.clone();
461        let flow_instance = FlowInstance::from(wrapper_entity_instance.clone());
462        assert_eq!(wrapper_type, flow_instance.ty);
463        assert_eq!(wrapper_type.namespace(), flow_instance.namespace());
464        assert_eq!(wrapper_type.path(), flow_instance.path());
465        assert_eq!(wrapper_type.type_name(), flow_instance.type_name());
466        assert_eq!(wrapper_entity_instance.id, flow_instance.id);
467        assert_eq!(String::new(), flow_instance.name);
468    }
469
470    #[test]
471    fn flow_instance_from_entity_instance_with_name_test() {
472        let wrapper_entity_instance = EntityInstance::random_instance().unwrap();
473        let wrapper_type = wrapper_entity_instance.ty.clone();
474        let flow_name = r_string();
475        let flow_instance = FlowInstance::from_instance_with_name(wrapper_entity_instance.clone(), flow_name.clone());
476        assert_eq!(wrapper_type, flow_instance.ty);
477        assert_eq!(wrapper_type.namespace(), flow_instance.namespace());
478        assert_eq!(wrapper_type.path(), flow_instance.path());
479        assert_eq!(wrapper_type.type_name(), flow_instance.type_name());
480        assert_eq!(wrapper_entity_instance.id, flow_instance.id);
481        assert_eq!(flow_name, flow_instance.name);
482    }
483
484    #[test]
485    fn flow_instance_json_schema() {
486        let schema = schema_for!(FlowInstance);
487        println!("{}", serde_json::to_string_pretty(&schema).unwrap());
488    }
489}