use std::{fmt, sync::Arc};
use crate::{PersistenceError, PersistenceResult};
pub const DEFAULT_PERSISTENCE_ID_SEPARATOR: &str = "|";
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PersistenceId(Arc<str>);
impl PersistenceId {
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}"
))
}
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)))
}
#[must_use]
pub fn entity_type(&self) -> &str {
self.0
.split_once(DEFAULT_PERSISTENCE_ID_SEPARATOR)
.map_or("", |(entity_type, _)| entity_type)
}
#[must_use]
pub fn entity_id(&self) -> &str {
self.0
.split_once(DEFAULT_PERSISTENCE_ID_SEPARATOR)
.map_or(&*self.0, |(_, entity_id)| entity_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 {
#[must_use]
pub const fn new(value: u64) -> Self {
Self(value)
}
#[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.");
#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Tag(String);
impl Tag {
#[must_use]
pub fn new(value: impl Into<String>) -> Self {
Self(value.into())
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[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() {
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);
}
}