reactive_graph_graph/types/extensions/
extension.rs

1use serde_json::json;
2use std::cmp::Ordering;
3use std::hash::Hash;
4use std::hash::Hasher;
5use std::ops::Deref;
6use std::ops::DerefMut;
7
8use dashmap::DashMap;
9use dashmap::iter::OwningIter;
10use schemars::JsonSchema;
11use schemars::Schema;
12use schemars::SchemaGenerator;
13use schemars::json_schema;
14use schemars::schema_for;
15use serde::Deserialize;
16use serde::Deserializer;
17use serde::Serialize;
18use serde::Serializer;
19use serde_json::Value;
20use std::borrow::Cow;
21use typed_builder::TypedBuilder;
22
23use crate::AddExtensionError;
24use crate::EntityType;
25use crate::EntityTypeId;
26use crate::ExtensionContainer;
27use crate::ExtensionJsonSchemaError;
28use crate::ExtensionTypeId;
29use crate::ExtensionTypeIds;
30use crate::JsonSchemaIdGetter;
31use crate::Namespace;
32use crate::NamespaceSegment;
33use crate::NamespacedType;
34use crate::NamespacedTypeContainer;
35use crate::NamespacedTypeGetter;
36use crate::RemoveExtensionError;
37use crate::TypeDefinition;
38use crate::TypeDefinitionGetter;
39use crate::TypeDescriptionGetter;
40use crate::TypeIdType;
41use crate::UpdateExtensionError;
42use schemars::consts::meta_schemas::DRAFT2020_12;
43
44#[cfg(any(test, feature = "test"))]
45use crate::NamespacedTypeError;
46#[cfg(any(test, feature = "test"))]
47use crate::PropertyInstances;
48#[cfg(any(test, feature = "test"))]
49use crate::PropertyTypes;
50#[cfg(any(test, feature = "test"))]
51use crate::RandomNamespacedType;
52#[cfg(any(test, feature = "test"))]
53use crate::RandomNamespacedTypeId;
54#[cfg(any(test, feature = "test"))]
55use reactive_graph_utils_test::DefaultFrom;
56#[cfg(any(test, feature = "test"))]
57use reactive_graph_utils_test::r_string;
58#[cfg(any(test, feature = "table"))]
59use tabled::Tabled;
60
61/// Extension on a type. The extension allows to extend information
62#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema, TypedBuilder)]
63#[cfg_attr(any(test, feature = "table"), derive(Tabled))]
64pub struct Extension {
65    /// The fully qualified namespace of the extension.
66    #[serde(rename = "type")]
67    #[schemars(required)]
68    #[builder(setter(into))]
69    #[cfg_attr(any(test, feature = "table"), tabled(rename = "Type", inline))]
70    pub ty: ExtensionTypeId,
71
72    /// The fully qualified namespace of the entity type which is the type constraint of the extension.
73    #[serde(rename = "entity_type")]
74    #[builder(default, setter(into))]
75    #[cfg_attr(any(test, feature = "table"), tabled(rename = "EntityType", inline))]
76    pub entity_ty: Option<EntityTypeId>,
77
78    /// Textual description of the extension.
79    #[serde(default = "String::new")]
80    #[builder(default, setter(into))]
81    #[cfg_attr(any(test, feature = "table"), tabled(rename = "Description"))]
82    pub description: String,
83
84    /// The extension as JSON representation.
85    #[cfg_attr(any(test, feature = "table"), tabled(skip))]
86    pub extension: Value,
87}
88
89impl Extension {
90    /// Constructs an extension from the given namespaced type with the given description, components, properties and extensions.
91    pub fn new<T: Into<ExtensionTypeId>, S: Into<String>>(ty: T, description: S, extension: Value) -> Extension {
92        Extension {
93            ty: ty.into(),
94            entity_ty: None,
95            description: description.into(),
96            extension,
97        }
98    }
99
100    /// Constructs an extension from the given namespaced type with the given description, components, properties and extensions.
101    pub fn new_with_type_constraint<T: Into<ExtensionTypeId>, ET: Into<EntityTypeId>, S: Into<String>>(
102        ty: T,
103        entity_ty: ET,
104        description: S,
105        extension: Value,
106    ) -> Extension {
107        Extension {
108            ty: ty.into(),
109            entity_ty: Some(entity_ty.into()),
110            description: description.into(),
111            extension,
112        }
113    }
114
115    pub fn json_schema(&self, entity_type: &EntityType) -> Result<Schema, ExtensionJsonSchemaError> {
116        let Some(entity_ty) = &self.entity_ty else {
117            return Err(ExtensionJsonSchemaError::NoSchemaEntityType(self.ty.clone()));
118        };
119        if &entity_type.ty != entity_ty {
120            return Err(ExtensionJsonSchemaError::SchemaEntityTypeDoesNotMatch(
121                self.ty.clone(),
122                entity_ty.clone(),
123                entity_type.ty.clone(),
124            ));
125        }
126
127        let mut schema = schema_for!(Extension);
128        let Some(json_schema) = schema.as_object_mut() else {
129            return Err(ExtensionJsonSchemaError::SchemaModificationError);
130        };
131
132        json_schema.insert("$id".to_string(), self.json_schema_id().into());
133
134        let Some(extension_properties) = json_schema.get_mut("properties").and_then(|p| p.as_object_mut()) else {
135            return Err(ExtensionJsonSchemaError::SchemaModificationError);
136        };
137
138        let mut entity_type_properties = entity_type.properties.as_json_schema_properties();
139        entity_type_properties.insert("$id".to_string(), self.json_schema_id_property());
140        let mut required = entity_type.properties.names();
141        required.sort();
142        extension_properties.insert(
143            "extension".to_string(),
144            json!({
145                "$schema": DRAFT2020_12,
146                "$id": entity_type.json_schema_id(),
147                "type": "object",
148                "title": entity_type.type_name(),
149                "description": entity_type.description(),
150                "properties": entity_type_properties,
151                "required": required,
152            }),
153        );
154        Ok(schema)
155    }
156}
157
158impl NamespacedTypeGetter for Extension {
159    fn namespaced_type(&self) -> NamespacedType {
160        self.ty.namespaced_type()
161    }
162
163    fn namespace(&self) -> Namespace {
164        self.ty.namespace()
165    }
166
167    fn path(&self) -> Namespace {
168        self.ty.path()
169    }
170
171    fn type_name(&self) -> NamespaceSegment {
172        self.ty.type_name()
173    }
174}
175
176impl TypeDefinitionGetter for Extension {
177    fn type_definition(&self) -> TypeDefinition {
178        self.ty.type_definition()
179    }
180
181    fn type_id_type() -> TypeIdType {
182        TypeIdType::Extension
183    }
184}
185
186impl TypeDescriptionGetter for Extension {
187    fn description(&self) -> String {
188        self.description.clone()
189    }
190}
191
192impl From<&Extension> for TypeDefinition {
193    fn from(extension: &Extension) -> Self {
194        extension.type_definition()
195    }
196}
197
198impl AsRef<ExtensionTypeId> for Extension {
199    fn as_ref(&self) -> &ExtensionTypeId {
200        &self.ty
201    }
202}
203
204impl PartialEq<ExtensionTypeId> for Extension {
205    fn eq(&self, ty: &ExtensionTypeId) -> bool {
206        self.ty == *ty
207    }
208}
209
210impl PartialOrd<Self> for Extension {
211    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
212        Some(self.cmp(other))
213    }
214}
215
216impl Ord for Extension {
217    fn cmp(&self, other: &Self) -> Ordering {
218        self.ty.cmp(&other.ty)
219    }
220}
221
222impl Hash for Extension {
223    fn hash<H: Hasher>(&self, state: &mut H) {
224        self.ty.hash(state);
225        self.description.hash(state);
226        // Ignore the extension content (for now)
227        // let ext_str = serde_json::to_string(&self.extension);
228        // ext_str.hash(state);
229    }
230}
231
232#[derive(Clone, Debug, Default)]
233pub struct Extensions(DashMap<ExtensionTypeId, Extension>);
234
235impl Extensions {
236    #[inline]
237    pub fn new() -> Self {
238        NamespacedTypeContainer::new()
239    }
240
241    #[inline]
242    pub fn push<E: Into<Extension>>(&self, extension: E) -> Option<Extension> {
243        NamespacedTypeContainer::push(self, extension)
244    }
245
246    pub fn extension<E: Into<Extension>>(self, extension: E) -> Self {
247        self.push(extension);
248        self
249    }
250}
251
252impl ExtensionContainer for Extensions {
253    fn has_own_extension(&self, ty: &ExtensionTypeId) -> bool {
254        self.0.contains_key(ty)
255    }
256
257    fn get_own_extension(&self, ty: &ExtensionTypeId) -> Option<Extension> {
258        self.0.get(ty).map(|e| e.value().clone())
259    }
260
261    fn add_extension<E: Into<Extension>>(&self, extension: E) -> Result<ExtensionTypeId, AddExtensionError> {
262        let extension = extension.into();
263        let ty = extension.ty.clone();
264        if self.0.contains_key(&ty) {
265            return Err(AddExtensionError::ExtensionAlreadyExist(ty));
266        }
267        self.push(extension);
268        Ok(ty)
269    }
270
271    fn update_extension<T: Into<ExtensionTypeId>, E: Into<Extension>>(&self, ty: T, extension: E) -> Result<Extension, UpdateExtensionError> {
272        let ty = ty.into();
273        if !self.0.contains_key(&ty) {
274            return Err(UpdateExtensionError::ExtensionDoesNotExist(ty));
275        }
276        let _ = self.0.remove(&ty);
277        let extension = extension.into();
278        self.push(extension.clone());
279        Ok(extension)
280    }
281
282    fn remove_extension<T: Into<ExtensionTypeId>>(&self, ty: T) -> Result<Extension, RemoveExtensionError> {
283        let ty = ty.into();
284        self.0
285            .remove(&ty)
286            .map(|(_, extension)| extension)
287            .ok_or(RemoveExtensionError::ExtensionDoesNotExist(ty))
288    }
289
290    fn merge_extensions<E: Into<Extensions>>(&mut self, extensions_to_merge: E) {
291        let extensions_to_merge = extensions_to_merge.into();
292        for (ty, extension_to_merge) in extensions_to_merge {
293            if !self.0.contains_key(&ty) {
294                self.push(extension_to_merge);
295            } else if let Some(mut existing_extension) = self.0.get_mut(&ty) {
296                existing_extension.description = extension_to_merge.description.clone();
297                existing_extension.extension = extension_to_merge.extension.clone();
298            }
299        }
300    }
301
302    fn get_own_extensions_cloned(&self) -> Extensions {
303        self.clone()
304    }
305}
306
307impl NamespacedTypeContainer for Extensions {
308    type TypeId = ExtensionTypeId;
309    type TypeIds = ExtensionTypeIds;
310    type Type = Extension;
311}
312
313impl Deref for Extensions {
314    type Target = DashMap<ExtensionTypeId, Extension>;
315
316    fn deref(&self) -> &Self::Target {
317        &self.0
318    }
319}
320
321impl DerefMut for Extensions {
322    fn deref_mut(&mut self) -> &mut Self::Target {
323        &mut self.0
324    }
325}
326
327impl IntoIterator for Extensions {
328    type Item = (ExtensionTypeId, Extension);
329    type IntoIter = OwningIter<ExtensionTypeId, Extension>;
330
331    fn into_iter(self) -> Self::IntoIter {
332        self.0.into_iter()
333    }
334}
335
336impl PartialEq for Extensions {
337    fn eq(&self, other: &Self) -> bool {
338        self.iter().all(|self_extension| {
339            other
340                .get(self_extension.key())
341                .filter(|other_extension| other_extension.value() == self_extension.value())
342                .is_some()
343        }) && other.iter().all(|other_extension| {
344            self.get(other_extension.key())
345                .filter(|self_extension| self_extension.value() == other_extension.value())
346                .is_some()
347        })
348    }
349}
350
351impl Eq for Extensions {}
352
353impl Hash for Extensions {
354    fn hash<H: Hasher>(&self, hasher: &mut H) {
355        self.to_vec().iter().for_each(|extension| {
356            // extension.name.hash(hasher);
357            extension.hash(hasher);
358            // TODO: hash extension.extension
359        });
360    }
361}
362
363impl Serialize for Extensions {
364    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
365    where
366        S: Serializer,
367    {
368        serializer.collect_seq(self.iter())
369    }
370}
371
372impl<'de> Deserialize<'de> for Extensions {
373    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
374    where
375        D: Deserializer<'de>,
376    {
377        Ok(Vec::<Extension>::deserialize(deserializer)?.into())
378    }
379}
380
381impl JsonSchema for Extensions {
382    fn schema_name() -> Cow<'static, str> {
383        "Extensions".into()
384    }
385
386    fn json_schema(schema_generator: &mut SchemaGenerator) -> Schema {
387        let sub_schema: Schema = schema_generator.subschema_for::<Extension>();
388        json_schema!({
389            "type": "array",
390            "items": sub_schema,
391            "description": "Extensions",
392        })
393    }
394}
395
396impl From<Vec<Extension>> for Extensions {
397    fn from(extensions: Vec<Extension>) -> Self {
398        extensions.into_iter().collect()
399    }
400}
401
402impl From<Extensions> for Vec<Extension> {
403    fn from(extensions: Extensions) -> Self {
404        extensions.to_vec()
405        // extensions.into_iter().map(|(_, extension)| extension).collect()
406    }
407}
408
409impl From<&Extensions> for Vec<Extension> {
410    fn from(extensions: &Extensions) -> Self {
411        extensions.0.iter().map(|extension| extension.clone()).collect()
412    }
413}
414
415impl From<DashMap<ExtensionTypeId, Extension>> for Extensions {
416    fn from(extensions: DashMap<ExtensionTypeId, Extension>) -> Self {
417        Self(extensions)
418    }
419}
420
421impl From<&DashMap<ExtensionTypeId, Extension>> for Extensions {
422    fn from(extensions: &DashMap<ExtensionTypeId, Extension>) -> Self {
423        Self(extensions.clone())
424    }
425}
426
427impl From<Extensions> for DashMap<ExtensionTypeId, Extension> {
428    fn from(extensions: Extensions) -> Self {
429        extensions.0
430    }
431}
432
433impl FromIterator<Extension> for Extensions {
434    fn from_iter<I: IntoIterator<Item = Extension>>(iter: I) -> Self {
435        let extensions = Extensions::new();
436        for extension in iter {
437            extensions.push(extension);
438        }
439        extensions
440    }
441}
442
443#[cfg(any(test, feature = "test"))]
444impl RandomNamespacedType for Extension {
445    type Error = NamespacedTypeError;
446    type TypeId = ExtensionTypeId;
447
448    fn random_type() -> Result<Self, NamespacedTypeError> {
449        Self::random_type_with_id(&ExtensionTypeId::random_type_id()?)
450    }
451
452    fn random_type_with_id(ty: &Self::TypeId) -> Result<Self, Self::Error> {
453        let entity_ty = if rand::random_bool(0.2) {
454            Some(EntityTypeId::random_type_id()?)
455        } else {
456            None
457        };
458        let extension = match &entity_ty {
459            None => json!(r_string()),
460            Some(entity_ty) => {
461                let property_types = PropertyTypes::random_types_no_extensions();
462                let property_instances = PropertyInstances::default_from(&property_types).property("$id", entity_ty.json_schema_id());
463                json!(property_instances)
464            }
465        };
466        Ok(Extension::builder()
467            .ty(ty)
468            .entity_ty(entity_ty)
469            .description(r_string())
470            .extension(extension)
471            .build())
472    }
473}
474
475#[cfg(test)]
476mod tests {
477    use crate::EntityInstance;
478    use crate::EntityType;
479    use crate::EntityTypeId;
480    use crate::Extension;
481    use crate::ExtensionTypeId;
482    use crate::NamespacedTypeGetter;
483    use crate::RandomNamespacedType;
484    use crate::RandomNamespacedTypeId;
485    use reactive_graph_utils_test::DefaultTryFrom;
486    use reactive_graph_utils_test::r_string;
487    use schemars::schema_for;
488    use serde_json::json;
489
490    #[test]
491    fn build_extension_without_entity_type() {
492        let description = r_string();
493        let ty = ExtensionTypeId::random_type_id().unwrap();
494        let extension = Extension::builder()
495            .ty(&ty)
496            .description(&description)
497            .extension(json!({
498                "hello": "World"
499            }))
500            .build();
501        assert_eq!(ty.namespace(), extension.namespace());
502        assert_eq!(ty.path(), extension.path());
503        assert_eq!(ty.type_name(), extension.type_name());
504        assert_eq!(description, extension.description);
505        assert_eq!(None, extension.entity_ty);
506    }
507
508    #[test]
509    fn build_extension_with_entity_type() {
510        let description = r_string();
511        let ty = ExtensionTypeId::random_type_id().unwrap();
512        let entity_type = EntityType::random_type().unwrap();
513        let extension_payload = EntityInstance::default_try_from(&entity_type).unwrap();
514        let extension_value = serde_json::to_value(&extension_payload).unwrap();
515        let extension = Extension::builder()
516            .ty(&ty)
517            .description(&description)
518            .entity_ty(Some(entity_type.ty.clone()))
519            .extension(extension_value.clone())
520            .build();
521        assert_eq!(ty.namespace(), extension.namespace());
522        assert_eq!(ty.path(), extension.path());
523        assert_eq!(ty.type_name(), extension.type_name());
524        assert_eq!(description, extension.description);
525        assert_eq!(Some(entity_type.ty), extension.entity_ty);
526        assert_eq!(extension_value, extension.extension);
527        assert_eq!(extension_payload, serde_json::from_value::<EntityInstance>(extension.extension).unwrap());
528    }
529
530    #[test]
531    fn create_extension() {
532        let ty = ExtensionTypeId::random_type_id().unwrap();
533        let description = r_string();
534        let json = json!({
535            "hello": "World"
536        });
537        let extension = Extension::new(&ty, &description, json.clone());
538        assert_eq!(ty.namespace(), extension.namespace());
539        assert_eq!(ty.path(), extension.path());
540        assert_eq!(ty.type_name(), extension.type_name());
541        assert_eq!(None, extension.entity_ty);
542        assert_eq!(description, extension.description);
543        assert_eq!(json, extension.extension);
544    }
545
546    #[test]
547    fn create_extension_with_type_constraint() {
548        let ty = ExtensionTypeId::random_type_id().unwrap();
549        let entity_ty = EntityTypeId::random_type_id().unwrap();
550        let description = r_string();
551        let json = json!({
552            "hello": "World"
553        });
554        let extension = Extension::new_with_type_constraint(&ty, &entity_ty, &description, json.clone());
555        assert_eq!(ty.namespace(), extension.namespace());
556        assert_eq!(ty.path(), extension.path());
557        assert_eq!(ty.type_name(), extension.type_name());
558        assert_eq!(Some(entity_ty), extension.entity_ty);
559        assert_eq!(description, extension.description);
560        assert_eq!(json, extension.extension);
561    }
562
563    #[test]
564    fn extension_json_schema() {
565        let schema = schema_for!(Extension);
566        println!("{}", serde_json::to_string_pretty(&schema).unwrap());
567    }
568
569    #[test]
570    fn extension_dynamic_json_schema() {
571        let description = r_string();
572        let ty = ExtensionTypeId::random_type_id().unwrap();
573        let entity_type = EntityType::random_type().unwrap();
574        let extension_payload = EntityInstance::default_try_from(&entity_type).unwrap();
575        let extension_value = serde_json::to_value(&extension_payload).unwrap();
576        let extension = Extension::builder()
577            .ty(&ty)
578            .description(&description)
579            .entity_ty(Some(entity_type.ty.clone()))
580            .extension(extension_value.clone())
581            .build();
582        let schema = extension
583            .json_schema(&entity_type)
584            .expect("Failed to generate dynamic json schema for extension!");
585        println!("{}", serde_json::to_string_pretty(schema.as_value()).unwrap());
586    }
587}