reactive_graph_graph/instances/relations/
instance_id.rs

1use schemars::JsonSchema;
2use serde::Deserialize;
3use serde::Serialize;
4use std::fmt::Display;
5use std::fmt::Formatter;
6use std::str::FromStr;
7use thiserror::Error;
8use uuid::Uuid;
9
10use crate::NamespaceSegment;
11use crate::NamespaceSegmentError;
12
13/// Separator for the string representation of a property connector.
14pub static INSTANCE_ID_SEPARATOR: &str = "__";
15
16#[derive(Debug, Error, PartialEq)]
17pub enum InstanceIdError {
18    #[error("The instance id {0} is invalid")]
19    InvalidInstanceId(String),
20    #[error("The instance id is invalid: {0}")]
21    NamespaceSegmentError(#[from] NamespaceSegmentError),
22    #[error("At least one segment is required")]
23    AtLeastOneSegmentRequired,
24    #[error("Named instance ids must not contain the instance id separator")]
25    MustNotContainDelimiter,
26    #[error("Named instance ids must not be empty")]
27    NamedInstanceIdMustNotBeEmpty,
28}
29
30#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, JsonSchema)]
31#[serde(into = "String", try_from = "String")]
32pub enum InstanceId {
33    Singleton,
34    Id(Uuid),
35    Named(NamespaceSegment),
36    MultiSegmented(Vec<NamespaceSegment>),
37}
38
39impl InstanceId {
40    pub fn new_singleton() -> Self {
41        InstanceId::Singleton
42    }
43
44    pub fn new_with_id(id: Uuid) -> Self {
45        InstanceId::Id(id)
46    }
47
48    pub fn new_with_random_id() -> Self {
49        InstanceId::Id(Uuid::new_v4())
50    }
51
52    pub fn new_segmented(segments: Vec<NamespaceSegment>) -> Result<Self, InstanceIdError> {
53        if segments.is_empty() {
54            return Err(InstanceIdError::AtLeastOneSegmentRequired);
55        }
56        if segments.len() == 1
57            && let Some(segment) = segments.first()
58        {
59            return Ok(InstanceId::Named(segment.clone()));
60        }
61        Ok(InstanceId::MultiSegmented(segments))
62    }
63
64    pub fn parse_named(instance_id: &str) -> Result<Self, InstanceIdError> {
65        if instance_id.is_empty() {
66            return Err(InstanceIdError::NamedInstanceIdMustNotBeEmpty);
67        }
68        if instance_id.contains(INSTANCE_ID_SEPARATOR) {
69            return Err(InstanceIdError::MustNotContainDelimiter);
70        }
71        Ok(InstanceId::Named(NamespaceSegment::from_str(instance_id).map_err(InstanceIdError::NamespaceSegmentError)?))
72    }
73}
74
75impl Display for InstanceId {
76    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
77        let id = match self {
78            InstanceId::Singleton => "".to_string(),
79            InstanceId::Id(id) => id.to_string(),
80            InstanceId::Named(name) => name.to_string(),
81            InstanceId::MultiSegmented(segments) => segments.iter().map(ToString::to_string).collect::<Vec<_>>().join(INSTANCE_ID_SEPARATOR),
82        };
83        write!(f, "{id}")
84    }
85}
86
87impl From<InstanceId> for String {
88    fn from(instance_id: InstanceId) -> Self {
89        instance_id.to_string()
90    }
91}
92
93impl FromStr for InstanceId {
94    type Err = InstanceIdError;
95
96    fn from_str(instance_id: &str) -> Result<Self, Self::Err> {
97        if instance_id.is_empty() {
98            return Ok(InstanceId::Singleton);
99        }
100        if let Ok(id) = Uuid::parse_str(instance_id) {
101            return Ok(InstanceId::Id(id));
102        }
103        if !instance_id.contains(INSTANCE_ID_SEPARATOR) {
104            return Ok(InstanceId::Named(NamespaceSegment::from_str(instance_id).map_err(InstanceIdError::NamespaceSegmentError)?));
105            // let instance_id = NamespaceSegment::from_str(instance_id).map_err(InstanceIdError::NamespaceSegmentError)?;
106        }
107        // let instance_id = NamespaceSegment::from_str(instance_id).map_err(InstanceIdError::NamespaceSegmentError)?;
108        // if !instance_id.as_ref().contains(INSTANCE_ID_SEPARATOR) {
109        //     return Ok(InstanceId::Named(instance_id));
110        // }
111        let mut segments = vec![];
112        for segment in instance_id.split(INSTANCE_ID_SEPARATOR) {
113            segments.push(NamespaceSegment::from_str(segment).map_err(|e| InstanceIdError::NamespaceSegmentError(e))?);
114        }
115        Ok(InstanceId::MultiSegmented(segments))
116    }
117}
118
119// Required because of #[serde(try_from = "String")]
120impl TryFrom<String> for InstanceId {
121    type Error = InstanceIdError;
122
123    fn try_from(instance_id: String) -> Result<Self, Self::Error> {
124        Self::from_str(instance_id.as_str())
125    }
126}
127
128#[cfg(test)]
129mod tests {
130    use super::InstanceId;
131    use super::InstanceIdError;
132    use crate::NamespaceSegment;
133    use crate::NamespaceSegmentError;
134    use std::str::FromStr;
135    use uuid::Uuid;
136
137    #[test]
138    fn new_singleton_test() {
139        let instance_id = InstanceId::Singleton;
140        assert_eq!("".to_string(), instance_id.to_string());
141        assert_eq!(InstanceId::Singleton, InstanceId::from_str("").expect("Failed to parse empty instance id"));
142    }
143
144    #[test]
145    fn new_with_id_test() {
146        let uuid = Uuid::new_v4();
147        let instance_id = InstanceId::new_with_id(uuid);
148        let uuid_2 = Uuid::parse_str(&instance_id.to_string()).expect("Failed to parse UUID from instance id ");
149        assert_eq!(uuid, uuid_2);
150    }
151
152    #[test]
153    fn new_with_random_id_test() {
154        let instance_id = InstanceId::new_with_random_id();
155        let uuid = Uuid::parse_str(&instance_id.to_string()).expect("Failed to parse UUID from instance id ");
156        assert_eq!(uuid.to_string(), format!("{instance_id}"));
157    }
158
159    #[test]
160    fn new_segmented_test() {
161        assert_eq!(Err(InstanceIdError::AtLeastOneSegmentRequired), InstanceId::new_segmented(vec![]));
162        let instance_id = InstanceId::new_segmented(vec![NamespaceSegment::from_str("asdf").unwrap()]).unwrap();
163        assert_eq!("asdf", format!("{instance_id}"));
164        let instance_id = InstanceId::new_segmented(vec![NamespaceSegment::from_str("asdf").unwrap(), NamespaceSegment::from_str("asdf").unwrap()]).unwrap();
165        assert_eq!("asdf__asdf", format!("{instance_id}"));
166        let instance_id = InstanceId::new_segmented(vec![
167            NamespaceSegment::from_str("asdf").unwrap(),
168            NamespaceSegment::from_str("asdf").unwrap(),
169            NamespaceSegment::from_str("asdf").unwrap(),
170        ])
171        .unwrap();
172        assert_eq!("asdf__asdf__asdf", format!("{instance_id}"));
173    }
174
175    #[test]
176    fn parse_named_test() {
177        assert_eq!("asdf", InstanceId::parse_named("asdf").unwrap().to_string());
178        assert_eq!("asdf_asdf", InstanceId::parse_named("asdf_asdf").unwrap().to_string());
179        assert_eq!(Err(InstanceIdError::MustNotContainDelimiter), InstanceId::parse_named("asdf__asdf"));
180        assert_eq!(
181            Err(InstanceIdError::NamespaceSegmentError(NamespaceSegmentError::MustNotContainDelimiter(
182                "asdf::asdf".to_string()
183            ))),
184            InstanceId::parse_named("asdf::asdf")
185        );
186    }
187}