Skip to main content

bus_core/
id.rs

1use serde::{Deserialize, Serialize};
2use std::{fmt, str::FromStr};
3use uuid::Uuid;
4
5/// Newtype wrapper over UUIDv7 used as the event bus message identifier.
6#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
7pub struct MessageId(Uuid);
8
9impl MessageId {
10    /// Generate a new UUIDv7-based message ID.
11    pub fn new() -> Self {
12        Self(Uuid::now_v7())
13    }
14
15    /// Wrap an existing UUID.
16    pub fn from_uuid(uuid: Uuid) -> Self {
17        Self(uuid)
18    }
19
20    /// Return the inner UUID.
21    pub fn as_uuid(&self) -> &Uuid {
22        &self.0
23    }
24}
25
26impl Default for MessageId {
27    fn default() -> Self {
28        Self::new()
29    }
30}
31
32impl fmt::Display for MessageId {
33    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
34        write!(formatter, "{}", self.0)
35    }
36}
37
38impl FromStr for MessageId {
39    type Err = uuid::Error;
40
41    fn from_str(value: &str) -> Result<Self, Self::Err> {
42        Ok(Self(Uuid::parse_str(value)?))
43    }
44}