Skip to main content

allsource_core/domain/value_objects/
article_id.rs

1use crate::error::Result;
2use serde::{Deserialize, Serialize};
3use std::fmt;
4
5/// Value Object: ArticleId
6///
7/// Represents a unique identifier for an article in the paywall system.
8/// Articles are identified by a slug or URL-safe identifier provided by the creator.
9///
10/// Domain Rules:
11/// - Cannot be empty
12/// - Must be between 1 and 256 characters
13/// - Must be URL-safe (alphanumeric, hyphens, underscores only)
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 ArticleId(String);
24
25impl ArticleId {
26    /// Create a new ArticleId with validation
27    ///
28    /// # Errors
29    /// Returns error if:
30    /// - ID is empty
31    /// - ID is longer than 256 characters
32    /// - ID contains invalid characters (only a-z, A-Z, 0-9, -, _ allowed)
33    ///
34    /// # Examples
35    /// ```
36    /// use allsource_core::domain::value_objects::ArticleId;
37    ///
38    /// let article_id = ArticleId::new("my-awesome-article".to_string()).unwrap();
39    /// assert_eq!(article_id.as_str(), "my-awesome-article");
40    /// ```
41    pub fn new(value: String) -> Result<Self> {
42        Self::validate(&value)?;
43        Ok(Self(value))
44    }
45
46    /// Create ArticleId without validation (for internal use, e.g., from trusted storage)
47    ///
48    /// # Safety
49    /// This bypasses validation. Only use when loading from trusted sources
50    /// where validation has already occurred.
51    pub(crate) fn new_unchecked(value: String) -> Self {
52        Self(value)
53    }
54
55    /// Get the string value
56    pub fn as_str(&self) -> &str {
57        &self.0
58    }
59
60    /// Get the inner String (consumes self)
61    pub fn into_inner(self) -> String {
62        self.0
63    }
64
65    /// Check if this article ID starts with a specific prefix
66    pub fn starts_with(&self, prefix: &str) -> bool {
67        self.0.starts_with(prefix)
68    }
69
70    /// Check if this article ID ends with a specific suffix
71    pub fn ends_with(&self, suffix: &str) -> bool {
72        self.0.ends_with(suffix)
73    }
74
75    /// Validate an article ID string
76    fn validate(value: &str) -> Result<()> {
77        // Rule: Cannot be empty
78        if value.is_empty() {
79            return Err(crate::error::AllSourceError::InvalidInput(
80                "Article ID cannot be empty".to_string(),
81            ));
82        }
83
84        // Rule: Maximum length 256 characters
85        if value.len() > 256 {
86            return Err(crate::error::AllSourceError::InvalidInput(format!(
87                "Article ID cannot exceed 256 characters, got {}",
88                value.len()
89            )));
90        }
91
92        // Rule: URL-safe characters only (alphanumeric, hyphens, underscores)
93        if !value
94            .chars()
95            .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
96        {
97            return Err(crate::error::AllSourceError::InvalidInput(format!(
98                "Article ID '{value}' contains invalid characters. Only alphanumeric, hyphens, and underscores allowed"
99            )));
100        }
101
102        Ok(())
103    }
104}
105
106impl fmt::Display for ArticleId {
107    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108        write!(f, "{}", self.0)
109    }
110}
111
112impl TryFrom<&str> for ArticleId {
113    type Error = crate::error::AllSourceError;
114
115    fn try_from(value: &str) -> Result<Self> {
116        ArticleId::new(value.to_string())
117    }
118}
119
120impl TryFrom<String> for ArticleId {
121    type Error = crate::error::AllSourceError;
122
123    fn try_from(value: String) -> Result<Self> {
124        ArticleId::new(value)
125    }
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131
132    #[test]
133    fn test_create_valid_article_ids() {
134        // Simple alphanumeric
135        let article_id = ArticleId::new("article123".to_string());
136        assert!(article_id.is_ok());
137        assert_eq!(article_id.unwrap().as_str(), "article123");
138
139        // With hyphens
140        let article_id = ArticleId::new("my-awesome-article".to_string());
141        assert!(article_id.is_ok());
142
143        // With underscores
144        let article_id = ArticleId::new("my_awesome_article".to_string());
145        assert!(article_id.is_ok());
146
147        // Mixed case
148        let article_id = ArticleId::new("MyAwesomeArticle".to_string());
149        assert!(article_id.is_ok());
150
151        // Complex format
152        let article_id = ArticleId::new("how-to-scale-to-1M-users_2024".to_string());
153        assert!(article_id.is_ok());
154    }
155
156    #[test]
157    fn test_reject_empty_article_id() {
158        let result = ArticleId::new(String::new());
159        assert!(result.is_err());
160
161        if let Err(e) = result {
162            assert!(e.to_string().contains("cannot be empty"));
163        }
164    }
165
166    #[test]
167    fn test_reject_too_long_article_id() {
168        // Create a 257-character string (exceeds max of 256)
169        let long_id = "a".repeat(257);
170        let result = ArticleId::new(long_id);
171        assert!(result.is_err());
172
173        if let Err(e) = result {
174            assert!(e.to_string().contains("cannot exceed 256 characters"));
175        }
176    }
177
178    #[test]
179    fn test_accept_max_length_article_id() {
180        // Exactly 256 characters should be OK
181        let max_id = "a".repeat(256);
182        let result = ArticleId::new(max_id);
183        assert!(result.is_ok());
184    }
185
186    #[test]
187    fn test_reject_invalid_characters() {
188        // Space is invalid
189        let result = ArticleId::new("article 123".to_string());
190        assert!(result.is_err());
191
192        // Special characters are invalid
193        let result = ArticleId::new("article@123".to_string());
194        assert!(result.is_err());
195
196        let result = ArticleId::new("article.123".to_string());
197        assert!(result.is_err());
198
199        let result = ArticleId::new("article/123".to_string());
200        assert!(result.is_err());
201
202        let result = ArticleId::new("article?query=1".to_string());
203        assert!(result.is_err());
204    }
205
206    #[test]
207    fn test_display_trait() {
208        let article_id = ArticleId::new("test-article".to_string()).unwrap();
209        assert_eq!(format!("{article_id}"), "test-article");
210    }
211
212    #[test]
213    fn test_try_from_str() {
214        let article_id: Result<ArticleId> = "valid-article".try_into();
215        assert!(article_id.is_ok());
216        assert_eq!(article_id.unwrap().as_str(), "valid-article");
217
218        let invalid: Result<ArticleId> = "".try_into();
219        assert!(invalid.is_err());
220    }
221
222    #[test]
223    fn test_try_from_string() {
224        let article_id: Result<ArticleId> = "valid-article".to_string().try_into();
225        assert!(article_id.is_ok());
226
227        let invalid: Result<ArticleId> = String::new().try_into();
228        assert!(invalid.is_err());
229    }
230
231    #[test]
232    fn test_into_inner() {
233        let article_id = ArticleId::new("test-article".to_string()).unwrap();
234        let inner = article_id.into_inner();
235        assert_eq!(inner, "test-article");
236    }
237
238    #[test]
239    fn test_starts_with() {
240        let article_id = ArticleId::new("kubernetes-tutorial".to_string()).unwrap();
241        assert!(article_id.starts_with("kubernetes"));
242        assert!(!article_id.starts_with("docker"));
243    }
244
245    #[test]
246    fn test_ends_with() {
247        let article_id = ArticleId::new("kubernetes-tutorial".to_string()).unwrap();
248        assert!(article_id.ends_with("tutorial"));
249        assert!(!article_id.ends_with("guide"));
250    }
251
252    #[test]
253    fn test_equality() {
254        let id1 = ArticleId::new("article-a".to_string()).unwrap();
255        let id2 = ArticleId::new("article-a".to_string()).unwrap();
256        let id3 = ArticleId::new("article-b".to_string()).unwrap();
257
258        // Value equality
259        assert_eq!(id1, id2);
260        assert_ne!(id1, id3);
261    }
262
263    #[test]
264    fn test_cloning() {
265        let id1 = ArticleId::new("article".to_string()).unwrap();
266        let id2 = id1.clone();
267        assert_eq!(id1, id2);
268    }
269
270    #[test]
271    fn test_hash_consistency() {
272        use std::collections::HashSet;
273
274        let id1 = ArticleId::new("article".to_string()).unwrap();
275        let id2 = ArticleId::new("article".to_string()).unwrap();
276
277        let mut set = HashSet::new();
278        set.insert(id1);
279
280        // Should find the same value (value equality)
281        assert!(set.contains(&id2));
282    }
283
284    #[test]
285    fn test_serde_serialization() {
286        let article_id = ArticleId::new("test-article".to_string()).unwrap();
287
288        // Serialize
289        let json = serde_json::to_string(&article_id).unwrap();
290        assert_eq!(json, "\"test-article\"");
291
292        // Deserialize
293        let deserialized: ArticleId = serde_json::from_str(&json).unwrap();
294        assert_eq!(deserialized, article_id);
295    }
296
297    #[test]
298    fn test_new_unchecked() {
299        // Should create without validation (for internal use)
300        let article_id = ArticleId::new_unchecked("invalid chars!@#".to_string());
301        assert_eq!(article_id.as_str(), "invalid chars!@#");
302    }
303}