Skip to main content

kanidmd_lib/repl/
cid.rs

1use std::{fmt, time::Duration};
2use time::OffsetDateTime;
3
4use crate::{be::dbvalue::DbCidV1, prelude::*};
5use serde::{Deserialize, Serialize};
6
7#[derive(Serialize, Deserialize, PartialEq, Clone, Eq, PartialOrd, Ord, Hash)]
8pub struct Cid {
9    // Mental note: Derive ord always checks in order of struct fields.
10    pub ts: Duration,
11    pub s_uuid: Uuid,
12}
13
14impl From<DbCidV1> for Cid {
15    fn from(
16        DbCidV1 {
17            server_id,
18            timestamp,
19        }: DbCidV1,
20    ) -> Self {
21        Cid {
22            ts: timestamp,
23            s_uuid: server_id,
24        }
25    }
26}
27
28impl fmt::Debug for Cid {
29    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30        write!(f, "{:032}-{}", self.ts.as_nanos(), self.s_uuid)
31    }
32}
33
34impl fmt::Display for Cid {
35    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36        write!(f, "{:032}-{}", self.ts.as_nanos(), self.s_uuid)
37    }
38}
39
40impl From<&Cid> for OffsetDateTime {
41    fn from(cid: &Cid) -> Self {
42        OffsetDateTime::UNIX_EPOCH + cid.ts
43    }
44}
45
46impl Cid {
47    pub(crate) fn new(s_uuid: Uuid, ts: Duration) -> Self {
48        Cid { s_uuid, ts }
49    }
50
51    pub fn new_lamport(s_uuid: Uuid, ts: Duration, max_ts: &Duration) -> Self {
52        let ts = if ts > *max_ts {
53            ts
54        } else {
55            *max_ts + Duration::from_nanos(1)
56        };
57        Cid { ts, s_uuid }
58    }
59
60    /// ⚠️  - Create a new cid at timestamp zero.
61    /// This is a TEST ONLY method and will never be exposed in production.
62    #[cfg(test)]
63    pub fn new_zero() -> Self {
64        Self::new_count(0)
65    }
66
67    /// ⚠️  - Create a new cid with a manually defined timestamp.
68    /// This is a TEST ONLY method and will never be exposed in production.
69    #[cfg(test)]
70    pub fn new_count(c: u64) -> Self {
71        Cid {
72            s_uuid: uuid!("00000000-0000-0000-0000-000000000000"),
73            ts: Duration::new(c, 0),
74        }
75    }
76
77    pub fn sub_secs(&self, secs: u64) -> Result<Self, OperationError> {
78        self.ts
79            .checked_sub(Duration::from_secs(secs))
80            .map(|r| Cid {
81                s_uuid: uuid!("00000000-0000-0000-0000-000000000000"),
82                ts: r,
83            })
84            .ok_or(OperationError::InvalidReplChangeId)
85    }
86}
87
88#[cfg(test)]
89mod tests {
90    use crate::prelude::*;
91    use std::{cmp::Ordering, time::Duration};
92
93    use crate::repl::cid::Cid;
94
95    #[test]
96    fn test_cid_ordering() {
97        // Check diff ts
98        let cid_a = Cid::new(
99            uuid!("00000000-0000-0000-0000-000000000001"),
100            Duration::new(5, 0),
101        );
102        let cid_b = Cid::new(
103            uuid!("00000000-0000-0000-0000-000000000001"),
104            Duration::new(15, 0),
105        );
106
107        assert_eq!(cid_a.cmp(&cid_a), Ordering::Equal);
108        assert_eq!(cid_a.cmp(&cid_b), Ordering::Less);
109        assert_eq!(cid_b.cmp(&cid_a), Ordering::Greater);
110
111        // check same ts, d_uuid, diff s_uuid
112        let cid_e = Cid::new(
113            uuid!("00000000-0000-0000-0000-000000000000"),
114            Duration::new(5, 0),
115        );
116        let cid_f = Cid::new(
117            uuid!("00000000-0000-0000-0000-000000000001"),
118            Duration::new(5, 0),
119        );
120
121        assert_eq!(cid_e.cmp(&cid_e), Ordering::Equal);
122        assert_eq!(cid_e.cmp(&cid_f), Ordering::Less);
123        assert_eq!(cid_f.cmp(&cid_e), Ordering::Greater);
124    }
125
126    #[test]
127    fn test_cid_lamport() {
128        let s_uuid = uuid!("00000000-0000-0000-0000-000000000001");
129
130        let ts5 = Duration::new(5, 0);
131        let ts10 = Duration::new(10, 0);
132        let ts15 = Duration::new(15, 0);
133
134        let cid_z = Cid::new_zero();
135
136        let cid_a = Cid::new_lamport(s_uuid, ts5, &ts5);
137        assert_eq!(cid_a.cmp(&cid_z), Ordering::Greater);
138        let cid_b = Cid::new_lamport(s_uuid, ts15, &ts10);
139        assert_eq!(cid_b.cmp(&cid_a), Ordering::Greater);
140        // Even with an older ts, we should still step forward.
141        let cid_c = Cid::new_lamport(s_uuid, ts10, &ts15);
142        assert_eq!(cid_c.cmp(&cid_b), Ordering::Greater);
143    }
144}