Skip to main content

allsource_core/domain/value_objects/
entity_id.rs

1use crate::error::Result;
2use serde::{Deserialize, Serialize};
3use std::fmt;
4
5/// Value Object: EntityId
6///
7/// Represents a unique identifier for an entity in the event sourcing system.
8/// Entities are the subjects of events (e.g., user-123, order-456, product-789).
9///
10/// Domain Rules:
11/// - Cannot be empty
12/// - Must be between 1 and 128 characters
13/// - Flexible format (allows any printable characters except whitespace)
14/// - Case-sensitive
15/// - Immutable once created
16///
17/// This is a Value Object:
18/// - Defined by its value, not identity
19/// - Immutable
20/// - Self-validating
21/// - Compared by value equality
22#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
23pub struct EntityId(String);
24
25impl EntityId {
26    pub(crate) fn heap_capacity(&self) -> usize {
27        self.0.capacity()
28    }
29
30    /// Create a new EntityId with validation
31    ///
32    /// # Errors
33    /// Returns error if:
34    /// - ID is empty
35    /// - ID is longer than 128 characters
36    /// - ID contains only whitespace
37    /// - ID contains control characters
38    ///
39    /// # Examples
40    /// ```
41    /// use allsource_core::domain::value_objects::EntityId;
42    ///
43    /// let entity_id = EntityId::new("user-123".to_string()).unwrap();
44    /// assert_eq!(entity_id.as_str(), "user-123");
45    ///
46    /// let entity_id = EntityId::new("order_ABC-456".to_string()).unwrap();
47    /// assert_eq!(entity_id.as_str(), "order_ABC-456");
48    /// ```
49    pub fn new(value: String) -> Result<Self> {
50        Self::validate(&value)?;
51        Ok(Self(value))
52    }
53
54    /// Create EntityId without validation (for internal use, e.g., from trusted storage)
55    ///
56    /// # Safety
57    /// This bypasses validation. Only use when loading from trusted sources
58    /// where validation has already occurred.
59    pub(crate) fn new_unchecked(value: String) -> Self {
60        Self(value)
61    }
62
63    /// Get the string value
64    pub fn as_str(&self) -> &str {
65        &self.0
66    }
67
68    /// Get the inner String (consumes self)
69    pub fn into_inner(self) -> String {
70        self.0
71    }
72
73    /// Check if this entity ID starts with a specific prefix
74    ///
75    /// # Examples
76    /// ```
77    /// use allsource_core::domain::value_objects::EntityId;
78    ///
79    /// let entity_id = EntityId::new("user-123".to_string()).unwrap();
80    /// assert!(entity_id.starts_with("user-"));
81    /// assert!(!entity_id.starts_with("order-"));
82    /// ```
83    pub fn starts_with(&self, prefix: &str) -> bool {
84        self.0.starts_with(prefix)
85    }
86
87    /// Check if this entity ID ends with a specific suffix
88    ///
89    /// # Examples
90    /// ```
91    /// use allsource_core::domain::value_objects::EntityId;
92    ///
93    /// let entity_id = EntityId::new("user-123".to_string()).unwrap();
94    /// assert!(entity_id.ends_with("-123"));
95    /// assert!(!entity_id.ends_with("-456"));
96    /// ```
97    pub fn ends_with(&self, suffix: &str) -> bool {
98        self.0.ends_with(suffix)
99    }
100
101    /// Extract a prefix before a delimiter (if present)
102    ///
103    /// # Examples
104    /// ```
105    /// use allsource_core::domain::value_objects::EntityId;
106    ///
107    /// let entity_id = EntityId::new("user-123".to_string()).unwrap();
108    /// assert_eq!(entity_id.prefix('-'), Some("user"));
109    ///
110    /// let entity_id = EntityId::new("simple".to_string()).unwrap();
111    /// assert_eq!(entity_id.prefix('-'), None);
112    /// ```
113    pub fn prefix(&self, delimiter: char) -> Option<&str> {
114        self.0
115            .split(delimiter)
116            .next()
117            .filter(|_| self.0.contains(delimiter))
118    }
119
120    /// Validate an entity ID string
121    fn validate(value: &str) -> Result<()> {
122        // Rule: Cannot be empty
123        if value.is_empty() {
124            return Err(crate::error::AllSourceError::InvalidInput(
125                "Entity ID cannot be empty".to_string(),
126            ));
127        }
128
129        // Rule: Maximum length 128 characters
130        if value.len() > 128 {
131            return Err(crate::error::AllSourceError::InvalidInput(format!(
132                "Entity ID cannot exceed 128 characters, got {}",
133                value.len()
134            )));
135        }
136
137        // Rule: No control characters (check before whitespace checks)
138        if value.chars().any(char::is_control) {
139            return Err(crate::error::AllSourceError::InvalidInput(
140                "Entity ID cannot contain control characters".to_string(),
141            ));
142        }
143
144        // Rule: Cannot be only whitespace
145        if value.trim().is_empty() {
146            return Err(crate::error::AllSourceError::InvalidInput(
147                "Entity ID cannot be only whitespace".to_string(),
148            ));
149        }
150
151        // Rule: No leading/trailing whitespace
152        if value != value.trim() {
153            return Err(crate::error::AllSourceError::InvalidInput(
154                "Entity ID cannot have leading or trailing whitespace".to_string(),
155            ));
156        }
157
158        Ok(())
159    }
160}
161
162// Implement Display for ergonomic string conversion
163impl fmt::Display for EntityId {
164    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165        write!(f, "{}", self.0)
166    }
167}
168
169// Implement From<&str> for convenience
170impl TryFrom<&str> for EntityId {
171    type Error = crate::error::AllSourceError;
172
173    fn try_from(value: &str) -> Result<Self> {
174        EntityId::new(value.to_string())
175    }
176}
177
178// Implement From<String> for convenience
179impl TryFrom<String> for EntityId {
180    type Error = crate::error::AllSourceError;
181
182    fn try_from(value: String) -> Result<Self> {
183        EntityId::new(value)
184    }
185}
186
187#[cfg(test)]
188mod tests {
189    use super::*;
190
191    #[test]
192    fn test_create_valid_entity_ids() {
193        // Simple alphanumeric
194        let entity_id = EntityId::new("user123".to_string());
195        assert!(entity_id.is_ok());
196        assert_eq!(entity_id.unwrap().as_str(), "user123");
197
198        // With hyphen
199        let entity_id = EntityId::new("user-123".to_string());
200        assert!(entity_id.is_ok());
201
202        // With underscore
203        let entity_id = EntityId::new("user_123".to_string());
204        assert!(entity_id.is_ok());
205
206        // Complex format
207        let entity_id = EntityId::new("order_ABC-456-XYZ".to_string());
208        assert!(entity_id.is_ok());
209
210        // UUID format
211        let entity_id = EntityId::new("550e8400-e29b-41d4-a716-446655440000".to_string());
212        assert!(entity_id.is_ok());
213
214        // With special characters (allowed)
215        let entity_id = EntityId::new("entity:123@domain".to_string());
216        assert!(entity_id.is_ok());
217    }
218
219    #[test]
220    fn test_reject_empty_entity_id() {
221        let result = EntityId::new(String::new());
222        assert!(result.is_err());
223
224        if let Err(e) = result {
225            assert!(e.to_string().contains("cannot be empty"));
226        }
227    }
228
229    #[test]
230    fn test_reject_whitespace_only() {
231        let result = EntityId::new("   ".to_string());
232        assert!(result.is_err());
233
234        if let Err(e) = result {
235            assert!(e.to_string().contains("cannot be only whitespace"));
236        }
237    }
238
239    #[test]
240    fn test_reject_leading_trailing_whitespace() {
241        // Leading whitespace
242        let result = EntityId::new(" user-123".to_string());
243        assert!(result.is_err());
244
245        // Trailing whitespace
246        let result = EntityId::new("user-123 ".to_string());
247        assert!(result.is_err());
248
249        // Both
250        let result = EntityId::new(" user-123 ".to_string());
251        assert!(result.is_err());
252
253        if let Err(e) = EntityId::new(" test ".to_string()) {
254            assert!(e.to_string().contains("leading or trailing whitespace"));
255        }
256    }
257
258    #[test]
259    fn test_reject_too_long_entity_id() {
260        // Create a 129-character string (exceeds max of 128)
261        let long_id = "a".repeat(129);
262        let result = EntityId::new(long_id);
263        assert!(result.is_err());
264
265        if let Err(e) = result {
266            assert!(e.to_string().contains("cannot exceed 128 characters"));
267        }
268    }
269
270    #[test]
271    fn test_accept_max_length_entity_id() {
272        // Exactly 128 characters should be OK
273        let max_id = "a".repeat(128);
274        let result = EntityId::new(max_id);
275        assert!(result.is_ok());
276    }
277
278    #[test]
279    fn test_reject_control_characters() {
280        // Newline
281        let result = EntityId::new("user\n123".to_string());
282        assert!(result.is_err());
283
284        // Tab
285        let result = EntityId::new("user\t123".to_string());
286        assert!(result.is_err());
287
288        // Null byte
289        let result = EntityId::new("user\x00123".to_string());
290        assert!(result.is_err());
291
292        if let Err(e) = EntityId::new("test\n".to_string()) {
293            assert!(e.to_string().contains("control characters"));
294        }
295    }
296
297    #[test]
298    fn test_starts_with() {
299        let entity_id = EntityId::new("user-123".to_string()).unwrap();
300        assert!(entity_id.starts_with("user-"));
301        assert!(entity_id.starts_with("user"));
302        assert!(!entity_id.starts_with("order-"));
303    }
304
305    #[test]
306    fn test_ends_with() {
307        let entity_id = EntityId::new("user-123".to_string()).unwrap();
308        assert!(entity_id.ends_with("-123"));
309        assert!(entity_id.ends_with("123"));
310        assert!(!entity_id.ends_with("-456"));
311    }
312
313    #[test]
314    fn test_prefix_extraction() {
315        let entity_id = EntityId::new("user-123".to_string()).unwrap();
316        assert_eq!(entity_id.prefix('-'), Some("user"));
317
318        let entity_id = EntityId::new("order_ABC_456".to_string()).unwrap();
319        assert_eq!(entity_id.prefix('_'), Some("order"));
320
321        // No delimiter
322        let entity_id = EntityId::new("simple".to_string()).unwrap();
323        assert_eq!(entity_id.prefix('-'), None);
324    }
325
326    #[test]
327    fn test_display_trait() {
328        let entity_id = EntityId::new("user-123".to_string()).unwrap();
329        assert_eq!(format!("{entity_id}"), "user-123");
330    }
331
332    #[test]
333    fn test_try_from_str() {
334        let entity_id: Result<EntityId> = "order-456".try_into();
335        assert!(entity_id.is_ok());
336        assert_eq!(entity_id.unwrap().as_str(), "order-456");
337
338        let invalid: Result<EntityId> = "".try_into();
339        assert!(invalid.is_err());
340    }
341
342    #[test]
343    fn test_try_from_string() {
344        let entity_id: Result<EntityId> = "product-789".to_string().try_into();
345        assert!(entity_id.is_ok());
346
347        let invalid: Result<EntityId> = String::new().try_into();
348        assert!(invalid.is_err());
349    }
350
351    #[test]
352    fn test_into_inner() {
353        let entity_id = EntityId::new("test-entity".to_string()).unwrap();
354        let inner = entity_id.into_inner();
355        assert_eq!(inner, "test-entity");
356    }
357
358    #[test]
359    fn test_equality() {
360        let id1 = EntityId::new("entity-a".to_string()).unwrap();
361        let id2 = EntityId::new("entity-a".to_string()).unwrap();
362        let id3 = EntityId::new("entity-b".to_string()).unwrap();
363
364        // Value equality
365        assert_eq!(id1, id2);
366        assert_ne!(id1, id3);
367    }
368
369    #[test]
370    fn test_cloning() {
371        let id1 = EntityId::new("entity".to_string()).unwrap();
372        let id2 = id1.clone();
373        assert_eq!(id1, id2);
374    }
375
376    #[test]
377    fn test_hash_consistency() {
378        use std::collections::HashSet;
379
380        let id1 = EntityId::new("entity-123".to_string()).unwrap();
381        let id2 = EntityId::new("entity-123".to_string()).unwrap();
382
383        let mut set = HashSet::new();
384        set.insert(id1);
385
386        // Should find the same value (value equality)
387        assert!(set.contains(&id2));
388    }
389
390    #[test]
391    fn test_serde_serialization() {
392        let entity_id = EntityId::new("user-123".to_string()).unwrap();
393
394        // Serialize
395        let json = serde_json::to_string(&entity_id).unwrap();
396        assert_eq!(json, "\"user-123\"");
397
398        // Deserialize
399        let deserialized: EntityId = serde_json::from_str(&json).unwrap();
400        assert_eq!(deserialized, entity_id);
401    }
402
403    #[test]
404    fn test_new_unchecked() {
405        // Should create without validation (for internal use)
406        let entity_id = EntityId::new_unchecked("invalid\nid".to_string());
407        assert_eq!(entity_id.as_str(), "invalid\nid");
408    }
409}