Skip to main content

datum_persistence/
id.rs

1use std::{fmt, sync::Arc};
2
3use crate::{PersistenceError, PersistenceResult};
4
5/// Default separator between the entity type and entity id.
6pub const DEFAULT_PERSISTENCE_ID_SEPARATOR: &str = "|";
7
8/// Stable identity of one persistent entity.
9///
10/// [`PersistenceId::new`] creates the conventional `entity_type|entity_id`
11/// form. [`PersistenceId::from_unique`] accepts an already-composed unique id;
12/// if it contains `|`, accessors split at the first occurrence, matching Akka's
13/// extraction semantics.
14///
15/// Backed by `Arc<str>` rather than `String`. Every event a running entity
16/// persists carries its own copy of the persistence id (see
17/// `StoredEvent::persistence_id` in `crate::journal`), and the behavior/state
18/// runtimes clone it once per stored event. `Arc<str>` makes [`Clone`] an
19/// atomic refcount bump instead of a heap allocation plus byte copy of the
20/// full `entity_type|entity_id` string. `PartialEq`/`Eq`/`PartialOrd`/`Ord`/
21/// `Hash`/`Display`/`Debug` all delegate through `Arc`'s deref to the
22/// contained `str`, so comparisons, ordering, hashing, and formatted output
23/// are unchanged from the previous `String` storage — this is purely an
24/// internal representation change; the public constructor/accessor API is
25/// identical.
26#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
27pub struct PersistenceId(Arc<str>);
28
29impl PersistenceId {
30    /// Creates an id from an entity type and entity id using `|` as separator.
31    ///
32    /// Neither component may contain the separator.
33    pub fn new(
34        entity_type: impl Into<String>,
35        entity_id: impl Into<String>,
36    ) -> PersistenceResult<Self> {
37        let entity_type = entity_type.into();
38        let entity_id = entity_id.into();
39        validate_component("entity type", &entity_type)?;
40        validate_component("entity id", &entity_id)?;
41        Self::from_unique(format!(
42            "{entity_type}{DEFAULT_PERSISTENCE_ID_SEPARATOR}{entity_id}"
43        ))
44    }
45
46    /// Creates an id from its complete, already-unique representation.
47    ///
48    /// This is the Rust-native spelling of Akka's `ofUniqueId`. A unique id
49    /// need not use the conventional separator, but it must not be blank.
50    pub fn from_unique(id: impl Into<String>) -> PersistenceResult<Self> {
51        let id = id.into();
52        if id.trim().is_empty() {
53            return Err(PersistenceError::InvalidPersistenceId(
54                "id must not be empty".to_owned(),
55            ));
56        }
57        Ok(Self(Arc::from(id)))
58    }
59
60    /// Returns the entity type, or an empty string when the id has no separator.
61    #[must_use]
62    pub fn entity_type(&self) -> &str {
63        self.0
64            .split_once(DEFAULT_PERSISTENCE_ID_SEPARATOR)
65            .map_or("", |(entity_type, _)| entity_type)
66    }
67
68    /// Returns the entity id portion of this persistence id.
69    #[must_use]
70    pub fn entity_id(&self) -> &str {
71        self.0
72            .split_once(DEFAULT_PERSISTENCE_ID_SEPARATOR)
73            .map_or(&*self.0, |(_, entity_id)| entity_id)
74    }
75
76    /// Returns the complete durable persistence id.
77    #[must_use]
78    pub fn id(&self) -> &str {
79        &self.0
80    }
81}
82
83impl fmt::Display for PersistenceId {
84    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85        f.write_str(self.id())
86    }
87}
88
89fn validate_component(name: &str, value: &str) -> PersistenceResult<()> {
90    if value.contains(DEFAULT_PERSISTENCE_ID_SEPARATOR) {
91        return Err(PersistenceError::InvalidPersistenceId(format!(
92            "{name} {value:?} contains reserved separator {DEFAULT_PERSISTENCE_ID_SEPARATOR:?}"
93        )));
94    }
95    Ok(())
96}
97
98macro_rules! numeric_identity {
99    ($name:ident, $description:literal) => {
100        #[doc = $description]
101        #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
102        pub struct $name(u64);
103
104        impl $name {
105            /// Creates a value from its durable numeric representation.
106            #[must_use]
107            pub const fn new(value: u64) -> Self {
108                Self(value)
109            }
110
111            /// Returns the durable numeric representation.
112            #[must_use]
113            pub const fn as_u64(self) -> u64 {
114                self.0
115            }
116        }
117
118        impl fmt::Display for $name {
119            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120                self.0.fmt(f)
121            }
122        }
123
124        impl From<u64> for $name {
125            fn from(value: u64) -> Self {
126                Self::new(value)
127            }
128        }
129
130        impl From<$name> for u64 {
131            fn from(value: $name) -> Self {
132                value.as_u64()
133            }
134        }
135    };
136}
137
138numeric_identity!(
139    SequenceNr,
140    "Monotonic event sequence number for one persistence id."
141);
142numeric_identity!(Revision, "Monotonic revision of one durable-state value.");
143
144/// Tag attached to a stored event or durable-state change for querying.
145#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
146pub struct Tag(String);
147
148impl Tag {
149    /// Creates a tag.
150    #[must_use]
151    pub fn new(value: impl Into<String>) -> Self {
152        Self(value.into())
153    }
154
155    /// Returns the tag text.
156    #[must_use]
157    pub fn as_str(&self) -> &str {
158        &self.0
159    }
160
161    /// Consumes the tag and returns its text.
162    #[must_use]
163    pub fn into_inner(self) -> String {
164        self.0
165    }
166}
167
168impl fmt::Display for Tag {
169    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
170        f.write_str(self.as_str())
171    }
172}
173
174impl AsRef<str> for Tag {
175    fn as_ref(&self) -> &str {
176        self.as_str()
177    }
178}
179
180impl From<String> for Tag {
181    fn from(value: String) -> Self {
182        Self::new(value)
183    }
184}
185
186impl From<&str> for Tag {
187    fn from(value: &str) -> Self {
188        Self::new(value)
189    }
190}
191
192#[cfg(test)]
193mod tests {
194    use super::*;
195
196    #[test]
197    fn structured_id_uses_default_separator() {
198        let id = PersistenceId::new("account", "42").unwrap();
199        assert_eq!(id.entity_type(), "account");
200        assert_eq!(id.entity_id(), "42");
201        assert_eq!(id.id(), "account|42");
202        assert_eq!(id.to_string(), "account|42");
203    }
204
205    #[test]
206    fn structured_id_rejects_reserved_separator() {
207        assert!(matches!(
208            PersistenceId::new("account|legacy", "42"),
209            Err(PersistenceError::InvalidPersistenceId(_))
210        ));
211        assert!(matches!(
212            PersistenceId::new("account", "region|42"),
213            Err(PersistenceError::InvalidPersistenceId(_))
214        ));
215    }
216
217    #[test]
218    fn unique_id_extracts_akka_compatible_components() {
219        let structured = PersistenceId::from_unique("account|region|42").unwrap();
220        assert_eq!(structured.entity_type(), "account");
221        assert_eq!(structured.entity_id(), "region|42");
222
223        let opaque = PersistenceId::from_unique("legacy-account-42").unwrap();
224        assert_eq!(opaque.entity_type(), "");
225        assert_eq!(opaque.entity_id(), "legacy-account-42");
226        assert!(PersistenceId::from_unique("  ").is_err());
227    }
228
229    #[test]
230    fn identity_newtypes_expose_stable_values() {
231        assert_eq!(SequenceNr::new(7).as_u64(), 7);
232        assert_eq!(Revision::new(3).to_string(), "3");
233        assert_eq!(Tag::new("blue").as_str(), "blue");
234    }
235
236    #[test]
237    fn clone_shares_the_underlying_allocation() {
238        // PersistenceId is Arc<str>-backed: cloning must be a refcount bump,
239        // not a fresh heap allocation, and equality/ordering/hashing must
240        // still compare by value rather than by allocation identity.
241        let id = PersistenceId::new("account", "42").unwrap();
242        let cloned = id.clone();
243        assert!(std::sync::Arc::ptr_eq(&id.0, &cloned.0));
244        assert_eq!(id, cloned);
245
246        let separately_built = PersistenceId::new("account", "42").unwrap();
247        assert!(!std::sync::Arc::ptr_eq(&id.0, &separately_built.0));
248        assert_eq!(id, separately_built);
249        assert_eq!(id.cmp(&separately_built), std::cmp::Ordering::Equal);
250    }
251}