datum-persistence 0.11.3

Event sourcing, durable state, and CQRS persistence for Datum
Documentation
use std::{fmt, sync::Arc};

use crate::{PersistenceError, PersistenceResult};

/// Default separator between the entity type and entity id.
pub const DEFAULT_PERSISTENCE_ID_SEPARATOR: &str = "|";

/// Stable identity of one persistent entity.
///
/// [`PersistenceId::new`] creates the conventional `entity_type|entity_id`
/// form. [`PersistenceId::from_unique`] accepts an already-composed unique id;
/// if it contains `|`, accessors split at the first occurrence, matching Akka's
/// extraction semantics.
///
/// Backed by `Arc<str>` rather than `String`. Every event a running entity
/// persists carries its own copy of the persistence id (see
/// `StoredEvent::persistence_id` in `crate::journal`), and the behavior/state
/// runtimes clone it once per stored event. `Arc<str>` makes [`Clone`] an
/// atomic refcount bump instead of a heap allocation plus byte copy of the
/// full `entity_type|entity_id` string. `PartialEq`/`Eq`/`PartialOrd`/`Ord`/
/// `Hash`/`Display`/`Debug` all delegate through `Arc`'s deref to the
/// contained `str`, so comparisons, ordering, hashing, and formatted output
/// are unchanged from the previous `String` storage — this is purely an
/// internal representation change; the public constructor/accessor API is
/// identical.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PersistenceId(Arc<str>);

impl PersistenceId {
    /// Creates an id from an entity type and entity id using `|` as separator.
    ///
    /// Neither component may contain the separator.
    pub fn new(
        entity_type: impl Into<String>,
        entity_id: impl Into<String>,
    ) -> PersistenceResult<Self> {
        let entity_type = entity_type.into();
        let entity_id = entity_id.into();
        validate_component("entity type", &entity_type)?;
        validate_component("entity id", &entity_id)?;
        Self::from_unique(format!(
            "{entity_type}{DEFAULT_PERSISTENCE_ID_SEPARATOR}{entity_id}"
        ))
    }

    /// Creates an id from its complete, already-unique representation.
    ///
    /// This is the Rust-native spelling of Akka's `ofUniqueId`. A unique id
    /// need not use the conventional separator, but it must not be blank.
    pub fn from_unique(id: impl Into<String>) -> PersistenceResult<Self> {
        let id = id.into();
        if id.trim().is_empty() {
            return Err(PersistenceError::InvalidPersistenceId(
                "id must not be empty".to_owned(),
            ));
        }
        Ok(Self(Arc::from(id)))
    }

    /// Returns the entity type, or an empty string when the id has no separator.
    #[must_use]
    pub fn entity_type(&self) -> &str {
        self.0
            .split_once(DEFAULT_PERSISTENCE_ID_SEPARATOR)
            .map_or("", |(entity_type, _)| entity_type)
    }

    /// Returns the entity id portion of this persistence id.
    #[must_use]
    pub fn entity_id(&self) -> &str {
        self.0
            .split_once(DEFAULT_PERSISTENCE_ID_SEPARATOR)
            .map_or(&*self.0, |(_, entity_id)| entity_id)
    }

    /// Returns the complete durable persistence id.
    #[must_use]
    pub fn id(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for PersistenceId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.id())
    }
}

fn validate_component(name: &str, value: &str) -> PersistenceResult<()> {
    if value.contains(DEFAULT_PERSISTENCE_ID_SEPARATOR) {
        return Err(PersistenceError::InvalidPersistenceId(format!(
            "{name} {value:?} contains reserved separator {DEFAULT_PERSISTENCE_ID_SEPARATOR:?}"
        )));
    }
    Ok(())
}

macro_rules! numeric_identity {
    ($name:ident, $description:literal) => {
        #[doc = $description]
        #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
        pub struct $name(u64);

        impl $name {
            /// Creates a value from its durable numeric representation.
            #[must_use]
            pub const fn new(value: u64) -> Self {
                Self(value)
            }

            /// Returns the durable numeric representation.
            #[must_use]
            pub const fn as_u64(self) -> u64 {
                self.0
            }
        }

        impl fmt::Display for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                self.0.fmt(f)
            }
        }

        impl From<u64> for $name {
            fn from(value: u64) -> Self {
                Self::new(value)
            }
        }

        impl From<$name> for u64 {
            fn from(value: $name) -> Self {
                value.as_u64()
            }
        }
    };
}

numeric_identity!(
    SequenceNr,
    "Monotonic event sequence number for one persistence id."
);
numeric_identity!(Revision, "Monotonic revision of one durable-state value.");

/// Tag attached to a stored event or durable-state change for querying.
#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Tag(String);

impl Tag {
    /// Creates a tag.
    #[must_use]
    pub fn new(value: impl Into<String>) -> Self {
        Self(value.into())
    }

    /// Returns the tag text.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consumes the tag and returns its text.
    #[must_use]
    pub fn into_inner(self) -> String {
        self.0
    }
}

impl fmt::Display for Tag {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl AsRef<str> for Tag {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl From<String> for Tag {
    fn from(value: String) -> Self {
        Self::new(value)
    }
}

impl From<&str> for Tag {
    fn from(value: &str) -> Self {
        Self::new(value)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn structured_id_uses_default_separator() {
        let id = PersistenceId::new("account", "42").unwrap();
        assert_eq!(id.entity_type(), "account");
        assert_eq!(id.entity_id(), "42");
        assert_eq!(id.id(), "account|42");
        assert_eq!(id.to_string(), "account|42");
    }

    #[test]
    fn structured_id_rejects_reserved_separator() {
        assert!(matches!(
            PersistenceId::new("account|legacy", "42"),
            Err(PersistenceError::InvalidPersistenceId(_))
        ));
        assert!(matches!(
            PersistenceId::new("account", "region|42"),
            Err(PersistenceError::InvalidPersistenceId(_))
        ));
    }

    #[test]
    fn unique_id_extracts_akka_compatible_components() {
        let structured = PersistenceId::from_unique("account|region|42").unwrap();
        assert_eq!(structured.entity_type(), "account");
        assert_eq!(structured.entity_id(), "region|42");

        let opaque = PersistenceId::from_unique("legacy-account-42").unwrap();
        assert_eq!(opaque.entity_type(), "");
        assert_eq!(opaque.entity_id(), "legacy-account-42");
        assert!(PersistenceId::from_unique("  ").is_err());
    }

    #[test]
    fn identity_newtypes_expose_stable_values() {
        assert_eq!(SequenceNr::new(7).as_u64(), 7);
        assert_eq!(Revision::new(3).to_string(), "3");
        assert_eq!(Tag::new("blue").as_str(), "blue");
    }

    #[test]
    fn clone_shares_the_underlying_allocation() {
        // PersistenceId is Arc<str>-backed: cloning must be a refcount bump,
        // not a fresh heap allocation, and equality/ordering/hashing must
        // still compare by value rather than by allocation identity.
        let id = PersistenceId::new("account", "42").unwrap();
        let cloned = id.clone();
        assert!(std::sync::Arc::ptr_eq(&id.0, &cloned.0));
        assert_eq!(id, cloned);

        let separately_built = PersistenceId::new("account", "42").unwrap();
        assert!(!std::sync::Arc::ptr_eq(&id.0, &separately_built.0));
        assert_eq!(id, separately_built);
        assert_eq!(id.cmp(&separately_built), std::cmp::Ordering::Equal);
    }
}