Skip to main content

runifold_core/
id.rs

1use std::fmt;
2
3use serde::{Deserialize, Serialize};
4use uuid::Uuid;
5
6macro_rules! define_id {
7    ($name:ident, $docs:literal) => {
8        #[doc = $docs]
9        #[derive(
10            Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize,
11        )]
12        #[serde(transparent)]
13        pub struct $name(Uuid);
14
15        impl $name {
16            /// Creates a time-ordered `UUIDv7` identifier.
17            pub fn new() -> Self {
18                Self(Uuid::now_v7())
19            }
20
21            /// Creates an identifier from an existing UUID.
22            pub const fn from_uuid(value: Uuid) -> Self {
23                Self(value)
24            }
25
26            /// Returns the underlying UUID.
27            pub const fn as_uuid(self) -> Uuid {
28                self.0
29            }
30        }
31
32        impl Default for $name {
33            fn default() -> Self {
34                Self::new()
35            }
36        }
37
38        impl fmt::Display for $name {
39            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
40                self.0.fmt(formatter)
41            }
42        }
43    };
44}
45
46define_id!(RunId, "A globally unique run identifier.");
47define_id!(EventId, "A globally unique event identifier.");
48define_id!(EffectId, "A globally unique effect identifier.");
49define_id!(CapabilityId, "A globally unique capability identifier.");
50define_id!(InvocationId, "A globally unique invocation identifier.");
51define_id!(CheckpointId, "A globally unique checkpoint identifier.");
52
53#[cfg(test)]
54mod tests {
55    use super::RunId;
56
57    #[test]
58    fn generated_ids_are_distinct_and_v7() {
59        let first = RunId::new();
60        let second = RunId::new();
61
62        assert_ne!(first, second);
63        assert_eq!(first.as_uuid().get_version_num(), 7);
64    }
65}