Skip to main content

statechronicle_domain/
ids.rs

1//! Prefixed newtype identifiers.
2//!
3//! Canonical identity for the protocol's core objects. Constructors here own
4//! validation; shared private trait shells forward parsing to those constructors:
5//!
6//! | Prefix | Id | Protocol |
7//! |---|---|---|
8//! | `stc_` | `StateId` | §9 |
9//! | `int_` | `IntentId` | §11.1 |
10//! | `evt_` | `EventId` | §12.1 |
11//! | `cmt_` | `CommitId` | §13.1 |
12//! | `snp_` | `SnapshotId` | §15 |
13//!
14//! Protocol examples show ULID-style string bodies, but the protocol does not
15//! mandate ULID. Only the exact prefix and the total length (≤
16//! [`statechronicle_core::limits::MAX_ID_LENGTH`]) are validated. Construction,
17//! parsing, and deserialization all fail closed on malformed input.
18
19#[cfg(test)]
20use core::str::FromStr;
21
22use statechronicle_core::limits::MAX_ID_LENGTH;
23
24use crate::error::DomainError;
25
26/// Prefix for state record ids (protocol §9).
27const STATE_PREFIX: &str = "stc_";
28/// Prefix for intent ids (protocol §11.1).
29const INTENT_PREFIX: &str = "int_";
30/// Prefix for event ids (protocol §12.1).
31const EVENT_PREFIX: &str = "evt_";
32/// Prefix for commit ids (protocol §13.1).
33const COMMIT_PREFIX: &str = "cmt_";
34/// Prefix for snapshot ids (protocol §15).
35const SNAPSHOT_PREFIX: &str = "snp_";
36
37/// Validates a prefixed id string: exact prefix, non-empty remainder, and
38/// total length within the protocol limit.
39///
40/// # Errors
41///
42/// Returns [`DomainError::InvalidId`] when `value` does not start with
43/// `prefix`, has an empty remainder, or exceeds
44/// [`MAX_ID_LENGTH`](statechronicle_core::limits::MAX_ID_LENGTH) characters.
45fn validate_id(kind: &'static str, prefix: &str, value: &str) -> Result<(), DomainError> {
46    let remainder = value
47        .strip_prefix(prefix)
48        .ok_or_else(|| DomainError::InvalidId {
49            kind,
50            value: String::from(value),
51            expected_prefix: String::from(prefix),
52        })?;
53    if remainder.is_empty() {
54        return Err(DomainError::InvalidId {
55            kind,
56            value: String::from(value),
57            expected_prefix: String::from(prefix),
58        });
59    }
60    if value.chars().any(char::is_control) {
61        return Err(DomainError::InvalidId {
62            kind,
63            value: String::from(value),
64            expected_prefix: String::from(prefix),
65        });
66    }
67    if value.chars().count() > MAX_ID_LENGTH {
68        return Err(DomainError::InvalidId {
69            kind,
70            value: String::from(value),
71            expected_prefix: String::from(prefix),
72        });
73    }
74    Ok(())
75}
76
77/// Identifies a state record within a tenant (protocol §9).
78#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
79pub struct StateId(pub String);
80
81impl StateId {
82    /// Constructs a validated `StateId` from its `stc_`-prefixed string form.
83    ///
84    /// # Errors
85    ///
86    /// Returns [`DomainError::InvalidId`] when `value` does not start with the
87    /// `stc_` prefix, has an empty remainder, or exceeds [`MAX_ID_LENGTH`]
88    /// characters.
89    pub fn new(value: String) -> Result<Self, DomainError> {
90        validate_id("state", STATE_PREFIX, &value)?;
91        Ok(Self(value))
92    }
93
94    /// Returns the id as its string form.
95    pub fn as_str(&self) -> &str {
96        &self.0
97    }
98}
99
100crate::validated_string::impl_validated_string!(StateId);
101
102/// Identifies an intent (protocol §11.1).
103#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
104pub struct IntentId(pub String);
105
106impl IntentId {
107    /// Constructs a validated `IntentId` from its `int_`-prefixed string form.
108    ///
109    /// # Errors
110    ///
111    /// Returns [`DomainError::InvalidId`] when `value` does not start with the
112    /// `int_` prefix, has an empty remainder, or exceeds [`MAX_ID_LENGTH`]
113    /// characters.
114    pub fn new(value: String) -> Result<Self, DomainError> {
115        validate_id("intent", INTENT_PREFIX, &value)?;
116        Ok(Self(value))
117    }
118
119    /// Returns the id as its string form.
120    pub fn as_str(&self) -> &str {
121        &self.0
122    }
123}
124
125crate::validated_string::impl_validated_string!(IntentId);
126
127/// Identifies an event (protocol §12.1).
128#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
129pub struct EventId(pub String);
130
131impl EventId {
132    /// Constructs a validated `EventId` from its `evt_`-prefixed string form.
133    ///
134    /// # Errors
135    ///
136    /// Returns [`DomainError::InvalidId`] when `value` does not start with the
137    /// `evt_` prefix, has an empty remainder, or exceeds [`MAX_ID_LENGTH`]
138    /// characters.
139    pub fn new(value: String) -> Result<Self, DomainError> {
140        validate_id("event", EVENT_PREFIX, &value)?;
141        Ok(Self(value))
142    }
143
144    /// Returns the id as its string form.
145    pub fn as_str(&self) -> &str {
146        &self.0
147    }
148}
149
150crate::validated_string::impl_validated_string!(EventId);
151
152/// Identifies a commit (protocol §13.1).
153#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
154pub struct CommitId(pub String);
155
156impl CommitId {
157    /// Constructs a validated `CommitId` from its `cmt_`-prefixed string form.
158    ///
159    /// # Errors
160    ///
161    /// Returns [`DomainError::InvalidId`] when `value` does not start with the
162    /// `cmt_` prefix, has an empty remainder, or exceeds [`MAX_ID_LENGTH`]
163    /// characters.
164    pub fn new(value: String) -> Result<Self, DomainError> {
165        validate_id("commit", COMMIT_PREFIX, &value)?;
166        Ok(Self(value))
167    }
168
169    /// Returns the id as its string form.
170    pub fn as_str(&self) -> &str {
171        &self.0
172    }
173}
174
175crate::validated_string::impl_validated_string!(CommitId);
176
177/// Identifies a snapshot (protocol §15).
178#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
179pub struct SnapshotId(pub String);
180
181impl SnapshotId {
182    /// Constructs a validated `SnapshotId` from its `snp_`-prefixed string
183    /// form.
184    ///
185    /// # Errors
186    ///
187    /// Returns [`DomainError::InvalidId`] when `value` does not start with the
188    /// `snp_` prefix, has an empty remainder, or exceeds [`MAX_ID_LENGTH`]
189    /// characters.
190    pub fn new(value: String) -> Result<Self, DomainError> {
191        validate_id("snapshot", SNAPSHOT_PREFIX, &value)?;
192        Ok(Self(value))
193    }
194
195    /// Returns the id as its string form.
196    pub fn as_str(&self) -> &str {
197        &self.0
198    }
199}
200
201crate::validated_string::impl_validated_string!(SnapshotId);
202
203#[cfg(test)]
204#[allow(clippy::unwrap_used, clippy::panic)]
205mod tests {
206    use super::*;
207
208    #[test]
209    fn new_accepts_valid_prefixed_ids() {
210        let state = StateId::new(String::from("stc_01JZ8WJ1V6MJ6Y3Z6Z9CA8B2K2")).unwrap();
211        assert_eq!(state.as_str(), "stc_01JZ8WJ1V6MJ6Y3Z6Z9CA8B2K2");
212
213        let intent = IntentId::new(String::from("int_01JZ8WJ1V6MJ6Y3Z6Z9CA8B2K2")).unwrap();
214        assert_eq!(intent.as_str(), "int_01JZ8WJ1V6MJ6Y3Z6Z9CA8B2K2");
215
216        let event = EventId::new(String::from("evt_01JZ8X2XRE5ZYW5V9R7VDQBSH4")).unwrap();
217        assert_eq!(event.as_str(), "evt_01JZ8X2XRE5ZYW5V9R7VDQBSH4");
218
219        let commit = CommitId::new(String::from("cmt_01JZ8X5HN3C4PXG5A9FGEWQF5W")).unwrap();
220        assert_eq!(commit.as_str(), "cmt_01JZ8X5HN3C4PXG5A9FGEWQF5W");
221
222        let snapshot = SnapshotId::new(String::from("snp_01JZ8X9P4DC6YC4K1YZEJX45E2")).unwrap();
223        assert_eq!(snapshot.as_str(), "snp_01JZ8X9P4DC6YC4K1YZEJX45E2");
224    }
225
226    #[test]
227    fn new_rejects_wrong_prefix() {
228        assert!(matches!(
229            StateId::new(String::from("int_not_a_state")),
230            Err(DomainError::InvalidId { kind: "state", .. })
231        ));
232        assert!(matches!(
233            IntentId::new(String::from("stc_not_an_intent")),
234            Err(DomainError::InvalidId { kind: "intent", .. })
235        ));
236        assert!(matches!(
237            EventId::new(String::from("cmt_not_an_event")),
238            Err(DomainError::InvalidId { kind: "event", .. })
239        ));
240        assert!(matches!(
241            CommitId::new(String::from("evt_not_a_commit")),
242            Err(DomainError::InvalidId { kind: "commit", .. })
243        ));
244        assert!(matches!(
245            SnapshotId::new(String::from("stc_not_a_snapshot")),
246            Err(DomainError::InvalidId {
247                kind: "snapshot",
248                ..
249            })
250        ));
251    }
252
253    #[test]
254    fn new_rejects_empty_remainder() {
255        assert!(StateId::new(String::from("stc_")).is_err());
256        assert!(IntentId::new(String::from("int_")).is_err());
257        assert!(EventId::new(String::from("evt_")).is_err());
258        assert!(CommitId::new(String::from("cmt_")).is_err());
259        assert!(SnapshotId::new(String::from("snp_")).is_err());
260    }
261
262    #[test]
263    fn new_enforces_length_limit() {
264        // Exactly at the limit (prefix + remainder) is accepted.
265        let at_limit = format!("stc_{}", "x".repeat(MAX_ID_LENGTH.saturating_sub(4)));
266        assert!(StateId::new(at_limit).is_ok());
267
268        // One character past the limit is rejected.
269        let over_limit = format!("stc_{}", "x".repeat(MAX_ID_LENGTH.saturating_sub(3)));
270        assert!(matches!(
271            StateId::new(over_limit),
272            Err(DomainError::InvalidId { kind: "state", .. })
273        ));
274    }
275
276    #[test]
277    fn unicode_id_limit_counts_characters_not_utf8_bytes() {
278        let at_limit = format!("stc_{}", "é".repeat(MAX_ID_LENGTH.saturating_sub(4)));
279        assert!(StateId::new(at_limit).is_ok());
280        let over_limit = format!("stc_{}", "é".repeat(MAX_ID_LENGTH.saturating_sub(3)));
281        assert!(StateId::new(over_limit).is_err());
282    }
283
284    #[test]
285    fn ids_reject_control_characters() {
286        assert!(StateId::new(String::from("stc_bad\nvalue")).is_err());
287        assert!(IntentId::new(String::from("int_bad\tvalue")).is_err());
288        assert!(EventId::new(String::from("evt_bad\rvalue")).is_err());
289        assert!(CommitId::new(String::from("cmt_bad\u{0000}value")).is_err());
290        assert!(SnapshotId::new(String::from("snp_bad\u{0007}value")).is_err());
291    }
292
293    #[test]
294    fn invalid_id_error_carries_context() {
295        let error = IntentId::new(String::from("evt_")).unwrap_err();
296        assert!(matches!(
297            error,
298            DomainError::InvalidId { kind: "intent", value, expected_prefix }
299            if value == "evt_" && expected_prefix == "int_"
300        ));
301    }
302
303    #[test]
304    fn from_str_and_display_roundtrip() {
305        let id = EventId::from_str("evt_01JZ8X2XRE5ZYW5V9R7VDQBSH4").unwrap();
306        assert_eq!(id.to_string(), "evt_01JZ8X2XRE5ZYW5V9R7VDQBSH4");
307        assert_eq!(EventId::from_str(id.as_str()).unwrap(), id);
308        assert!(EventId::from_str("stc_bad").is_err());
309    }
310
311    #[test]
312    fn try_from_roundtrips_and_rejects() {
313        let id = CommitId::try_from("cmt_01JZ8X5HN3C4PXG5A9FGEWQF5W").unwrap();
314        assert_eq!(id.as_str(), "cmt_01JZ8X5HN3C4PXG5A9FGEWQF5W");
315
316        let owned: CommitId = String::from("cmt_01JZ8X5HN3C4PXG5A9FGEWQF5W")
317            .try_into()
318            .unwrap();
319        assert_eq!(owned, id);
320
321        assert!(CommitId::try_from(String::from("int_0")).is_err());
322        assert!(CommitId::try_from("cmt_").is_err());
323    }
324
325    #[test]
326    fn serde_roundtrips_through_string_form() {
327        let id = IntentId::new(String::from("int_01JZ8WJ1V6MJ6Y3Z6Z9CA8B2K2")).unwrap();
328        let json = serde_json::to_string(&id).unwrap();
329        assert_eq!(json, "\"int_01JZ8WJ1V6MJ6Y3Z6Z9CA8B2K2\"");
330
331        let decoded: IntentId = serde_json::from_str(&json).unwrap();
332        assert_eq!(decoded, id);
333    }
334
335    #[test]
336    fn deserialize_rejects_invalid_string() {
337        let empty_remainder = serde_json::from_str::<IntentId>("\"int_\"");
338        assert!(empty_remainder.is_err());
339
340        let wrong_prefix = serde_json::from_str::<IntentId>("\"evt_x\"");
341        assert!(wrong_prefix.is_err());
342    }
343
344    #[test]
345    fn ids_of_different_kinds_are_distinct_types() {
346        let state = StateId::new(String::from("stc_abc")).unwrap();
347        let _intent = IntentId::new(String::from("int_abc")).unwrap();
348        assert_eq!(state.as_str(), "stc_abc");
349    }
350}